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 @chapter 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 One of the great strengths of Scheme is that there is no straightforward
19 distinction between ``data'' and ``functionality''. For example,
20 Guile's support for dynamic linking could be described:
24 either in a ``data-centric'' way, as the behaviour and properties of the
25 ``dynamically linked object'' data type, and the operations that may be
26 applied to instances of this type
29 or in a ``functionality-centric'' way, as the set of procedures that
30 constitute Guile's support for dynamic linking, in the context of the
34 The contents of this chapter are, therefore, a matter of judgment. By
35 @dfn{generic}, we mean to select those data types whose typical use as
36 @emph{data} in a wide variety of programming contexts is more important
37 than their use in the implementation of a particular piece of
38 @emph{functionality}. The last section of this chapter provides
39 references for all the data types that are documented not here but in a
40 ``functionality-centric'' way elsewhere in the manual.
43 * Booleans:: True/false values.
44 * Numbers:: Numerical data types.
45 * Characters:: New character names.
46 * Strings:: Special things about strings.
47 * Regular Expressions:: Pattern matching and substitution.
49 * Keywords:: Self-quoting, customizable display keywords.
50 * Other Types:: "Functionality-centric" data types.
58 The two boolean values are @code{#t} for true and @code{#f} for false.
60 Boolean values are returned by predicate procedures, such as the general
61 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
62 (@pxref{Equality}) and numerical and string comparison operators like
63 @code{string=?} (@pxref{String Comparison}) and @code{<=}
73 (equal? "house" "houses")
81 In test condition contexts like @code{if} and @code{cond} (@pxref{if
82 cond case}), where a group of subexpressions will be evaluated only if a
83 @var{condition} expression evaluates to ``true'', ``true'' means any
84 value at all except @code{#f}.
97 A result of this asymmetry is that typical Scheme source code more often
98 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
99 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
100 not necessary to represent an @code{if} or @code{cond} true value.
102 It is important to note that @code{#f} is @strong{not} equivalent to any
103 other Scheme value. In particular, @code{#f} is not the same as the
104 number 0 (like in C and C++), and not the same as the ``empty list''
105 (like in some Lisp dialects).
107 In C, the two Scheme boolean values are available as the two constants
108 @code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
109 Care must be taken with the false value @code{SCM_BOOL_F}: it is not
110 false when used in C conditionals. In order to test for it, use
111 @code{SCM_FALSEP} or @code{SCM_NFALSEP}.
114 @deffn {Scheme Procedure} not x
115 @deffnx {C Function} scm_not (x)
116 Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
120 @deffn {Scheme Procedure} boolean? obj
121 @deffnx {C Function} scm_boolean_p (obj)
122 Return @code{#t} iff @var{obj} is either @code{#t} or @code{#f}.
126 @deffn {C Macro} SCM_BOOL_T
127 Represents a value that is true in the Scheme sense.
131 @deffn {C Macro} SCM_BOOL_F
132 Represents a value that is false in the Scheme sense.
136 @deffn {C Macro} SCM_FALSEP (SCM obj)
137 Return true in the C sense when @var{obj} is false in the Scheme
138 sense; return false in the C sense otherwise.
142 @deffn {C Macro} SCM_NFALSEP (SCM obj)
143 Return true in the C sense when @var{obj} is true in the Scheme
144 sense; return false in the C sense otherwise.
148 @section Numerical data types
151 Guile supports a rich ``tower'' of numerical types --- integer,
152 rational, real and complex --- and provides an extensive set of
153 mathematical and scientific functions for operating on numerical
154 data. This section of the manual documents those types and functions.
156 You may also find it illuminating to read R5RS's presentation of numbers
157 in Scheme, which is particularly clear and accessible: see
158 @ref{Numbers,,,r5rs,R5RS}.
161 * Numerical Tower:: Scheme's numerical "tower".
162 * Integers:: Whole numbers.
163 * Reals and Rationals:: Real and rational numbers.
164 * Complex Numbers:: Complex numbers.
165 * Exactness:: Exactness and inexactness.
166 * Number Syntax:: Read syntax for numerical data.
167 * Integer Operations:: Operations on integer values.
168 * Comparison:: Comparison predicates.
169 * Conversion:: Converting numbers to and from strings.
170 * Complex:: Complex number operations.
171 * Arithmetic:: Arithmetic functions.
172 * Scientific:: Scientific functions.
173 * Primitive Numerics:: Primitive numeric functions.
174 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
175 * Random:: Random number generation.
179 @node Numerical Tower
180 @subsection Scheme's Numerical ``Tower''
183 Scheme's numerical ``tower'' consists of the following categories of
188 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
191 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
192 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
193 pi (an irrational number) doesn't. These include integers
197 The set of numbers that describes all possible positions along a
198 one-dimensional line. This includes rationals as well as irrational
201 @item complex numbers
202 The set of numbers that describes all possible positions in a two
203 dimensional space. This includes real as well as imaginary numbers
204 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
205 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
209 It is called a tower because each category ``sits on'' the one that
210 follows it, in the sense that every integer is also a rational, every
211 rational is also real, and every real number is also a complex number
212 (but with zero imaginary part).
214 In addition to the classification into integers, rationals, reals and
215 complex numbers, Scheme also distinguishes between whether a number is
216 represented exactly or not. For example, the result of
217 @m{2\sin(\pi/4),sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)} but Guile
218 can neither represent @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
219 Instead, it stores an inexact approximation, using the C type
222 Guile can represent exact rationals of any magnitude, inexact
223 rationals that fit into a C @code{double}, and inexact complex numbers
224 with @code{double} real and imaginary parts.
226 The @code{number?} predicate may be applied to any Scheme value to
227 discover whether the value is any of the supported numerical types.
229 @deffn {Scheme Procedure} number? obj
230 @deffnx {C Function} scm_number_p (obj)
231 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
240 (number? "hello there!")
243 (define pi 3.141592654)
248 The next few subsections document each of Guile's numerical data types
254 @tpindex Integer numbers
258 Integers are whole numbers, that is numbers with no fractional part,
259 such as 2, 83, and @minus{}3789.
261 Integers in Guile can be arbitrarily big, as shown by the following
265 (define (factorial n)
266 (let loop ((n n) (product 1))
269 (loop (- n 1) (* product n)))))
275 @result{} 2432902008176640000
278 @result{} -119622220865480194561963161495657715064383733760000000000
281 Readers whose background is in programming languages where integers are
282 limited by the need to fit into just 4 or 8 bytes of memory may find
283 this surprising, or suspect that Guile's representation of integers is
284 inefficient. In fact, Guile achieves a near optimal balance of
285 convenience and efficiency by using the host computer's native
286 representation of integers where possible, and a more general
287 representation where the required number does not fit in the native
288 form. Conversion between these two representations is automatic and
289 completely invisible to the Scheme level programmer.
291 The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
292 inexact integers. They are explained in detail in the next section,
293 together with reals and rationals.
295 @c REFFIXME Maybe point here to discussion of handling immediates/bignums
296 @c on the C level, where the conversion is not so automatic - NJ
298 @deffn {Scheme Procedure} integer? x
299 @deffnx {C Function} scm_integer_p (x)
300 Return @code{#t} if @var{x} is an integer number, else @code{#f}.
315 @node Reals and Rationals
316 @subsection Real and Rational Numbers
317 @tpindex Real numbers
318 @tpindex Rational numbers
323 Mathematically, the real numbers are the set of numbers that describe
324 all possible points along a continuous, infinite, one-dimensional line.
325 The rational numbers are the set of all numbers that can be written as
326 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
327 All rational numbers are also real, but there are real numbers that
328 are not rational, for example the square root of 2, and pi.
330 Guile can represent both exact and inexact rational numbers, but it
331 can not represent irrational numbers. Exact rationals are represented
332 by storing the numerator and denominator as two exact integers.
333 Inexact rationals are stored as floating point numbers using the C
336 Exact rationals are written as a fraction of integers. There must be
337 no whitespace around the slash:
344 Even though the actual encoding of inexact rationals is in binary, it
345 may be helpful to think of it as a decimal number with a limited
346 number of significant figures and a decimal point somewhere, since
347 this corresponds to the standard notation for non-whole numbers. For
353 -5648394822220000000000.0
357 The limited precision of Guile's encoding means that any ``real'' number
358 in Guile can be written in a rational form, by multiplying and then dividing
359 by sufficient powers of 10 (or in fact, 2). For example,
360 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
361 100000000000000000. In Guile's current incarnation, therefore, the
362 @code{rational?} and @code{real?} predicates are equivalent.
365 Dividing by an exact zero leads to a error message, as one might
366 expect. However, dividing by an inexact zero does not produce an
367 error. Instead, the result of the division is either plus or minus
368 infinity, depending on the sign of the divided number.
370 The infinities are written @samp{+inf.0} and @samp{-inf.0},
371 respectivly. This syntax is also recognized by @code{read} as an
372 extension to the usual Scheme syntax.
374 Dividing zero by zero yields something that is not a number at all:
375 @samp{+nan.0}. This is the special `not a number' value.
377 On platforms that follow @acronym{IEEE} 754 for their floating point
378 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
379 are implemented using the corresponding @acronym{IEEE} 754 values.
380 They behave in arithmetic operations like @acronym{IEEE} 754 describes
381 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
383 The infinities are inexact integers and are considered to be both even
384 and odd. While @samp{+nan.0} is not @code{=} to itself, it is
385 @code{eqv?} to itself.
387 To test for the special values, use the functions @code{inf?} and
390 @deffn {Scheme Procedure} real? obj
391 @deffnx {C Function} scm_real_p (obj)
392 Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
393 that the sets of integer and rational values form subsets of the set
394 of real numbers, so the predicate will also be fulfilled if @var{obj}
395 is an integer number or a rational number.
398 @deffn {Scheme Procedure} rational? x
399 @deffnx {C Function} scm_rational_p (x)
400 Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
401 Note that the set of integer values forms a subset of the set of
402 rational numbers, i. e. the predicate will also be fulfilled if
403 @var{x} is an integer number.
405 Since Guile can not represent irrational numbers, every number
406 satisfying @code{real?} also satisfies @code{rational?} in Guile.
409 @deffn {Scheme Procedure} rationalize x eps
410 @deffnx {C Function} scm_rationalize (x, eps)
411 Returns the @emph{simplest} rational number differing
412 from @var{x} by no more than @var{eps}.
414 As required by @acronym{R5RS}, @code{rationalize} returns only then an
415 exact result when both its arguments are exact. Thus, you might need
416 to use @code{inexact->exact} on the arguments.
419 (rationalize (inexact->exact 1.2) 1/100)
425 @deffn {Scheme Procedure} inf? x
426 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
430 @deffn {Scheme Procedure} nan? x
431 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
434 @node Complex Numbers
435 @subsection Complex Numbers
436 @tpindex Complex numbers
440 Complex numbers are the set of numbers that describe all possible points
441 in a two-dimensional space. The two coordinates of a particular point
442 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
443 the complex number that describes that point.
445 In Guile, complex numbers are written in rectangular form as the sum of
446 their real and imaginary parts, using the symbol @code{i} to indicate
459 Guile represents a complex number with a non-zero imaginary part as a
460 pair of inexact rationals, so the real and imaginary parts of a
461 complex number have the same properties of inexactness and limited
462 precision as single inexact rational numbers. Guile can not represent
463 exact complex numbers with non-zero imaginary parts.
465 @deffn {Scheme Procedure} complex? x
466 @deffnx {C Function} scm_number_p (x)
467 Return @code{#t} if @var{x} is a complex number, @code{#f}
468 otherwise. Note that the sets of real, rational and integer
469 values form subsets of the set of complex numbers, i. e. the
470 predicate will also be fulfilled if @var{x} is a real,
471 rational or integer number.
476 @subsection Exact and Inexact Numbers
477 @tpindex Exact numbers
478 @tpindex Inexact numbers
482 @rnindex exact->inexact
483 @rnindex inexact->exact
485 R5RS requires that a calculation involving inexact numbers always
486 produces an inexact result. To meet this requirement, Guile
487 distinguishes between an exact integer value such as @samp{5} and the
488 corresponding inexact real value which, to the limited precision
489 available, has no fractional part, and is printed as @samp{5.0}. Guile
490 will only convert the latter value to the former when forced to do so by
491 an invocation of the @code{inexact->exact} procedure.
493 @deffn {Scheme Procedure} exact? z
494 @deffnx {C Function} scm_exact_p (z)
495 Return @code{#t} if the number @var{z} is exact, @code{#f}
511 @deffn {Scheme Procedure} inexact? z
512 @deffnx {C Function} scm_inexact_p (z)
513 Return @code{#t} if the number @var{z} is inexact, @code{#f}
517 @deffn {Scheme Procedure} inexact->exact z
518 @deffnx {C Function} scm_inexact_to_exact (z)
519 Return an exact number that is numerically closest to @var{z}, when
520 there is one. For inexact rationals, Guile returns the exact rational
521 that is numerically equal to the inexact rational. Inexact complex
522 numbers with a non-zero imaginary part can not be made exact.
529 The following happens because 12/10 is not exactly representable as a
530 @code{double} (on most platforms). However, when reading a decimal
531 number that has been marked exact with the ``#e'' prefix, Guile is
532 able to represent it correctly.
536 @result{} 5404319552844595/4503599627370496
544 @c begin (texi-doc-string "guile" "exact->inexact")
545 @deffn {Scheme Procedure} exact->inexact z
546 @deffnx {C Function} scm_exact_to_inexact (z)
547 Convert the number @var{z} to its inexact representation.
552 @subsection Read Syntax for Numerical Data
554 The read syntax for integers is a string of digits, optionally
555 preceded by a minus or plus character, a code indicating the
556 base in which the integer is encoded, and a code indicating whether
557 the number is exact or inexact. The supported base codes are:
562 the integer is written in binary (base 2)
566 the integer is written in octal (base 8)
570 the integer is written in decimal (base 10)
574 the integer is written in hexadecimal (base 16)
577 If the base code is omitted, the integer is assumed to be decimal. The
578 following examples show how these base codes are used.
597 The codes for indicating exactness (which can, incidentally, be applied
598 to all numerical values) are:
607 the number is inexact.
610 If the exactness indicator is omitted, the number is exact unless it
611 contains a radix point. Since Guile can not represent exact complex
612 numbers, an error is signalled when asking for them.
622 ERROR: Wrong type argument
625 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
626 plus and minus infinity, respectively. The value must be written
627 exactly as shown, that is, they always must have a sign and exactly
628 one zero digit after the decimal point. It also understands
629 @samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
630 The sign is ignored for `not-a-number' and the value is always printed
633 @node Integer Operations
634 @subsection Operations on Integer Values
643 @deffn {Scheme Procedure} odd? n
644 @deffnx {C Function} scm_odd_p (n)
645 Return @code{#t} if @var{n} is an odd number, @code{#f}
649 @deffn {Scheme Procedure} even? n
650 @deffnx {C Function} scm_even_p (n)
651 Return @code{#t} if @var{n} is an even number, @code{#f}
655 @c begin (texi-doc-string "guile" "quotient")
656 @c begin (texi-doc-string "guile" "remainder")
657 @deffn {Scheme Procedure} quotient n d
658 @deffnx {Scheme Procedure} remainder n d
659 @deffnx {C Function} scm_quotient (n, d)
660 @deffnx {C Function} scm_remainder (n, d)
661 Return the quotient or remainder from @var{n} divided by @var{d}. The
662 quotient is rounded towards zero, and the remainder will have the same
663 sign as @var{n}. In all cases quotient and remainder satisfy
664 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
667 (remainder 13 4) @result{} 1
668 (remainder -13 4) @result{} -1
672 @c begin (texi-doc-string "guile" "modulo")
673 @deffn {Scheme Procedure} modulo n d
674 @deffnx {C Function} scm_modulo (n, d)
675 Return the remainder from @var{n} divided by @var{d}, with the same
679 (modulo 13 4) @result{} 1
680 (modulo -13 4) @result{} 3
681 (modulo 13 -4) @result{} -3
682 (modulo -13 -4) @result{} -1
686 @c begin (texi-doc-string "guile" "gcd")
687 @deffn {Scheme Procedure} gcd
688 @deffnx {C Function} scm_gcd (x, y)
689 Return the greatest common divisor of all arguments.
690 If called without arguments, 0 is returned.
692 The C function @code{scm_gcd} always takes two arguments, while the
693 Scheme function can take an arbitrary number.
696 @c begin (texi-doc-string "guile" "lcm")
697 @deffn {Scheme Procedure} lcm
698 @deffnx {C Function} scm_lcm (x, y)
699 Return the least common multiple of the arguments.
700 If called without arguments, 1 is returned.
702 The C function @code{scm_lcm} always takes two arguments, while the
703 Scheme function can take an arbitrary number.
708 @subsection Comparison Predicates
713 The C comparison functions below always takes two arguments, while the
714 Scheme functions can take an arbitrary number. Also keep in mind that
715 the C functions return one of the Scheme boolean values
716 @code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
717 is concerned. Thus, always write @code{SCM_NFALSEP (scm_num_eq_p (x,
718 y))} when testing the two Scheme numbers @code{x} and @code{y} for
719 equality, for example.
721 @c begin (texi-doc-string "guile" "=")
722 @deffn {Scheme Procedure} =
723 @deffnx {C Function} scm_num_eq_p (x, y)
724 Return @code{#t} if all parameters are numerically equal.
727 @c begin (texi-doc-string "guile" "<")
728 @deffn {Scheme Procedure} <
729 @deffnx {C Function} scm_less_p (x, y)
730 Return @code{#t} if the list of parameters is monotonically
734 @c begin (texi-doc-string "guile" ">")
735 @deffn {Scheme Procedure} >
736 @deffnx {C Function} scm_gr_p (x, y)
737 Return @code{#t} if the list of parameters is monotonically
741 @c begin (texi-doc-string "guile" "<=")
742 @deffn {Scheme Procedure} <=
743 @deffnx {C Function} scm_leq_p (x, y)
744 Return @code{#t} if the list of parameters is monotonically
748 @c begin (texi-doc-string "guile" ">=")
749 @deffn {Scheme Procedure} >=
750 @deffnx {C Function} scm_geq_p (x, y)
751 Return @code{#t} if the list of parameters is monotonically
755 @c begin (texi-doc-string "guile" "zero?")
756 @deffn {Scheme Procedure} zero? z
757 @deffnx {C Function} scm_zero_p (z)
758 Return @code{#t} if @var{z} is an exact or inexact number equal to
762 @c begin (texi-doc-string "guile" "positive?")
763 @deffn {Scheme Procedure} positive? x
764 @deffnx {C Function} scm_positive_p (x)
765 Return @code{#t} if @var{x} is an exact or inexact number greater than
769 @c begin (texi-doc-string "guile" "negative?")
770 @deffn {Scheme Procedure} negative? x
771 @deffnx {C Function} scm_negative_p (x)
772 Return @code{#t} if @var{x} is an exact or inexact number less than
778 @subsection Converting Numbers To and From Strings
779 @rnindex number->string
780 @rnindex string->number
782 @deffn {Scheme Procedure} number->string n [radix]
783 @deffnx {C Function} scm_number_to_string (n, radix)
784 Return a string holding the external representation of the
785 number @var{n} in the given @var{radix}. If @var{n} is
786 inexact, a radix of 10 will be used.
789 @deffn {Scheme Procedure} string->number string [radix]
790 @deffnx {C Function} scm_string_to_number (string, radix)
791 Return a number of the maximally precise representation
792 expressed by the given @var{string}. @var{radix} must be an
793 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
794 is a default radix that may be overridden by an explicit radix
795 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
796 supplied, then the default radix is 10. If string is not a
797 syntactically valid notation for a number, then
798 @code{string->number} returns @code{#f}.
803 @subsection Complex Number Operations
804 @rnindex make-rectangular
811 @deffn {Scheme Procedure} make-rectangular real imaginary
812 @deffnx {C Function} scm_make_rectangular (real, imaginary)
813 Return a complex number constructed of the given @var{real} and
814 @var{imaginary} parts.
817 @deffn {Scheme Procedure} make-polar x y
818 @deffnx {C Function} scm_make_polar (x, y)
819 Return the complex number @var{x} * e^(i * @var{y}).
822 @c begin (texi-doc-string "guile" "real-part")
823 @deffn {Scheme Procedure} real-part z
824 @deffnx {C Function} scm_real_part (z)
825 Return the real part of the number @var{z}.
828 @c begin (texi-doc-string "guile" "imag-part")
829 @deffn {Scheme Procedure} imag-part z
830 @deffnx {C Function} scm_imag_part (z)
831 Return the imaginary part of the number @var{z}.
834 @c begin (texi-doc-string "guile" "magnitude")
835 @deffn {Scheme Procedure} magnitude z
836 @deffnx {C Function} scm_magnitude (z)
837 Return the magnitude of the number @var{z}. This is the same as
838 @code{abs} for real arguments, but also allows complex numbers.
841 @c begin (texi-doc-string "guile" "angle")
842 @deffn {Scheme Procedure} angle z
843 @deffnx {C Function} scm_angle (z)
844 Return the angle of the complex number @var{z}.
849 @subsection Arithmetic Functions
862 The C arithmetic functions below always takes two arguments, while the
863 Scheme functions can take an arbitrary number. When you need to
864 invoke them with just one argument, for example to compute the
865 equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
866 one: @code{scm_difference (x, SCM_UNDEFINED)}.
868 @c begin (texi-doc-string "guile" "+")
869 @deffn {Scheme Procedure} + z1 @dots{}
870 @deffnx {C Function} scm_sum (z1, z2)
871 Return the sum of all parameter values. Return 0 if called without any
875 @c begin (texi-doc-string "guile" "-")
876 @deffn {Scheme Procedure} - z1 z2 @dots{}
877 @deffnx {C Function} scm_difference (z1, z2)
878 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
879 the sum of all but the first argument are subtracted from the first
883 @c begin (texi-doc-string "guile" "*")
884 @deffn {Scheme Procedure} * z1 @dots{}
885 @deffnx {C Function} scm_product (z1, z2)
886 Return the product of all arguments. If called without arguments, 1 is
890 @c begin (texi-doc-string "guile" "/")
891 @deffn {Scheme Procedure} / z1 z2 @dots{}
892 @deffnx {C Function} scm_divide (z1, z2)
893 Divide the first argument by the product of the remaining arguments. If
894 called with one argument @var{z1}, 1/@var{z1} is returned.
897 @c begin (texi-doc-string "guile" "abs")
898 @deffn {Scheme Procedure} abs x
899 @deffnx {C Function} scm_abs (x)
900 Return the absolute value of @var{x}.
902 @var{x} must be a number with zero imaginary part. To calculate the
903 magnitude of a complex number, use @code{magnitude} instead.
906 @c begin (texi-doc-string "guile" "max")
907 @deffn {Scheme Procedure} max x1 x2 @dots{}
908 @deffnx {C Function} scm_max (x1, x2)
909 Return the maximum of all parameter values.
912 @c begin (texi-doc-string "guile" "min")
913 @deffn {Scheme Procedure} min x1 x2 @dots{}
914 @deffnx {C Function} scm_min (x1, x2)
915 Return the minimum of all parameter values.
918 @c begin (texi-doc-string "guile" "truncate")
919 @deffn {Scheme Procedure} truncate
920 @deffnx {C Function} scm_truncate_number (x)
921 Round the inexact number @var{x} towards zero.
924 @c begin (texi-doc-string "guile" "round")
925 @deffn {Scheme Procedure} round x
926 @deffnx {C Function} scm_round_number (x)
927 Round the inexact number @var{x} to the nearest integer. When exactly
928 halfway between two integers, round to the even one.
931 @c begin (texi-doc-string "guile" "floor")
932 @deffn {Scheme Procedure} floor x
933 @deffnx {C Function} scm_floor (x)
934 Round the number @var{x} towards minus infinity.
937 @c begin (texi-doc-string "guile" "ceiling")
938 @deffn {Scheme Procedure} ceiling x
939 @deffnx {C Function} scm_ceiling (x)
940 Round the number @var{x} towards infinity.
945 @subsection Scientific Functions
947 The following procedures accept any kind of number as arguments,
948 including complex numbers.
951 @c begin (texi-doc-string "guile" "sqrt")
952 @deffn {Scheme Procedure} sqrt z
953 Return the square root of @var{z}.
957 @c begin (texi-doc-string "guile" "expt")
958 @deffn {Scheme Procedure} expt z1 z2
959 Return @var{z1} raised to the power of @var{z2}.
963 @c begin (texi-doc-string "guile" "sin")
964 @deffn {Scheme Procedure} sin z
965 Return the sine of @var{z}.
969 @c begin (texi-doc-string "guile" "cos")
970 @deffn {Scheme Procedure} cos z
971 Return the cosine of @var{z}.
975 @c begin (texi-doc-string "guile" "tan")
976 @deffn {Scheme Procedure} tan z
977 Return the tangent of @var{z}.
981 @c begin (texi-doc-string "guile" "asin")
982 @deffn {Scheme Procedure} asin z
983 Return the arcsine of @var{z}.
987 @c begin (texi-doc-string "guile" "acos")
988 @deffn {Scheme Procedure} acos z
989 Return the arccosine of @var{z}.
993 @c begin (texi-doc-string "guile" "atan")
994 @deffn {Scheme Procedure} atan z
995 @deffnx {Scheme Procedure} atan y x
996 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1000 @c begin (texi-doc-string "guile" "exp")
1001 @deffn {Scheme Procedure} exp z
1002 Return e to the power of @var{z}, where e is the base of natural
1003 logarithms (2.71828@dots{}).
1007 @c begin (texi-doc-string "guile" "log")
1008 @deffn {Scheme Procedure} log z
1009 Return the natural logarithm of @var{z}.
1012 @c begin (texi-doc-string "guile" "log10")
1013 @deffn {Scheme Procedure} log10 z
1014 Return the base 10 logarithm of @var{z}.
1017 @c begin (texi-doc-string "guile" "sinh")
1018 @deffn {Scheme Procedure} sinh z
1019 Return the hyperbolic sine of @var{z}.
1022 @c begin (texi-doc-string "guile" "cosh")
1023 @deffn {Scheme Procedure} cosh z
1024 Return the hyperbolic cosine of @var{z}.
1027 @c begin (texi-doc-string "guile" "tanh")
1028 @deffn {Scheme Procedure} tanh z
1029 Return the hyperbolic tangent of @var{z}.
1032 @c begin (texi-doc-string "guile" "asinh")
1033 @deffn {Scheme Procedure} asinh z
1034 Return the hyperbolic arcsine of @var{z}.
1037 @c begin (texi-doc-string "guile" "acosh")
1038 @deffn {Scheme Procedure} acosh z
1039 Return the hyperbolic arccosine of @var{z}.
1042 @c begin (texi-doc-string "guile" "atanh")
1043 @deffn {Scheme Procedure} atanh z
1044 Return the hyperbolic arctangent of @var{z}.
1048 @node Primitive Numerics
1049 @subsection Primitive Numeric Functions
1051 Many of Guile's numeric procedures which accept any kind of numbers as
1052 arguments, including complex numbers, are implemented as Scheme
1053 procedures that use the following real number-based primitives. These
1054 primitives signal an error if they are called with complex arguments.
1056 @c begin (texi-doc-string "guile" "$abs")
1057 @deffn {Scheme Procedure} $abs x
1058 Return the absolute value of @var{x}.
1061 @c begin (texi-doc-string "guile" "$sqrt")
1062 @deffn {Scheme Procedure} $sqrt x
1063 Return the square root of @var{x}.
1066 @deffn {Scheme Procedure} $expt x y
1067 @deffnx {C Function} scm_sys_expt (x, y)
1068 Return @var{x} raised to the power of @var{y}. This
1069 procedure does not accept complex arguments.
1072 @c begin (texi-doc-string "guile" "$sin")
1073 @deffn {Scheme Procedure} $sin x
1074 Return the sine of @var{x}.
1077 @c begin (texi-doc-string "guile" "$cos")
1078 @deffn {Scheme Procedure} $cos x
1079 Return the cosine of @var{x}.
1082 @c begin (texi-doc-string "guile" "$tan")
1083 @deffn {Scheme Procedure} $tan x
1084 Return the tangent of @var{x}.
1087 @c begin (texi-doc-string "guile" "$asin")
1088 @deffn {Scheme Procedure} $asin x
1089 Return the arcsine of @var{x}.
1092 @c begin (texi-doc-string "guile" "$acos")
1093 @deffn {Scheme Procedure} $acos x
1094 Return the arccosine of @var{x}.
1097 @c begin (texi-doc-string "guile" "$atan")
1098 @deffn {Scheme Procedure} $atan x
1099 Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
1103 @deffn {Scheme Procedure} $atan2 x y
1104 @deffnx {C Function} scm_sys_atan2 (x, y)
1105 Return the arc tangent of the two arguments @var{x} and
1106 @var{y}. This is similar to calculating the arc tangent of
1107 @var{x} / @var{y}, except that the signs of both arguments
1108 are used to determine the quadrant of the result. This
1109 procedure does not accept complex arguments.
1112 @c begin (texi-doc-string "guile" "$exp")
1113 @deffn {Scheme Procedure} $exp x
1114 Return e to the power of @var{x}, where e is the base of natural
1115 logarithms (2.71828@dots{}).
1118 @c begin (texi-doc-string "guile" "$log")
1119 @deffn {Scheme Procedure} $log x
1120 Return the natural logarithm of @var{x}.
1123 @c begin (texi-doc-string "guile" "$sinh")
1124 @deffn {Scheme Procedure} $sinh x
1125 Return the hyperbolic sine of @var{x}.
1128 @c begin (texi-doc-string "guile" "$cosh")
1129 @deffn {Scheme Procedure} $cosh x
1130 Return the hyperbolic cosine of @var{x}.
1133 @c begin (texi-doc-string "guile" "$tanh")
1134 @deffn {Scheme Procedure} $tanh x
1135 Return the hyperbolic tangent of @var{x}.
1138 @c begin (texi-doc-string "guile" "$asinh")
1139 @deffn {Scheme Procedure} $asinh x
1140 Return the hyperbolic arcsine of @var{x}.
1143 @c begin (texi-doc-string "guile" "$acosh")
1144 @deffn {Scheme Procedure} $acosh x
1145 Return the hyperbolic arccosine of @var{x}.
1148 @c begin (texi-doc-string "guile" "$atanh")
1149 @deffn {Scheme Procedure} $atanh x
1150 Return the hyperbolic arctangent of @var{x}.
1153 C functions for the above are provided by the standard mathematics
1154 library. Naturally these expect and return @code{double} arguments
1155 (@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1157 @multitable {xx} {Scheme Procedure} {C Function}
1158 @item @tab Scheme Procedure @tab C Function
1160 @item @tab @code{$abs} @tab @code{fabs}
1161 @item @tab @code{$sqrt} @tab @code{sqrt}
1162 @item @tab @code{$sin} @tab @code{sin}
1163 @item @tab @code{$cos} @tab @code{cos}
1164 @item @tab @code{$tan} @tab @code{tan}
1165 @item @tab @code{$asin} @tab @code{asin}
1166 @item @tab @code{$acos} @tab @code{acos}
1167 @item @tab @code{$atan} @tab @code{atan}
1168 @item @tab @code{$atan2} @tab @code{atan2}
1169 @item @tab @code{$exp} @tab @code{exp}
1170 @item @tab @code{$expt} @tab @code{pow}
1171 @item @tab @code{$log} @tab @code{log}
1172 @item @tab @code{$sinh} @tab @code{sinh}
1173 @item @tab @code{$cosh} @tab @code{cosh}
1174 @item @tab @code{$tanh} @tab @code{tanh}
1175 @item @tab @code{$asinh} @tab @code{asinh}
1176 @item @tab @code{$acosh} @tab @code{acosh}
1177 @item @tab @code{$atanh} @tab @code{atanh}
1180 @code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1181 not be available on older systems. Guile provides the following
1182 equivalents (on all systems).
1184 @deftypefn {C Function} double scm_asinh (double x)
1185 @deftypefnx {C Function} double scm_acosh (double x)
1186 @deftypefnx {C Function} double scm_atanh (double x)
1187 Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1192 @node Bitwise Operations
1193 @subsection Bitwise Operations
1195 For the following bitwise functions, negative numbers are treated as
1196 infinite precision twos-complements. For instance @math{-6} is bits
1197 @math{@dots{}111010}, with infinitely many ones on the left. It can
1198 be seen that adding 6 (binary 110) to such a bit pattern gives all
1201 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1202 @deffnx {C Function} scm_logand (n1, n2)
1203 Return the bitwise @sc{and} of the integer arguments.
1206 (logand) @result{} -1
1207 (logand 7) @result{} 7
1208 (logand #b111 #b011 #b001) @result{} 1
1212 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1213 @deffnx {C Function} scm_logior (n1, n2)
1214 Return the bitwise @sc{or} of the integer arguments.
1217 (logior) @result{} 0
1218 (logior 7) @result{} 7
1219 (logior #b000 #b001 #b011) @result{} 3
1223 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1224 @deffnx {C Function} scm_loxor (n1, n2)
1225 Return the bitwise @sc{xor} of the integer arguments. A bit is
1226 set in the result if it is set in an odd number of arguments.
1229 (logxor) @result{} 0
1230 (logxor 7) @result{} 7
1231 (logxor #b000 #b001 #b011) @result{} 2
1232 (logxor #b000 #b001 #b011 #b011) @result{} 1
1236 @deffn {Scheme Procedure} lognot n
1237 @deffnx {C Function} scm_lognot (n)
1238 Return the integer which is the ones-complement of the integer
1239 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1242 (number->string (lognot #b10000000) 2)
1243 @result{} "-10000001"
1244 (number->string (lognot #b0) 2)
1249 @deffn {Scheme Procedure} logtest j k
1250 @deffnx {C Function} scm_logtest (j, k)
1252 (logtest j k) @equiv{} (not (zero? (logand j k)))
1254 (logtest #b0100 #b1011) @result{} #f
1255 (logtest #b0100 #b0111) @result{} #t
1259 @deffn {Scheme Procedure} logbit? index j
1260 @deffnx {C Function} scm_logbit_p (index, j)
1262 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1264 (logbit? 0 #b1101) @result{} #t
1265 (logbit? 1 #b1101) @result{} #f
1266 (logbit? 2 #b1101) @result{} #t
1267 (logbit? 3 #b1101) @result{} #t
1268 (logbit? 4 #b1101) @result{} #f
1272 @deffn {Scheme Procedure} ash n cnt
1273 @deffnx {C Function} scm_ash (n, cnt)
1274 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1275 @var{cnt} is negative. This is an ``arithmetic'' shift.
1277 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1278 when @var{cnt} is negative it's a division, rounded towards negative
1279 infinity. (Note that this is not the same rounding as @code{quotient}
1282 With @var{n} viewed as an infinite precision twos complement,
1283 @code{ash} means a left shift introducing zero bits, or a right shift
1287 (number->string (ash #b1 3) 2) @result{} "1000"
1288 (number->string (ash #b1010 -1) 2) @result{} "101"
1290 ;; -23 is bits ...11101001, -6 is bits ...111010
1291 (ash -23 -2) @result{} -6
1295 @deffn {Scheme Procedure} logcount n
1296 @deffnx {C Function} scm_logcount (n)
1297 Return the number of bits in integer @var{n}. If integer is
1298 positive, the 1-bits in its binary representation are counted.
1299 If negative, the 0-bits in its two's-complement binary
1300 representation are counted. If 0, 0 is returned.
1303 (logcount #b10101010)
1312 @deffn {Scheme Procedure} integer-length n
1313 @deffnx {C Function} scm_integer_length (n)
1314 Return the number of bits necessary to represent @var{n}.
1316 For positive @var{n} this is how many bits to the most significant one
1317 bit. For negative @var{n} it's how many bits to the most significant
1318 zero bit in twos complement form.
1321 (integer-length #b10101010) @result{} 8
1322 (integer-length #b1111) @result{} 4
1323 (integer-length 0) @result{} 0
1324 (integer-length -1) @result{} 0
1325 (integer-length -256) @result{} 8
1326 (integer-length -257) @result{} 9
1330 @deffn {Scheme Procedure} integer-expt n k
1331 @deffnx {C Function} scm_integer_expt (n, k)
1332 Return @var{n} raised to the non-negative integer exponent
1343 @deffn {Scheme Procedure} bit-extract n start end
1344 @deffnx {C Function} scm_bit_extract (n, start, end)
1345 Return the integer composed of the @var{start} (inclusive)
1346 through @var{end} (exclusive) bits of @var{n}. The
1347 @var{start}th bit becomes the 0-th bit in the result.
1350 (number->string (bit-extract #b1101101010 0 4) 2)
1352 (number->string (bit-extract #b1101101010 4 9) 2)
1359 @subsection Random Number Generation
1361 Pseudo-random numbers are generated from a random state object, which
1362 can be created with @code{seed->random-state}. The @var{state}
1363 parameter to the various functions below is optional, it defaults to
1364 the state object in the @code{*random-state*} variable.
1366 @deffn {Scheme Procedure} copy-random-state [state]
1367 @deffnx {C Function} scm_copy_random_state (state)
1368 Return a copy of the random state @var{state}.
1371 @deffn {Scheme Procedure} random n [state]
1372 @deffnx {C Function} scm_random (n, state)
1373 Return a number in [0, @var{n}).
1375 Accepts a positive integer or real n and returns a
1376 number of the same type between zero (inclusive) and
1377 @var{n} (exclusive). The values returned have a uniform
1381 @deffn {Scheme Procedure} random:exp [state]
1382 @deffnx {C Function} scm_random_exp (state)
1383 Return an inexact real in an exponential distribution with mean
1384 1. For an exponential distribution with mean @var{u} use @code{(*
1385 @var{u} (random:exp))}.
1388 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1389 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1390 Fills @var{vect} with inexact real random numbers the sum of whose
1391 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1392 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1393 the coordinates are uniformly distributed over the surface of the unit
1397 @deffn {Scheme Procedure} random:normal [state]
1398 @deffnx {C Function} scm_random_normal (state)
1399 Return an inexact real in a normal distribution. The distribution
1400 used has mean 0 and standard deviation 1. For a normal distribution
1401 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1402 (* @var{d} (random:normal)))}.
1405 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1406 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1407 Fills @var{vect} with inexact real random numbers that are
1408 independent and standard normally distributed
1409 (i.e., with mean 0 and variance 1).
1412 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1413 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1414 Fills @var{vect} with inexact real random numbers the sum of whose
1415 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1416 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1417 the coordinates are uniformly distributed within the unit
1418 @var{n}-sphere. The sum of the squares of the numbers is returned.
1419 @c FIXME: What does this mean, particularly the n-sphere part?
1422 @deffn {Scheme Procedure} random:uniform [state]
1423 @deffnx {C Function} scm_random_uniform (state)
1424 Return a uniformly distributed inexact real random number in
1428 @deffn {Scheme Procedure} seed->random-state seed
1429 @deffnx {C Function} scm_seed_to_random_state (seed)
1430 Return a new random state using @var{seed}.
1433 @defvar *random-state*
1434 The global random state used by the above functions when the
1435 @var{state} parameter is not given.
1444 [@strong{FIXME}: how do you specify regular (non-control) characters?]
1446 Most of the ``control characters'' (those below codepoint 32) in the
1447 @acronym{ASCII} character set, as well as the space, may be referred
1448 to by name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and
1449 so on. The following table describes the @acronym{ASCII} names for
1452 @multitable @columnfractions .25 .25 .25 .25
1453 @item 0 = @code{#\nul}
1454 @tab 1 = @code{#\soh}
1455 @tab 2 = @code{#\stx}
1456 @tab 3 = @code{#\etx}
1457 @item 4 = @code{#\eot}
1458 @tab 5 = @code{#\enq}
1459 @tab 6 = @code{#\ack}
1460 @tab 7 = @code{#\bel}
1461 @item 8 = @code{#\bs}
1462 @tab 9 = @code{#\ht}
1463 @tab 10 = @code{#\nl}
1464 @tab 11 = @code{#\vt}
1465 @item 12 = @code{#\np}
1466 @tab 13 = @code{#\cr}
1467 @tab 14 = @code{#\so}
1468 @tab 15 = @code{#\si}
1469 @item 16 = @code{#\dle}
1470 @tab 17 = @code{#\dc1}
1471 @tab 18 = @code{#\dc2}
1472 @tab 19 = @code{#\dc3}
1473 @item 20 = @code{#\dc4}
1474 @tab 21 = @code{#\nak}
1475 @tab 22 = @code{#\syn}
1476 @tab 23 = @code{#\etb}
1477 @item 24 = @code{#\can}
1478 @tab 25 = @code{#\em}
1479 @tab 26 = @code{#\sub}
1480 @tab 27 = @code{#\esc}
1481 @item 28 = @code{#\fs}
1482 @tab 29 = @code{#\gs}
1483 @tab 30 = @code{#\rs}
1484 @tab 31 = @code{#\us}
1485 @item 32 = @code{#\sp}
1488 The ``delete'' character (octal 177) may be referred to with the name
1491 Several characters have more than one name:
1493 @multitable {@code{#\backspace}} {Original}
1494 @item Alias @tab Original
1495 @item @code{#\space} @tab @code{#\sp}
1496 @item @code{#\newline} @tab @code{#\nl}
1497 @item @code{#\tab} @tab @code{#\ht}
1498 @item @code{#\backspace} @tab @code{#\bs}
1499 @item @code{#\return} @tab @code{#\cr}
1500 @item @code{#\page} @tab @code{#\np}
1501 @item @code{#\null} @tab @code{#\nul}
1505 @deffn {Scheme Procedure} char? x
1506 @deffnx {C Function} scm_char_p (x)
1507 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1511 @deffn {Scheme Procedure} char=? x y
1512 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1516 @deffn {Scheme Procedure} char<? x y
1517 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1522 @deffn {Scheme Procedure} char<=? x y
1523 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1524 @acronym{ASCII} sequence, else @code{#f}.
1528 @deffn {Scheme Procedure} char>? x y
1529 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1530 sequence, else @code{#f}.
1534 @deffn {Scheme Procedure} char>=? x y
1535 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1536 @acronym{ASCII} sequence, else @code{#f}.
1540 @deffn {Scheme Procedure} char-ci=? x y
1541 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1542 case, else @code{#f}.
1546 @deffn {Scheme Procedure} char-ci<? x y
1547 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1548 ignoring case, else @code{#f}.
1552 @deffn {Scheme Procedure} char-ci<=? x y
1553 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1554 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1558 @deffn {Scheme Procedure} char-ci>? x y
1559 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1560 sequence ignoring case, else @code{#f}.
1564 @deffn {Scheme Procedure} char-ci>=? x y
1565 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1566 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1569 @rnindex char-alphabetic?
1570 @deffn {Scheme Procedure} char-alphabetic? chr
1571 @deffnx {C Function} scm_char_alphabetic_p (chr)
1572 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1573 Alphabetic means the same thing as the @code{isalpha} C library function.
1576 @rnindex char-numeric?
1577 @deffn {Scheme Procedure} char-numeric? chr
1578 @deffnx {C Function} scm_char_numeric_p (chr)
1579 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1580 Numeric means the same thing as the @code{isdigit} C library function.
1583 @rnindex char-whitespace?
1584 @deffn {Scheme Procedure} char-whitespace? chr
1585 @deffnx {C Function} scm_char_whitespace_p (chr)
1586 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1587 Whitespace means the same thing as the @code{isspace} C library function.
1590 @rnindex char-upper-case?
1591 @deffn {Scheme Procedure} char-upper-case? chr
1592 @deffnx {C Function} scm_char_upper_case_p (chr)
1593 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1594 Uppercase means the same thing as the @code{isupper} C library function.
1597 @rnindex char-lower-case?
1598 @deffn {Scheme Procedure} char-lower-case? chr
1599 @deffnx {C Function} scm_char_lower_case_p (chr)
1600 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1601 Lowercase means the same thing as the @code{islower} C library function.
1604 @deffn {Scheme Procedure} char-is-both? chr
1605 @deffnx {C Function} scm_char_is_both_p (chr)
1606 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1607 @code{#f}. Uppercase and lowercase are as defined by the
1608 @code{isupper} and @code{islower} C library functions.
1611 @rnindex char->integer
1612 @deffn {Scheme Procedure} char->integer chr
1613 @deffnx {C Function} scm_char_to_integer (chr)
1614 Return the number corresponding to ordinal position of @var{chr} in the
1615 @acronym{ASCII} sequence.
1618 @rnindex integer->char
1619 @deffn {Scheme Procedure} integer->char n
1620 @deffnx {C Function} scm_integer_to_char (n)
1621 Return the character at position @var{n} in the @acronym{ASCII} sequence.
1624 @rnindex char-upcase
1625 @deffn {Scheme Procedure} char-upcase chr
1626 @deffnx {C Function} scm_char_upcase (chr)
1627 Return the uppercase character version of @var{chr}.
1630 @rnindex char-downcase
1631 @deffn {Scheme Procedure} char-downcase chr
1632 @deffnx {C Function} scm_char_downcase (chr)
1633 Return the lowercase character version of @var{chr}.
1636 @xref{Classification of Characters,,,libc,GNU C Library Reference
1637 Manual}, for information about the @code{is*} Standard C functions
1645 Strings are fixed-length sequences of characters. They can be created
1646 by calling constructor procedures, but they can also literally get
1647 entered at the @acronym{REPL} or in Scheme source files.
1649 Guile provides a rich set of string processing procedures, because text
1650 handling is very important when Guile is used as a scripting language.
1652 Strings always carry the information about how many characters they are
1653 composed of with them, so there is no special end-of-string character,
1654 like in C. That means that Scheme strings can contain any character,
1655 even the @samp{NUL} character @samp{\0}. But note: Since most operating
1656 system calls dealing with strings (such as for file operations) expect
1657 strings to be zero-terminated, they might do unexpected things when
1658 called with string containing unusual characters.
1661 * String Syntax:: Read syntax for strings.
1662 * String Predicates:: Testing strings for certain properties.
1663 * String Constructors:: Creating new string objects.
1664 * List/String Conversion:: Converting from/to lists of characters.
1665 * String Selection:: Select portions from strings.
1666 * String Modification:: Modify parts or whole strings.
1667 * String Comparison:: Lexicographic ordering predicates.
1668 * String Searching:: Searching in strings.
1669 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1670 * Appending Strings:: Appending strings to form a new string.
1674 @subsection String Read Syntax
1676 The read syntax for strings is an arbitrarily long sequence of
1677 characters enclosed in double quotes (@code{"}).@footnote{Actually,
1678 the current implementation restricts strings to a length of
1679 @math{2^24}, or 16,777,216, characters. Sorry.} If you want to
1680 insert a double quote character into a string literal, it must be
1681 prefixed with a backslash @samp{\} character (called an @dfn{escape
1684 The following are examples of string literals:
1693 @c FIXME::martin: What about escape sequences like \r, \n etc.?
1695 @node String Predicates
1696 @subsection String Predicates
1698 The following procedures can be used to check whether a given string
1699 fulfills some specified property.
1702 @deffn {Scheme Procedure} string? obj
1703 @deffnx {C Function} scm_string_p (obj)
1704 Return @code{#t} if @var{obj} is a string, else @code{#f}.
1707 @deffn {Scheme Procedure} string-null? str
1708 @deffnx {C Function} scm_string_null_p (str)
1709 Return @code{#t} if @var{str}'s length is zero, and
1710 @code{#f} otherwise.
1712 (string-null? "") @result{} #t
1714 (string-null? y) @result{} #f
1718 @node String Constructors
1719 @subsection String Constructors
1721 The string constructor procedures create new string objects, possibly
1722 initializing them with some specified character data.
1724 @c FIXME::martin: list->string belongs into `List/String Conversion'
1727 @rnindex list->string
1728 @deffn {Scheme Procedure} string . chrs
1729 @deffnx {Scheme Procedure} list->string chrs
1730 @deffnx {C Function} scm_string (chrs)
1731 Return a newly allocated string composed of the arguments,
1735 @rnindex make-string
1736 @deffn {Scheme Procedure} make-string k [chr]
1737 @deffnx {C Function} scm_make_string (k, chr)
1738 Return a newly allocated string of
1739 length @var{k}. If @var{chr} is given, then all elements of
1740 the string are initialized to @var{chr}, otherwise the contents
1741 of the @var{string} are unspecified.
1744 @node List/String Conversion
1745 @subsection List/String conversion
1747 When processing strings, it is often convenient to first convert them
1748 into a list representation by using the procedure @code{string->list},
1749 work with the resulting list, and then convert it back into a string.
1750 These procedures are useful for similar tasks.
1752 @rnindex string->list
1753 @deffn {Scheme Procedure} string->list str
1754 @deffnx {C Function} scm_string_to_list (str)
1755 Return a newly allocated list of the characters that make up
1756 the given string @var{str}. @code{string->list} and
1757 @code{list->string} are inverses as far as @samp{equal?} is
1761 @deffn {Scheme Procedure} string-split str chr
1762 @deffnx {C Function} scm_string_split (str, chr)
1763 Split the string @var{str} into the a list of the substrings delimited
1764 by appearances of the character @var{chr}. Note that an empty substring
1765 between separator characters will result in an empty string in the
1769 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
1771 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
1773 (string-split "::" #\:)
1777 (string-split "" #\:)
1784 @node String Selection
1785 @subsection String Selection
1787 Portions of strings can be extracted by these procedures.
1788 @code{string-ref} delivers individual characters whereas
1789 @code{substring} can be used to extract substrings from longer strings.
1791 @rnindex string-length
1792 @deffn {Scheme Procedure} string-length string
1793 @deffnx {C Function} scm_string_length (string)
1794 Return the number of characters in @var{string}.
1798 @deffn {Scheme Procedure} string-ref str k
1799 @deffnx {C Function} scm_string_ref (str, k)
1800 Return character @var{k} of @var{str} using zero-origin
1801 indexing. @var{k} must be a valid index of @var{str}.
1804 @rnindex string-copy
1805 @deffn {Scheme Procedure} string-copy str
1806 @deffnx {C Function} scm_string_copy (str)
1807 Return a newly allocated copy of the given @var{string}.
1811 @deffn {Scheme Procedure} substring str start [end]
1812 @deffnx {C Function} scm_substring (str, start, end)
1813 Return a newly allocated string formed from the characters
1814 of @var{str} beginning with index @var{start} (inclusive) and
1815 ending with index @var{end} (exclusive).
1816 @var{str} must be a string, @var{start} and @var{end} must be
1817 exact integers satisfying:
1819 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
1822 @node String Modification
1823 @subsection String Modification
1825 These procedures are for modifying strings in-place. This means that the
1826 result of the operation is not a new string; instead, the original string's
1827 memory representation is modified.
1829 @rnindex string-set!
1830 @deffn {Scheme Procedure} string-set! str k chr
1831 @deffnx {C Function} scm_string_set_x (str, k, chr)
1832 Store @var{chr} in element @var{k} of @var{str} and return
1833 an unspecified value. @var{k} must be a valid index of
1837 @rnindex string-fill!
1838 @deffn {Scheme Procedure} string-fill! str chr
1839 @deffnx {C Function} scm_string_fill_x (str, chr)
1840 Store @var{char} in every element of the given @var{string} and
1841 return an unspecified value.
1844 @deffn {Scheme Procedure} substring-fill! str start end fill
1845 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
1846 Change every character in @var{str} between @var{start} and
1847 @var{end} to @var{fill}.
1850 (define y "abcdefg")
1851 (substring-fill! y 1 3 #\r)
1857 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
1858 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
1859 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1860 into @var{str2} beginning at position @var{start2}.
1861 @var{str1} and @var{str2} can be the same string.
1865 @node String Comparison
1866 @subsection String Comparison
1868 The procedures in this section are similar to the character ordering
1869 predicates (@pxref{Characters}), but are defined on character sequences.
1870 They all return @code{#t} on success and @code{#f} on failure. The
1871 predicates ending in @code{-ci} ignore the character case when comparing
1876 @deffn {Scheme Procedure} string=? s1 s2
1877 Lexicographic equality predicate; return @code{#t} if the two
1878 strings are the same length and contain the same characters in
1879 the same positions, otherwise return @code{#f}.
1881 The procedure @code{string-ci=?} treats upper and lower case
1882 letters as though they were the same character, but
1883 @code{string=?} treats upper and lower case as distinct
1888 @deffn {Scheme Procedure} string<? s1 s2
1889 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1890 is lexicographically less than @var{s2}.
1894 @deffn {Scheme Procedure} string<=? s1 s2
1895 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1896 is lexicographically less than or equal to @var{s2}.
1900 @deffn {Scheme Procedure} string>? s1 s2
1901 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1902 is lexicographically greater than @var{s2}.
1906 @deffn {Scheme Procedure} string>=? s1 s2
1907 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1908 is lexicographically greater than or equal to @var{s2}.
1911 @rnindex string-ci=?
1912 @deffn {Scheme Procedure} string-ci=? s1 s2
1913 Case-insensitive string equality predicate; return @code{#t} if
1914 the two strings are the same length and their component
1915 characters match (ignoring case) at each position; otherwise
1920 @deffn {Scheme Procedure} string-ci<? s1 s2
1921 Case insensitive lexicographic ordering predicate; return
1922 @code{#t} if @var{s1} is lexicographically less than @var{s2}
1927 @deffn {Scheme Procedure} string-ci<=? s1 s2
1928 Case insensitive lexicographic ordering predicate; return
1929 @code{#t} if @var{s1} is lexicographically less than or equal
1930 to @var{s2} regardless of case.
1933 @rnindex string-ci>?
1934 @deffn {Scheme Procedure} string-ci>? s1 s2
1935 Case insensitive lexicographic ordering predicate; return
1936 @code{#t} if @var{s1} is lexicographically greater than
1937 @var{s2} regardless of case.
1940 @rnindex string-ci>=?
1941 @deffn {Scheme Procedure} string-ci>=? s1 s2
1942 Case insensitive lexicographic ordering predicate; return
1943 @code{#t} if @var{s1} is lexicographically greater than or
1944 equal to @var{s2} regardless of case.
1948 @node String Searching
1949 @subsection String Searching
1951 When searching for the index of a character in a string, these
1952 procedures can be used.
1954 @deffn {Scheme Procedure} string-index str chr [frm [to]]
1955 @deffnx {C Function} scm_string_index (str, chr, frm, to)
1956 Return the index of the first occurrence of @var{chr} in
1957 @var{str}. The optional integer arguments @var{frm} and
1958 @var{to} limit the search to a portion of the string. This
1959 procedure essentially implements the @code{index} or
1960 @code{strchr} functions from the C library.
1963 (string-index "weiner" #\e)
1966 (string-index "weiner" #\e 2)
1969 (string-index "weiner" #\e 2 4)
1974 @deffn {Scheme Procedure} string-rindex str chr [frm [to]]
1975 @deffnx {C Function} scm_string_rindex (str, chr, frm, to)
1976 Like @code{string-index}, but search from the right of the
1977 string rather than from the left. This procedure essentially
1978 implements the @code{rindex} or @code{strrchr} functions from
1982 (string-rindex "weiner" #\e)
1985 (string-rindex "weiner" #\e 2 4)
1988 (string-rindex "weiner" #\e 2 5)
1993 @node Alphabetic Case Mapping
1994 @subsection Alphabetic Case Mapping
1996 These are procedures for mapping strings to their upper- or lower-case
1997 equivalents, respectively, or for capitalizing strings.
1999 @deffn {Scheme Procedure} string-upcase str
2000 @deffnx {C Function} scm_string_upcase (str)
2001 Return a freshly allocated string containing the characters of
2002 @var{str} in upper case.
2005 @deffn {Scheme Procedure} string-upcase! str
2006 @deffnx {C Function} scm_string_upcase_x (str)
2007 Destructively upcase every character in @var{str} and return
2010 y @result{} "arrdefg"
2011 (string-upcase! y) @result{} "ARRDEFG"
2012 y @result{} "ARRDEFG"
2016 @deffn {Scheme Procedure} string-downcase str
2017 @deffnx {C Function} scm_string_downcase (str)
2018 Return a freshly allocation string containing the characters in
2019 @var{str} in lower case.
2022 @deffn {Scheme Procedure} string-downcase! str
2023 @deffnx {C Function} scm_string_downcase_x (str)
2024 Destructively downcase every character in @var{str} and return
2027 y @result{} "ARRDEFG"
2028 (string-downcase! y) @result{} "arrdefg"
2029 y @result{} "arrdefg"
2033 @deffn {Scheme Procedure} string-capitalize str
2034 @deffnx {C Function} scm_string_capitalize (str)
2035 Return a freshly allocated string with the characters in
2036 @var{str}, where the first character of every word is
2040 @deffn {Scheme Procedure} string-capitalize! str
2041 @deffnx {C Function} scm_string_capitalize_x (str)
2042 Upcase the first character of every word in @var{str}
2043 destructively and return @var{str}.
2046 y @result{} "hello world"
2047 (string-capitalize! y) @result{} "Hello World"
2048 y @result{} "Hello World"
2053 @node Appending Strings
2054 @subsection Appending Strings
2056 The procedure @code{string-append} appends several strings together to
2057 form a longer result string.
2059 @rnindex string-append
2060 @deffn {Scheme Procedure} string-append . args
2061 @deffnx {C Function} scm_string_append (args)
2062 Return a newly allocated string whose characters form the
2063 concatenation of the given strings, @var{args}.
2067 (string-append h "world"))
2068 @result{} "hello world"
2073 @node Regular Expressions
2074 @section Regular Expressions
2075 @tpindex Regular expressions
2077 @cindex regular expressions
2079 @cindex emacs regexp
2081 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
2082 describes a whole class of strings. A full description of regular
2083 expressions and their syntax is beyond the scope of this manual;
2084 an introduction can be found in the Emacs manual (@pxref{Regexps,
2085 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
2086 in many general Unix reference books.
2088 If your system does not include a POSIX regular expression library,
2089 and you have not linked Guile with a third-party regexp library such
2090 as Rx, these functions will not be available. You can tell whether
2091 your Guile installation includes regular expression support by
2092 checking whether @code{(provided? 'regex)} returns true.
2094 The following regexp and string matching features are provided by the
2095 @code{(ice-9 regex)} module. Before using the described functions,
2096 you should load this module by executing @code{(use-modules (ice-9
2100 * Regexp Functions:: Functions that create and match regexps.
2101 * Match Structures:: Finding what was matched by a regexp.
2102 * Backslash Escapes:: Removing the special meaning of regexp
2107 @node Regexp Functions
2108 @subsection Regexp Functions
2110 By default, Guile supports POSIX extended regular expressions.
2111 That means that the characters @samp{(}, @samp{)}, @samp{+} and
2112 @samp{?} are special, and must be escaped if you wish to match the
2115 This regular expression interface was modeled after that
2116 implemented by SCSH, the Scheme Shell. It is intended to be
2117 upwardly compatible with SCSH regular expressions.
2119 @deffn {Scheme Procedure} string-match pattern str [start]
2120 Compile the string @var{pattern} into a regular expression and compare
2121 it with @var{str}. The optional numeric argument @var{start} specifies
2122 the position of @var{str} at which to begin matching.
2124 @code{string-match} returns a @dfn{match structure} which
2125 describes what, if anything, was matched by the regular
2126 expression. @xref{Match Structures}. If @var{str} does not match
2127 @var{pattern} at all, @code{string-match} returns @code{#f}.
2130 Two examples of a match follow. In the first example, the pattern
2131 matches the four digits in the match string. In the second, the pattern
2135 (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
2136 @result{} #("blah2002" (4 . 8))
2138 (string-match "[A-Za-z]" "123456")
2142 Each time @code{string-match} is called, it must compile its
2143 @var{pattern} argument into a regular expression structure. This
2144 operation is expensive, which makes @code{string-match} inefficient if
2145 the same regular expression is used several times (for example, in a
2146 loop). For better performance, you can compile a regular expression in
2147 advance and then match strings against the compiled regexp.
2149 @deffn {Scheme Procedure} make-regexp pat . flags
2150 @deffnx {C Function} scm_make_regexp (pat, flags)
2151 Compile the regular expression described by @var{pat}, and
2152 return the compiled regexp structure. If @var{pat} does not
2153 describe a legal regular expression, @code{make-regexp} throws
2154 a @code{regular-expression-syntax} error.
2156 The @var{flags} arguments change the behavior of the compiled
2157 regular expression. The following flags may be supplied:
2161 Consider uppercase and lowercase letters to be the same when
2163 @item regexp/newline
2164 If a newline appears in the target string, then permit the
2165 @samp{^} and @samp{$} operators to match immediately after or
2166 immediately before the newline, respectively. Also, the
2167 @samp{.} and @samp{[^...]} operators will never match a newline
2168 character. The intent of this flag is to treat the target
2169 string as a buffer containing many lines of text, and the
2170 regular expression as a pattern that may match a single one of
2173 Compile a basic (``obsolete'') regexp instead of the extended
2174 (``modern'') regexps that are the default. Basic regexps do
2175 not consider @samp{|}, @samp{+} or @samp{?} to be special
2176 characters, and require the @samp{@{...@}} and @samp{(...)}
2177 metacharacters to be backslash-escaped (@pxref{Backslash
2178 Escapes}). There are several other differences between basic
2179 and extended regular expressions, but these are the most
2181 @item regexp/extended
2182 Compile an extended regular expression rather than a basic
2183 regexp. This is the default behavior; this flag will not
2184 usually be needed. If a call to @code{make-regexp} includes
2185 both @code{regexp/basic} and @code{regexp/extended} flags, the
2186 one which comes last will override the earlier one.
2190 @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
2191 @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
2192 Match the compiled regular expression @var{rx} against
2193 @code{str}. If the optional integer @var{start} argument is
2194 provided, begin matching from that position in the string.
2195 Return a match structure describing the results of the match,
2196 or @code{#f} if no match could be found.
2198 The @var{flags} arguments change the matching behavior.
2199 The following flags may be supplied:
2203 Operator @samp{^} always fails (unless @code{regexp/newline}
2204 is used). Use this when the beginning of the string should
2205 not be considered the beginning of a line.
2207 Operator @samp{$} always fails (unless @code{regexp/newline}
2208 is used). Use this when the end of the string should not be
2209 considered the end of a line.
2214 ;; Regexp to match uppercase letters
2215 (define r (make-regexp "[A-Z]*"))
2217 ;; Regexp to match letters, ignoring case
2218 (define ri (make-regexp "[A-Z]*" regexp/icase))
2220 ;; Search for bob using regexp r
2221 (match:substring (regexp-exec r "bob"))
2222 @result{} "" ; no match
2224 ;; Search for bob using regexp ri
2225 (match:substring (regexp-exec ri "Bob"))
2226 @result{} "Bob" ; matched case insensitive
2229 @deffn {Scheme Procedure} regexp? obj
2230 @deffnx {C Function} scm_regexp_p (obj)
2231 Return @code{#t} if @var{obj} is a compiled regular expression,
2232 or @code{#f} otherwise.
2235 Regular expressions are commonly used to find patterns in one string and
2236 replace them with the contents of another string.
2238 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2239 @deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
2240 Write to the output port @var{port} selected contents of the match
2241 structure @var{match}. Each @var{item} specifies what should be
2242 written, and may be one of the following arguments:
2246 A string. String arguments are written out verbatim.
2249 An integer. The submatch with that number is written.
2252 The symbol @samp{pre}. The portion of the matched string preceding
2253 the regexp match is written.
2256 The symbol @samp{post}. The portion of the matched string following
2257 the regexp match is written.
2260 The @var{port} argument may be @code{#f}, in which case nothing is
2261 written; instead, @code{regexp-substitute} constructs a string from the
2262 specified @var{item}s and returns that.
2265 The following example takes a regular expression that matches a standard
2266 @sc{yyyymmdd}-format date such as @code{"20020828"}. The
2267 @code{regexp-substitute} call returns a string computed from the
2268 information in the match structure, consisting of the fields and text
2269 from the original string reordered and reformatted.
2272 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2273 (define s "Date 20020429 12am.")
2274 (define sm (string-match date-regex s))
2275 (regexp-substitute #f sm 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2276 @result{} "Date 04-29-2002 12am. (20020429)"
2279 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2280 @deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
2281 Similar to @code{regexp-substitute}, but can be used to perform global
2282 substitutions on @var{str}. Instead of taking a match structure as an
2283 argument, @code{regexp-substitute/global} takes two string arguments: a
2284 @var{regexp} string describing a regular expression, and a @var{target}
2285 string which should be matched against this regular expression.
2287 Each @var{item} behaves as in @code{regexp-substitute}, with the
2288 following exceptions:
2292 A function may be supplied. When this function is called, it will be
2293 passed one argument: a match structure for a given regular expression
2294 match. It should return a string to be written out to @var{port}.
2297 The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
2298 on the unmatched portion of @var{str}. This @emph{must} be supplied in
2299 order to perform global search-and-replace on @var{str}; if it is not
2300 present among the @var{item}s, then @code{regexp-substitute/global} will
2301 return after processing a single match.
2305 The example above for @code{regexp-substitute} could be rewritten as
2306 follows to remove the @code{string-match} stage:
2309 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2310 (define s "Date 20020429 12am.")
2311 (regexp-substitute/global #f date-regex s
2312 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2313 @result{} "Date 04-29-2002 12am. (20020429)"
2317 @node Match Structures
2318 @subsection Match Structures
2320 @cindex match structures
2322 A @dfn{match structure} is the object returned by @code{string-match} and
2323 @code{regexp-exec}. It describes which portion of a string, if any,
2324 matched the given regular expression. Match structures include: a
2325 reference to the string that was checked for matches; the starting and
2326 ending positions of the regexp match; and, if the regexp included any
2327 parenthesized subexpressions, the starting and ending positions of each
2330 In each of the regexp match functions described below, the @code{match}
2331 argument must be a match structure returned by a previous call to
2332 @code{string-match} or @code{regexp-exec}. Most of these functions
2333 return some information about the original target string that was
2334 matched against a regular expression; we will call that string
2335 @var{target} for easy reference.
2337 @c begin (scm-doc-string "regex.scm" "regexp-match?")
2338 @deffn {Scheme Procedure} regexp-match? obj
2339 Return @code{#t} if @var{obj} is a match structure returned by a
2340 previous call to @code{regexp-exec}, or @code{#f} otherwise.
2343 @c begin (scm-doc-string "regex.scm" "match:substring")
2344 @deffn {Scheme Procedure} match:substring match [n]
2345 Return the portion of @var{target} matched by subexpression number
2346 @var{n}. Submatch 0 (the default) represents the entire regexp match.
2347 If the regular expression as a whole matched, but the subexpression
2348 number @var{n} did not match, return @code{#f}.
2352 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2356 ;; match starting at offset 6 in the string
2358 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
2362 @c begin (scm-doc-string "regex.scm" "match:start")
2363 @deffn {Scheme Procedure} match:start match [n]
2364 Return the starting position of submatch number @var{n}.
2367 In the following example, the result is 4, since the match starts at
2371 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2376 @c begin (scm-doc-string "regex.scm" "match:end")
2377 @deffn {Scheme Procedure} match:end match [n]
2378 Return the ending position of submatch number @var{n}.
2381 In the following example, the result is 8, since the match runs between
2382 characters 4 and 8 (i.e. the ``2002'').
2385 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2390 @c begin (scm-doc-string "regex.scm" "match:prefix")
2391 @deffn {Scheme Procedure} match:prefix match
2392 Return the unmatched portion of @var{target} preceding the regexp match.
2395 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2401 @c begin (scm-doc-string "regex.scm" "match:suffix")
2402 @deffn {Scheme Procedure} match:suffix match
2403 Return the unmatched portion of @var{target} following the regexp match.
2407 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2412 @c begin (scm-doc-string "regex.scm" "match:count")
2413 @deffn {Scheme Procedure} match:count match
2414 Return the number of parenthesized subexpressions from @var{match}.
2415 Note that the entire regular expression match itself counts as a
2416 subexpression, and failed submatches are included in the count.
2419 @c begin (scm-doc-string "regex.scm" "match:string")
2420 @deffn {Scheme Procedure} match:string match
2421 Return the original @var{target} string.
2425 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2427 @result{} "blah2002foo"
2431 @node Backslash Escapes
2432 @subsection Backslash Escapes
2434 Sometimes you will want a regexp to match characters like @samp{*} or
2435 @samp{$} exactly. For example, to check whether a particular string
2436 represents a menu entry from an Info node, it would be useful to match
2437 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2438 because the asterisk is a metacharacter, it won't match the @samp{*} at
2439 the beginning of the string. In this case, we want to make the first
2442 You can do this by preceding the metacharacter with a backslash
2443 character @samp{\}. (This is also called @dfn{quoting} the
2444 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2445 sees a backslash in a regular expression, it considers the following
2446 glyph to be an ordinary character, no matter what special meaning it
2447 would ordinarily have. Therefore, we can make the above example work by
2448 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2449 the regular expression engine to match only a single asterisk in the
2452 Since the backslash is itself a metacharacter, you may force a regexp to
2453 match a backslash in the target string by preceding the backslash with
2454 itself. For example, to find variable references in a @TeX{} program,
2455 you might want to find occurrences of the string @samp{\let\} followed
2456 by any number of alphabetic characters. The regular expression
2457 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2458 regexp each match a single backslash in the target string.
2460 @c begin (scm-doc-string "regex.scm" "regexp-quote")
2461 @deffn {Scheme Procedure} regexp-quote str
2462 Quote each special character found in @var{str} with a backslash, and
2463 return the resulting string.
2466 @strong{Very important:} Using backslash escapes in Guile source code
2467 (as in Emacs Lisp or C) can be tricky, because the backslash character
2468 has special meaning for the Guile reader. For example, if Guile
2469 encounters the character sequence @samp{\n} in the middle of a string
2470 while processing Scheme code, it replaces those characters with a
2471 newline character. Similarly, the character sequence @samp{\t} is
2472 replaced by a horizontal tab. Several of these @dfn{escape sequences}
2473 are processed by the Guile reader before your code is executed.
2474 Unrecognized escape sequences are ignored: if the characters @samp{\*}
2475 appear in a string, they will be translated to the single character
2478 This translation is obviously undesirable for regular expressions, since
2479 we want to be able to include backslashes in a string in order to
2480 escape regexp metacharacters. Therefore, to make sure that a backslash
2481 is preserved in a string in your Guile program, you must use @emph{two}
2482 consecutive backslashes:
2485 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2488 The string in this example is preprocessed by the Guile reader before
2489 any code is executed. The resulting argument to @code{make-regexp} is
2490 the string @samp{^\* [^:]*}, which is what we really want.
2492 This also means that in order to write a regular expression that matches
2493 a single backslash character, the regular expression string in the
2494 source code must include @emph{four} backslashes. Each consecutive pair
2495 of backslashes gets translated by the Guile reader to a single
2496 backslash, and the resulting double-backslash is interpreted by the
2497 regexp engine as matching a single backslash character. Hence:
2500 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2503 The reason for the unwieldiness of this syntax is historical. Both
2504 regular expression pattern matchers and Unix string processing systems
2505 have traditionally used backslashes with the special meanings
2506 described above. The POSIX regular expression specification and ANSI C
2507 standard both require these semantics. Attempting to abandon either
2508 convention would cause other kinds of compatibility problems, possibly
2509 more severe ones. Therefore, without extending the Scheme reader to
2510 support strings with different quoting conventions (an ungainly and
2511 confusing extension when implemented in other languages), we must adhere
2512 to this cumbersome escape syntax.
2519 Symbols in Scheme are widely used in three ways: as items of discrete
2520 data, as lookup keys for alists and hash tables, and to denote variable
2523 A @dfn{symbol} is similar to a string in that it is defined by a
2524 sequence of characters. The sequence of characters is known as the
2525 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
2526 name doesn't include any characters that could be confused with other
2527 elements of Scheme syntax --- a symbol is written in a Scheme program by
2528 writing the sequence of characters that make up the name, @emph{without}
2529 any quotation marks or other special syntax. For example, the symbol
2530 whose name is ``multiply-by-2'' is written, simply:
2536 Notice how this differs from a @emph{string} with contents
2537 ``multiply-by-2'', which is written with double quotation marks, like
2544 Looking beyond how they are written, symbols are different from strings
2545 in two important respects.
2547 The first important difference is uniqueness. If the same-looking
2548 string is read twice from two different places in a program, the result
2549 is two @emph{different} string objects whose contents just happen to be
2550 the same. If, on the other hand, the same-looking symbol is read twice
2551 from two different places in a program, the result is the @emph{same}
2552 symbol object both times.
2554 Given two read symbols, you can use @code{eq?} to test whether they are
2555 the same (that is, have the same name). @code{eq?} is the most
2556 efficient comparison operator in Scheme, and comparing two symbols like
2557 this is as fast as comparing, for example, two numbers. Given two
2558 strings, on the other hand, you must use @code{equal?} or
2559 @code{string=?}, which are much slower comparison operators, to
2560 determine whether the strings have the same contents.
2563 (define sym1 (quote hello))
2564 (define sym2 (quote hello))
2565 (eq? sym1 sym2) @result{} #t
2567 (define str1 "hello")
2568 (define str2 "hello")
2569 (eq? str1 str2) @result{} #f
2570 (equal? str1 str2) @result{} #t
2573 The second important difference is that symbols, unlike strings, are not
2574 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
2575 example above: @code{(quote hello)} evaluates to the symbol named
2576 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
2577 symbol named "hello" and evaluated as a variable reference @dots{} about
2578 which more below (@pxref{Symbol Variables}).
2581 * Symbol Data:: Symbols as discrete data.
2582 * Symbol Keys:: Symbols as lookup keys.
2583 * Symbol Variables:: Symbols as denoting variables.
2584 * Symbol Primitives:: Operations related to symbols.
2585 * Symbol Props:: Function slots and property lists.
2586 * Symbol Read Syntax:: Extended read syntax for symbols.
2587 * Symbol Uninterned:: Uninterned symbols.
2592 @subsection Symbols as Discrete Data
2594 Numbers and symbols are similar to the extent that they both lend
2595 themselves to @code{eq?} comparison. But symbols are more descriptive
2596 than numbers, because a symbol's name can be used directly to describe
2597 the concept for which that symbol stands.
2599 For example, imagine that you need to represent some colours in a
2600 computer program. Using numbers, you would have to choose arbitrarily
2601 some mapping between numbers and colours, and then take care to use that
2602 mapping consistently:
2605 ;; 1=red, 2=green, 3=purple
2607 (if (eq? (colour-of car) 1)
2612 You can make the mapping more explicit and the code more readable by
2620 (if (eq? (colour-of car) red)
2625 But the simplest and clearest approach is not to use numbers at all, but
2626 symbols whose names specify the colours that they refer to:
2629 (if (eq? (colour-of car) 'red)
2633 The descriptive advantages of symbols over numbers increase as the set
2634 of concepts that you want to describe grows. Suppose that a car object
2635 can have other properties as well, such as whether it has or uses:
2639 automatic or manual transmission
2641 leaded or unleaded fuel
2643 power steering (or not).
2647 Then a car's combined property set could be naturally represented and
2648 manipulated as a list of symbols:
2651 (properties-of car1)
2653 (red manual unleaded power-steering)
2655 (if (memq 'power-steering (properties-of car1))
2656 (display "Unfit people can drive this car.\n")
2657 (display "You'll need strong arms to drive this car!\n"))
2659 Unfit people can drive this car.
2662 Remember, the fundamental property of symbols that we are relying on
2663 here is that an occurrence of @code{'red} in one part of a program is an
2664 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
2665 another part of a program; this means that symbols can usefully be
2666 compared using @code{eq?}. At the same time, symbols have naturally
2667 descriptive names. This combination of efficiency and descriptive power
2668 makes them ideal for use as discrete data.
2672 @subsection Symbols as Lookup Keys
2674 Given their efficiency and descriptive power, it is natural to use
2675 symbols as the keys in an association list or hash table.
2677 To illustrate this, consider a more structured representation of the car
2678 properties example from the preceding subsection. Rather than
2679 mixing all the properties up together in a flat list, we could use an
2680 association list like this:
2683 (define car1-properties '((colour . red)
2684 (transmission . manual)
2686 (steering . power-assisted)))
2689 Notice how this structure is more explicit and extensible than the flat
2690 list. For example it makes clear that @code{manual} refers to the
2691 transmission rather than, say, the windows or the locking of the car.
2692 It also allows further properties to use the same symbols among their
2693 possible values without becoming ambiguous:
2696 (define car1-properties '((colour . red)
2697 (transmission . manual)
2699 (steering . power-assisted)
2701 (locking . manual)))
2704 With a representation like this, it is easy to use the efficient
2705 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
2706 extract or change individual pieces of information:
2709 (assq-ref car1-properties 'fuel) @result{} unleaded
2710 (assq-ref car1-properties 'transmission) @result{} manual
2712 (assq-set! car1-properties 'seat-colour 'black)
2715 (transmission . manual)
2717 (steering . power-assisted)
2718 (seat-colour . black)
2719 (locking . manual)))
2722 Hash tables also have keys, and exactly the same arguments apply to the
2723 use of symbols in hash tables as in association lists. The hash value
2724 that Guile uses to decide where to add a symbol-keyed entry to a hash
2725 table can be obtained by calling the @code{symbol-hash} procedure:
2727 @deffn {Scheme Procedure} symbol-hash symbol
2728 @deffnx {C Function} scm_symbol_hash (symbol)
2729 Return a hash value for @var{symbol}.
2732 See @ref{Hash Tables} for information about hash tables in general, and
2733 for why you might choose to use a hash table rather than an association
2737 @node Symbol Variables
2738 @subsection Symbols as Denoting Variables
2740 When an unquoted symbol in a Scheme program is evaluated, it is
2741 interpreted as a variable reference, and the result of the evaluation is
2742 the appropriate variable's value.
2744 For example, when the expression @code{(string-length "abcd")} is read
2745 and evaluated, the sequence of characters @code{string-length} is read
2746 as the symbol whose name is "string-length". This symbol is associated
2747 with a variable whose value is the procedure that implements string
2748 length calculation. Therefore evaluation of the @code{string-length}
2749 symbol results in that procedure.
2751 The details of the connection between an unquoted symbol and the
2752 variable to which it refers are explained elsewhere. See @ref{Binding
2753 Constructs}, for how associations between symbols and variables are
2754 created, and @ref{Modules}, for how those associations are affected by
2755 Guile's module system.
2758 @node Symbol Primitives
2759 @subsection Operations Related to Symbols
2761 Given any Scheme value, you can determine whether it is a symbol using
2762 the @code{symbol?} primitive:
2765 @deffn {Scheme Procedure} symbol? obj
2766 @deffnx {C Function} scm_symbol_p (obj)
2767 Return @code{#t} if @var{obj} is a symbol, otherwise return
2771 Once you know that you have a symbol, you can obtain its name as a
2772 string by calling @code{symbol->string}. Note that Guile differs by
2773 default from R5RS on the details of @code{symbol->string} as regards
2776 @rnindex symbol->string
2777 @deffn {Scheme Procedure} symbol->string s
2778 @deffnx {C Function} scm_symbol_to_string (s)
2779 Return the name of symbol @var{s} as a string. By default, Guile reads
2780 symbols case-sensitively, so the string returned will have the same case
2781 variation as the sequence of characters that caused @var{s} to be
2784 If Guile is set to read symbols case-insensitively (as specified by
2785 R5RS), and @var{s} comes into being as part of a literal expression
2786 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
2787 by a call to the @code{read} or @code{string-ci->symbol} procedures,
2788 Guile converts any alphabetic characters in the symbol's name to
2789 lower case before creating the symbol object, so the string returned
2790 here will be in lower case.
2792 If @var{s} was created by @code{string->symbol}, the case of characters
2793 in the string returned will be the same as that in the string that was
2794 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
2795 setting at the time @var{s} was created.
2797 It is an error to apply mutation procedures like @code{string-set!} to
2798 strings returned by this procedure.
2801 Most symbols are created by writing them literally in code. However it
2802 is also possible to create symbols programmatically using the following
2803 @code{string->symbol} and @code{string-ci->symbol} procedures:
2805 @rnindex string->symbol
2806 @deffn {Scheme Procedure} string->symbol string
2807 @deffnx {C Function} scm_string_to_symbol (string)
2808 Return the symbol whose name is @var{string}. This procedure can create
2809 symbols with names containing special characters or letters in the
2810 non-standard case, but it is usually a bad idea to create such symbols
2811 because in some implementations of Scheme they cannot be read as
2815 @deffn {Scheme Procedure} string-ci->symbol str
2816 @deffnx {C Function} scm_string_ci_to_symbol (str)
2817 Return the symbol whose name is @var{str}. If Guile is currently
2818 reading symbols case-insensitively, @var{str} is converted to lowercase
2819 before the returned symbol is looked up or created.
2822 The following examples illustrate Guile's detailed behaviour as regards
2823 the case-sensitivity of symbols:
2826 (read-enable 'case-insensitive) ; R5RS compliant behaviour
2828 (symbol->string 'flying-fish) @result{} "flying-fish"
2829 (symbol->string 'Martin) @result{} "martin"
2831 (string->symbol "Malvina")) @result{} "Malvina"
2833 (eq? 'mISSISSIppi 'mississippi) @result{} #t
2834 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
2835 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
2837 (string->symbol (symbol->string 'LolliPop))) @result{} #t
2838 (string=? "K. Harper, M.D."
2840 (string->symbol "K. Harper, M.D."))) @result{} #t
2842 (read-disable 'case-insensitive) ; Guile default behaviour
2844 (symbol->string 'flying-fish) @result{} "flying-fish"
2845 (symbol->string 'Martin) @result{} "Martin"
2847 (string->symbol "Malvina")) @result{} "Malvina"
2849 (eq? 'mISSISSIppi 'mississippi) @result{} #f
2850 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
2851 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
2853 (string->symbol (symbol->string 'LolliPop))) @result{} #t
2854 (string=? "K. Harper, M.D."
2856 (string->symbol "K. Harper, M.D."))) @result{} #t
2859 From C, there are lower level functions that construct a Scheme symbol
2860 from a null terminated C string or from a sequence of bytes whose length
2861 is specified explicitly.
2863 @deffn {C Function} scm_str2symbol (const char * name)
2864 @deffnx {C Function} scm_mem2symbol (const char * name, size_t len)
2865 Construct and return a Scheme symbol whose name is specified by
2866 @var{name}. For @code{scm_str2symbol} @var{name} must be null
2867 terminated; For @code{scm_mem2symbol} the length of @var{name} is
2868 specified explicitly by @var{len}.
2871 Finally, some applications, especially those that generate new Scheme
2872 code dynamically, need to generate symbols for use in the generated
2873 code. The @code{gensym} primitive meets this need:
2875 @deffn {Scheme Procedure} gensym [prefix]
2876 @deffnx {C Function} scm_gensym (prefix)
2877 Create a new symbol with a name constructed from a prefix and a counter
2878 value. The string @var{prefix} can be specified as an optional
2879 argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
2880 at each call. There is no provision for resetting the counter.
2883 The symbols generated by @code{gensym} are @emph{likely} to be unique,
2884 since their names begin with a space and it is only otherwise possible
2885 to generate such symbols if a programmer goes out of their way to do
2886 so. Uniqueness can be guaranteed by instead using uninterned symbols
2887 (@pxref{Symbol Uninterned}), though they can't be usefully written out
2892 @subsection Function Slots and Property Lists
2894 In traditional Lisp dialects, symbols are often understood as having
2895 three kinds of value at once:
2899 a @dfn{variable} value, which is used when the symbol appears in
2900 code in a variable reference context
2903 a @dfn{function} value, which is used when the symbol appears in
2904 code in a function name position (i.e. as the first element in an
2908 a @dfn{property list} value, which is used when the symbol is given as
2909 the first argument to Lisp's @code{put} or @code{get} functions.
2912 Although Scheme (as one of its simplifications with respect to Lisp)
2913 does away with the distinction between variable and function namespaces,
2914 Guile currently retains some elements of the traditional structure in
2915 case they turn out to be useful when implementing translators for other
2916 languages, in particular Emacs Lisp.
2918 Specifically, Guile symbols have two extra slots. for a symbol's
2919 property list, and for its ``function value.'' The following procedures
2920 are provided to access these slots.
2922 @deffn {Scheme Procedure} symbol-fref symbol
2923 @deffnx {C Function} scm_symbol_fref (symbol)
2924 Return the contents of @var{symbol}'s @dfn{function slot}.
2927 @deffn {Scheme Procedure} symbol-fset! symbol value
2928 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
2929 Set the contents of @var{symbol}'s function slot to @var{value}.
2932 @deffn {Scheme Procedure} symbol-pref symbol
2933 @deffnx {C Function} scm_symbol_pref (symbol)
2934 Return the @dfn{property list} currently associated with @var{symbol}.
2937 @deffn {Scheme Procedure} symbol-pset! symbol value
2938 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
2939 Set @var{symbol}'s property list to @var{value}.
2942 @deffn {Scheme Procedure} symbol-property sym prop
2943 From @var{sym}'s property list, return the value for property
2944 @var{prop}. The assumption is that @var{sym}'s property list is an
2945 association list whose keys are distinguished from each other using
2946 @code{equal?}; @var{prop} should be one of the keys in that list. If
2947 the property list has no entry for @var{prop}, @code{symbol-property}
2951 @deffn {Scheme Procedure} set-symbol-property! sym prop val
2952 In @var{sym}'s property list, set the value for property @var{prop} to
2953 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
2954 none already exists. For the structure of the property list, see
2955 @code{symbol-property}.
2958 @deffn {Scheme Procedure} symbol-property-remove! sym prop
2959 From @var{sym}'s property list, remove the entry for property
2960 @var{prop}, if there is one. For the structure of the property list,
2961 see @code{symbol-property}.
2964 Support for these extra slots may be removed in a future release, and it
2965 is probably better to avoid using them. (In release 1.6, Guile itself
2966 uses the property list slot sparingly, and the function slot not at
2967 all.) For a more modern and Schemely approach to properties, see
2968 @ref{Object Properties}.
2971 @node Symbol Read Syntax
2972 @subsection Extended Read Syntax for Symbols
2974 The read syntax for a symbol is a sequence of letters, digits, and
2975 @dfn{extended alphabetic characters}, beginning with a character that
2976 cannot begin a number. In addition, the special cases of @code{+},
2977 @code{-}, and @code{...} are read as symbols even though numbers can
2978 begin with @code{+}, @code{-} or @code{.}.
2980 Extended alphabetic characters may be used within identifiers as if
2981 they were letters. The set of extended alphabetic characters is:
2984 ! $ % & * + - . / : < = > ? @@ ^ _ ~
2987 In addition to the standard read syntax defined above (which is taken
2988 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
2989 Scheme})), Guile provides an extended symbol read syntax that allows the
2990 inclusion of unusual characters such as space characters, newlines and
2991 parentheses. If (for whatever reason) you need to write a symbol
2992 containing characters not mentioned above, you can do so as follows.
2996 Begin the symbol with the characters @code{#@{},
2999 write the characters of the symbol and
3002 finish the symbol with the characters @code{@}#}.
3005 Here are a few examples of this form of read syntax. The first symbol
3006 needs to use extended syntax because it contains a space character, the
3007 second because it contains a line break, and the last because it looks
3019 Although Guile provides this extended read syntax for symbols,
3020 widespread usage of it is discouraged because it is not portable and not
3024 @node Symbol Uninterned
3025 @subsection Uninterned Symbols
3027 What makes symbols useful is that they are automatically kept unique.
3028 There are no two symbols that are distinct objects but have the same
3029 name. But of course, there is no rule without exception. In addition
3030 to the normal symbols that have been discussed up to now, you can also
3031 create special @dfn{uninterned} symbols that behave slightly
3034 To understand what is different about them and why they might be useful,
3035 we look at how normal symbols are actually kept unique.
3037 Whenever Guile wants to find the symbol with a specific name, for
3038 example during @code{read} or when executing @code{string->symbol}, it
3039 first looks into a table of all existing symbols to find out whether a
3040 symbol with the given name already exists. When this is the case, Guile
3041 just returns that symbol. When not, a new symbol with the name is
3042 created and entered into the table so that it can be found later.
3044 Sometimes you might want to create a symbol that is guaranteed `fresh',
3045 i.e. a symbol that did not exist previously. You might also want to
3046 somehow guarantee that no one else will ever unintentionally stumble
3047 across your symbol in the future. These properties of a symbol are
3048 often needed when generating code during macro expansion. When
3049 introducing new temporary variables, you want to guarantee that they
3050 don't conflict with variables in other people's code.
3052 The simplest way to arrange for this is to create a new symbol but
3053 not enter it into the global table of all symbols. That way, no one
3054 will ever get access to your symbol by chance. Symbols that are not in
3055 the table are called @dfn{uninterned}. Of course, symbols that
3056 @emph{are} in the table are called @dfn{interned}.
3058 You create new uninterned symbols with the function @code{make-symbol}.
3059 You can test whether a symbol is interned or not with
3060 @code{symbol-interned?}.
3062 Uninterned symbols break the rule that the name of a symbol uniquely
3063 identifies the symbol object. Because of this, they can not be written
3064 out and read back in like interned symbols. Currently, Guile has no
3065 support for reading uninterned symbols. Note that the function
3066 @code{gensym} does not return uninterned symbols for this reason.
3068 @deffn {Scheme Procedure} make-symbol name
3069 @deffnx {C Function} scm_make_symbol (name)
3070 Return a new uninterned symbol with the name @var{name}. The returned
3071 symbol is guaranteed to be unique and future calls to
3072 @code{string->symbol} will not return it.
3075 @deffn {Scheme Procedure} symbol-interned? symbol
3076 @deffnx {C Function} scm_symbol_interned_p (symbol)
3077 Return @code{#t} if @var{symbol} is interned, otherwise return
3084 (define foo-1 (string->symbol "foo"))
3085 (define foo-2 (string->symbol "foo"))
3086 (define foo-3 (make-symbol "foo"))
3087 (define foo-4 (make-symbol "foo"))
3091 ; Two interned symbols with the same name are the same object,
3095 ; but a call to make-symbol with the same name returns a
3100 ; A call to make-symbol always returns a new object, even for
3104 @result{} #<uninterned-symbol foo 8085290>
3105 ; Uninterned symbols print differently from interned symbols,
3109 ; but they are still symbols,
3111 (symbol-interned? foo-3)
3113 ; just not interned.
3121 Keywords are self-evaluating objects with a convenient read syntax that
3122 makes them easy to type.
3124 Guile's keyword support conforms to R5RS, and adds a (switchable) read
3125 syntax extension to permit keywords to begin with @code{:} as well as
3129 * Why Use Keywords?:: Motivation for keyword usage.
3130 * Coding With Keywords:: How to use keywords.
3131 * Keyword Read Syntax:: Read syntax for keywords.
3132 * Keyword Procedures:: Procedures for dealing with keywords.
3133 * Keyword Primitives:: The underlying primitive procedures.
3136 @node Why Use Keywords?
3137 @subsection Why Use Keywords?
3139 Keywords are useful in contexts where a program or procedure wants to be
3140 able to accept a large number of optional arguments without making its
3141 interface unmanageable.
3143 To illustrate this, consider a hypothetical @code{make-window}
3144 procedure, which creates a new window on the screen for drawing into
3145 using some graphical toolkit. There are many parameters that the caller
3146 might like to specify, but which could also be sensibly defaulted, for
3151 color depth -- Default: the color depth for the screen
3154 background color -- Default: white
3157 width -- Default: 600
3160 height -- Default: 400
3163 If @code{make-window} did not use keywords, the caller would have to
3164 pass in a value for each possible argument, remembering the correct
3165 argument order and using a special value to indicate the default value
3169 (make-window 'default ;; Color depth
3170 'default ;; Background color
3173 @dots{}) ;; More make-window arguments
3176 With keywords, on the other hand, defaulted arguments are omitted, and
3177 non-default arguments are clearly tagged by the appropriate keyword. As
3178 a result, the invocation becomes much clearer:
3181 (make-window #:width 800 #:height 100)
3184 On the other hand, for a simpler procedure with few arguments, the use
3185 of keywords would be a hindrance rather than a help. The primitive
3186 procedure @code{cons}, for example, would not be improved if it had to
3190 (cons #:car x #:cdr y)
3193 So the decision whether to use keywords or not is purely pragmatic: use
3194 them if they will clarify the procedure invocation at point of call.
3196 @node Coding With Keywords
3197 @subsection Coding With Keywords
3199 If a procedure wants to support keywords, it should take a rest argument
3200 and then use whatever means is convenient to extract keywords and their
3201 corresponding arguments from the contents of that rest argument.
3203 The following example illustrates the principle: the code for
3204 @code{make-window} uses a helper procedure called
3205 @code{get-keyword-value} to extract individual keyword arguments from
3209 (define (get-keyword-value args keyword default)
3210 (let ((kv (memq keyword args)))
3211 (if (and kv (>= (length kv) 2))
3215 (define (make-window . args)
3216 (let ((depth (get-keyword-value args #:depth screen-depth))
3217 (bg (get-keyword-value args #:bg "white"))
3218 (width (get-keyword-value args #:width 800))
3219 (height (get-keyword-value args #:height 100))
3224 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
3225 optargs)} module provides a set of powerful macros that you can use to
3226 implement keyword-supporting procedures like this:
3229 (use-modules (ice-9 optargs))
3231 (define (make-window . args)
3232 (let-keywords args #f ((depth screen-depth)
3240 Or, even more economically, like this:
3243 (use-modules (ice-9 optargs))
3245 (define* (make-window #:key (depth screen-depth)
3252 For further details on @code{let-keywords}, @code{define*} and other
3253 facilities provided by the @code{(ice-9 optargs)} module, see
3254 @ref{Optional Arguments}.
3257 @node Keyword Read Syntax
3258 @subsection Keyword Read Syntax
3260 Guile, by default, only recognizes the keyword syntax specified by R5RS.
3261 A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
3262 as a Scheme symbol (@pxref{Symbol Read Syntax}), is the external
3263 representation of the keyword named @code{NAME}. Keyword objects print
3264 using this syntax as well, so values containing keyword objects can be
3265 read back into Guile. When used in an expression, keywords are
3266 self-quoting objects.
3268 If the @code{keyword} read option is set to @code{'prefix}, Guile also
3269 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
3270 of the form @code{:NAME} are read as symbols, as required by R5RS.
3272 To enable and disable the alternative non-R5RS keyword syntax, you use
3273 the @code{read-set!} procedure documented in @ref{User level options
3274 interfaces} and @ref{Reader options}.
3277 (read-set! keywords 'prefix)
3287 (read-set! keywords #f)
3295 ERROR: In expression :type:
3296 ERROR: Unbound variable: :type
3297 ABORT: (unbound-variable)
3300 @node Keyword Procedures
3301 @subsection Keyword Procedures
3303 The following procedures can be used for converting symbols to keywords
3306 @deffn {Scheme Procedure} symbol->keyword sym
3307 Return a keyword with the same characters as in @var{sym}.
3310 @deffn {Scheme Procedure} keyword->symbol kw
3311 Return a symbol with the same characters as in @var{kw}.
3315 @node Keyword Primitives
3316 @subsection Keyword Primitives
3318 Internally, a keyword is implemented as something like a tagged symbol,
3319 where the tag identifies the keyword as being self-evaluating, and the
3320 symbol, known as the keyword's @dfn{dash symbol} has the same name as
3321 the keyword name but prefixed by a single dash. For example, the
3322 keyword @code{#:name} has the corresponding dash symbol @code{-name}.
3324 Most keyword objects are constructed automatically by the reader when it
3325 reads a token beginning with @code{#:}. However, if you need to
3326 construct a keyword object programmatically, you can do so by calling
3327 @code{make-keyword-from-dash-symbol} with the corresponding dash symbol
3328 (as the reader does). The dash symbol for a keyword object can be
3329 retrieved using the @code{keyword-dash-symbol} procedure.
3331 @deffn {Scheme Procedure} make-keyword-from-dash-symbol symbol
3332 @deffnx {C Function} scm_make_keyword_from_dash_symbol (symbol)
3333 Make a keyword object from a @var{symbol} that starts with a dash.
3337 (make-keyword-from-dash-symbol '-foo)
3342 @deffn {Scheme Procedure} keyword? obj
3343 @deffnx {C Function} scm_keyword_p (obj)
3344 Return @code{#t} if the argument @var{obj} is a keyword, else
3348 @deffn {Scheme Procedure} keyword-dash-symbol keyword
3349 @deffnx {C Function} scm_keyword_dash_symbol (keyword)
3350 Return the dash symbol for @var{keyword}.
3351 This is the inverse of @code{make-keyword-from-dash-symbol}.
3355 (keyword-dash-symbol #:foo)
3360 @deftypefn {C Function} SCM scm_c_make_keyword (char *@var{str})
3361 Make a keyword object from a string. For example,
3364 scm_c_make_keyword ("foo")
3368 @c FIXME: What can be said about the string argument? Currently it's
3369 @c not used after creation, but should that be documented?
3374 @section ``Functionality-Centric'' Data Types
3376 Procedures and macros are documented in their own chapter: see
3377 @ref{Procedures and Macros}.
3379 Variable objects are documented as part of the description of Guile's
3380 module system: see @ref{Variables}.
3382 Asyncs, dynamic roots and fluids are described in the chapter on
3383 scheduling: see @ref{Scheduling}.
3385 Hooks are documented in the chapter on general utility functions: see
3388 Ports are described in the chapter on I/O: see @ref{Input and Output}.
3392 @c TeX-master: "guile.texi"