2 @node Simple Data Types
3 @chapter Simple Generic Data Types
5 This chapter describes those of Guile's simple data types which are
6 primarily used for their role as items of generic data. By
7 @dfn{simple} we mean data types that are not primarily used as
8 containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
9 For the documentation of such @dfn{compound} data types, see
10 @ref{Compound Data Types}.
12 One of the great strengths of Scheme is that there is no straightforward
13 distinction between ``data'' and ``functionality''. For example,
14 Guile's support for dynamic linking could be described:
18 either in a ``data-centric'' way, as the behaviour and properties of the
19 ``dynamically linked object'' data type, and the operations that may be
20 applied to instances of this type
23 or in a ``functionality-centric'' way, as the set of procedures that
24 constitute Guile's support for dynamic linking, in the context of the
28 The contents of this chapter are, therefore, a matter of judgment. By
29 @dfn{generic}, we mean to select those data types whose typical use as
30 @emph{data} in a wide variety of programming contexts is more important
31 than their use in the implementation of a particular piece of
32 @emph{functionality}. The last section of this chapter provides
33 references for all the data types that are documented not here but in a
34 ``functionality-centric'' way elsewhere in the manual.
37 * Booleans:: True/false values.
38 * Numbers:: Numerical data types.
39 * Characters:: New character names.
40 * Strings:: Special things about strings.
41 * Regular Expressions:: Pattern matching and substitution.
43 * Keywords:: Self-quoting, customizable display keywords.
44 * Other Types:: "Functionality-centric" data types.
52 The two boolean values are @code{#t} for true and @code{#f} for false.
54 Boolean values are returned by predicate procedures, such as the general
55 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
56 (@pxref{Equality}) and numerical and string comparison operators like
57 @code{string=?} (@pxref{String Comparison}) and @code{<=}
67 (equal? "house" "houses")
75 In test condition contexts like @code{if} and @code{cond} (@pxref{if
76 cond case}), where a group of subexpressions will be evaluated only if a
77 @var{condition} expression evaluates to ``true'', ``true'' means any
78 value at all except @code{#f}.
91 A result of this asymmetry is that typical Scheme source code more often
92 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
93 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
94 not necessary to represent an @code{if} or @code{cond} true value.
96 It is important to note that @code{#f} is @strong{not} equivalent to any
97 other Scheme value. In particular, @code{#f} is not the same as the
98 number 0 (like in C and C++), and not the same as the ``empty list''
99 (like in some Lisp dialects).
101 The @code{not} procedure returns the boolean inverse of its argument:
104 @deffn {Scheme Procedure} not x
105 @deffnx {C Function} scm_not (x)
106 Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
109 The @code{boolean?} procedure is a predicate that returns @code{#t} if
110 its argument is one of the boolean values, otherwise @code{#f}.
113 @deffn {Scheme Procedure} boolean? obj
114 @deffnx {C Function} scm_boolean_p (obj)
115 Return @code{#t} iff @var{obj} is either @code{#t} or @code{#f}.
120 @section Numerical data types
123 Guile supports a rich ``tower'' of numerical types --- integer,
124 rational, real and complex --- and provides an extensive set of
125 mathematical and scientific functions for operating on numerical
126 data. This section of the manual documents those types and functions.
128 You may also find it illuminating to read R5RS's presentation of numbers
129 in Scheme, which is particularly clear and accessible: see
130 @ref{Numbers,,,r5rs,R5RS}.
133 * Numerical Tower:: Scheme's numerical "tower".
134 * Integers:: Whole numbers.
135 * Reals and Rationals:: Real and rational numbers.
136 * Complex Numbers:: Complex numbers.
137 * Exactness:: Exactness and inexactness.
138 * Number Syntax:: Read syntax for numerical data.
139 * Integer Operations:: Operations on integer values.
140 * Comparison:: Comparison predicates.
141 * Conversion:: Converting numbers to and from strings.
142 * Complex:: Complex number operations.
143 * Arithmetic:: Arithmetic functions.
144 * Scientific:: Scientific functions.
145 * Primitive Numerics:: Primitive numeric functions.
146 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
147 * Random:: Random number generation.
151 @node Numerical Tower
152 @subsection Scheme's Numerical ``Tower''
155 Scheme's numerical ``tower'' consists of the following categories of
160 Whole numbers, positive or negative; e.g.@: --5, 0, 18.
163 The set of numbers that can be expressed as @math{@var{p}/@var{q}}
164 where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
165 pi (an irrational number) doesn't. These include integers
169 The set of numbers that describes all possible positions along a
170 one-dimensional line. This includes rationals as well as irrational
173 @item complex numbers
174 The set of numbers that describes all possible positions in a two
175 dimensional space. This includes real as well as imaginary numbers
176 (@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
177 @var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
181 It is called a tower because each category ``sits on'' the one that
182 follows it, in the sense that every integer is also a rational, every
183 rational is also real, and every real number is also a complex number
184 (but with zero imaginary part).
186 Of these, Guile implements integers, reals and complex numbers as
187 distinct types. Rationals are implemented as regards the read syntax
188 for rational numbers that is specified by R5RS, but are immediately
189 converted by Guile to the corresponding real number.
191 The @code{number?} predicate may be applied to any Scheme value to
192 discover whether the value is any of the supported numerical types.
194 @deffn {Scheme Procedure} number? obj
195 @deffnx {C Function} scm_number_p (obj)
196 Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
205 (number? "hello there!")
208 (define pi 3.141592654)
213 The next few subsections document each of Guile's numerical data types
219 @tpindex Integer numbers
223 Integers are whole numbers, that is numbers with no fractional part,
224 such as 2, 83, and @minus{}3789.
226 Integers in Guile can be arbitrarily big, as shown by the following
230 (define (factorial n)
231 (let loop ((n n) (product 1))
234 (loop (- n 1) (* product n)))))
240 @result{} 2432902008176640000
243 @result{} -119622220865480194561963161495657715064383733760000000000
246 Readers whose background is in programming languages where integers are
247 limited by the need to fit into just 4 or 8 bytes of memory may find
248 this surprising, or suspect that Guile's representation of integers is
249 inefficient. In fact, Guile achieves a near optimal balance of
250 convenience and efficiency by using the host computer's native
251 representation of integers where possible, and a more general
252 representation where the required number does not fit in the native
253 form. Conversion between these two representations is automatic and
254 completely invisible to the Scheme level programmer.
256 The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
257 inexact integers. They are explained in detail in the next section,
258 together with reals and rationals.
260 @c REFFIXME Maybe point here to discussion of handling immediates/bignums
261 @c on the C level, where the conversion is not so automatic - NJ
263 @deffn {Scheme Procedure} integer? x
264 @deffnx {C Function} scm_integer_p (x)
265 Return @code{#t} if @var{x} is an integer number, else @code{#f}.
280 @node Reals and Rationals
281 @subsection Real and Rational Numbers
282 @tpindex Real numbers
283 @tpindex Rational numbers
288 Mathematically, the real numbers are the set of numbers that describe
289 all possible points along a continuous, infinite, one-dimensional line.
290 The rational numbers are the set of all numbers that can be written as
291 fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
292 All rational numbers are also real, but there are real numbers that
293 are not rational, for example the square root of 2, and pi.
295 Guile represents both real and rational numbers approximately using a
296 floating point encoding with limited precision. Even though the actual
297 encoding is in binary, it may be helpful to think of it as a decimal
298 number with a limited number of significant figures and a decimal point
299 somewhere, since this corresponds to the standard notation for non-whole
300 numbers. For example:
305 -5648394822220000000000.0
309 The limited precision of Guile's encoding means that any ``real'' number
310 in Guile can be written in a rational form, by multiplying and then dividing
311 by sufficient powers of 10 (or in fact, 2). For example,
312 @samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
313 100000000000000000. In Guile's current incarnation, therefore, the
314 @code{rational?} and @code{real?} predicates are equivalent.
316 Another aspect of this equivalence is that Guile currently does not
317 preserve the exactness that is possible with rational arithmetic.
318 If such exactness is needed, it is of course possible to implement
319 exact rational arithmetic at the Scheme level using Guile's arbitrary
322 A planned future revision of Guile's numerical tower will make it
323 possible to implement exact representations and arithmetic for both
324 rational numbers and real irrational numbers such as square roots,
325 and in such a way that the new kinds of number integrate seamlessly
326 with those that are already implemented.
328 Dividing by an exact zero leads to a error message, as one might
329 expect. However, dividing by an inexact zero does not produce an
330 error. Instead, the result of the division is either plus or minus
331 infinity, depending on the sign of the divided number.
333 The infinities are written @samp{+inf.0} and @samp{-inf.0},
334 respectibly. This syntax is also recognized by @code{read} as an
335 extension to the usual Scheme syntax.
337 Dividing zero by zero yields something that is not a number at all:
338 @samp{+nan.0}. This is the special `not a number' value.
340 On platforms that follow @acronym{IEEE} 754 for their floating point
341 arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
342 are implemented using the corresponding @acronym{IEEE} 754 values.
343 They behave in arithmetic operations like @acronym{IEEE} 754 describes
344 it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
346 The infinities are inexact integers and are considered to be both even
347 and odd. While @samp{+nan.0} is not @code{=} to itself, it is
348 @code{eqv?} to itself.
350 To test for the special values, use the functions @code{inf?} and
353 @deffn {Scheme Procedure} real? obj
354 @deffnx {C Function} scm_real_p (obj)
355 Return @code{#t} if @var{obj} is a real number, else @code{#f}.
356 Note that the sets of integer and rational values form subsets
357 of the set of real numbers, so the predicate will also be fulfilled
358 if @var{obj} is an integer number or a rational number.
361 @deffn {Scheme Procedure} rational? x
362 @deffnx {C Function} scm_real_p (x)
363 Return @code{#t} if @var{x} is a rational number, @code{#f}
364 otherwise. Note that the set of integer values forms a subset of
365 the set of rational numbers, i. e. the predicate will also be
366 fulfilled if @var{x} is an integer number. Real numbers
367 will also satisfy this predicate, because of their limited
371 @deffn {Scheme Procedure} inf? x
372 Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
376 @deffn {Scheme Procedure} nan? x
377 Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
380 @node Complex Numbers
381 @subsection Complex Numbers
382 @tpindex Complex numbers
386 Complex numbers are the set of numbers that describe all possible points
387 in a two-dimensional space. The two coordinates of a particular point
388 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
389 the complex number that describes that point.
391 In Guile, complex numbers are written in rectangular form as the sum of
392 their real and imaginary parts, using the symbol @code{i} to indicate
405 Guile represents a complex number as a pair of numbers both of which are
406 real, so the real and imaginary parts of a complex number have the same
407 properties of inexactness and limited precision as single real numbers.
409 @deffn {Scheme Procedure} complex? x
410 @deffnx {C Function} scm_number_p (x)
411 Return @code{#t} if @var{x} is a complex number, @code{#f}
412 otherwise. Note that the sets of real, rational and integer
413 values form subsets of the set of complex numbers, i. e. the
414 predicate will also be fulfilled if @var{x} is a real,
415 rational or integer number.
420 @subsection Exact and Inexact Numbers
421 @tpindex Exact numbers
422 @tpindex Inexact numbers
426 @rnindex exact->inexact
427 @rnindex inexact->exact
429 R5RS requires that a calculation involving inexact numbers always
430 produces an inexact result. To meet this requirement, Guile
431 distinguishes between an exact integer value such as @samp{5} and the
432 corresponding inexact real value which, to the limited precision
433 available, has no fractional part, and is printed as @samp{5.0}. Guile
434 will only convert the latter value to the former when forced to do so by
435 an invocation of the @code{inexact->exact} procedure.
437 @deffn {Scheme Procedure} exact? x
438 @deffnx {C Function} scm_exact_p (x)
439 Return @code{#t} if @var{x} is an exact number, @code{#f}
443 @deffn {Scheme Procedure} inexact? x
444 @deffnx {C Function} scm_inexact_p (x)
445 Return @code{#t} if @var{x} is an inexact number, @code{#f}
449 @deffn {Scheme Procedure} inexact->exact z
450 @deffnx {C Function} scm_inexact_to_exact (z)
451 Return an exact number that is numerically closest to @var{z}.
454 @c begin (texi-doc-string "guile" "exact->inexact")
455 @deffn {Scheme Procedure} exact->inexact z
456 Convert the number @var{z} to its inexact representation.
461 @subsection Read Syntax for Numerical Data
463 The read syntax for integers is a string of digits, optionally
464 preceded by a minus or plus character, a code indicating the
465 base in which the integer is encoded, and a code indicating whether
466 the number is exact or inexact. The supported base codes are:
471 the integer is written in binary (base 2)
475 the integer is written in octal (base 8)
479 the integer is written in decimal (base 10)
483 the integer is written in hexadecimal (base 16)
486 If the base code is omitted, the integer is assumed to be decimal. The
487 following examples show how these base codes are used.
506 The codes for indicating exactness (which can, incidentally, be applied
507 to all numerical values) are:
516 the number is inexact.
519 If the exactness indicator is omitted, the integer is assumed to be exact,
520 since Guile's internal representation for integers is always exact.
521 Real numbers have limited precision similar to the precision of the
522 @code{double} type in C. A consequence of the limited precision is that
523 all real numbers in Guile are also rational, since any number @var{r} with a
524 limited number of decimal places, say @var{n}, can be made into an integer by
525 multiplying by @math{10^n}.
527 Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
528 plus and minus infinity, respectively. The value must be written
529 exactly as shown, that is, the always must have a sign and exactly one
530 zero digit after the decimal point. It also understands @samp{+nan.0}
531 and @samp{-nan.0} for the special `not-a-number' value. The sign is
532 ignored for `not-a-number' and the value is always printed as @samp{+nan.0}.
534 @node Integer Operations
535 @subsection Operations on Integer Values
544 @deffn {Scheme Procedure} odd? n
545 @deffnx {C Function} scm_odd_p (n)
546 Return @code{#t} if @var{n} is an odd number, @code{#f}
550 @deffn {Scheme Procedure} even? n
551 @deffnx {C Function} scm_even_p (n)
552 Return @code{#t} if @var{n} is an even number, @code{#f}
556 @c begin (texi-doc-string "guile" "quotient")
557 @c begin (texi-doc-string "guile" "remainder")
558 @deffn {Scheme Procedure} quotient n d
559 @deffnx {Scheme Procedure} remainder n d
560 Return the quotient or remainder from @var{n} divided by @var{d}. The
561 quotient is rounded towards zero, and the remainder will have the same
562 sign as @var{n}. In all cases quotient and remainder satisfy
563 @math{@var{n} = @var{q}*@var{d} + @var{r}}.
566 (remainder 13 4) @result{} 1
567 (remainder -13 4) @result{} -1
571 @c begin (texi-doc-string "guile" "modulo")
572 @deffn {Scheme Procedure} modulo n d
573 Return the remainder from @var{n} divided by @var{d}, with the same
577 (modulo 13 4) @result{} 1
578 (modulo -13 4) @result{} 3
579 (modulo 13 -4) @result{} -3
580 (modulo -13 -4) @result{} -1
584 @c begin (texi-doc-string "guile" "gcd")
585 @deffn {Scheme Procedure} gcd
586 Return the greatest common divisor of all arguments.
587 If called without arguments, 0 is returned.
590 @c begin (texi-doc-string "guile" "lcm")
591 @deffn {Scheme Procedure} lcm
592 Return the least common multiple of the arguments.
593 If called without arguments, 1 is returned.
598 @subsection Comparison Predicates
603 @c begin (texi-doc-string "guile" "=")
604 @deffn {Scheme Procedure} =
605 Return @code{#t} if all parameters are numerically equal.
608 @c begin (texi-doc-string "guile" "<")
609 @deffn {Scheme Procedure} <
610 Return @code{#t} if the list of parameters is monotonically
614 @c begin (texi-doc-string "guile" ">")
615 @deffn {Scheme Procedure} >
616 Return @code{#t} if the list of parameters is monotonically
620 @c begin (texi-doc-string "guile" "<=")
621 @deffn {Scheme Procedure} <=
622 Return @code{#t} if the list of parameters is monotonically
626 @c begin (texi-doc-string "guile" ">=")
627 @deffn {Scheme Procedure} >=
628 Return @code{#t} if the list of parameters is monotonically
632 @c begin (texi-doc-string "guile" "zero?")
633 @deffn {Scheme Procedure} zero?
634 Return @code{#t} if @var{z} is an exact or inexact number equal to
638 @c begin (texi-doc-string "guile" "positive?")
639 @deffn {Scheme Procedure} positive?
640 Return @code{#t} if @var{x} is an exact or inexact number greater than
644 @c begin (texi-doc-string "guile" "negative?")
645 @deffn {Scheme Procedure} negative?
646 Return @code{#t} if @var{x} is an exact or inexact number less than
652 @subsection Converting Numbers To and From Strings
653 @rnindex number->string
654 @rnindex string->number
656 @deffn {Scheme Procedure} number->string n [radix]
657 @deffnx {C Function} scm_number_to_string (n, radix)
658 Return a string holding the external representation of the
659 number @var{n} in the given @var{radix}. If @var{n} is
660 inexact, a radix of 10 will be used.
663 @deffn {Scheme Procedure} string->number string [radix]
664 @deffnx {C Function} scm_string_to_number (string, radix)
665 Return a number of the maximally precise representation
666 expressed by the given @var{string}. @var{radix} must be an
667 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
668 is a default radix that may be overridden by an explicit radix
669 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
670 supplied, then the default radix is 10. If string is not a
671 syntactically valid notation for a number, then
672 @code{string->number} returns @code{#f}.
677 @subsection Complex Number Operations
678 @rnindex make-rectangular
685 @deffn {Scheme Procedure} make-rectangular real imaginary
686 @deffnx {C Function} scm_make_rectangular (real, imaginary)
687 Return a complex number constructed of the given @var{real} and
688 @var{imaginary} parts.
691 @deffn {Scheme Procedure} make-polar x y
692 @deffnx {C Function} scm_make_polar (x, y)
693 Return the complex number @var{x} * e^(i * @var{y}).
696 @c begin (texi-doc-string "guile" "real-part")
697 @deffn {Scheme Procedure} real-part z
698 Return the real part of the number @var{z}.
701 @c begin (texi-doc-string "guile" "imag-part")
702 @deffn {Scheme Procedure} imag-part z
703 Return the imaginary part of the number @var{z}.
706 @c begin (texi-doc-string "guile" "magnitude")
707 @deffn {Scheme Procedure} magnitude z
708 Return the magnitude of the number @var{z}. This is the same as
709 @code{abs} for real arguments, but also allows complex numbers.
712 @c begin (texi-doc-string "guile" "angle")
713 @deffn {Scheme Procedure} angle z
714 Return the angle of the complex number @var{z}.
719 @subsection Arithmetic Functions
732 @c begin (texi-doc-string "guile" "+")
733 @deffn {Scheme Procedure} + z1 @dots{}
734 Return the sum of all parameter values. Return 0 if called without any
738 @c begin (texi-doc-string "guile" "-")
739 @deffn {Scheme Procedure} - z1 z2 @dots{}
740 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
741 the sum of all but the first argument are subtracted from the first
745 @c begin (texi-doc-string "guile" "*")
746 @deffn {Scheme Procedure} * z1 @dots{}
747 Return the product of all arguments. If called without arguments, 1 is
751 @c begin (texi-doc-string "guile" "/")
752 @deffn {Scheme Procedure} / z1 z2 @dots{}
753 Divide the first argument by the product of the remaining arguments. If
754 called with one argument @var{z1}, 1/@var{z1} is returned.
757 @c begin (texi-doc-string "guile" "abs")
758 @deffn {Scheme Procedure} abs x
759 @deffnx {C Function} scm_abs (x)
760 Return the absolute value of @var{x}.
762 @var{x} must be a number with zero imaginary part. To calculate the
763 magnitude of a complex number, use @code{magnitude} instead.
766 @c begin (texi-doc-string "guile" "max")
767 @deffn {Scheme Procedure} max x1 x2 @dots{}
768 Return the maximum of all parameter values.
771 @c begin (texi-doc-string "guile" "min")
772 @deffn {Scheme Procedure} min x1 x2 @dots{}
773 Return the minimum of all parameter values.
776 @c begin (texi-doc-string "guile" "truncate")
777 @deffn {Scheme Procedure} truncate
778 Round the inexact number @var{x} towards zero.
781 @c begin (texi-doc-string "guile" "round")
782 @deffn {Scheme Procedure} round x
783 Round the inexact number @var{x} to the nearest integer. When exactly
784 halfway between two integers, round to the even one.
787 @c begin (texi-doc-string "guile" "floor")
788 @deffn {Scheme Procedure} floor x
789 Round the number @var{x} towards minus infinity.
792 @c begin (texi-doc-string "guile" "ceiling")
793 @deffn {Scheme Procedure} ceiling x
794 Round the number @var{x} towards infinity.
797 C functions for some of the above rounding functions are provided by
798 the standard C mathematics library. Naturally these expect and return
799 @code{double} arguments (@pxref{Rounding Functions,,, libc, GNU C
800 Library Reference Manual}).
802 @multitable {xx} {Scheme Procedure} {C Function}
803 @item @tab Scheme Procedure @tab C Function
804 @item @tab @code{floor} @tab @code{floor}
805 @item @tab @code{ceiling} @tab @code{ceil}
806 @item @tab @code{truncate} @tab @code{trunc}
809 @code{trunc} is C99 standard and might not be available on older
810 systems. Guile provides an @code{scm_truncate} equivalent (on all
811 systems), plus a C level version of the Scheme @code{round} procedure.
813 @deftypefn {C Function} double scm_truncate (double x)
814 @deftypefnx {C Function} double scm_round (double x)
819 @subsection Scientific Functions
821 The following procedures accept any kind of number as arguments,
822 including complex numbers.
825 @c begin (texi-doc-string "guile" "sqrt")
826 @deffn {Scheme Procedure} sqrt z
827 Return the square root of @var{z}.
831 @c begin (texi-doc-string "guile" "expt")
832 @deffn {Scheme Procedure} expt z1 z2
833 Return @var{z1} raised to the power of @var{z2}.
837 @c begin (texi-doc-string "guile" "sin")
838 @deffn {Scheme Procedure} sin z
839 Return the sine of @var{z}.
843 @c begin (texi-doc-string "guile" "cos")
844 @deffn {Scheme Procedure} cos z
845 Return the cosine of @var{z}.
849 @c begin (texi-doc-string "guile" "tan")
850 @deffn {Scheme Procedure} tan z
851 Return the tangent of @var{z}.
855 @c begin (texi-doc-string "guile" "asin")
856 @deffn {Scheme Procedure} asin z
857 Return the arcsine of @var{z}.
861 @c begin (texi-doc-string "guile" "acos")
862 @deffn {Scheme Procedure} acos z
863 Return the arccosine of @var{z}.
867 @c begin (texi-doc-string "guile" "atan")
868 @deffn {Scheme Procedure} atan z
869 @deffnx {Scheme Procedure} atan y x
870 Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
874 @c begin (texi-doc-string "guile" "exp")
875 @deffn {Scheme Procedure} exp z
876 Return e to the power of @var{z}, where e is the base of natural
877 logarithms (2.71828@dots{}).
881 @c begin (texi-doc-string "guile" "log")
882 @deffn {Scheme Procedure} log z
883 Return the natural logarithm of @var{z}.
886 @c begin (texi-doc-string "guile" "log10")
887 @deffn {Scheme Procedure} log10 z
888 Return the base 10 logarithm of @var{z}.
891 @c begin (texi-doc-string "guile" "sinh")
892 @deffn {Scheme Procedure} sinh z
893 Return the hyperbolic sine of @var{z}.
896 @c begin (texi-doc-string "guile" "cosh")
897 @deffn {Scheme Procedure} cosh z
898 Return the hyperbolic cosine of @var{z}.
901 @c begin (texi-doc-string "guile" "tanh")
902 @deffn {Scheme Procedure} tanh z
903 Return the hyperbolic tangent of @var{z}.
906 @c begin (texi-doc-string "guile" "asinh")
907 @deffn {Scheme Procedure} asinh z
908 Return the hyperbolic arcsine of @var{z}.
911 @c begin (texi-doc-string "guile" "acosh")
912 @deffn {Scheme Procedure} acosh z
913 Return the hyperbolic arccosine of @var{z}.
916 @c begin (texi-doc-string "guile" "atanh")
917 @deffn {Scheme Procedure} atanh z
918 Return the hyperbolic arctangent of @var{z}.
922 @node Primitive Numerics
923 @subsection Primitive Numeric Functions
925 Many of Guile's numeric procedures which accept any kind of numbers as
926 arguments, including complex numbers, are implemented as Scheme
927 procedures that use the following real number-based primitives. These
928 primitives signal an error if they are called with complex arguments.
930 @c begin (texi-doc-string "guile" "$abs")
931 @deffn {Scheme Procedure} $abs x
932 Return the absolute value of @var{x}.
935 @c begin (texi-doc-string "guile" "$sqrt")
936 @deffn {Scheme Procedure} $sqrt x
937 Return the square root of @var{x}.
940 @deffn {Scheme Procedure} $expt x y
941 @deffnx {C Function} scm_sys_expt (x, y)
942 Return @var{x} raised to the power of @var{y}. This
943 procedure does not accept complex arguments.
946 @c begin (texi-doc-string "guile" "$sin")
947 @deffn {Scheme Procedure} $sin x
948 Return the sine of @var{x}.
951 @c begin (texi-doc-string "guile" "$cos")
952 @deffn {Scheme Procedure} $cos x
953 Return the cosine of @var{x}.
956 @c begin (texi-doc-string "guile" "$tan")
957 @deffn {Scheme Procedure} $tan x
958 Return the tangent of @var{x}.
961 @c begin (texi-doc-string "guile" "$asin")
962 @deffn {Scheme Procedure} $asin x
963 Return the arcsine of @var{x}.
966 @c begin (texi-doc-string "guile" "$acos")
967 @deffn {Scheme Procedure} $acos x
968 Return the arccosine of @var{x}.
971 @c begin (texi-doc-string "guile" "$atan")
972 @deffn {Scheme Procedure} $atan x
973 Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
977 @deffn {Scheme Procedure} $atan2 x y
978 @deffnx {C Function} scm_sys_atan2 (x, y)
979 Return the arc tangent of the two arguments @var{x} and
980 @var{y}. This is similar to calculating the arc tangent of
981 @var{x} / @var{y}, except that the signs of both arguments
982 are used to determine the quadrant of the result. This
983 procedure does not accept complex arguments.
986 @c begin (texi-doc-string "guile" "$exp")
987 @deffn {Scheme Procedure} $exp x
988 Return e to the power of @var{x}, where e is the base of natural
989 logarithms (2.71828@dots{}).
992 @c begin (texi-doc-string "guile" "$log")
993 @deffn {Scheme Procedure} $log x
994 Return the natural logarithm of @var{x}.
997 @c begin (texi-doc-string "guile" "$sinh")
998 @deffn {Scheme Procedure} $sinh x
999 Return the hyperbolic sine of @var{x}.
1002 @c begin (texi-doc-string "guile" "$cosh")
1003 @deffn {Scheme Procedure} $cosh x
1004 Return the hyperbolic cosine of @var{x}.
1007 @c begin (texi-doc-string "guile" "$tanh")
1008 @deffn {Scheme Procedure} $tanh x
1009 Return the hyperbolic tangent of @var{x}.
1012 @c begin (texi-doc-string "guile" "$asinh")
1013 @deffn {Scheme Procedure} $asinh x
1014 Return the hyperbolic arcsine of @var{x}.
1017 @c begin (texi-doc-string "guile" "$acosh")
1018 @deffn {Scheme Procedure} $acosh x
1019 Return the hyperbolic arccosine of @var{x}.
1022 @c begin (texi-doc-string "guile" "$atanh")
1023 @deffn {Scheme Procedure} $atanh x
1024 Return the hyperbolic arctangent of @var{x}.
1027 C functions for the above are provided by the standard mathematics
1028 library. Naturally these expect and return @code{double} arguments
1029 (@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1031 @multitable {xx} {Scheme Procedure} {C Function}
1032 @item @tab Scheme Procedure @tab C Function
1034 @item @tab @code{$abs} @tab @code{fabs}
1035 @item @tab @code{$sqrt} @tab @code{sqrt}
1036 @item @tab @code{$sin} @tab @code{sin}
1037 @item @tab @code{$cos} @tab @code{cos}
1038 @item @tab @code{$tan} @tab @code{tan}
1039 @item @tab @code{$asin} @tab @code{asin}
1040 @item @tab @code{$acos} @tab @code{acos}
1041 @item @tab @code{$atan} @tab @code{atan}
1042 @item @tab @code{$atan2} @tab @code{atan2}
1043 @item @tab @code{$exp} @tab @code{exp}
1044 @item @tab @code{$expt} @tab @code{pow}
1045 @item @tab @code{$log} @tab @code{log}
1046 @item @tab @code{$sinh} @tab @code{sinh}
1047 @item @tab @code{$cosh} @tab @code{cosh}
1048 @item @tab @code{$tanh} @tab @code{tanh}
1049 @item @tab @code{$asinh} @tab @code{asinh}
1050 @item @tab @code{$acosh} @tab @code{acosh}
1051 @item @tab @code{$atanh} @tab @code{atanh}
1054 @code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1055 not be available on older systems. Guile provides the following
1056 equivalents (on all systems).
1058 @deftypefn {C Function} double scm_asinh (double x)
1059 @deftypefnx {C Function} double scm_acosh (double x)
1060 @deftypefnx {C Function} double scm_atanh (double x)
1061 Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1066 @node Bitwise Operations
1067 @subsection Bitwise Operations
1069 For the following bitwise functions, negative numbers are treated as
1070 infinite precision twos-complements. For instance @math{-6} is bits
1071 @math{@dots{}111010}, with infinitely many ones on the left. It can
1072 be seen that adding 6 (binary 110) to such a bit pattern gives all
1075 @deffn {Scheme Procedure} logand n1 n2 @dots{}
1076 Return the bitwise @sc{and} of the integer arguments.
1079 (logand) @result{} -1
1080 (logand 7) @result{} 7
1081 (logand #b111 #b011 #b001) @result{} 1
1085 @deffn {Scheme Procedure} logior n1 n2 @dots{}
1086 Return the bitwise @sc{or} of the integer arguments.
1089 (logior) @result{} 0
1090 (logior 7) @result{} 7
1091 (logior #b000 #b001 #b011) @result{} 3
1095 @deffn {Scheme Procedure} logxor n1 n2 @dots{}
1096 Return the bitwise @sc{xor} of the integer arguments. A bit is
1097 set in the result if it is set in an odd number of arguments.
1100 (logxor) @result{} 0
1101 (logxor 7) @result{} 7
1102 (logxor #b000 #b001 #b011) @result{} 2
1103 (logxor #b000 #b001 #b011 #b011) @result{} 1
1107 @deffn {Scheme Procedure} lognot n
1108 @deffnx {C Function} scm_lognot (n)
1109 Return the integer which is the ones-complement of the integer
1110 argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1113 (number->string (lognot #b10000000) 2)
1114 @result{} "-10000001"
1115 (number->string (lognot #b0) 2)
1120 @deffn {Scheme Procedure} logtest j k
1121 @deffnx {C Function} scm_logtest (j, k)
1123 (logtest j k) @equiv{} (not (zero? (logand j k)))
1125 (logtest #b0100 #b1011) @result{} #f
1126 (logtest #b0100 #b0111) @result{} #t
1130 @deffn {Scheme Procedure} logbit? index j
1131 @deffnx {C Function} scm_logbit_p (index, j)
1133 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1135 (logbit? 0 #b1101) @result{} #t
1136 (logbit? 1 #b1101) @result{} #f
1137 (logbit? 2 #b1101) @result{} #t
1138 (logbit? 3 #b1101) @result{} #t
1139 (logbit? 4 #b1101) @result{} #f
1143 @deffn {Scheme Procedure} ash n cnt
1144 @deffnx {C Function} scm_ash (n, cnt)
1145 Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1146 @var{cnt} is negative. This is an ``arithmetic'' shift.
1148 This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1149 when @var{cnt} is negative it's a division, rounded towards negative
1150 infinity. (Note that this is not the same rounding as @code{quotient}
1153 With @var{n} viewed as an infinite precision twos complement,
1154 @code{ash} means a left shift introducing zero bits, or a right shift
1158 (number->string (ash #b1 3) 2) @result{} "1000"
1159 (number->string (ash #b1010 -1) 2) @result{} "101"
1161 ;; -23 is bits ...11101001, -6 is bits ...111010
1162 (ash -23 -2) @result{} -6
1166 @deffn {Scheme Procedure} logcount n
1167 @deffnx {C Function} scm_logcount (n)
1168 Return the number of bits in integer @var{n}. If integer is
1169 positive, the 1-bits in its binary representation are counted.
1170 If negative, the 0-bits in its two's-complement binary
1171 representation are counted. If 0, 0 is returned.
1174 (logcount #b10101010)
1183 @deffn {Scheme Procedure} integer-length n
1184 @deffnx {C Function} scm_integer_length (n)
1185 Return the number of bits necessary to represent @var{n}.
1187 For positive @var{n} this is how many bits to the most significant one
1188 bit. For negative @var{n} it's how many bits to the most significant
1189 zero bit in twos complement form.
1192 (integer-length #b10101010) @result{} 8
1193 (integer-length #b1111) @result{} 4
1194 (integer-length 0) @result{} 0
1195 (integer-length -1) @result{} 0
1196 (integer-length -256) @result{} 8
1197 (integer-length -257) @result{} 9
1201 @deffn {Scheme Procedure} integer-expt n k
1202 @deffnx {C Function} scm_integer_expt (n, k)
1203 Return @var{n} raised to the non-negative integer exponent
1214 @deffn {Scheme Procedure} bit-extract n start end
1215 @deffnx {C Function} scm_bit_extract (n, start, end)
1216 Return the integer composed of the @var{start} (inclusive)
1217 through @var{end} (exclusive) bits of @var{n}. The
1218 @var{start}th bit becomes the 0-th bit in the result.
1221 (number->string (bit-extract #b1101101010 0 4) 2)
1223 (number->string (bit-extract #b1101101010 4 9) 2)
1230 @subsection Random Number Generation
1232 @deffn {Scheme Procedure} copy-random-state [state]
1233 @deffnx {C Function} scm_copy_random_state (state)
1234 Return a copy of the random state @var{state}.
1237 @deffn {Scheme Procedure} random n [state]
1238 @deffnx {C Function} scm_random (n, state)
1239 Return a number in [0, @var{n}).
1241 Accepts a positive integer or real n and returns a
1242 number of the same type between zero (inclusive) and
1243 @var{n} (exclusive). The values returned have a uniform
1246 The optional argument @var{state} must be of the type produced
1247 by @code{seed->random-state}. It defaults to the value of the
1248 variable @var{*random-state*}. This object is used to maintain
1249 the state of the pseudo-random-number generator and is altered
1250 as a side effect of the random operation.
1253 @deffn {Scheme Procedure} random:exp [state]
1254 @deffnx {C Function} scm_random_exp (state)
1255 Return an inexact real in an exponential distribution with mean
1256 1. For an exponential distribution with mean @var{u} use @code{(*
1257 @var{u} (random:exp))}.
1260 @deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1261 @deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1262 Fills @var{vect} with inexact real random numbers the sum of whose
1263 squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1264 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1265 the coordinates are uniformly distributed over the surface of the unit
1269 @deffn {Scheme Procedure} random:normal [state]
1270 @deffnx {C Function} scm_random_normal (state)
1271 Return an inexact real in a normal distribution. The distribution
1272 used has mean 0 and standard deviation 1. For a normal distribution
1273 with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1274 (* @var{d} (random:normal)))}.
1277 @deffn {Scheme Procedure} random:normal-vector! vect [state]
1278 @deffnx {C Function} scm_random_normal_vector_x (vect, state)
1279 Fills @var{vect} with inexact real random numbers that are
1280 independent and standard normally distributed
1281 (i.e., with mean 0 and variance 1).
1284 @deffn {Scheme Procedure} random:solid-sphere! vect [state]
1285 @deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1286 Fills @var{vect} with inexact real random numbers the sum of whose
1287 squares is less than 1.0. Thinking of @var{vect} as coordinates in
1288 space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1289 the coordinates are uniformly distributed within the unit
1290 @var{n}-sphere. The sum of the squares of the numbers is returned.
1291 @c FIXME: What does this mean, particularly the n-sphere part?
1294 @deffn {Scheme Procedure} random:uniform [state]
1295 @deffnx {C Function} scm_random_uniform (state)
1296 Return a uniformly distributed inexact real random number in
1300 @deffn {Scheme Procedure} seed->random-state seed
1301 @deffnx {C Function} scm_seed_to_random_state (seed)
1302 Return a new random state using @var{seed}.
1311 [@strong{FIXME}: how do you specify regular (non-control) characters?]
1313 Most of the ``control characters'' (those below codepoint 32) in the
1314 @acronym{ASCII} character set, as well as the space, may be referred
1315 to by name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and
1316 so on. The following table describes the @acronym{ASCII} names for
1319 @multitable @columnfractions .25 .25 .25 .25
1320 @item 0 = @code{#\nul}
1321 @tab 1 = @code{#\soh}
1322 @tab 2 = @code{#\stx}
1323 @tab 3 = @code{#\etx}
1324 @item 4 = @code{#\eot}
1325 @tab 5 = @code{#\enq}
1326 @tab 6 = @code{#\ack}
1327 @tab 7 = @code{#\bel}
1328 @item 8 = @code{#\bs}
1329 @tab 9 = @code{#\ht}
1330 @tab 10 = @code{#\nl}
1331 @tab 11 = @code{#\vt}
1332 @item 12 = @code{#\np}
1333 @tab 13 = @code{#\cr}
1334 @tab 14 = @code{#\so}
1335 @tab 15 = @code{#\si}
1336 @item 16 = @code{#\dle}
1337 @tab 17 = @code{#\dc1}
1338 @tab 18 = @code{#\dc2}
1339 @tab 19 = @code{#\dc3}
1340 @item 20 = @code{#\dc4}
1341 @tab 21 = @code{#\nak}
1342 @tab 22 = @code{#\syn}
1343 @tab 23 = @code{#\etb}
1344 @item 24 = @code{#\can}
1345 @tab 25 = @code{#\em}
1346 @tab 26 = @code{#\sub}
1347 @tab 27 = @code{#\esc}
1348 @item 28 = @code{#\fs}
1349 @tab 29 = @code{#\gs}
1350 @tab 30 = @code{#\rs}
1351 @tab 31 = @code{#\us}
1352 @item 32 = @code{#\sp}
1355 The ``delete'' character (octal 177) may be referred to with the name
1358 Several characters have more than one name:
1360 @multitable {@code{#\backspace}} {Original}
1361 @item Alias @tab Original
1362 @item @code{#\space} @tab @code{#\sp}
1363 @item @code{#\newline} @tab @code{#\nl}
1364 @item @code{#\tab} @tab @code{#\ht}
1365 @item @code{#\backspace} @tab @code{#\bs}
1366 @item @code{#\return} @tab @code{#\cr}
1367 @item @code{#\page} @tab @code{#\np}
1368 @item @code{#\null} @tab @code{#\nul}
1372 @deffn {Scheme Procedure} char? x
1373 @deffnx {C Function} scm_char_p (x)
1374 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1378 @deffn {Scheme Procedure} char=? x y
1379 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1383 @deffn {Scheme Procedure} char<? x y
1384 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1389 @deffn {Scheme Procedure} char<=? x y
1390 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1391 @acronym{ASCII} sequence, else @code{#f}.
1395 @deffn {Scheme Procedure} char>? x y
1396 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1397 sequence, else @code{#f}.
1401 @deffn {Scheme Procedure} char>=? x y
1402 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1403 @acronym{ASCII} sequence, else @code{#f}.
1407 @deffn {Scheme Procedure} char-ci=? x y
1408 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1409 case, else @code{#f}.
1413 @deffn {Scheme Procedure} char-ci<? x y
1414 Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1415 ignoring case, else @code{#f}.
1419 @deffn {Scheme Procedure} char-ci<=? x y
1420 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1421 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1425 @deffn {Scheme Procedure} char-ci>? x y
1426 Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1427 sequence ignoring case, else @code{#f}.
1431 @deffn {Scheme Procedure} char-ci>=? x y
1432 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1433 @acronym{ASCII} sequence ignoring case, else @code{#f}.
1436 @rnindex char-alphabetic?
1437 @deffn {Scheme Procedure} char-alphabetic? chr
1438 @deffnx {C Function} scm_char_alphabetic_p (chr)
1439 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1440 Alphabetic means the same thing as the @code{isalpha} C library function.
1443 @rnindex char-numeric?
1444 @deffn {Scheme Procedure} char-numeric? chr
1445 @deffnx {C Function} scm_char_numeric_p (chr)
1446 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1447 Numeric means the same thing as the @code{isdigit} C library function.
1450 @rnindex char-whitespace?
1451 @deffn {Scheme Procedure} char-whitespace? chr
1452 @deffnx {C Function} scm_char_whitespace_p (chr)
1453 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1454 Whitespace means the same thing as the @code{isspace} C library function.
1457 @rnindex char-upper-case?
1458 @deffn {Scheme Procedure} char-upper-case? chr
1459 @deffnx {C Function} scm_char_upper_case_p (chr)
1460 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1461 Uppercase means the same thing as the @code{isupper} C library function.
1464 @rnindex char-lower-case?
1465 @deffn {Scheme Procedure} char-lower-case? chr
1466 @deffnx {C Function} scm_char_lower_case_p (chr)
1467 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1468 Lowercase means the same thing as the @code{islower} C library function.
1471 @deffn {Scheme Procedure} char-is-both? chr
1472 @deffnx {C Function} scm_char_is_both_p (chr)
1473 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1474 @code{#f}. Uppercase and lowercase are as defined by the
1475 @code{isupper} and @code{islower} C library functions.
1478 @rnindex char->integer
1479 @deffn {Scheme Procedure} char->integer chr
1480 @deffnx {C Function} scm_char_to_integer (chr)
1481 Return the number corresponding to ordinal position of @var{chr} in the
1482 @acronym{ASCII} sequence.
1485 @rnindex integer->char
1486 @deffn {Scheme Procedure} integer->char n
1487 @deffnx {C Function} scm_integer_to_char (n)
1488 Return the character at position @var{n} in the @acronym{ASCII} sequence.
1491 @rnindex char-upcase
1492 @deffn {Scheme Procedure} char-upcase chr
1493 @deffnx {C Function} scm_char_upcase (chr)
1494 Return the uppercase character version of @var{chr}.
1497 @rnindex char-downcase
1498 @deffn {Scheme Procedure} char-downcase chr
1499 @deffnx {C Function} scm_char_downcase (chr)
1500 Return the lowercase character version of @var{chr}.
1503 @xref{Classification of Characters,,,libc,GNU C Library Reference
1504 Manual}, for information about the @code{is*} Standard C functions
1512 Strings are fixed-length sequences of characters. They can be created
1513 by calling constructor procedures, but they can also literally get
1514 entered at the @acronym{REPL} or in Scheme source files.
1516 Guile provides a rich set of string processing procedures, because text
1517 handling is very important when Guile is used as a scripting language.
1519 Strings always carry the information about how many characters they are
1520 composed of with them, so there is no special end-of-string character,
1521 like in C. That means that Scheme strings can contain any character,
1522 even the @samp{NUL} character @samp{\0}. But note: Since most operating
1523 system calls dealing with strings (such as for file operations) expect
1524 strings to be zero-terminated, they might do unexpected things when
1525 called with string containing unusual characters.
1528 * String Syntax:: Read syntax for strings.
1529 * String Predicates:: Testing strings for certain properties.
1530 * String Constructors:: Creating new string objects.
1531 * List/String Conversion:: Converting from/to lists of characters.
1532 * String Selection:: Select portions from strings.
1533 * String Modification:: Modify parts or whole strings.
1534 * String Comparison:: Lexicographic ordering predicates.
1535 * String Searching:: Searching in strings.
1536 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1537 * Appending Strings:: Appending strings to form a new string.
1541 @subsection String Read Syntax
1543 The read syntax for strings is an arbitrarily long sequence of
1544 characters enclosed in double quotes (@code{"}).@footnote{Actually,
1545 the current implementation restricts strings to a length of
1546 @math{2^24}, or 16,777,216, characters. Sorry.} If you want to
1547 insert a double quote character into a string literal, it must be
1548 prefixed with a backslash @samp{\} character (called an @dfn{escape
1551 The following are examples of string literals:
1560 @c FIXME::martin: What about escape sequences like \r, \n etc.?
1562 @node String Predicates
1563 @subsection String Predicates
1565 The following procedures can be used to check whether a given string
1566 fulfills some specified property.
1569 @deffn {Scheme Procedure} string? obj
1570 @deffnx {C Function} scm_string_p (obj)
1571 Return @code{#t} if @var{obj} is a string, else @code{#f}.
1574 @deffn {Scheme Procedure} string-null? str
1575 @deffnx {C Function} scm_string_null_p (str)
1576 Return @code{#t} if @var{str}'s length is zero, and
1577 @code{#f} otherwise.
1579 (string-null? "") @result{} #t
1581 (string-null? y) @result{} #f
1585 @node String Constructors
1586 @subsection String Constructors
1588 The string constructor procedures create new string objects, possibly
1589 initializing them with some specified character data.
1591 @c FIXME::martin: list->string belongs into `List/String Conversion'
1594 @rnindex list->string
1595 @deffn {Scheme Procedure} string . chrs
1596 @deffnx {Scheme Procedure} list->string chrs
1597 @deffnx {C Function} scm_string (chrs)
1598 Return a newly allocated string composed of the arguments,
1602 @rnindex make-string
1603 @deffn {Scheme Procedure} make-string k [chr]
1604 @deffnx {C Function} scm_make_string (k, chr)
1605 Return a newly allocated string of
1606 length @var{k}. If @var{chr} is given, then all elements of
1607 the string are initialized to @var{chr}, otherwise the contents
1608 of the @var{string} are unspecified.
1611 @node List/String Conversion
1612 @subsection List/String conversion
1614 When processing strings, it is often convenient to first convert them
1615 into a list representation by using the procedure @code{string->list},
1616 work with the resulting list, and then convert it back into a string.
1617 These procedures are useful for similar tasks.
1619 @rnindex string->list
1620 @deffn {Scheme Procedure} string->list str
1621 @deffnx {C Function} scm_string_to_list (str)
1622 Return a newly allocated list of the characters that make up
1623 the given string @var{str}. @code{string->list} and
1624 @code{list->string} are inverses as far as @samp{equal?} is
1628 @deffn {Scheme Procedure} string-split str chr
1629 @deffnx {C Function} scm_string_split (str, chr)
1630 Split the string @var{str} into the a list of the substrings delimited
1631 by appearances of the character @var{chr}. Note that an empty substring
1632 between separator characters will result in an empty string in the
1636 (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
1638 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
1640 (string-split "::" #\:)
1644 (string-split "" #\:)
1651 @node String Selection
1652 @subsection String Selection
1654 Portions of strings can be extracted by these procedures.
1655 @code{string-ref} delivers individual characters whereas
1656 @code{substring} can be used to extract substrings from longer strings.
1658 @rnindex string-length
1659 @deffn {Scheme Procedure} string-length string
1660 @deffnx {C Function} scm_string_length (string)
1661 Return the number of characters in @var{string}.
1665 @deffn {Scheme Procedure} string-ref str k
1666 @deffnx {C Function} scm_string_ref (str, k)
1667 Return character @var{k} of @var{str} using zero-origin
1668 indexing. @var{k} must be a valid index of @var{str}.
1671 @rnindex string-copy
1672 @deffn {Scheme Procedure} string-copy str
1673 @deffnx {C Function} scm_string_copy (str)
1674 Return a newly allocated copy of the given @var{string}.
1678 @deffn {Scheme Procedure} substring str start [end]
1679 @deffnx {C Function} scm_substring (str, start, end)
1680 Return a newly allocated string formed from the characters
1681 of @var{str} beginning with index @var{start} (inclusive) and
1682 ending with index @var{end} (exclusive).
1683 @var{str} must be a string, @var{start} and @var{end} must be
1684 exact integers satisfying:
1686 0 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
1689 @node String Modification
1690 @subsection String Modification
1692 These procedures are for modifying strings in-place. This means that the
1693 result of the operation is not a new string; instead, the original string's
1694 memory representation is modified.
1696 @rnindex string-set!
1697 @deffn {Scheme Procedure} string-set! str k chr
1698 @deffnx {C Function} scm_string_set_x (str, k, chr)
1699 Store @var{chr} in element @var{k} of @var{str} and return
1700 an unspecified value. @var{k} must be a valid index of
1704 @rnindex string-fill!
1705 @deffn {Scheme Procedure} string-fill! str chr
1706 @deffnx {C Function} scm_string_fill_x (str, chr)
1707 Store @var{char} in every element of the given @var{string} and
1708 return an unspecified value.
1711 @deffn {Scheme Procedure} substring-fill! str start end fill
1712 @deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
1713 Change every character in @var{str} between @var{start} and
1714 @var{end} to @var{fill}.
1717 (define y "abcdefg")
1718 (substring-fill! y 1 3 #\r)
1724 @deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
1725 @deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
1726 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1727 into @var{str2} beginning at position @var{start2}.
1728 @var{str1} and @var{str2} can be the same string.
1732 @node String Comparison
1733 @subsection String Comparison
1735 The procedures in this section are similar to the character ordering
1736 predicates (@pxref{Characters}), but are defined on character sequences.
1737 They all return @code{#t} on success and @code{#f} on failure. The
1738 predicates ending in @code{-ci} ignore the character case when comparing
1743 @deffn {Scheme Procedure} string=? s1 s2
1744 Lexicographic equality predicate; return @code{#t} if the two
1745 strings are the same length and contain the same characters in
1746 the same positions, otherwise return @code{#f}.
1748 The procedure @code{string-ci=?} treats upper and lower case
1749 letters as though they were the same character, but
1750 @code{string=?} treats upper and lower case as distinct
1755 @deffn {Scheme Procedure} string<? s1 s2
1756 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1757 is lexicographically less than @var{s2}.
1761 @deffn {Scheme Procedure} string<=? s1 s2
1762 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1763 is lexicographically less than or equal to @var{s2}.
1767 @deffn {Scheme Procedure} string>? s1 s2
1768 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1769 is lexicographically greater than @var{s2}.
1773 @deffn {Scheme Procedure} string>=? s1 s2
1774 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1775 is lexicographically greater than or equal to @var{s2}.
1778 @rnindex string-ci=?
1779 @deffn {Scheme Procedure} string-ci=? s1 s2
1780 Case-insensitive string equality predicate; return @code{#t} if
1781 the two strings are the same length and their component
1782 characters match (ignoring case) at each position; otherwise
1787 @deffn {Scheme Procedure} string-ci<? s1 s2
1788 Case insensitive lexicographic ordering predicate; return
1789 @code{#t} if @var{s1} is lexicographically less than @var{s2}
1794 @deffn {Scheme Procedure} string-ci<=? s1 s2
1795 Case insensitive lexicographic ordering predicate; return
1796 @code{#t} if @var{s1} is lexicographically less than or equal
1797 to @var{s2} regardless of case.
1800 @rnindex string-ci>?
1801 @deffn {Scheme Procedure} string-ci>? s1 s2
1802 Case insensitive lexicographic ordering predicate; return
1803 @code{#t} if @var{s1} is lexicographically greater than
1804 @var{s2} regardless of case.
1807 @rnindex string-ci>=?
1808 @deffn {Scheme Procedure} string-ci>=? s1 s2
1809 Case insensitive lexicographic ordering predicate; return
1810 @code{#t} if @var{s1} is lexicographically greater than or
1811 equal to @var{s2} regardless of case.
1815 @node String Searching
1816 @subsection String Searching
1818 When searching for the index of a character in a string, these
1819 procedures can be used.
1821 @deffn {Scheme Procedure} string-index str chr [frm [to]]
1822 @deffnx {C Function} scm_string_index (str, chr, frm, to)
1823 Return the index of the first occurrence of @var{chr} in
1824 @var{str}. The optional integer arguments @var{frm} and
1825 @var{to} limit the search to a portion of the string. This
1826 procedure essentially implements the @code{index} or
1827 @code{strchr} functions from the C library.
1830 (string-index "weiner" #\e)
1833 (string-index "weiner" #\e 2)
1836 (string-index "weiner" #\e 2 4)
1841 @deffn {Scheme Procedure} string-rindex str chr [frm [to]]
1842 @deffnx {C Function} scm_string_rindex (str, chr, frm, to)
1843 Like @code{string-index}, but search from the right of the
1844 string rather than from the left. This procedure essentially
1845 implements the @code{rindex} or @code{strrchr} functions from
1849 (string-rindex "weiner" #\e)
1852 (string-rindex "weiner" #\e 2 4)
1855 (string-rindex "weiner" #\e 2 5)
1860 @node Alphabetic Case Mapping
1861 @subsection Alphabetic Case Mapping
1863 These are procedures for mapping strings to their upper- or lower-case
1864 equivalents, respectively, or for capitalizing strings.
1866 @deffn {Scheme Procedure} string-upcase str
1867 @deffnx {C Function} scm_string_upcase (str)
1868 Return a freshly allocated string containing the characters of
1869 @var{str} in upper case.
1872 @deffn {Scheme Procedure} string-upcase! str
1873 @deffnx {C Function} scm_string_upcase_x (str)
1874 Destructively upcase every character in @var{str} and return
1877 y @result{} "arrdefg"
1878 (string-upcase! y) @result{} "ARRDEFG"
1879 y @result{} "ARRDEFG"
1883 @deffn {Scheme Procedure} string-downcase str
1884 @deffnx {C Function} scm_string_downcase (str)
1885 Return a freshly allocation string containing the characters in
1886 @var{str} in lower case.
1889 @deffn {Scheme Procedure} string-downcase! str
1890 @deffnx {C Function} scm_string_downcase_x (str)
1891 Destructively downcase every character in @var{str} and return
1894 y @result{} "ARRDEFG"
1895 (string-downcase! y) @result{} "arrdefg"
1896 y @result{} "arrdefg"
1900 @deffn {Scheme Procedure} string-capitalize str
1901 @deffnx {C Function} scm_string_capitalize (str)
1902 Return a freshly allocated string with the characters in
1903 @var{str}, where the first character of every word is
1907 @deffn {Scheme Procedure} string-capitalize! str
1908 @deffnx {C Function} scm_string_capitalize_x (str)
1909 Upcase the first character of every word in @var{str}
1910 destructively and return @var{str}.
1913 y @result{} "hello world"
1914 (string-capitalize! y) @result{} "Hello World"
1915 y @result{} "Hello World"
1920 @node Appending Strings
1921 @subsection Appending Strings
1923 The procedure @code{string-append} appends several strings together to
1924 form a longer result string.
1926 @rnindex string-append
1927 @deffn {Scheme Procedure} string-append . args
1928 @deffnx {C Function} scm_string_append (args)
1929 Return a newly allocated string whose characters form the
1930 concatenation of the given strings, @var{args}.
1934 (string-append h "world"))
1935 @result{} "hello world"
1940 @node Regular Expressions
1941 @section Regular Expressions
1942 @tpindex Regular expressions
1944 @cindex regular expressions
1946 @cindex emacs regexp
1948 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
1949 describes a whole class of strings. A full description of regular
1950 expressions and their syntax is beyond the scope of this manual;
1951 an introduction can be found in the Emacs manual (@pxref{Regexps,
1952 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
1953 in many general Unix reference books.
1955 If your system does not include a POSIX regular expression library,
1956 and you have not linked Guile with a third-party regexp library such
1957 as Rx, these functions will not be available. You can tell whether
1958 your Guile installation includes regular expression support by
1959 checking whether @code{(provided? 'regex)} returns true.
1961 The following regexp and string matching features are provided by the
1962 @code{(ice-9 regex)} module. Before using the described functions,
1963 you should load this module by executing @code{(use-modules (ice-9
1967 * Regexp Functions:: Functions that create and match regexps.
1968 * Match Structures:: Finding what was matched by a regexp.
1969 * Backslash Escapes:: Removing the special meaning of regexp
1974 @node Regexp Functions
1975 @subsection Regexp Functions
1977 By default, Guile supports POSIX extended regular expressions.
1978 That means that the characters @samp{(}, @samp{)}, @samp{+} and
1979 @samp{?} are special, and must be escaped if you wish to match the
1982 This regular expression interface was modeled after that
1983 implemented by SCSH, the Scheme Shell. It is intended to be
1984 upwardly compatible with SCSH regular expressions.
1986 @deffn {Scheme Procedure} string-match pattern str [start]
1987 Compile the string @var{pattern} into a regular expression and compare
1988 it with @var{str}. The optional numeric argument @var{start} specifies
1989 the position of @var{str} at which to begin matching.
1991 @code{string-match} returns a @dfn{match structure} which
1992 describes what, if anything, was matched by the regular
1993 expression. @xref{Match Structures}. If @var{str} does not match
1994 @var{pattern} at all, @code{string-match} returns @code{#f}.
1997 Two examples of a match follow. In the first example, the pattern
1998 matches the four digits in the match string. In the second, the pattern
2002 (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
2003 @result{} #("blah2002" (4 . 8))
2005 (string-match "[A-Za-z]" "123456")
2009 Each time @code{string-match} is called, it must compile its
2010 @var{pattern} argument into a regular expression structure. This
2011 operation is expensive, which makes @code{string-match} inefficient if
2012 the same regular expression is used several times (for example, in a
2013 loop). For better performance, you can compile a regular expression in
2014 advance and then match strings against the compiled regexp.
2016 @deffn {Scheme Procedure} make-regexp pat . flags
2017 @deffnx {C Function} scm_make_regexp (pat, flags)
2018 Compile the regular expression described by @var{pat}, and
2019 return the compiled regexp structure. If @var{pat} does not
2020 describe a legal regular expression, @code{make-regexp} throws
2021 a @code{regular-expression-syntax} error.
2023 The @var{flags} arguments change the behavior of the compiled
2024 regular expression. The following flags may be supplied:
2028 Consider uppercase and lowercase letters to be the same when
2030 @item regexp/newline
2031 If a newline appears in the target string, then permit the
2032 @samp{^} and @samp{$} operators to match immediately after or
2033 immediately before the newline, respectively. Also, the
2034 @samp{.} and @samp{[^...]} operators will never match a newline
2035 character. The intent of this flag is to treat the target
2036 string as a buffer containing many lines of text, and the
2037 regular expression as a pattern that may match a single one of
2040 Compile a basic (``obsolete'') regexp instead of the extended
2041 (``modern'') regexps that are the default. Basic regexps do
2042 not consider @samp{|}, @samp{+} or @samp{?} to be special
2043 characters, and require the @samp{@{...@}} and @samp{(...)}
2044 metacharacters to be backslash-escaped (@pxref{Backslash
2045 Escapes}). There are several other differences between basic
2046 and extended regular expressions, but these are the most
2048 @item regexp/extended
2049 Compile an extended regular expression rather than a basic
2050 regexp. This is the default behavior; this flag will not
2051 usually be needed. If a call to @code{make-regexp} includes
2052 both @code{regexp/basic} and @code{regexp/extended} flags, the
2053 one which comes last will override the earlier one.
2057 @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
2058 @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
2059 Match the compiled regular expression @var{rx} against
2060 @code{str}. If the optional integer @var{start} argument is
2061 provided, begin matching from that position in the string.
2062 Return a match structure describing the results of the match,
2063 or @code{#f} if no match could be found.
2065 The @var{flags} arguments change the matching behavior.
2066 The following flags may be supplied:
2070 Operator @samp{^} always fails (unless @code{regexp/newline}
2071 is used). Use this when the beginning of the string should
2072 not be considered the beginning of a line.
2074 Operator @samp{$} always fails (unless @code{regexp/newline}
2075 is used). Use this when the end of the string should not be
2076 considered the end of a line.
2081 ;; Regexp to match uppercase letters
2082 (define r (make-regexp "[A-Z]*"))
2084 ;; Regexp to match letters, ignoring case
2085 (define ri (make-regexp "[A-Z]*" regexp/icase))
2087 ;; Search for bob using regexp r
2088 (match:substring (regexp-exec r "bob"))
2089 @result{} "" ; no match
2091 ;; Search for bob using regexp ri
2092 (match:substring (regexp-exec ri "Bob"))
2093 @result{} "Bob" ; matched case insensitive
2096 @deffn {Scheme Procedure} regexp? obj
2097 @deffnx {C Function} scm_regexp_p (obj)
2098 Return @code{#t} if @var{obj} is a compiled regular expression,
2099 or @code{#f} otherwise.
2102 Regular expressions are commonly used to find patterns in one string and
2103 replace them with the contents of another string.
2105 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2106 @deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
2107 Write to the output port @var{port} selected contents of the match
2108 structure @var{match}. Each @var{item} specifies what should be
2109 written, and may be one of the following arguments:
2113 A string. String arguments are written out verbatim.
2116 An integer. The submatch with that number is written.
2119 The symbol @samp{pre}. The portion of the matched string preceding
2120 the regexp match is written.
2123 The symbol @samp{post}. The portion of the matched string following
2124 the regexp match is written.
2127 The @var{port} argument may be @code{#f}, in which case nothing is
2128 written; instead, @code{regexp-substitute} constructs a string from the
2129 specified @var{item}s and returns that.
2132 The following example takes a regular expression that matches a standard
2133 @sc{yyyymmdd}-format date such as @code{"20020828"}. The
2134 @code{regexp-substitute} call returns a string computed from the
2135 information in the match structure, consisting of the fields and text
2136 from the original string reordered and reformatted.
2139 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2140 (define s "Date 20020429 12am.")
2141 (define sm (string-match date-regex s))
2142 (regexp-substitute #f sm 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2143 @result{} "Date 04-29-2002 12am. (20020429)"
2146 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2147 @deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
2148 Similar to @code{regexp-substitute}, but can be used to perform global
2149 substitutions on @var{str}. Instead of taking a match structure as an
2150 argument, @code{regexp-substitute/global} takes two string arguments: a
2151 @var{regexp} string describing a regular expression, and a @var{target}
2152 string which should be matched against this regular expression.
2154 Each @var{item} behaves as in @code{regexp-substitute}, with the
2155 following exceptions:
2159 A function may be supplied. When this function is called, it will be
2160 passed one argument: a match structure for a given regular expression
2161 match. It should return a string to be written out to @var{port}.
2164 The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
2165 on the unmatched portion of @var{str}. This @emph{must} be supplied in
2166 order to perform global search-and-replace on @var{str}; if it is not
2167 present among the @var{item}s, then @code{regexp-substitute/global} will
2168 return after processing a single match.
2172 The example above for @code{regexp-substitute} could be rewritten as
2173 follows to remove the @code{string-match} stage:
2176 (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2177 (define s "Date 20020429 12am.")
2178 (regexp-substitute/global #f date-regex s
2179 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2180 @result{} "Date 04-29-2002 12am. (20020429)"
2184 @node Match Structures
2185 @subsection Match Structures
2187 @cindex match structures
2189 A @dfn{match structure} is the object returned by @code{string-match} and
2190 @code{regexp-exec}. It describes which portion of a string, if any,
2191 matched the given regular expression. Match structures include: a
2192 reference to the string that was checked for matches; the starting and
2193 ending positions of the regexp match; and, if the regexp included any
2194 parenthesized subexpressions, the starting and ending positions of each
2197 In each of the regexp match functions described below, the @code{match}
2198 argument must be a match structure returned by a previous call to
2199 @code{string-match} or @code{regexp-exec}. Most of these functions
2200 return some information about the original target string that was
2201 matched against a regular expression; we will call that string
2202 @var{target} for easy reference.
2204 @c begin (scm-doc-string "regex.scm" "regexp-match?")
2205 @deffn {Scheme Procedure} regexp-match? obj
2206 Return @code{#t} if @var{obj} is a match structure returned by a
2207 previous call to @code{regexp-exec}, or @code{#f} otherwise.
2210 @c begin (scm-doc-string "regex.scm" "match:substring")
2211 @deffn {Scheme Procedure} match:substring match [n]
2212 Return the portion of @var{target} matched by subexpression number
2213 @var{n}. Submatch 0 (the default) represents the entire regexp match.
2214 If the regular expression as a whole matched, but the subexpression
2215 number @var{n} did not match, return @code{#f}.
2219 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2223 ;; match starting at offset 6 in the string
2225 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
2229 @c begin (scm-doc-string "regex.scm" "match:start")
2230 @deffn {Scheme Procedure} match:start match [n]
2231 Return the starting position of submatch number @var{n}.
2234 In the following example, the result is 4, since the match starts at
2238 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2243 @c begin (scm-doc-string "regex.scm" "match:end")
2244 @deffn {Scheme Procedure} match:end match [n]
2245 Return the ending position of submatch number @var{n}.
2248 In the following example, the result is 8, since the match runs between
2249 characters 4 and 8 (i.e. the ``2002'').
2252 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2257 @c begin (scm-doc-string "regex.scm" "match:prefix")
2258 @deffn {Scheme Procedure} match:prefix match
2259 Return the unmatched portion of @var{target} preceding the regexp match.
2262 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2268 @c begin (scm-doc-string "regex.scm" "match:suffix")
2269 @deffn {Scheme Procedure} match:suffix match
2270 Return the unmatched portion of @var{target} following the regexp match.
2274 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2279 @c begin (scm-doc-string "regex.scm" "match:count")
2280 @deffn {Scheme Procedure} match:count match
2281 Return the number of parenthesized subexpressions from @var{match}.
2282 Note that the entire regular expression match itself counts as a
2283 subexpression, and failed submatches are included in the count.
2286 @c begin (scm-doc-string "regex.scm" "match:string")
2287 @deffn {Scheme Procedure} match:string match
2288 Return the original @var{target} string.
2292 (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2294 @result{} "blah2002foo"
2298 @node Backslash Escapes
2299 @subsection Backslash Escapes
2301 Sometimes you will want a regexp to match characters like @samp{*} or
2302 @samp{$} exactly. For example, to check whether a particular string
2303 represents a menu entry from an Info node, it would be useful to match
2304 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2305 because the asterisk is a metacharacter, it won't match the @samp{*} at
2306 the beginning of the string. In this case, we want to make the first
2309 You can do this by preceding the metacharacter with a backslash
2310 character @samp{\}. (This is also called @dfn{quoting} the
2311 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2312 sees a backslash in a regular expression, it considers the following
2313 glyph to be an ordinary character, no matter what special meaning it
2314 would ordinarily have. Therefore, we can make the above example work by
2315 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2316 the regular expression engine to match only a single asterisk in the
2319 Since the backslash is itself a metacharacter, you may force a regexp to
2320 match a backslash in the target string by preceding the backslash with
2321 itself. For example, to find variable references in a @TeX{} program,
2322 you might want to find occurrences of the string @samp{\let\} followed
2323 by any number of alphabetic characters. The regular expression
2324 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2325 regexp each match a single backslash in the target string.
2327 @c begin (scm-doc-string "regex.scm" "regexp-quote")
2328 @deffn {Scheme Procedure} regexp-quote str
2329 Quote each special character found in @var{str} with a backslash, and
2330 return the resulting string.
2333 @strong{Very important:} Using backslash escapes in Guile source code
2334 (as in Emacs Lisp or C) can be tricky, because the backslash character
2335 has special meaning for the Guile reader. For example, if Guile
2336 encounters the character sequence @samp{\n} in the middle of a string
2337 while processing Scheme code, it replaces those characters with a
2338 newline character. Similarly, the character sequence @samp{\t} is
2339 replaced by a horizontal tab. Several of these @dfn{escape sequences}
2340 are processed by the Guile reader before your code is executed.
2341 Unrecognized escape sequences are ignored: if the characters @samp{\*}
2342 appear in a string, they will be translated to the single character
2345 This translation is obviously undesirable for regular expressions, since
2346 we want to be able to include backslashes in a string in order to
2347 escape regexp metacharacters. Therefore, to make sure that a backslash
2348 is preserved in a string in your Guile program, you must use @emph{two}
2349 consecutive backslashes:
2352 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2355 The string in this example is preprocessed by the Guile reader before
2356 any code is executed. The resulting argument to @code{make-regexp} is
2357 the string @samp{^\* [^:]*}, which is what we really want.
2359 This also means that in order to write a regular expression that matches
2360 a single backslash character, the regular expression string in the
2361 source code must include @emph{four} backslashes. Each consecutive pair
2362 of backslashes gets translated by the Guile reader to a single
2363 backslash, and the resulting double-backslash is interpreted by the
2364 regexp engine as matching a single backslash character. Hence:
2367 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2370 The reason for the unwieldiness of this syntax is historical. Both
2371 regular expression pattern matchers and Unix string processing systems
2372 have traditionally used backslashes with the special meanings
2373 described above. The POSIX regular expression specification and ANSI C
2374 standard both require these semantics. Attempting to abandon either
2375 convention would cause other kinds of compatibility problems, possibly
2376 more severe ones. Therefore, without extending the Scheme reader to
2377 support strings with different quoting conventions (an ungainly and
2378 confusing extension when implemented in other languages), we must adhere
2379 to this cumbersome escape syntax.
2386 Symbols in Scheme are widely used in three ways: as items of discrete
2387 data, as lookup keys for alists and hash tables, and to denote variable
2390 A @dfn{symbol} is similar to a string in that it is defined by a
2391 sequence of characters. The sequence of characters is known as the
2392 symbol's @dfn{name}. In the usual case --- that is, where the symbol's
2393 name doesn't include any characters that could be confused with other
2394 elements of Scheme syntax --- a symbol is written in a Scheme program by
2395 writing the sequence of characters that make up the name, @emph{without}
2396 any quotation marks or other special syntax. For example, the symbol
2397 whose name is ``multiply-by-2'' is written, simply:
2403 Notice how this differs from a @emph{string} with contents
2404 ``multiply-by-2'', which is written with double quotation marks, like
2411 Looking beyond how they are written, symbols are different from strings
2412 in two important respects.
2414 The first important difference is uniqueness. If the same-looking
2415 string is read twice from two different places in a program, the result
2416 is two @emph{different} string objects whose contents just happen to be
2417 the same. If, on the other hand, the same-looking symbol is read twice
2418 from two different places in a program, the result is the @emph{same}
2419 symbol object both times.
2421 Given two read symbols, you can use @code{eq?} to test whether they are
2422 the same (that is, have the same name). @code{eq?} is the most
2423 efficient comparison operator in Scheme, and comparing two symbols like
2424 this is as fast as comparing, for example, two numbers. Given two
2425 strings, on the other hand, you must use @code{equal?} or
2426 @code{string=?}, which are much slower comparison operators, to
2427 determine whether the strings have the same contents.
2430 (define sym1 (quote hello))
2431 (define sym2 (quote hello))
2432 (eq? sym1 sym2) @result{} #t
2434 (define str1 "hello")
2435 (define str2 "hello")
2436 (eq? str1 str2) @result{} #f
2437 (equal? str1 str2) @result{} #t
2440 The second important difference is that symbols, unlike strings, are not
2441 self-evaluating. This is why we need the @code{(quote @dots{})}s in the
2442 example above: @code{(quote hello)} evaluates to the symbol named
2443 "hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
2444 symbol named "hello" and evaluated as a variable reference @dots{} about
2445 which more below (@pxref{Symbol Variables}).
2448 * Symbol Data:: Symbols as discrete data.
2449 * Symbol Keys:: Symbols as lookup keys.
2450 * Symbol Variables:: Symbols as denoting variables.
2451 * Symbol Primitives:: Operations related to symbols.
2452 * Symbol Props:: Function slots and property lists.
2453 * Symbol Read Syntax:: Extended read syntax for symbols.
2454 * Symbol Uninterned:: Uninterned symbols.
2459 @subsection Symbols as Discrete Data
2461 Numbers and symbols are similar to the extent that they both lend
2462 themselves to @code{eq?} comparison. But symbols are more descriptive
2463 than numbers, because a symbol's name can be used directly to describe
2464 the concept for which that symbol stands.
2466 For example, imagine that you need to represent some colours in a
2467 computer program. Using numbers, you would have to choose arbitrarily
2468 some mapping between numbers and colours, and then take care to use that
2469 mapping consistently:
2472 ;; 1=red, 2=green, 3=purple
2474 (if (eq? (colour-of car) 1)
2479 You can make the mapping more explicit and the code more readable by
2487 (if (eq? (colour-of car) red)
2492 But the simplest and clearest approach is not to use numbers at all, but
2493 symbols whose names specify the colours that they refer to:
2496 (if (eq? (colour-of car) 'red)
2500 The descriptive advantages of symbols over numbers increase as the set
2501 of concepts that you want to describe grows. Suppose that a car object
2502 can have other properties as well, such as whether it has or uses:
2506 automatic or manual transmission
2508 leaded or unleaded fuel
2510 power steering (or not).
2514 Then a car's combined property set could be naturally represented and
2515 manipulated as a list of symbols:
2518 (properties-of car1)
2520 (red manual unleaded power-steering)
2522 (if (memq 'power-steering (properties-of car1))
2523 (display "Unfit people can drive this car.\n")
2524 (display "You'll need strong arms to drive this car!\n"))
2526 Unfit people can drive this car.
2529 Remember, the fundamental property of symbols that we are relying on
2530 here is that an occurrence of @code{'red} in one part of a program is an
2531 @emph{indistinguishable} symbol from an occurrence of @code{'red} in
2532 another part of a program; this means that symbols can usefully be
2533 compared using @code{eq?}. At the same time, symbols have naturally
2534 descriptive names. This combination of efficiency and descriptive power
2535 makes them ideal for use as discrete data.
2539 @subsection Symbols as Lookup Keys
2541 Given their efficiency and descriptive power, it is natural to use
2542 symbols as the keys in an association list or hash table.
2544 To illustrate this, consider a more structured representation of the car
2545 properties example from the preceding subsection. Rather than
2546 mixing all the properties up together in a flat list, we could use an
2547 association list like this:
2550 (define car1-properties '((colour . red)
2551 (transmission . manual)
2553 (steering . power-assisted)))
2556 Notice how this structure is more explicit and extensible than the flat
2557 list. For example it makes clear that @code{manual} refers to the
2558 transmission rather than, say, the windows or the locking of the car.
2559 It also allows further properties to use the same symbols among their
2560 possible values without becoming ambiguous:
2563 (define car1-properties '((colour . red)
2564 (transmission . manual)
2566 (steering . power-assisted)
2568 (locking . manual)))
2571 With a representation like this, it is easy to use the efficient
2572 @code{assq-XXX} family of procedures (@pxref{Association Lists}) to
2573 extract or change individual pieces of information:
2576 (assq-ref car1-properties 'fuel) @result{} unleaded
2577 (assq-ref car1-properties 'transmission) @result{} manual
2579 (assq-set! car1-properties 'seat-colour 'black)
2582 (transmission . manual)
2584 (steering . power-assisted)
2585 (seat-colour . black)
2586 (locking . manual)))
2589 Hash tables also have keys, and exactly the same arguments apply to the
2590 use of symbols in hash tables as in association lists. The hash value
2591 that Guile uses to decide where to add a symbol-keyed entry to a hash
2592 table can be obtained by calling the @code{symbol-hash} procedure:
2594 @deffn {Scheme Procedure} symbol-hash symbol
2595 @deffnx {C Function} scm_symbol_hash (symbol)
2596 Return a hash value for @var{symbol}.
2599 See @ref{Hash Tables} for information about hash tables in general, and
2600 for why you might choose to use a hash table rather than an association
2604 @node Symbol Variables
2605 @subsection Symbols as Denoting Variables
2607 When an unquoted symbol in a Scheme program is evaluated, it is
2608 interpreted as a variable reference, and the result of the evaluation is
2609 the appropriate variable's value.
2611 For example, when the expression @code{(string-length "abcd")} is read
2612 and evaluated, the sequence of characters @code{string-length} is read
2613 as the symbol whose name is "string-length". This symbol is associated
2614 with a variable whose value is the procedure that implements string
2615 length calculation. Therefore evaluation of the @code{string-length}
2616 symbol results in that procedure.
2618 The details of the connection between an unquoted symbol and the
2619 variable to which it refers are explained elsewhere. See @ref{Binding
2620 Constructs}, for how associations between symbols and variables are
2621 created, and @ref{Modules}, for how those associations are affected by
2622 Guile's module system.
2625 @node Symbol Primitives
2626 @subsection Operations Related to Symbols
2628 Given any Scheme value, you can determine whether it is a symbol using
2629 the @code{symbol?} primitive:
2632 @deffn {Scheme Procedure} symbol? obj
2633 @deffnx {C Function} scm_symbol_p (obj)
2634 Return @code{#t} if @var{obj} is a symbol, otherwise return
2638 Once you know that you have a symbol, you can obtain its name as a
2639 string by calling @code{symbol->string}. Note that Guile differs by
2640 default from R5RS on the details of @code{symbol->string} as regards
2643 @rnindex symbol->string
2644 @deffn {Scheme Procedure} symbol->string s
2645 @deffnx {C Function} scm_symbol_to_string (s)
2646 Return the name of symbol @var{s} as a string. By default, Guile reads
2647 symbols case-sensitively, so the string returned will have the same case
2648 variation as the sequence of characters that caused @var{s} to be
2651 If Guile is set to read symbols case-insensitively (as specified by
2652 R5RS), and @var{s} comes into being as part of a literal expression
2653 (@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
2654 by a call to the @code{read} or @code{string-ci->symbol} procedures,
2655 Guile converts any alphabetic characters in the symbol's name to
2656 lower case before creating the symbol object, so the string returned
2657 here will be in lower case.
2659 If @var{s} was created by @code{string->symbol}, the case of characters
2660 in the string returned will be the same as that in the string that was
2661 passed to @code{string->symbol}, regardless of Guile's case-sensitivity
2662 setting at the time @var{s} was created.
2664 It is an error to apply mutation procedures like @code{string-set!} to
2665 strings returned by this procedure.
2668 Most symbols are created by writing them literally in code. However it
2669 is also possible to create symbols programmatically using the following
2670 @code{string->symbol} and @code{string-ci->symbol} procedures:
2672 @rnindex string->symbol
2673 @deffn {Scheme Procedure} string->symbol string
2674 @deffnx {C Function} scm_string_to_symbol (string)
2675 Return the symbol whose name is @var{string}. This procedure can create
2676 symbols with names containing special characters or letters in the
2677 non-standard case, but it is usually a bad idea to create such symbols
2678 because in some implementations of Scheme they cannot be read as
2682 @deffn {Scheme Procedure} string-ci->symbol str
2683 @deffnx {C Function} scm_string_ci_to_symbol (str)
2684 Return the symbol whose name is @var{str}. If Guile is currently
2685 reading symbols case-insensitively, @var{str} is converted to lowercase
2686 before the returned symbol is looked up or created.
2689 The following examples illustrate Guile's detailed behaviour as regards
2690 the case-sensitivity of symbols:
2693 (read-enable 'case-insensitive) ; R5RS compliant behaviour
2695 (symbol->string 'flying-fish) @result{} "flying-fish"
2696 (symbol->string 'Martin) @result{} "martin"
2698 (string->symbol "Malvina")) @result{} "Malvina"
2700 (eq? 'mISSISSIppi 'mississippi) @result{} #t
2701 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
2702 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
2704 (string->symbol (symbol->string 'LolliPop))) @result{} #t
2705 (string=? "K. Harper, M.D."
2707 (string->symbol "K. Harper, M.D."))) @result{} #t
2709 (read-disable 'case-insensitive) ; Guile default behaviour
2711 (symbol->string 'flying-fish) @result{} "flying-fish"
2712 (symbol->string 'Martin) @result{} "Martin"
2714 (string->symbol "Malvina")) @result{} "Malvina"
2716 (eq? 'mISSISSIppi 'mississippi) @result{} #f
2717 (string->symbol "mISSISSIppi") @result{} mISSISSIppi
2718 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
2720 (string->symbol (symbol->string 'LolliPop))) @result{} #t
2721 (string=? "K. Harper, M.D."
2723 (string->symbol "K. Harper, M.D."))) @result{} #t
2726 From C, there are lower level functions that construct a Scheme symbol
2727 from a null terminated C string or from a sequence of bytes whose length
2728 is specified explicitly.
2730 @deffn {C Function} scm_str2symbol (const char * name)
2731 @deffnx {C Function} scm_mem2symbol (const char * name, size_t len)
2732 Construct and return a Scheme symbol whose name is specified by
2733 @var{name}. For @code{scm_str2symbol} @var{name} must be null
2734 terminated; For @code{scm_mem2symbol} the length of @var{name} is
2735 specified explicitly by @var{len}.
2738 Finally, some applications, especially those that generate new Scheme
2739 code dynamically, need to generate symbols for use in the generated
2740 code. The @code{gensym} primitive meets this need:
2742 @deffn {Scheme Procedure} gensym [prefix]
2743 @deffnx {C Function} scm_gensym (prefix)
2744 Create a new symbol with a name constructed from a prefix and a counter
2745 value. The string @var{prefix} can be specified as an optional
2746 argument. Default prefix is @samp{ g}. The counter is increased by 1
2747 at each call. There is no provision for resetting the counter.
2750 The symbols generated by @code{gensym} are @emph{likely} to be unique,
2751 since their names begin with a space and it is only otherwise possible
2752 to generate such symbols if a programmer goes out of their way to do
2753 so. The 1.8 release of Guile will include a way of creating
2754 symbols that are @emph{guaranteed} to be unique.
2758 @subsection Function Slots and Property Lists
2760 In traditional Lisp dialects, symbols are often understood as having
2761 three kinds of value at once:
2765 a @dfn{variable} value, which is used when the symbol appears in
2766 code in a variable reference context
2769 a @dfn{function} value, which is used when the symbol appears in
2770 code in a function name position (i.e. as the first element in an
2774 a @dfn{property list} value, which is used when the symbol is given as
2775 the first argument to Lisp's @code{put} or @code{get} functions.
2778 Although Scheme (as one of its simplifications with respect to Lisp)
2779 does away with the distinction between variable and function namespaces,
2780 Guile currently retains some elements of the traditional structure in
2781 case they turn out to be useful when implementing translators for other
2782 languages, in particular Emacs Lisp.
2784 Specifically, Guile symbols have two extra slots. for a symbol's
2785 property list, and for its ``function value.'' The following procedures
2786 are provided to access these slots.
2788 @deffn {Scheme Procedure} symbol-fref symbol
2789 @deffnx {C Function} scm_symbol_fref (symbol)
2790 Return the contents of @var{symbol}'s @dfn{function slot}.
2793 @deffn {Scheme Procedure} symbol-fset! symbol value
2794 @deffnx {C Function} scm_symbol_fset_x (symbol, value)
2795 Set the contents of @var{symbol}'s function slot to @var{value}.
2798 @deffn {Scheme Procedure} symbol-pref symbol
2799 @deffnx {C Function} scm_symbol_pref (symbol)
2800 Return the @dfn{property list} currently associated with @var{symbol}.
2803 @deffn {Scheme Procedure} symbol-pset! symbol value
2804 @deffnx {C Function} scm_symbol_pset_x (symbol, value)
2805 Set @var{symbol}'s property list to @var{value}.
2808 @deffn {Scheme Procedure} symbol-property sym prop
2809 From @var{sym}'s property list, return the value for property
2810 @var{prop}. The assumption is that @var{sym}'s property list is an
2811 association list whose keys are distinguished from each other using
2812 @code{equal?}; @var{prop} should be one of the keys in that list. If
2813 the property list has no entry for @var{prop}, @code{symbol-property}
2817 @deffn {Scheme Procedure} set-symbol-property! sym prop val
2818 In @var{sym}'s property list, set the value for property @var{prop} to
2819 @var{val}, or add a new entry for @var{prop}, with value @var{val}, if
2820 none already exists. For the structure of the property list, see
2821 @code{symbol-property}.
2824 @deffn {Scheme Procedure} symbol-property-remove! sym prop
2825 From @var{sym}'s property list, remove the entry for property
2826 @var{prop}, if there is one. For the structure of the property list,
2827 see @code{symbol-property}.
2830 Support for these extra slots may be removed in a future release, and it
2831 is probably better to avoid using them. (In release 1.6, Guile itself
2832 uses the property list slot sparingly, and the function slot not at
2833 all.) For a more modern and Schemely approach to properties, see
2834 @ref{Object Properties}.
2837 @node Symbol Read Syntax
2838 @subsection Extended Read Syntax for Symbols
2840 The read syntax for a symbol is a sequence of letters, digits, and
2841 @dfn{extended alphabetic characters}, beginning with a character that
2842 cannot begin a number. In addition, the special cases of @code{+},
2843 @code{-}, and @code{...} are read as symbols even though numbers can
2844 begin with @code{+}, @code{-} or @code{.}.
2846 Extended alphabetic characters may be used within identifiers as if
2847 they were letters. The set of extended alphabetic characters is:
2850 ! $ % & * + - . / : < = > ? @@ ^ _ ~
2853 In addition to the standard read syntax defined above (which is taken
2854 from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
2855 Scheme})), Guile provides an extended symbol read syntax that allows the
2856 inclusion of unusual characters such as space characters, newlines and
2857 parentheses. If (for whatever reason) you need to write a symbol
2858 containing characters not mentioned above, you can do so as follows.
2862 Begin the symbol with the characters @code{#@{},
2865 write the characters of the symbol and
2868 finish the symbol with the characters @code{@}#}.
2871 Here are a few examples of this form of read syntax. The first symbol
2872 needs to use extended syntax because it contains a space character, the
2873 second because it contains a line break, and the last because it looks
2885 Although Guile provides this extended read syntax for symbols,
2886 widespread usage of it is discouraged because it is not portable and not
2890 @node Symbol Uninterned
2891 @subsection Uninterned Symbols
2893 What makes symbols useful is that they are automatically kept unique.
2894 There are no two symbols that are distinct objects but have the same
2895 name. But of course, there is no rule without exception. In addition
2896 to the normal symbols that have been discussed up to now, you can also
2897 create special @dfn{uninterned} symbols that behave slightly
2900 To understand what is different about them and why they might be useful,
2901 we look at how normal symbols are actually kept unique.
2903 Whenever Guile wants to find the symbol with a specific name, for
2904 example during @code{read} or when executing @code{string->symbol}, it
2905 first looks into a table of all existing symbols to find out whether a
2906 symbol with the given name already exists. When this is the case, Guile
2907 just returns that symbol. When not, a new symbol with the name is
2908 created and entered into the table so that it can be found later.
2910 Sometimes you might want to create a symbol that is guaranteed `fresh',
2911 i.e. a symbol that did not exist previously. You might also want to
2912 somehow guarantee that no one else will ever unintentionally stumble
2913 across your symbol in the future. These properties of a symbol are
2914 often needed when generating code during macro expansion. When
2915 introducing new temporary variables, you want to guarantee that they
2916 don't conflict with variables in other people's code.
2918 The simplest way to arrange for this is to create a new symbol but
2919 not enter it into the global table of all symbols. That way, no one
2920 will ever get access to your symbol by chance. Symbols that are not in
2921 the table are called @dfn{uninterned}. Of course, symbols that
2922 @emph{are} in the table are called @dfn{interned}.
2924 You create new uninterned symbols with the function @code{make-symbol}.
2925 You can test whether a symbol is interned or not with
2926 @code{symbol-interned?}.
2928 Uninterned symbols break the rule that the name of a symbol uniquely
2929 identifies the symbol object. Because of this, they can not be written
2930 out and read back in like interned symbols. Currently, Guile has no
2931 support for reading uninterned symbols. Note that the function
2932 @code{gensym} does not return uninterned symbols for this reason.
2934 @deffn {Scheme Procedure} make-symbol name
2935 @deffnx {C Function} scm_make_symbol (name)
2936 Return a new uninterned symbol with the name @var{name}. The returned
2937 symbol is guaranteed to be unique and future calls to
2938 @code{string->symbol} will not return it.
2941 @deffn {Scheme Procedure} symbol-interned? symbol
2942 @deffnx {C Function} scm_symbol_interned_p (symbol)
2943 Return @code{#t} if @var{symbol} is interned, otherwise return
2950 (define foo-1 (string->symbol "foo"))
2951 (define foo-2 (string->symbol "foo"))
2952 (define foo-3 (make-symbol "foo"))
2953 (define foo-4 (make-symbol "foo"))
2957 ; Two interned symbols with the same name are the same object,
2961 ; but a call to make-symbol with the same name returns a
2966 ; A call to make-symbol always returns a new object, even for
2970 @result{} #<uninterned-symbol foo 8085290>
2971 ; Uninterned symbols print differently from interned symbols,
2975 ; but they are still symbols,
2977 (symbol-interned? foo-3)
2979 ; just not interned.
2987 Keywords are self-evaluating objects with a convenient read syntax that
2988 makes them easy to type.
2990 Guile's keyword support conforms to R5RS, and adds a (switchable) read
2991 syntax extension to permit keywords to begin with @code{:} as well as
2995 * Why Use Keywords?:: Motivation for keyword usage.
2996 * Coding With Keywords:: How to use keywords.
2997 * Keyword Read Syntax:: Read syntax for keywords.
2998 * Keyword Procedures:: Procedures for dealing with keywords.
2999 * Keyword Primitives:: The underlying primitive procedures.
3002 @node Why Use Keywords?
3003 @subsection Why Use Keywords?
3005 Keywords are useful in contexts where a program or procedure wants to be
3006 able to accept a large number of optional arguments without making its
3007 interface unmanageable.
3009 To illustrate this, consider a hypothetical @code{make-window}
3010 procedure, which creates a new window on the screen for drawing into
3011 using some graphical toolkit. There are many parameters that the caller
3012 might like to specify, but which could also be sensibly defaulted, for
3017 color depth -- Default: the color depth for the screen
3020 background color -- Default: white
3023 width -- Default: 600
3026 height -- Default: 400
3029 If @code{make-window} did not use keywords, the caller would have to
3030 pass in a value for each possible argument, remembering the correct
3031 argument order and using a special value to indicate the default value
3035 (make-window 'default ;; Color depth
3036 'default ;; Background color
3039 @dots{}) ;; More make-window arguments
3042 With keywords, on the other hand, defaulted arguments are omitted, and
3043 non-default arguments are clearly tagged by the appropriate keyword. As
3044 a result, the invocation becomes much clearer:
3047 (make-window #:width 800 #:height 100)
3050 On the other hand, for a simpler procedure with few arguments, the use
3051 of keywords would be a hindrance rather than a help. The primitive
3052 procedure @code{cons}, for example, would not be improved if it had to
3056 (cons #:car x #:cdr y)
3059 So the decision whether to use keywords or not is purely pragmatic: use
3060 them if they will clarify the procedure invocation at point of call.
3062 @node Coding With Keywords
3063 @subsection Coding With Keywords
3065 If a procedure wants to support keywords, it should take a rest argument
3066 and then use whatever means is convenient to extract keywords and their
3067 corresponding arguments from the contents of that rest argument.
3069 The following example illustrates the principle: the code for
3070 @code{make-window} uses a helper procedure called
3071 @code{get-keyword-value} to extract individual keyword arguments from
3075 (define (get-keyword-value args keyword default)
3076 (let ((kv (memq keyword args)))
3077 (if (and kv (>= (length kv) 2))
3081 (define (make-window . args)
3082 (let ((depth (get-keyword-value args #:depth screen-depth))
3083 (bg (get-keyword-value args #:bg "white"))
3084 (width (get-keyword-value args #:width 800))
3085 (height (get-keyword-value args #:height 100))
3090 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
3091 optargs)} module provides a set of powerful macros that you can use to
3092 implement keyword-supporting procedures like this:
3095 (use-modules (ice-9 optargs))
3097 (define (make-window . args)
3098 (let-keywords args #f ((depth screen-depth)
3106 Or, even more economically, like this:
3109 (use-modules (ice-9 optargs))
3111 (define* (make-window #:key (depth screen-depth)
3118 For further details on @code{let-keywords}, @code{define*} and other
3119 facilities provided by the @code{(ice-9 optargs)} module, see
3120 @ref{Optional Arguments}.
3123 @node Keyword Read Syntax
3124 @subsection Keyword Read Syntax
3126 Guile, by default, only recognizes the keyword syntax specified by R5RS.
3127 A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
3128 as a Scheme symbol (@pxref{Symbol Read Syntax}), is the external
3129 representation of the keyword named @code{NAME}. Keyword objects print
3130 using this syntax as well, so values containing keyword objects can be
3131 read back into Guile. When used in an expression, keywords are
3132 self-quoting objects.
3134 If the @code{keyword} read option is set to @code{'prefix}, Guile also
3135 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
3136 of the form @code{:NAME} are read as symbols, as required by R5RS.
3138 To enable and disable the alternative non-R5RS keyword syntax, you use
3139 the @code{read-set!} procedure documented in @ref{User level options
3140 interfaces} and @ref{Reader options}.
3143 (read-set! keywords 'prefix)
3153 (read-set! keywords #f)
3161 ERROR: In expression :type:
3162 ERROR: Unbound variable: :type
3163 ABORT: (unbound-variable)
3166 @node Keyword Procedures
3167 @subsection Keyword Procedures
3169 The following procedures can be used for converting symbols to keywords
3172 @deffn {Scheme Procedure} symbol->keyword sym
3173 Return a keyword with the same characters as in @var{sym}.
3176 @deffn {Scheme Procedure} keyword->symbol kw
3177 Return a symbol with the same characters as in @var{kw}.
3181 @node Keyword Primitives
3182 @subsection Keyword Primitives
3184 Internally, a keyword is implemented as something like a tagged symbol,
3185 where the tag identifies the keyword as being self-evaluating, and the
3186 symbol, known as the keyword's @dfn{dash symbol} has the same name as
3187 the keyword name but prefixed by a single dash. For example, the
3188 keyword @code{#:name} has the corresponding dash symbol @code{-name}.
3190 Most keyword objects are constructed automatically by the reader when it
3191 reads a token beginning with @code{#:}. However, if you need to
3192 construct a keyword object programmatically, you can do so by calling
3193 @code{make-keyword-from-dash-symbol} with the corresponding dash symbol
3194 (as the reader does). The dash symbol for a keyword object can be
3195 retrieved using the @code{keyword-dash-symbol} procedure.
3197 @deffn {Scheme Procedure} make-keyword-from-dash-symbol symbol
3198 @deffnx {C Function} scm_make_keyword_from_dash_symbol (symbol)
3199 Make a keyword object from a @var{symbol} that starts with a dash.
3203 (make-keyword-from-dash-symbol '-foo)
3208 @deffn {Scheme Procedure} keyword? obj
3209 @deffnx {C Function} scm_keyword_p (obj)
3210 Return @code{#t} if the argument @var{obj} is a keyword, else
3214 @deffn {Scheme Procedure} keyword-dash-symbol keyword
3215 @deffnx {C Function} scm_keyword_dash_symbol (keyword)
3216 Return the dash symbol for @var{keyword}.
3217 This is the inverse of @code{make-keyword-from-dash-symbol}.
3221 (keyword-dash-symbol #:foo)
3226 @deftypefn {C Function} SCM scm_c_make_keyword (char *@var{str})
3227 Make a keyword object from a string. For example,
3230 scm_c_make_keyword ("foo")
3234 @c FIXME: What can be said about the string argument? Currently it's
3235 @c not used after creation, but should that be documented?
3240 @section ``Functionality-Centric'' Data Types
3242 Procedures and macros are documented in their own chapter: see
3243 @ref{Procedures and Macros}.
3245 Variable objects are documented as part of the description of Guile's
3246 module system: see @ref{Variables}.
3248 Asyncs, dynamic roots and fluids are described in the chapter on
3249 scheduling: see @ref{Scheduling}.
3251 Hooks are documented in the chapter on general utility functions: see
3254 Ports are described in the chapter on I/O: see @ref{Input and Output}.
3258 @c TeX-master: "guile.texi"