3 @chapter Data Types for Generic Use
5 This chapter describes all the data types that Guile provides for
8 One of the great strengths of Scheme is that there is no straightforward
9 distinction between ``data'' and ``functionality''. For example,
10 Guile's support for dynamic linking could be described
14 either in a ``data-centric'' way, as the behaviour and properties of the
15 ``dynamically linked object'' data type, and the operations that may be
16 applied to instances of this type
19 or in a ``functionality-centric'' way, as the set of procedures that
20 constitute Guile's support for dynamic linking, in the context of the
24 The contents of this chapter are, therefore, a matter of judgement. By
25 ``generic use'', we mean to select those data types whose typical use as
26 @emph{data} in a wide variety of programming contexts is more important
27 than their use in the implementation of a particular piece of
34 The table of contents for this chapter
37 The following table of contents
39 shows the data types that are documented in this chapter. The final
40 section of this chapter lists all the core Guile data types that are not
41 documented here, and provides links to the ``functionality-centric''
42 sections of this manual that cover them.
45 * Booleans:: True/false values.
46 * Numbers:: Numerical data types.
47 * Characters:: New character names.
48 * Strings:: Special things about strings.
49 * Regular Expressions:: Pattern matching and substitution.
50 * Symbols and Variables:: Manipulating the Scheme symbol table.
51 * Keywords:: Self-quoting, customizable display keywords.
52 * Pairs:: Scheme's basic building block.
53 * Lists:: Special list functions supported by Guile.
54 * Vectors:: One-dimensional arrays of Scheme objects.
57 * Arrays:: Arrays of values.
58 * Association Lists and Hash Tables:: Dictionary data types.
59 * Hooks:: User-customizable event lists.
60 * Other Data Types:: Data types that are documented elsewhere.
68 The two boolean values are @code{#t} for true and @code{#f} for false.
70 Boolean values are returned by predicate procedures, such as the general
71 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
72 (@pxref{Equality}) and numerical and string comparison operators like
73 @code{string=?} (@pxref{String Comparison}) and @code{<=}
85 (equal? "house" "houses")
94 In test condition contexts like @code{if} and @code{cond} (@pxref{if
95 cond case}), where a group of subexpressions will be evaluated only if a
96 @var{condition} expression evaluates to ``true'', ``true'' means any
97 value at all except @code{#f}.
113 A result of this asymmetry is that typical Scheme source code more often
114 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
115 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
116 not necessary to represent an @code{if} or @code{cond} true value.
118 It is important to note that @code{#f} is @strong{not} equivalent to any
119 other Scheme value. In particular, @code{#f} is not the same as the
120 number 0 (like in C and C++), and not the same as the ``empty list''
121 (like in some Lisp dialects).
123 The @code{not} procedure returns the boolean inverse of its argument:
126 @deffn primitive not x
127 Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
130 The @code{boolean?} procedure is a predicate that returns @code{#t} if
131 its argument is one of the boolean values, otherwise @code{#f}.
134 @deffn primitive boolean? obj
135 Return @code{#t} iff @var{obj} is either @code{#t} or @code{#f}.
140 @section Numerical data types
143 Guile supports a rich ``tower'' of numerical types --- integer,
144 rational, real and complex --- and provides an extensive set of
145 mathematical and scientific functions for operating on numerical
146 data. This section of the manual documents those types and functions.
148 You may also find it illuminating to read R5RS's presentation of numbers
149 in Scheme, which is particularly clear and accessible: see
150 @xref{Numbers,,,r5rs}.
153 * Numerical Tower:: Scheme's numerical "tower".
154 * Integers:: Whole numbers.
155 * Reals and Rationals:: Real and rational numbers.
156 * Complex Numbers:: Complex numbers.
157 * Exactness:: Exactness and inexactness.
158 * Number Syntax:: Read syntax for numerical data.
159 * Integer Operations:: Operations on integer values.
160 * Comparison:: Comparison predicates.
161 * Conversion:: Converting numbers to and from strings.
162 * Complex:: Complex number operations.
163 * Arithmetic:: Arithmetic functions.
164 * Scientific:: Scientific functions.
165 * Primitive Numerics:: Primitive numeric functions.
166 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
167 * Random:: Random number generation.
171 @node Numerical Tower
172 @subsection Scheme's Numerical ``Tower''
175 Scheme's numerical ``tower'' consists of the following categories of
180 integers (whole numbers)
183 rationals (the set of numbers that can be expressed as P/Q where P and Q
187 real numbers (the set of numbers that describes all possible positions
188 along a one dimensional line)
191 complex numbers (the set of numbers that describes all possible
192 positions in a two dimensional space)
195 It is called a tower because each category ``sits on'' the one that
196 follows it, in the sense that every integer is also a rational, every
197 rational is also real, and every real number is also a complex number
198 (but with zero imaginary part).
200 Of these, Guile implements integers, reals and complex numbers as
201 distinct types. Rationals are implemented as regards the read syntax
202 for rational numbers that is specified by R5RS, but are immediately
203 converted by Guile to the corresponding real number.
205 The @code{number?} predicate may be applied to any Scheme value to
206 discover whether the value is any of the supported numerical types.
208 @deffn primitive number? obj
209 Return @code{#t} if @var{obj} is any kind of number, @code{#f} else.
219 (number? "hello there!")
223 (define pi 3.141592654)
229 The next few subsections document each of Guile's numerical data types
235 @tpindex Integer numbers
239 Integers are whole numbers, that is numbers with no fractional part,
240 such as 2, 83 and -3789.
242 Integers in Guile can be arbitrarily big, as shown by the following
246 (define (factorial n)
247 (let loop ((n n) (product 1))
250 (loop (- n 1) (* product n)))))
262 -119622220865480194561963161495657715064383733760000000000
265 Readers whose background is in programming languages where integers are
266 limited by the need to fit into just 4 or 8 bytes of memory may find
267 this surprising, or suspect that Guile's representation of integers is
268 inefficient. In fact, Guile achieves a near optimal balance of
269 convenience and efficiency by using the host computer's native
270 representation of integers where possible, and a more general
271 representation where the required number does not fit in the native
272 form. Conversion between these two representations is automatic and
273 completely invisible to the Scheme level programmer.
275 @c REFFIXME Maybe point here to discussion of handling immediates/bignums
276 @c on the C level, where the conversion is not so automatic - NJ
278 @deffn primitive integer? x
279 Return @code{#t} if @var{x} is an integer number, @code{#f} else.
293 @node Reals and Rationals
294 @subsection Real and Rational Numbers
295 @tpindex Real numbers
296 @tpindex Rational numbers
301 Mathematically, the real numbers are the set of numbers that describe
302 all possible points along a continuous, infinite, one-dimensional line.
303 The rational numbers are the set of all numbers that can be written as
304 fractions P/Q, where P and Q are integers. All rational numbers are
305 also real, but there are real numbers that are not rational, for example
306 the square root of 2, and pi.
308 Guile represents both real and rational numbers approximately using a
309 floating point encoding with limited precision. Even though the actual
310 encoding is in binary, it may be helpful to think of it as a decimal
311 number with a limited number of significant figures and a decimal point
312 somewhere, since this corresponds to the standard notation for non-whole
313 numbers. For example:
318 -5648394822220000000000.0
322 The limited precision of Guile's encoding means that any ``real'' number
323 in Guile can be written in a rational form, by multiplying and then dividing
324 by sufficient powers of 10 (or in fact, 2). For example,
325 @code{-0.00000142857931198} is the same as @code{142857931198} divided by
326 @code{100000000000000000}. In Guile's current incarnation, therefore,
327 the @code{rational?} and @code{real?} predicates are equivalent.
329 Another aspect of this equivalence is that Guile currently does not
330 preserve the exactness that is possible with rational arithmetic.
331 If such exactness is needed, it is of course possible to implement
332 exact rational arithmetic at the Scheme level using Guile's arbitrary
335 A planned future revision of Guile's numerical tower will make it
336 possible to implement exact representations and arithmetic for both
337 rational numbers and real irrational numbers such as square roots,
338 and in such a way that the new kinds of number integrate seamlessly
339 with those that are already implemented.
341 @deffn primitive real? obj
342 Return @code{#t} if @var{obj} is a real number, @code{#f} else.
343 Note that the sets of integer and rational values form subsets
344 of the set of real numbers, so the predicate will also be fulfilled
345 if @var{obj} is an integer number or a rational number.
348 @deffn primitive rational? x
349 Return @code{#t} if @var{x} is a rational number, @code{#f}
350 else. Note that the set of integer values forms a subset of
351 the set of rational numbers, i. e. the predicate will also be
352 fulfilled if @var{x} is an integer number. Real numbers
353 will also satisfy this predicate, because of their limited
358 @node Complex Numbers
359 @subsection Complex Numbers
360 @tpindex Complex numbers
364 Complex numbers are the set of numbers that describe all possible points
365 in a two-dimensional space. The two coordinates of a particular point
366 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
367 the complex number that describes that point.
369 In Guile, complex numbers are written in rectangular form as the sum of
370 their real and imaginary parts, using the symbol @code{i} to indicate
383 Guile represents a complex number as a pair of numbers both of which are
384 real, so the real and imaginary parts of a complex number have the same
385 properties of inexactness and limited precision as single real numbers.
387 @deffn primitive complex? x
388 Return @code{#t} if @var{x} is a complex number, @code{#f}
389 else. Note that the sets of real, rational and integer
390 values form subsets of the set of complex numbers, i. e. the
391 predicate will also be fulfilled if @var{x} is a real,
392 rational or integer number.
397 @subsection Exact and Inexact Numbers
398 @tpindex Exact numbers
399 @tpindex Inexact numbers
403 @rnindex exact->inexact
404 @rnindex inexact->exact
406 R5RS requires that a calculation involving inexact numbers always
407 produces an inexact result. To meet this requirement, Guile
408 distinguishes between an exact integer value such as @code{5} and the
409 corresponding inexact real value which, to the limited precision
410 available, has no fractional part, and is printed as @code{5.0}. Guile
411 will only convert the latter value to the former when forced to do so by
412 an invocation of the @code{inexact->exact} procedure.
414 @deffn primitive exact? x
415 Return @code{#t} if @var{x} is an exact number, @code{#f}
419 @deffn primitive inexact? x
420 Return @code{#t} if @var{x} is an inexact number, @code{#f}
424 @deffn primitive inexact->exact z
425 Return an exact number that is numerically closest to @var{z}.
428 @c begin (texi-doc-string "guile" "exact->inexact")
429 @deffn primitive exact->inexact z
430 Convert the number @var{z} to its inexact representation.
435 @subsection Read Syntax for Numerical Data
437 The read syntax for integers is a string of digits, optionally
438 preceded by a minus or plus character, a code indicating the
439 base in which the integer is encoded, and a code indicating whether
440 the number is exact or inexact. The supported base codes are:
444 @code{#b}, @code{#B} --- the integer is written in binary (base 2)
447 @code{#o}, @code{#O} --- the integer is written in octal (base 8)
450 @code{#d}, @code{#D} --- the integer is written in decimal (base 10)
453 @code{#x}, @code{#X} --- the integer is written in hexadecimal (base 16).
456 If the base code is omitted, the integer is assumed to be decimal. The
457 following examples show how these base codes are used.
481 The codes for indicating exactness (which can, incidentally, be applied
482 to all numerical values) are:
486 @code{#e}, @code{#E} --- the number is exact
489 @code{#i}, @code{#I} --- the number is inexact.
492 If the exactness indicator is omitted, the integer is assumed to be exact,
493 since Guile's internal representation for integers is always exact.
494 Real numbers have limited precision similar to the precision of the
495 @code{double} type in C. A consequence of the limited precision is that
496 all real numbers in Guile are also rational, since any number R with a
497 limited number of decimal places, say N, can be made into an integer by
501 @node Integer Operations
502 @subsection Operations on Integer Values
511 @deffn primitive odd? n
512 Return @code{#t} if @var{n} is an odd number, @code{#f}
516 @deffn primitive even? n
517 Return @code{#t} if @var{n} is an even number, @code{#f}
521 @c begin (texi-doc-string "guile" "quotient")
522 @deffn primitive quotient
523 Return the quotient of the numbers @var{x} and @var{y}.
526 @c begin (texi-doc-string "guile" "remainder")
527 @deffn primitive remainder
528 Return the remainder of the numbers @var{x} and @var{y}.
530 (remainder 13 4) @result{} 1
531 (remainder -13 4) @result{} -1
535 @c begin (texi-doc-string "guile" "modulo")
536 @deffn primitive modulo
537 Return the modulo of the numbers @var{x} and @var{y}.
539 (modulo 13 4) @result{} 1
540 (modulo -13 4) @result{} 3
544 @c begin (texi-doc-string "guile" "gcd")
546 Return the greatest common divisor of all arguments.
547 If called without arguments, 0 is returned.
550 @c begin (texi-doc-string "guile" "lcm")
552 Return the least common multiple of the arguments.
553 If called without arguments, 1 is returned.
558 @subsection Comparison Predicates
563 @c begin (texi-doc-string "guile" "=")
565 Return @code{#t} if all parameters are numerically equal.
568 @c begin (texi-doc-string "guile" "<")
570 Return @code{#t} if the list of parameters is monotonically
574 @c begin (texi-doc-string "guile" ">")
576 Return @code{#t} if the list of parameters is monotonically
580 @c begin (texi-doc-string "guile" "<=")
582 Return @code{#t} if the list of parameters is monotonically
586 @c begin (texi-doc-string "guile" ">=")
588 Return @code{#t} if the list of parameters is monotonically
592 @c begin (texi-doc-string "guile" "zero?")
593 @deffn primitive zero?
594 Return @code{#t} if @var{z} is an exact or inexact number equal to
598 @c begin (texi-doc-string "guile" "positive?")
599 @deffn primitive positive?
600 Return @code{#t} if @var{x} is an exact or inexact number greater than
604 @c begin (texi-doc-string "guile" "negative?")
605 @deffn primitive negative?
606 Return @code{#t} if @var{x} is an exact or inexact number less than
612 @subsection Converting Numbers To and From Strings
613 @rnindex number->string
614 @rnindex string->number
616 @deffn primitive number->string n [radix]
617 Return a string holding the external representation of the
618 number @var{n} in the given @var{radix}. If @var{n} is
619 inexact, a radix of 10 will be used.
622 @deffn primitive string->number string [radix]
623 Return a number of the maximally precise representation
624 expressed by the given @var{string}. @var{radix} must be an
625 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
626 is a default radix that may be overridden by an explicit radix
627 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
628 supplied, then the default radix is 10. If string is not a
629 syntactically valid notation for a number, then
630 @code{string->number} returns @code{#f}.
635 @subsection Complex Number Operations
636 @rnindex make-rectangular
643 @deffn primitive make-rectangular real imaginary
644 Return a complex number constructed of the given @var{real} and
645 @var{imaginary} parts.
648 @deffn primitive make-polar x y
649 Return the complex number @var{x} * e^(i * @var{y}).
652 @c begin (texi-doc-string "guile" "real-part")
653 @deffn primitive real-part
654 Return the real part of the number @var{z}.
657 @c begin (texi-doc-string "guile" "imag-part")
658 @deffn primitive imag-part
659 Return the imaginary part of the number @var{z}.
662 @c begin (texi-doc-string "guile" "magnitude")
663 @deffn primitive magnitude
664 Return the magnitude of the number @var{z}. This is the same as
665 @code{abs} for real arguments, but also allows complex numbers.
668 @c begin (texi-doc-string "guile" "angle")
669 @deffn primitive angle
670 Return the angle of the complex number @var{z}.
675 @subsection Arithmetic Functions
688 @c begin (texi-doc-string "guile" "+")
689 @deffn primitive + z1 @dots{}
690 Return the sum of all parameter values. Return 0 if called without any
694 @c begin (texi-doc-string "guile" "-")
695 @deffn primitive - z1 z2 @dots{}
696 If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
697 the sum of all but the first argument are subtracted from the first
701 @c begin (texi-doc-string "guile" "*")
702 @deffn primitive * z1 @dots{}
703 Return the product of all arguments. If called without arguments, 1 is
707 @c begin (texi-doc-string "guile" "/")
708 @deffn primitive / z1 z2 @dots{}
709 Divide the first argument by the product of the remaining arguments. If
710 called with one argument @var{z1}, 1/@var{z1} is returned.
713 @c begin (texi-doc-string "guile" "abs")
714 @deffn primitive abs x
715 Return the absolute value of @var{x}.
718 @c begin (texi-doc-string "guile" "max")
719 @deffn primitive max x1 x2 @dots{}
720 Return the maximum of all parameter values.
723 @c begin (texi-doc-string "guile" "min")
724 @deffn primitive min x1 x2 @dots{}
725 Return the minium of all parameter values.
728 @c begin (texi-doc-string "guile" "truncate")
729 @deffn primitive truncate
730 Round the inexact number @var{x} towards zero.
733 @c begin (texi-doc-string "guile" "round")
734 @deffn primitive round x
735 Round the inexact number @var{x} towards zero.
738 @c begin (texi-doc-string "guile" "floor")
739 @deffn primitive floor x
740 Round the number @var{x} towards minus infinity.
743 @c begin (texi-doc-string "guile" "ceiling")
744 @deffn primitive ceiling x
745 Round the number @var{x} towards infinity.
750 @subsection Scientific Functions
752 The following procedures accept any kind of number as arguments,
753 including complex numbers.
756 @c begin (texi-doc-string "guile" "sqrt")
757 @deffn procedure sqrt z
758 Return the square root of @var{z}.
762 @c begin (texi-doc-string "guile" "expt")
763 @deffn procedure expt z1 z2
764 Return @var{z1} raised to the power of @var{z2}.
768 @c begin (texi-doc-string "guile" "sin")
769 @deffn procedure sin z
770 Return the sine of @var{z}.
774 @c begin (texi-doc-string "guile" "cos")
775 @deffn procedure cos z
776 Return the cosine of @var{z}.
780 @c begin (texi-doc-string "guile" "tan")
781 @deffn procedure tan z
782 Return the tangent of @var{z}.
786 @c begin (texi-doc-string "guile" "asin")
787 @deffn procedure asin z
788 Return the arcsine of @var{z}.
792 @c begin (texi-doc-string "guile" "acos")
793 @deffn procedure acos z
794 Return the arccosine of @var{z}.
798 @c begin (texi-doc-string "guile" "atan")
799 @deffn procedure atan z
800 Return the arctangent of @var{z}.
804 @c begin (texi-doc-string "guile" "exp")
805 @deffn procedure exp z
806 Return e to the power of @var{z}, where e is the base of natural
807 logarithms (2.71828@dots{}).
811 @c begin (texi-doc-string "guile" "log")
812 @deffn procedure log z
813 Return the natural logarithm of @var{z}.
816 @c begin (texi-doc-string "guile" "log10")
817 @deffn procedure log10 z
818 Return the base 10 logarithm of @var{z}.
821 @c begin (texi-doc-string "guile" "sinh")
822 @deffn procedure sinh z
823 Return the hyperbolic sine of @var{z}.
826 @c begin (texi-doc-string "guile" "cosh")
827 @deffn procedure cosh z
828 Return the hyperbolic cosine of @var{z}.
831 @c begin (texi-doc-string "guile" "tanh")
832 @deffn procedure tanh z
833 Return the hyperbolic tangent of @var{z}.
836 @c begin (texi-doc-string "guile" "asinh")
837 @deffn procedure asinh z
838 Return the hyperbolic arcsine of @var{z}.
841 @c begin (texi-doc-string "guile" "acosh")
842 @deffn procedure acosh z
843 Return the hyperbolic arccosine of @var{z}.
846 @c begin (texi-doc-string "guile" "atanh")
847 @deffn procedure atanh z
848 Return the hyperbolic arctangent of @var{z}.
852 @node Primitive Numerics
853 @subsection Primitive Numeric Functions
855 Many of Guile's numeric procedures which accept any kind of numbers as
856 arguments, including complex numbers, are implemented as Scheme
857 procedures that use the following real number-based primitives. These
858 primitives signal an error if they are called with complex arguments.
860 @c begin (texi-doc-string "guile" "$abs")
861 @deffn primitive $abs x
862 Return the absolute value of @var{x}.
865 @c begin (texi-doc-string "guile" "$sqrt")
866 @deffn primitive $sqrt x
867 Return the square root of @var{x}.
870 @deffn primitive $expt x y
871 Return @var{x} raised to the power of @var{y}. This
872 procedure does not accept complex arguments.
875 @c begin (texi-doc-string "guile" "$sin")
876 @deffn primitive $sin x
877 Return the sine of @var{x}.
880 @c begin (texi-doc-string "guile" "$cos")
881 @deffn primitive $cos x
882 Return the cosine of @var{x}.
885 @c begin (texi-doc-string "guile" "$tan")
886 @deffn primitive $tan x
887 Return the tangent of @var{x}.
890 @c begin (texi-doc-string "guile" "$asin")
891 @deffn primitive $asin x
892 Return the arcsine of @var{x}.
895 @c begin (texi-doc-string "guile" "$acos")
896 @deffn primitive $acos x
897 Return the arccosine of @var{x}.
900 @c begin (texi-doc-string "guile" "$atan")
901 @deffn primitive $atan x
902 Return the arctangent of @var{x} in the range -PI/2 to PI/2.
905 @deffn primitive $atan2 x y
906 Return the arc tangent of the two arguments @var{x} and
907 @var{y}. This is similar to calculating the arc tangent of
908 @var{x} / @var{y}, except that the signs of both arguments
909 are used to determine the quadrant of the result. This
910 procedure does not accept complex arguments.
913 @c begin (texi-doc-string "guile" "$exp")
914 @deffn primitive $exp x
915 Return e to the power of @var{x}, where e is the base of natural
916 logarithms (2.71828@dots{}).
919 @c begin (texi-doc-string "guile" "$log")
920 @deffn primitive $log x
921 Return the natural logarithm of @var{x}.
924 @c begin (texi-doc-string "guile" "$sinh")
925 @deffn primitive $sinh x
926 Return the hyperbolic sine of @var{x}.
929 @c begin (texi-doc-string "guile" "$cosh")
930 @deffn primitive $cosh x
931 Return the hyperbolic cosine of @var{x}.
934 @c begin (texi-doc-string "guile" "$tanh")
935 @deffn primitive $tanh x
936 Return the hyperbolic tangent of @var{x}.
939 @c begin (texi-doc-string "guile" "$asinh")
940 @deffn primitive $asinh x
941 Return the hyperbolic arcsine of @var{x}.
944 @c begin (texi-doc-string "guile" "$acosh")
945 @deffn primitive $acosh x
946 Return the hyperbolic arccosine of @var{x}.
949 @c begin (texi-doc-string "guile" "$atanh")
950 @deffn primitive $atanh x
951 Return the hyperbolic arctangent of @var{x}.
955 @node Bitwise Operations
956 @subsection Bitwise Operations
958 @deffn primitive logand n1 n2
959 Return the bitwise AND of the integer arguments.
962 (logand) @result{} -1
963 (logand 7) @result{} 7
964 (logand #b111 #b011 #b001) @result{} 1
968 @deffn primitive logior n1 n2
969 Return the bitwise OR of the integer arguments.
973 (logior 7) @result{} 7
974 (logior #b000 #b001 #b011) @result{} 3
978 @deffn primitive logxor n1 n2
979 Return the bitwise XOR of the integer arguments. A bit is
980 set in the result if it is set in an odd number of arguments.
983 (logxor 7) @result{} 7
984 (logxor #b000 #b001 #b011) @result{} 2
985 (logxor #b000 #b001 #b011 #b011) @result{} 1
989 @deffn primitive lognot n
990 Return the integer which is the 2s-complement of the integer
994 (number->string (lognot #b10000000) 2)
995 @result{} "-10000001"
996 (number->string (lognot #b0) 2)
1001 @deffn primitive logtest j k
1003 (logtest j k) @equiv{} (not (zero? (logand j k)))
1005 (logtest #b0100 #b1011) @result{} #f
1006 (logtest #b0100 #b0111) @result{} #t
1010 @deffn primitive logbit? index j
1012 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1014 (logbit? 0 #b1101) @result{} #t
1015 (logbit? 1 #b1101) @result{} #f
1016 (logbit? 2 #b1101) @result{} #t
1017 (logbit? 3 #b1101) @result{} #t
1018 (logbit? 4 #b1101) @result{} #f
1022 @deffn primitive ash n cnt
1023 The function ash performs an arithmetic shift left by @var{cnt}
1024 bits (or shift right, if @var{cnt} is negative). 'Arithmetic'
1025 means, that the function does not guarantee to keep the bit
1026 structure of @var{n}, but rather guarantees that the result
1027 will always be rounded towards minus infinity. Therefore, the
1028 results of ash and a corresponding bitwise shift will differ if
1029 @var{n} is negative.
1031 Formally, the function returns an integer equivalent to
1032 @code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
1035 (number->string (ash #b1 3) 2) @result{} "1000"
1036 (number->string (ash #b1010 -1) 2) @result{} "101"
1040 @deffn primitive logcount n
1041 Return the number of bits in integer @var{n}. If integer is
1042 positive, the 1-bits in its binary representation are counted.
1043 If negative, the 0-bits in its two's-complement binary
1044 representation are counted. If 0, 0 is returned.
1047 (logcount #b10101010)
1056 @deffn primitive integer-length n
1057 Return the number of bits neccessary to represent @var{n}.
1060 (integer-length #b10101010)
1064 (integer-length #b1111)
1069 @deffn primitive integer-expt n k
1070 Return @var{n} raised to the non-negative integer exponent
1081 @deffn primitive bit-extract n start end
1082 Return the integer composed of the @var{start} (inclusive)
1083 through @var{end} (exclusive) bits of @var{n}. The
1084 @var{start}th bit becomes the 0-th bit in the result.
1087 (number->string (bit-extract #b1101101010 0 4) 2)
1089 (number->string (bit-extract #b1101101010 4 9) 2)
1096 @subsection Random Number Generation
1098 @deffn primitive copy-random-state [state]
1099 Return a copy of the random state @var{state}.
1102 @deffn primitive random n [state]
1103 Return a number in [0,N).
1105 Accepts a positive integer or real n and returns a
1106 number of the same type between zero (inclusive) and
1107 N (exclusive). The values returned have a uniform
1110 The optional argument @var{state} must be of the type produced
1111 by @code{seed->random-state}. It defaults to the value of the
1112 variable @var{*random-state*}. This object is used to maintain
1113 the state of the pseudo-random-number generator and is altered
1114 as a side effect of the random operation.
1117 @deffn primitive random:exp [state]
1118 Return an inexact real in an exponential distribution with mean
1119 1. For an exponential distribution with mean u use (* u
1123 @deffn primitive random:hollow-sphere! v [state]
1124 Fills vect with inexact real random numbers
1125 the sum of whose squares is equal to 1.0.
1126 Thinking of vect as coordinates in space of
1127 dimension n = (vector-length vect), the coordinates
1128 are uniformly distributed over the surface of the
1132 @deffn primitive random:normal [state]
1133 Return an inexact real in a normal distribution. The
1134 distribution used has mean 0 and standard deviation 1. For a
1135 normal distribution with mean m and standard deviation d use
1136 @code{(+ m (* d (random:normal)))}.
1139 @deffn primitive random:normal-vector! v [state]
1140 Fills vect with inexact real random numbers that are
1141 independent and standard normally distributed
1142 (i.e., with mean 0 and variance 1).
1145 @deffn primitive random:solid-sphere! v [state]
1146 Fills vect with inexact real random numbers
1147 the sum of whose squares is less than 1.0.
1148 Thinking of vect as coordinates in space of
1149 dimension n = (vector-length vect), the coordinates
1150 are uniformly distributed within the unit n-sphere.
1151 The sum of the squares of the numbers is returned.
1154 @deffn primitive random:uniform [state]
1155 Return a uniformly distributed inexact real random number in
1159 @deffn primitive seed->random-state seed
1160 Return a new random state using @var{seed}.
1168 Most of the characters in the ASCII character set may be referred to by
1169 name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and so on.
1170 The following table describes the ASCII names for each character.
1172 @multitable @columnfractions .25 .25 .25 .25
1173 @item 0 = @code{#\nul}
1174 @tab 1 = @code{#\soh}
1175 @tab 2 = @code{#\stx}
1176 @tab 3 = @code{#\etx}
1177 @item 4 = @code{#\eot}
1178 @tab 5 = @code{#\enq}
1179 @tab 6 = @code{#\ack}
1180 @tab 7 = @code{#\bel}
1181 @item 8 = @code{#\bs}
1182 @tab 9 = @code{#\ht}
1183 @tab 10 = @code{#\nl}
1184 @tab 11 = @code{#\vt}
1185 @item 12 = @code{#\np}
1186 @tab 13 = @code{#\cr}
1187 @tab 14 = @code{#\so}
1188 @tab 15 = @code{#\si}
1189 @item 16 = @code{#\dle}
1190 @tab 17 = @code{#\dc1}
1191 @tab 18 = @code{#\dc2}
1192 @tab 19 = @code{#\dc3}
1193 @item 20 = @code{#\dc4}
1194 @tab 21 = @code{#\nak}
1195 @tab 22 = @code{#\syn}
1196 @tab 23 = @code{#\etb}
1197 @item 24 = @code{#\can}
1198 @tab 25 = @code{#\em}
1199 @tab 26 = @code{#\sub}
1200 @tab 27 = @code{#\esc}
1201 @item 28 = @code{#\fs}
1202 @tab 29 = @code{#\gs}
1203 @tab 30 = @code{#\rs}
1204 @tab 31 = @code{#\us}
1205 @item 32 = @code{#\sp}
1208 The @code{delete} character (octal 177) may be referred to with the name
1211 Several characters have more than one name:
1215 @code{#\space}, @code{#\sp}
1217 @code{#\newline}, @code{#\nl}
1219 @code{#\tab}, @code{#\ht}
1221 @code{#\backspace}, @code{#\bs}
1223 @code{#\return}, @code{#\cr}
1225 @code{#\page}, @code{#\np}
1227 @code{#\null}, @code{#\nul}
1231 @deffn primitive char? x
1232 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1236 @deffn primitive char=? x y
1237 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1241 @deffn primitive char<? x y
1242 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence,
1247 @deffn primitive char<=? x y
1248 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1249 ASCII sequence, else @code{#f}.
1253 @deffn primitive char>? x y
1254 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1255 sequence, else @code{#f}.
1259 @deffn primitive char>=? x y
1260 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1261 ASCII sequence, else @code{#f}.
1265 @deffn primitive char-ci=? x y
1266 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1267 case, else @code{#f}.
1271 @deffn primitive char-ci<? x y
1272 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence
1273 ignoring case, else @code{#f}.
1277 @deffn primitive char-ci<=? x y
1278 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1279 ASCII sequence ignoring case, else @code{#f}.
1283 @deffn primitive char-ci>? x y
1284 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1285 sequence ignoring case, else @code{#f}.
1289 @deffn primitive char-ci>=? x y
1290 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1291 ASCII sequence ignoring case, else @code{#f}.
1294 @rnindex char-alphabetic?
1295 @deffn primitive char-alphabetic? chr
1296 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1297 Alphabetic means the same thing as the isalpha C library function.
1300 @rnindex char-numeric?
1301 @deffn primitive char-numeric? chr
1302 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1303 Numeric means the same thing as the isdigit C library function.
1306 @rnindex char-whitespace?
1307 @deffn primitive char-whitespace? chr
1308 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1309 Whitespace means the same thing as the isspace C library function.
1312 @rnindex char-upper-case?
1313 @deffn primitive char-upper-case? chr
1314 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1315 Uppercase means the same thing as the isupper C library function.
1318 @rnindex char-lower-case?
1319 @deffn primitive char-lower-case? chr
1320 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1321 Lowercase means the same thing as the islower C library function.
1324 @deffn primitive char-is-both? chr
1325 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else @code{#f}.
1326 Uppercase and lowercase are as defined by the isupper and islower
1327 C library functions.
1330 @rnindex char->integer
1331 @deffn primitive char->integer chr
1332 Return the number corresponding to ordinal position of @var{chr} in the
1336 @rnindex integer->char
1337 @deffn primitive integer->char n
1338 Return the character at position @var{n} in the ASCII sequence.
1341 @rnindex char-upcase
1342 @deffn primitive char-upcase chr
1343 Return the uppercase character version of @var{chr}.
1346 @rnindex char-downcase
1347 @deffn primitive char-downcase chr
1348 Return the lowercase character version of @var{chr}.
1356 Strings are fixed-length sequences of characters. They can be created
1357 by calling constructor procedures, but they can also literally get
1358 entered at the REPL or in Scheme source files.
1360 Guile provides a rich set of string processing procedures, because text
1361 handling is very important when Guile is used as a scripting language.
1363 Strings always carry the information about how many characters they are
1364 composed of with them, so there is no special end-of-string character,
1365 like in C. That means that Scheme strings can contain any character,
1366 even the NUL character @code{'\0'}. But note: Since most operating
1367 system calls dealing with strings (such as for file operations) expect
1368 strings to be zero-terminated, they might do unexpected things when
1369 called with string containing unusal characters.
1372 * String Syntax:: Read syntax for strings.
1373 * String Predicates:: Testing strings for certain properties.
1374 * String Constructors:: Creating new string objects.
1375 * List/String Conversion:: Converting from/to lists of characters.
1376 * String Selection:: Select portions from strings.
1377 * String Modification:: Modify parts or whole strings.
1378 * String Comparison:: Lexicographic ordering predicates.
1379 * String Searching:: Searching in strings.
1380 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1381 * Appending Strings:: Appending strings to form a new string.
1382 * String Miscellanea:: Miscellaneous string procedures.
1386 @subsection String Read Syntax
1388 The read syntax for strings is an arbitrarily long sequence of
1389 characters enclosed in double quotes (@code{"}). @footnote{Actually, the
1390 current implementation restricts strings to a length of 2^24
1391 characters.} If you want to insert a double quote character into a
1392 string literal, it must be prefixed with a backslash @code{\} character
1393 (called an @dfn{escape character}).
1395 The following are examples of string literals:
1404 @c FIXME::martin: What about escape sequences like \r, \n etc.?
1406 @node String Predicates
1407 @subsection String Predicates
1409 The following procedures can be used to check whether a given string
1410 fulfills some specified property.
1413 @deffn primitive string? obj
1414 Return @code{#t} iff @var{obj} is a string, else @code{#f}.
1417 @deffn primitive string-null? str
1418 Return @code{#t} if @var{str}'s length is nonzero, and
1419 @code{#f} otherwise.
1421 (string-null? "") @result{} #t
1423 (string-null? y) @result{} #f
1427 @node String Constructors
1428 @subsection String Constructors
1430 The string constructor procedures create new string objects, possibly
1431 initializing them with some specified character data.
1433 @c FIXME::martin: list->string belongs into `List/String Conversion'
1436 @rnindex list->string
1437 @deffn primitive string . chrs
1438 @deffnx primitive list->string chrs
1439 Return a newly allocated string composed of the arguments,
1443 @rnindex make-string
1444 @deffn primitive make-string k [chr]
1445 Return a newly allocated string of
1446 length @var{k}. If @var{chr} is given, then all elements of
1447 the string are initialized to @var{chr}, otherwise the contents
1448 of the @var{string} are unspecified.
1451 @node List/String Conversion
1452 @subsection List/String conversion
1454 When processing strings, it is often convenient to first convert them
1455 into a list representation by using the procedure @code{string->list},
1456 work with the resulting list, and then convert it back into a string.
1457 These procedures are useful for similar tasks.
1459 @rnindex string->list
1460 @deffn primitive string->list str
1461 Return a newly allocated list of the characters that make up
1462 the given string @var{str}. @code{string->list} and
1463 @code{list->string} are inverses as far as @samp{equal?} is
1467 @deffn primitive string-split str chr
1468 Split the string @var{str} into the a list of the substrings delimited
1469 by appearances of the character @var{chr}. Note that an empty substring
1470 between separator characters will result in an empty string in the
1474 (string-split "root:x:0:0:root:/root:/bin/bash" #:)
1476 ("root" "x" "0" "0" "root" "/root" "/bin/bash")
1478 (string-split "::" #:)
1482 (string-split "" #:)
1489 @node String Selection
1490 @subsection String Selection
1492 Portions of strings can be extracted by these procedures.
1493 @code{string-ref} delivers individual characters whereas
1494 @code{substring} can be used to extract substrings from longer strings.
1496 @rnindex string-length
1497 @deffn primitive string-length string
1498 Return the number of characters in @var{string}.
1502 @deffn primitive string-ref str k
1503 Return character @var{k} of @var{str} using zero-origin
1504 indexing. @var{k} must be a valid index of @var{str}.
1507 @rnindex string-copy
1508 @deffn primitive string-copy str
1509 Return a newly allocated copy of the given @var{string}.
1513 @deffn primitive substring str start [end]
1514 Return a newly allocated string formed from the characters
1515 of @var{str} beginning with index @var{start} (inclusive) and
1516 ending with index @var{end} (exclusive).
1517 @var{str} must be a string, @var{start} and @var{end} must be
1518 exact integers satisfying:
1520 0 <= @var{start} <= @var{end} <= (string-length @var{str}).
1523 @node String Modification
1524 @subsection String Modification
1526 These procedures are for modifying strings in-place. This means that the
1527 result of the operation is not a new string; instead, the original string's
1528 memory representation is modified.
1530 @rnindex string-set!
1531 @deffn primitive string-set! str k chr
1532 Store @var{chr} in element @var{k} of @var{str} and return
1533 an unspecified value. @var{k} must be a valid index of
1537 @rnindex string-fill!
1538 @deffn primitive string-fill! str chr
1539 Store @var{char} in every element of the given @var{string} and
1540 return an unspecified value.
1543 @deffn primitive substring-fill! str start end fill
1544 Change every character in @var{str} between @var{start} and
1545 @var{end} to @var{fill}.
1548 (define y "abcdefg")
1549 (substring-fill! y 1 3 #\r)
1555 @deffn primitive substring-move! str1 start1 end1 str2 start2
1556 @deffnx primitive substring-move-left! str1 start1 end1 str2 start2
1557 @deffnx primitive substring-move-right! str1 start1 end1 str2 start2
1558 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1559 into @var{str2} beginning at position @var{start2}.
1560 @code{substring-move-right!} begins copying from the rightmost character
1561 and moves left, and @code{substring-move-left!} copies from the leftmost
1562 character moving right.
1564 It is useful to have two functions that copy in different directions so
1565 that substrings can be copied back and forth within a single string. If
1566 you wish to copy text from the left-hand side of a string to the
1567 right-hand side of the same string, and the source and destination
1568 overlap, you must be careful to copy the rightmost characters of the
1569 text first, to avoid clobbering your data. Hence, when @var{str1} and
1570 @var{str2} are the same string, you should use
1571 @code{substring-move-right!} when moving text from left to right, and
1572 @code{substring-move-left!} otherwise. If @code{str1} and @samp{str2}
1573 are different strings, it does not matter which function you use.
1576 (define x (make-string 10 #\a))
1578 (substring-move-left! x 2 5 y 0)
1583 @result{} "aaaaaaaaaa"
1586 (substring-move-left! x 2 5 y 0)
1590 (define y "abcdefg")
1591 (substring-move-left! y 2 5 y 3)
1595 (define y "abcdefg")
1596 (substring-move-right! y 2 5 y 0)
1600 (define y "abcdefg")
1601 (substring-move-right! y 2 5 y 3)
1608 @node String Comparison
1609 @subsection String Comparison
1611 The procedures in this section are similar to the character ordering
1612 predicates (@pxref{Characters}), but are defined on character sequences.
1613 They all return @code{#t} on success and @code{#f} on failure. The
1614 predicates ending in @code{-ci} ignore the character case when comparing
1619 @deffn primitive string=? s1 s2
1620 Lexicographic equality predicate; return @code{#t} if the two
1621 strings are the same length and contain the same characters in
1622 the same positions, otherwise return @code{#f}.
1624 The procedure @code{string-ci=?} treats upper and lower case
1625 letters as though they were the same character, but
1626 @code{string=?} treats upper and lower case as distinct
1631 @deffn primitive string<? s1 s2
1632 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1633 is lexicographically less than @var{s2}.
1637 @deffn primitive string<=? s1 s2
1638 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1639 is lexicographically less than or equal to @var{s2}.
1643 @deffn primitive string>? s1 s2
1644 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1645 is lexicographically greater than @var{s2}.
1649 @deffn primitive string>=? s1 s2
1650 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1651 is lexicographically greater than or equal to @var{s2}.
1654 @rnindex string-ci=?
1655 @deffn primitive string-ci=? s1 s2
1656 Case-insensitive string equality predicate; return @code{#t} if
1657 the two strings are the same length and their component
1658 characters match (ignoring case) at each position; otherwise
1663 @deffn primitive string-ci<? s1 s2
1664 Case insensitive lexicographic ordering predicate; return
1665 @code{#t} if @var{s1} is lexicographically less than @var{s2}
1670 @deffn primitive string-ci<=? s1 s2
1671 Case insensitive lexicographic ordering predicate; return
1672 @code{#t} if @var{s1} is lexicographically less than or equal
1673 to @var{s2} regardless of case.
1676 @rnindex string-ci>?
1677 @deffn primitive string-ci>? s1 s2
1678 Case insensitive lexicographic ordering predicate; return
1679 @code{#t} if @var{s1} is lexicographically greater than
1680 @var{s2} regardless of case.
1683 @rnindex string-ci>=?
1684 @deffn primitive string-ci>=? s1 s2
1685 Case insensitive lexicographic ordering predicate; return
1686 @code{#t} if @var{s1} is lexicographically greater than or
1687 equal to @var{s2} regardless of case.
1691 @node String Searching
1692 @subsection String Searching
1694 When searching the index of a character in a string, these procedures
1697 @deffn primitive string-index str chr [frm [to]]
1698 Return the index of the first occurrence of @var{chr} in
1699 @var{str}. The optional integer arguments @var{frm} and
1700 @var{to} limit the search to a portion of the string. This
1701 procedure essentially implements the @code{index} or
1702 @code{strchr} functions from the C library.
1705 (string-index "weiner" #\e)
1708 (string-index "weiner" #\e 2)
1711 (string-index "weiner" #\e 2 4)
1716 @deffn primitive string-rindex str chr [frm [to]]
1717 Like @code{string-index}, but search from the right of the
1718 string rather than from the left. This procedure essentially
1719 implements the @code{rindex} or @code{strrchr} functions from
1723 (string-rindex "weiner" #\e)
1726 (string-rindex "weiner" #\e 2 4)
1729 (string-rindex "weiner" #\e 2 5)
1734 @node Alphabetic Case Mapping
1735 @subsection Alphabetic Case Mapping
1737 These are procedures for mapping strings to their upper- or lower-case
1738 equivalents, respectively, or for capitalizing strings.
1740 @deffn primitive string-upcase str
1741 Return a freshly allocated string containing the characters of
1742 @var{str} in upper case.
1745 @deffn primitive string-upcase! str
1746 Destructively upcase every character in @var{str} and return
1749 y @result{} "arrdefg"
1750 (string-upcase! y) @result{} "ARRDEFG"
1751 y @result{} "ARRDEFG"
1755 @deffn primitive string-downcase str
1756 Return a freshly allocation string containing the characters in
1757 @var{str} in lower case.
1760 @deffn primitive string-downcase! str
1761 Destructively downcase every character in @var{str} and return
1764 y @result{} "ARRDEFG"
1765 (string-downcase! y) @result{} "arrdefg"
1766 y @result{} "arrdefg"
1770 @deffn primitive string-capitalize str
1771 Return a freshly allocated string with the characters in
1772 @var{str}, where the first character of every word is
1776 @deffn primitive string-capitalize! str
1777 Upcase the first character of every word in @var{str}
1778 destructively and return @var{str}.
1781 y @result{} "hello world"
1782 (string-capitalize! y) @result{} "Hello World"
1783 y @result{} "Hello World"
1788 @node Appending Strings
1789 @subsection Appending Strings
1791 The procedure @code{string-append} appends several strings together to
1792 form a longer result string.
1794 @rnindex string-append
1795 @deffn primitive string-append string1 @dots{}
1796 Return a newly allocated string whose characters form the
1797 concatenation of the given strings.
1801 @node String Miscellanea
1802 @subsection String Miscellanea
1804 This section contains all remaining string procedures.
1806 @deffn primitive string-ci->symbol str
1807 Return the symbol whose name is @var{str}. @var{str} is
1808 converted to lowercase before the conversion is done, if Guile
1809 is currently reading symbols case-insensitively.
1813 @node Regular Expressions
1814 @section Regular Expressions
1815 @tpindex Regular expressions
1817 @cindex regular expressions
1819 @cindex emacs regexp
1821 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
1822 describes a whole class of strings. A full description of regular
1823 expressions and their syntax is beyond the scope of this manual;
1824 an introduction can be found in the Emacs manual (@pxref{Regexps,
1825 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
1826 in many general Unix reference books.
1828 If your system does not include a POSIX regular expression library, and
1829 you have not linked Guile with a third-party regexp library such as Rx,
1830 these functions will not be available. You can tell whether your Guile
1831 installation includes regular expression support by checking whether the
1832 @code{*features*} list includes the @code{regex} symbol.
1835 * Regexp Functions:: Functions that create and match regexps.
1836 * Match Structures:: Finding what was matched by a regexp.
1837 * Backslash Escapes:: Removing the special meaning of regexp metacharacters.
1838 * Rx Interface:: Tom Lord's Rx library does things differently.
1841 [FIXME: it may be useful to include an Examples section. Parts of this
1842 interface are bewildering on first glance.]
1844 @node Regexp Functions
1845 @subsection Regexp Functions
1847 By default, Guile supports POSIX extended regular expressions.
1848 That means that the characters @samp{(}, @samp{)}, @samp{+} and
1849 @samp{?} are special, and must be escaped if you wish to match the
1852 This regular expression interface was modeled after that
1853 implemented by SCSH, the Scheme Shell. It is intended to be
1854 upwardly compatible with SCSH regular expressions.
1856 @c begin (scm-doc-string "regex.scm" "string-match")
1857 @deffn procedure string-match pattern str [start]
1858 Compile the string @var{pattern} into a regular expression and compare
1859 it with @var{str}. The optional numeric argument @var{start} specifies
1860 the position of @var{str} at which to begin matching.
1862 @code{string-match} returns a @dfn{match structure} which
1863 describes what, if anything, was matched by the regular
1864 expression. @xref{Match Structures}. If @var{str} does not match
1865 @var{pattern} at all, @code{string-match} returns @code{#f}.
1868 Each time @code{string-match} is called, it must compile its
1869 @var{pattern} argument into a regular expression structure. This
1870 operation is expensive, which makes @code{string-match} inefficient if
1871 the same regular expression is used several times (for example, in a
1872 loop). For better performance, you can compile a regular expression in
1873 advance and then match strings against the compiled regexp.
1875 @deffn primitive make-regexp pat . flags
1876 Compile the regular expression described by @var{pat}, and
1877 return the compiled regexp structure. If @var{pat} does not
1878 describe a legal regular expression, @code{make-regexp} throws
1879 a @code{regular-expression-syntax} error.
1881 The @var{flags} arguments change the behavior of the compiled
1882 regular expression. The following flags may be supplied:
1886 Consider uppercase and lowercase letters to be the same when
1888 @item regexp/newline
1889 If a newline appears in the target string, then permit the
1890 @samp{^} and @samp{$} operators to match immediately after or
1891 immediately before the newline, respectively. Also, the
1892 @samp{.} and @samp{[^...]} operators will never match a newline
1893 character. The intent of this flag is to treat the target
1894 string as a buffer containing many lines of text, and the
1895 regular expression as a pattern that may match a single one of
1898 Compile a basic (``obsolete'') regexp instead of the extended
1899 (``modern'') regexps that are the default. Basic regexps do
1900 not consider @samp{|}, @samp{+} or @samp{?} to be special
1901 characters, and require the @samp{@{...@}} and @samp{(...)}
1902 metacharacters to be backslash-escaped (@pxref{Backslash
1903 Escapes}). There are several other differences between basic
1904 and extended regular expressions, but these are the most
1906 @item regexp/extended
1907 Compile an extended regular expression rather than a basic
1908 regexp. This is the default behavior; this flag will not
1909 usually be needed. If a call to @code{make-regexp} includes
1910 both @code{regexp/basic} and @code{regexp/extended} flags, the
1911 one which comes last will override the earlier one.
1915 @deffn primitive regexp-exec rx str [start [flags]]
1916 Match the compiled regular expression @var{rx} against
1917 @code{str}. If the optional integer @var{start} argument is
1918 provided, begin matching from that position in the string.
1919 Return a match structure describing the results of the match,
1920 or @code{#f} if no match could be found.
1922 The @var{flags} arguments change the matching behavior.
1923 The following flags may be supplied:
1927 Operator @samp{^} always fails (unless @code{regexp/newline}
1928 is used). Use this when the beginning of the string should
1929 not be considered the beginning of a line.
1931 Operator @samp{$} always fails (unless @code{regexp/newline}
1932 is used). Use this when the end of the string should not be
1933 considered the end of a line.
1937 @deffn primitive regexp? obj
1938 Return @code{#t} if @var{obj} is a compiled regular expression,
1939 or @code{#f} otherwise.
1942 Regular expressions are commonly used to find patterns in one string and
1943 replace them with the contents of another string.
1945 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
1946 @deffn procedure regexp-substitute port match [item@dots{}]
1947 Write to the output port @var{port} selected contents of the match
1948 structure @var{match}. Each @var{item} specifies what should be
1949 written, and may be one of the following arguments:
1953 A string. String arguments are written out verbatim.
1956 An integer. The submatch with that number is written.
1959 The symbol @samp{pre}. The portion of the matched string preceding
1960 the regexp match is written.
1963 The symbol @samp{post}. The portion of the matched string following
1964 the regexp match is written.
1967 @var{port} may be @code{#f}, in which case nothing is written; instead,
1968 @code{regexp-substitute} constructs a string from the specified
1969 @var{item}s and returns that.
1972 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
1973 @deffn procedure regexp-substitute/global port regexp target [item@dots{}]
1974 Similar to @code{regexp-substitute}, but can be used to perform global
1975 substitutions on @var{str}. Instead of taking a match structure as an
1976 argument, @code{regexp-substitute/global} takes two string arguments: a
1977 @var{regexp} string describing a regular expression, and a @var{target}
1978 string which should be matched against this regular expression.
1980 Each @var{item} behaves as in @var{regexp-substitute}, with the
1981 following exceptions:
1985 A function may be supplied. When this function is called, it will be
1986 passed one argument: a match structure for a given regular expression
1987 match. It should return a string to be written out to @var{port}.
1990 The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
1991 on the unmatched portion of @var{str}. This @emph{must} be supplied in
1992 order to perform global search-and-replace on @var{str}; if it is not
1993 present among the @var{item}s, then @code{regexp-substitute/global} will
1994 return after processing a single match.
1998 @node Match Structures
1999 @subsection Match Structures
2001 @cindex match structures
2003 A @dfn{match structure} is the object returned by @code{string-match} and
2004 @code{regexp-exec}. It describes which portion of a string, if any,
2005 matched the given regular expression. Match structures include: a
2006 reference to the string that was checked for matches; the starting and
2007 ending positions of the regexp match; and, if the regexp included any
2008 parenthesized subexpressions, the starting and ending positions of each
2011 In each of the regexp match functions described below, the @code{match}
2012 argument must be a match structure returned by a previous call to
2013 @code{string-match} or @code{regexp-exec}. Most of these functions
2014 return some information about the original target string that was
2015 matched against a regular expression; we will call that string
2016 @var{target} for easy reference.
2018 @c begin (scm-doc-string "regex.scm" "regexp-match?")
2019 @deffn procedure regexp-match? obj
2020 Return @code{#t} if @var{obj} is a match structure returned by a
2021 previous call to @code{regexp-exec}, or @code{#f} otherwise.
2024 @c begin (scm-doc-string "regex.scm" "match:substring")
2025 @deffn procedure match:substring match [n]
2026 Return the portion of @var{target} matched by subexpression number
2027 @var{n}. Submatch 0 (the default) represents the entire regexp match.
2028 If the regular expression as a whole matched, but the subexpression
2029 number @var{n} did not match, return @code{#f}.
2032 @c begin (scm-doc-string "regex.scm" "match:start")
2033 @deffn procedure match:start match [n]
2034 Return the starting position of submatch number @var{n}.
2037 @c begin (scm-doc-string "regex.scm" "match:end")
2038 @deffn procedure match:end match [n]
2039 Return the ending position of submatch number @var{n}.
2042 @c begin (scm-doc-string "regex.scm" "match:prefix")
2043 @deffn procedure match:prefix match
2044 Return the unmatched portion of @var{target} preceding the regexp match.
2047 @c begin (scm-doc-string "regex.scm" "match:suffix")
2048 @deffn procedure match:suffix match
2049 Return the unmatched portion of @var{target} following the regexp match.
2052 @c begin (scm-doc-string "regex.scm" "match:count")
2053 @deffn procedure match:count match
2054 Return the number of parenthesized subexpressions from @var{match}.
2055 Note that the entire regular expression match itself counts as a
2056 subexpression, and failed submatches are included in the count.
2059 @c begin (scm-doc-string "regex.scm" "match:string")
2060 @deffn procedure match:string match
2061 Return the original @var{target} string.
2064 @node Backslash Escapes
2065 @subsection Backslash Escapes
2067 Sometimes you will want a regexp to match characters like @samp{*} or
2068 @samp{$} exactly. For example, to check whether a particular string
2069 represents a menu entry from an Info node, it would be useful to match
2070 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2071 because the asterisk is a metacharacter, it won't match the @samp{*} at
2072 the beginning of the string. In this case, we want to make the first
2075 You can do this by preceding the metacharacter with a backslash
2076 character @samp{\}. (This is also called @dfn{quoting} the
2077 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2078 sees a backslash in a regular expression, it considers the following
2079 glyph to be an ordinary character, no matter what special meaning it
2080 would ordinarily have. Therefore, we can make the above example work by
2081 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2082 the regular expression engine to match only a single asterisk in the
2085 Since the backslash is itself a metacharacter, you may force a regexp to
2086 match a backslash in the target string by preceding the backslash with
2087 itself. For example, to find variable references in a @TeX{} program,
2088 you might want to find occurrences of the string @samp{\let\} followed
2089 by any number of alphabetic characters. The regular expression
2090 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2091 regexp each match a single backslash in the target string.
2093 @c begin (scm-doc-string "regex.scm" "regexp-quote")
2094 @deffn procedure regexp-quote str
2095 Quote each special character found in @var{str} with a backslash, and
2096 return the resulting string.
2099 @strong{Very important:} Using backslash escapes in Guile source code
2100 (as in Emacs Lisp or C) can be tricky, because the backslash character
2101 has special meaning for the Guile reader. For example, if Guile
2102 encounters the character sequence @samp{\n} in the middle of a string
2103 while processing Scheme code, it replaces those characters with a
2104 newline character. Similarly, the character sequence @samp{\t} is
2105 replaced by a horizontal tab. Several of these @dfn{escape sequences}
2106 are processed by the Guile reader before your code is executed.
2107 Unrecognized escape sequences are ignored: if the characters @samp{\*}
2108 appear in a string, they will be translated to the single character
2111 This translation is obviously undesirable for regular expressions, since
2112 we want to be able to include backslashes in a string in order to
2113 escape regexp metacharacters. Therefore, to make sure that a backslash
2114 is preserved in a string in your Guile program, you must use @emph{two}
2115 consecutive backslashes:
2118 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2121 The string in this example is preprocessed by the Guile reader before
2122 any code is executed. The resulting argument to @code{make-regexp} is
2123 the string @samp{^\* [^:]*}, which is what we really want.
2125 This also means that in order to write a regular expression that matches
2126 a single backslash character, the regular expression string in the
2127 source code must include @emph{four} backslashes. Each consecutive pair
2128 of backslashes gets translated by the Guile reader to a single
2129 backslash, and the resulting double-backslash is interpreted by the
2130 regexp engine as matching a single backslash character. Hence:
2133 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2136 The reason for the unwieldiness of this syntax is historical. Both
2137 regular expression pattern matchers and Unix string processing systems
2138 have traditionally used backslashes with the special meanings
2139 described above. The POSIX regular expression specification and ANSI C
2140 standard both require these semantics. Attempting to abandon either
2141 convention would cause other kinds of compatibility problems, possibly
2142 more severe ones. Therefore, without extending the Scheme reader to
2143 support strings with different quoting conventions (an ungainly and
2144 confusing extension when implemented in other languages), we must adhere
2145 to this cumbersome escape syntax.
2148 @subsection Rx Interface
2150 @c FIXME::martin: Shouldn't this be removed or moved to the
2151 @c ``Guile Modules'' chapter? The functions are not available in
2154 [FIXME: this is taken from Gary and Mark's quick summaries and should be
2155 reviewed and expanded. Rx is pretty stable, so could already be done!]
2158 @cindex finite automaton
2160 Guile includes an interface to Tom Lord's Rx library (currently only to
2161 POSIX regular expressions). Use of the library requires a two step
2162 process: compile a regular expression into an efficient structure, then
2163 use the structure in any number of string comparisons.
2165 For example, given the
2166 regular expression @samp{abc.} (which matches any string containing
2167 @samp{abc} followed by any single character):
2170 guile> @kbd{(define r (regcomp "abc."))}
2173 guile> @kbd{(regexec r "abc")}
2175 guile> @kbd{(regexec r "abcd")}
2180 The definitions of @code{regcomp} and @code{regexec} are as follows:
2182 @c NJFIXME not in libguile!
2183 @deffn primitive regcomp pattern [flags]
2184 Compile the regular expression pattern using POSIX rules. Flags is
2185 optional and should be specified using symbolic names:
2186 @defvar REG_EXTENDED
2187 use extended POSIX syntax
2190 use case-insensitive matching
2193 allow anchors to match after newline characters in the
2194 string and prevents @code{.} or @code{[^...]} from matching newlines.
2197 The @code{logior} procedure can be used to combine multiple flags.
2198 The default is to use
2199 POSIX basic syntax, which makes @code{+} and @code{?} literals and @code{\+}
2201 operators. Backslashes in @var{pattern} must be escaped if specified in a
2202 literal string e.g., @code{"\\(a\\)\\?"}.
2205 @c NJFIXME not in libguile!
2206 @deffn primitive regexec regex string [match-pick] [flags]
2208 Match @var{string} against the compiled POSIX regular expression
2210 @var{match-pick} and @var{flags} are optional. Possible flags (which can be
2211 combined using the logior procedure) are:
2214 The beginning of line operator won't match the beginning of
2215 @var{string} (presumably because it's not the beginning of a line)
2219 Similar to REG_NOTBOL, but prevents the end of line operator
2220 from matching the end of @var{string}.
2223 If no match is possible, regexec returns #f. Otherwise @var{match-pick}
2224 determines the return value:
2226 @code{#t} or unspecified: a newly-allocated vector is returned,
2227 containing pairs with the indices of the matched part of @var{string} and any
2230 @code{""}: a list is returned: the first element contains a nested list
2231 with the matched part of @var{string} surrounded by the the unmatched parts.
2232 Remaining elements are matched substrings (if any). All returned
2233 substrings share memory with @var{string}.
2235 @code{#f}: regexec returns #t if a match is made, otherwise #f.
2237 vector: the supplied vector is returned, with the first element replaced
2238 by a pair containing the indices of the matched portion of @var{string} and
2239 further elements replaced by pairs containing the indices of matched
2240 substrings (if any).
2242 list: a list will be returned, with each member of the list
2243 specified by a code in the corresponding position of the supplied list:
2245 a number: the numbered matching substring (0 for the entire match).
2247 @code{#\<}: the beginning of @var{string} to the beginning of the part matched
2250 @code{#\>}: the end of the matched part of @var{string} to the end of
2253 @code{#\c}: the "final tag", which seems to be associated with the "cut
2254 operator", which doesn't seem to be available through the posix
2257 e.g., @code{(list #\< 0 1 #\>)}. The returned substrings share memory with
2261 Here are some other procedures that might be used when using regular
2264 @c NJFIXME not in libguile!
2265 @deffn primitive compiled-regexp? obj
2266 Test whether obj is a compiled regular expression.
2269 @c NJFIXME not in libguile!
2270 @deffn primitive regexp->dfa regex [flags]
2273 @c NJFIXME not in libguile!
2274 @deffn primitive dfa-fork dfa
2277 @c NJFIXME not in libguile!
2278 @deffn primitive reset-dfa! dfa
2281 @c NJFIXME not in libguile!
2282 @deffn primitive dfa-final-tag dfa
2285 @c NJFIXME not in libguile!
2286 @deffn primitive dfa-continuable? dfa
2289 @c NJFIXME not in libguile!
2290 @deffn primitive advance-dfa! dfa string
2294 @node Symbols and Variables
2295 @section Symbols and Variables
2297 @c FIXME::martin: Review me!
2299 Symbols are a data type with a special property. On the one hand,
2300 symbols are used for denoting variables in a Scheme program, on the
2301 other they can be used as literal data as well.
2303 The association between symbols and values is maintained in special data
2304 structures, the symbol tables.
2306 In addition, Guile offers variables as first-class objects. They can
2307 be used for interacting with the module system.
2310 * Symbols:: All about symbols as a data type.
2311 * Symbol Tables:: Tables for mapping symbols to values.
2312 * Variables:: First-class variables.
2319 @c FIXME::martin: Review me!
2321 Symbols are especially useful because two symbols which are spelled the
2322 same way are equivalent in the sense of @code{eq?}. That means that
2323 they are actually the same Scheme object. The advantage is that symbols
2324 can be compared extremely efficiently, although they carry more
2325 information for the human reader than, say, numbers.
2327 It is very common in Scheme programs to use symbols as keys in
2328 association lists (@pxref{Association Lists}) or hash tables
2329 (@pxref{Hash Tables}), because this usage improves the readability a
2330 lot, and does not cause any performance loss.
2332 The read syntax for symbols is a sequence of letters, digits, and
2333 @emph{extended alphabetic characters} that begins with a character that
2334 cannot begin a number is an identifier. In addition, @code{+},
2335 @code{-}, and @code{...} are identifiers.
2337 Extended alphabetic characters may be used within identifiers as if
2338 they were letters. The following are extended alphabetic characters:
2341 ! $ % & * + - . / : < = > ? @@ ^ _ ~
2344 In addition to the read syntax defined above (which is taken from R5RS
2345 (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on Scheme})), Guile
2346 provides a method for writing symbols with unusual characters, such as
2347 space characters. If you (for whatever reason) need to write a symbol
2348 containing characters not mentioned above, you write symbols as follows:
2352 Begin the symbol with the two character @code{#@{},
2355 write the characters of the symbol and
2358 finish the symbol with the characters @code{@}#}.
2361 Here are a few examples of this form of read syntax; the first
2362 containing a space character, the second containing a line break and the
2363 last one looks like a number.
2372 Usage of this form of read syntax is discouraged, because it is not
2373 portable at all, and is not very readable.
2376 @deffn primitive symbol? obj
2377 Return @code{#t} if @var{obj} is a symbol, otherwise return
2381 @rnindex string->symbol
2382 @deffn primitive string->symbol string
2383 Return the symbol whose name is @var{string}. This procedure
2384 can create symbols with names containing special characters or
2385 letters in the non-standard case, but it is usually a bad idea
2386 to create such symbols because in some implementations of
2387 Scheme they cannot be read as themselves. See
2388 @code{symbol->string}.
2390 The following examples assume that the implementation's
2391 standard case is lower case:
2394 (eq? 'mISSISSIppi 'mississippi) @result{} #t
2395 (string->symbol "mISSISSIppi") @result{} @r{the symbol with name "mISSISSIppi"}
2396 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
2398 (string->symbol (symbol->string 'JollyWog))) @result{} #t
2399 (string=? "K. Harper, M.D."
2401 (string->symbol "K. Harper, M.D."))) @result{}#t
2405 @rnindex symbol->string
2406 @deffn primitive symbol->string s
2407 Return the name of @var{symbol} as a string. If the symbol was
2408 part of an object returned as the value of a literal expression
2409 (section @pxref{Literal expressions,,,r5rs, The Revised^5
2410 Report on Scheme}) or by a call to the @code{read} procedure,
2411 and its name contains alphabetic characters, then the string
2412 returned will contain characters in the implementation's
2413 preferred standard case---some implementations will prefer
2414 upper case, others lower case. If the symbol was returned by
2415 @code{string->symbol}, the case of characters in the string
2416 returned will be the same as the case in the string that was
2417 passed to @code{string->symbol}. It is an error to apply
2418 mutation procedures like @code{string-set!} to strings returned
2421 The following examples assume that the implementation's
2422 standard case is lower case:
2425 (symbol->string 'flying-fish) @result{} "flying-fish"
2426 (symbol->string 'Martin) @result{} "martin"
2428 (string->symbol "Malvina")) @result{} "Malvina"
2433 @subsection Symbol Tables
2435 @c FIXME::martin: Review me!
2437 @c FIXME::martin: Are all these procedures still relevant?
2439 Guile symbol tables are hash tables. Each hash table, also called an
2440 @dfn{obarray} (for `object array'), is a vector of association lists.
2441 Each entry in the alists is a pair (@var{SYMBOL} . @var{VALUE}). To
2442 @dfn{intern} a symbol in a symbol table means to return its
2443 (@var{SYMBOL} . @var{VALUE}) pair, adding a new entry to the symbol
2444 table (with an undefined value) if none is yet present.
2446 @c FIXME::martin: According to NEWS, removed. Remove here too, or
2447 @c leave for compatibility?
2448 @c @c docstring begin (texi-doc-string "guile" "builtin-bindings")
2449 @c @deffn primitive builtin-bindings
2450 @c Create and return a copy of the global symbol table, removing all
2454 @deffn primitive gensym [prefix]
2455 Create a new symbol with a name constructed from a prefix and
2456 a counter value. The string @var{prefix} can be specified as
2457 an optional argument. Default prefix is @code{g}. The counter
2458 is increased by 1 at each call. There is no provision for
2459 resetting the counter.
2462 @deffn primitive gentemp [prefix [obarray]]
2463 Create a new symbol with a name unique in an obarray.
2464 The name is constructed from an optional string @var{prefix}
2465 and a counter value. The default prefix is @code{t}. The
2466 @var{obarray} is specified as a second optional argument.
2467 Default is the system obarray where all normal symbols are
2468 interned. The counter is increased by 1 at each
2469 call. There is no provision for resetting the counter.
2472 @deffn primitive intern-symbol obarray string
2473 Add a new symbol to @var{obarray} with name @var{string}, bound to an
2474 unspecified initial value. The symbol table is not modified if a symbol
2475 with this name is already present.
2478 @deffn primitive string->obarray-symbol obarray string [soft?]
2479 Intern a new symbol in @var{obarray}, a symbol table, with name
2483 @deffn primitive symbol-binding obarray string
2484 Look up in @var{obarray} the symbol whose name is @var{string}, and
2485 return the value to which it is bound. If @var{obarray} is @code{#f},
2486 use the global symbol table. If @var{string} is not interned in
2487 @var{obarray}, an error is signalled.
2490 @deffn primitive symbol-bound? obarray string
2491 Return @code{#t} if @var{obarray} contains a symbol with name
2492 @var{string} bound to a defined value. This differs from
2493 @var{symbol-interned?} in that the mere mention of a symbol
2494 usually causes it to be interned; @code{symbol-bound?}
2495 determines whether a symbol has been given any meaningful
2499 @deffn primitive symbol-fref symbol
2500 Return the contents of @var{symbol}'s @dfn{function slot}.
2503 @deffn primitive symbol-fset! symbol value
2504 Change the binding of @var{symbol}'s function slot.
2507 @deffn primitive symbol-hash symbol
2508 Return a hash value for @var{symbol}.
2511 @deffn primitive symbol-interned? obarray string
2512 Return @code{#t} if @var{obarray} contains a symbol with name
2513 @var{string}, and @code{#f} otherwise.
2516 @deffn primitive symbol-pref symbol
2517 Return the @dfn{property list} currently associated with @var{symbol}.
2520 @deffn primitive symbol-pset! symbol value
2521 Change the binding of @var{symbol}'s property slot.
2524 @deffn primitive symbol-set! obarray string value
2525 Find the symbol in @var{obarray} whose name is @var{string}, and rebind
2526 it to @var{value}. An error is signalled if @var{string} is not present
2530 @deffn primitive unintern-symbol obarray string
2531 Remove the symbol with name @var{string} from @var{obarray}. This
2532 function returns @code{#t} if the symbol was present and @code{#f}
2537 @subsection Variables
2540 @c FIXME::martin: Review me!
2542 Variables are objects with two fields. They contain a value and they
2543 can contain a symbol, which is the name of the variable. A variable is
2544 said to be bound if it does not contain the object denoting unbound
2545 variables in the value slot.
2547 Variables do not have a read syntax, they have to be created by calling
2548 one of the constructor procedures @code{make-variable} or
2549 @code{make-undefined-variable} or retrieved by @code{builtin-variable}.
2551 First-class variables are especially useful for interacting with the
2552 current module system (@pxref{The Guile module system}).
2554 @deffn primitive builtin-variable name
2555 Return the built-in variable with the name @var{name}.
2556 @var{name} must be a symbol (not a string).
2557 Then use @code{variable-ref} to access its value.
2560 @deffn primitive make-undefined-variable
2561 Return a variable that is initially unbound.
2564 @deffn primitive make-variable init
2565 Return a variable initialized to value @var{init}.
2568 @deffn primitive variable-bound? var
2569 Return @code{#t} iff @var{var} is bound to a value.
2570 Throws an error if @var{var} is not a variable object.
2573 @deffn primitive variable-ref var
2574 Dereference @var{var} and return its value.
2575 @var{var} must be a variable object; see @code{make-variable}
2576 and @code{make-undefined-variable}.
2579 @deffn primitive variable-set! var val
2580 Set the value of the variable @var{var} to @var{val}.
2581 @var{var} must be a variable object, @var{val} can be any
2582 value. Return an unspecified value.
2585 @deffn primitive variable? obj
2586 Return @code{#t} iff @var{obj} is a variable object, else
2595 Keywords are self-evaluating objects with a convenient read syntax that
2596 makes them easy to type.
2598 Guile's keyword support conforms to R5RS, and adds a (switchable) read
2599 syntax extension to permit keywords to begin with @code{:} as well as
2603 * Why Use Keywords?:: Motivation for keyword usage.
2604 * Coding With Keywords:: How to use keywords.
2605 * Keyword Read Syntax:: Read syntax for keywords.
2606 * Keyword Procedures:: Procedures for dealing with keywords.
2607 * Keyword Primitives:: The underlying primitive procedures.
2610 @node Why Use Keywords?
2611 @subsection Why Use Keywords?
2613 Keywords are useful in contexts where a program or procedure wants to be
2614 able to accept a large number of optional arguments without making its
2615 interface unmanageable.
2617 To illustrate this, consider a hypothetical @code{make-window}
2618 procedure, which creates a new window on the screen for drawing into
2619 using some graphical toolkit. There are many parameters that the caller
2620 might like to specify, but which could also be sensibly defaulted, for
2625 colour depth -- Default: the colour depth for the screen
2628 background colour -- Default: white
2631 width -- Default: 600
2634 height -- Default: 400
2637 If @code{make-window} did not use keywords, the caller would have to
2638 pass in a value for each possible argument, remembering the correct
2639 argument order and using a special value to indicate the default value
2643 (make-window 'default ;; Colour depth
2644 'default ;; Background colour
2647 @dots{}) ;; More make-window arguments
2650 With keywords, on the other hand, defaulted arguments are omitted, and
2651 non-default arguments are clearly tagged by the appropriate keyword. As
2652 a result, the invocation becomes much clearer:
2655 (make-window #:width 800 #:height 100)
2658 On the other hand, for a simpler procedure with few arguments, the use
2659 of keywords would be a hindrance rather than a help. The primitive
2660 procedure @code{cons}, for example, would not be improved if it had to
2664 (cons #:car x #:cdr y)
2667 So the decision whether to use keywords or not is purely pragmatic: use
2668 them if they will clarify the procedure invocation at point of call.
2670 @node Coding With Keywords
2671 @subsection Coding With Keywords
2673 If a procedure wants to support keywords, it should take a rest argument
2674 and then use whatever means is convenient to extract keywords and their
2675 corresponding arguments from the contents of that rest argument.
2677 The following example illustrates the principle: the code for
2678 @code{make-window} uses a helper procedure called
2679 @code{get-keyword-value} to extract individual keyword arguments from
2683 (define (get-keyword-value args keyword default)
2684 (let ((kv (memq keyword args)))
2685 (if (and kv (>= (length kv) 2))
2689 (define (make-window . args)
2690 (let ((depth (get-keyword-value args #:depth screen-depth))
2691 (bg (get-keyword-value args #:bg "white"))
2692 (width (get-keyword-value args #:width 800))
2693 (height (get-keyword-value args #:height 100))
2698 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
2699 optargs)} module provides a set of powerful macros that you can use to
2700 implement keyword-supporting procedures like this:
2703 (use-modules (ice-9 optargs))
2705 (define (make-window . args)
2706 (let-keywords args #f ((depth screen-depth)
2714 Or, even more economically, like this:
2717 (use-modules (ice-9 optargs))
2719 (define* (make-window #:key (depth screen-depth)
2726 For further details on @code{let-keywords}, @code{define*} and other
2727 facilities provided by the @code{(ice-9 optargs)} module, @ref{Optional
2731 @node Keyword Read Syntax
2732 @subsection Keyword Read Syntax
2734 Guile, by default, only recognizes the keyword syntax specified by R5RS.
2735 A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
2736 as a Scheme symbol, is the external representation of the keyword named
2737 @code{NAME}. Keyword objects print using this syntax as well, so values
2738 containing keyword objects can be read back into Guile. When used in an
2739 expression, keywords are self-quoting objects.
2741 If the @code{keyword} read option is set to @code{'prefix}, Guile also
2742 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
2743 of the form @code{:NAME} are read as symbols, as required by R5RS.
2745 To enable and disable the alternative non-R5RS keyword syntax, you use
2746 the @code{read-options} procedure documented in @ref{General option
2747 interface} and @ref{Reader options}.
2750 (read-set! keywords 'prefix)
2760 (read-set! keywords #f)
2768 ERROR: In expression :type:
2769 ERROR: Unbound variable: :type
2770 ABORT: (unbound-variable)
2773 @node Keyword Procedures
2774 @subsection Keyword Procedures
2776 @c FIXME::martin: Review me!
2778 The following procedures can be used for converting symbols to keywords
2781 @deffn procedure symbol->keyword sym
2782 Return a keyword with the same characters as in @var{sym}.
2785 @deffn procedure keyword->symbol kw
2786 Return a symbol with the same characters as in @var{kw}.
2790 @node Keyword Primitives
2791 @subsection Keyword Primitives
2793 Internally, a keyword is implemented as something like a tagged symbol,
2794 where the tag identifies the keyword as being self-evaluating, and the
2795 symbol, known as the keyword's @dfn{dash symbol} has the same name as
2796 the keyword name but prefixed by a single dash. For example, the
2797 keyword @code{#:name} has the corresponding dash symbol @code{-name}.
2799 Most keyword objects are constructed automatically by the reader when it
2800 reads a token beginning with @code{#:}. However, if you need to
2801 construct a keyword object programmatically, you can do so by calling
2802 @code{make-keyword-from-dash-symbol} with the corresponding dash symbol
2803 (as the reader does). The dash symbol for a keyword object can be
2804 retrieved using the @code{keyword-dash-symbol} procedure.
2806 @deffn primitive make-keyword-from-dash-symbol symbol
2807 Make a keyword object from a @var{symbol} that starts with a dash.
2810 @deffn primitive keyword? obj
2811 Return @code{#t} if the argument @var{obj} is a keyword, else
2815 @deffn primitive keyword-dash-symbol keyword
2816 Return the dash symbol for @var{keyword}.
2817 This is the inverse of @code{make-keyword-from-dash-symbol}.
2824 @c FIXME::martin: Review me!
2826 Pairs are used to combine two Scheme objects into one compound object.
2827 Hence the name: A pair stores a pair of objects.
2829 The data type @emph{pair} is extremely important in Scheme, just like in
2830 any other Lisp dialect. The reason is that pairs are not only used to
2831 make two values available as one object, but that pairs are used for
2832 constructing lists of values. Because lists are so important in Scheme,
2833 they are described in a section of their own (@pxref{Lists}).
2835 Pairs can literally get entered in source code or at the REPL, in the
2836 so-called @dfn{dotted list} syntax. This syntax consists of an opening
2837 parentheses, the first element of the pair, a dot, the second element
2838 and a closing parentheses. The following example shows how a pair
2839 consisting of the two numbers 1 and 2, and a pair containing the symbols
2840 @code{foo} and @code{bar} can be entered. It is very important to write
2841 the whitespace before and after the dot, because otherwise the Scheme
2842 parser whould not be able to figure out where to split the tokens.
2849 But beware, if you want to try out these examples, you have to
2850 @dfn{quote} the expressions. More information about quotation is
2851 available in the section (REFFIXME). The correct way to try these
2852 examples is as follows.
2863 A new pair is made by calling the procedure @code{cons} with two
2864 arguments. Then the argument values are stored into a newly allocated
2865 pair, and the pair is returned. The name @code{cons} stands for
2866 @emph{construct}. Use the procedure @code{pair?} to test whether a
2867 given Scheme object is a pair or not.
2870 @deffn primitive cons x y
2871 Return a newly allocated pair whose car is @var{x} and whose
2872 cdr is @var{y}. The pair is guaranteed to be different (in the
2873 sense of @code{eq?}) from every previously existing object.
2877 @deffn primitive pair? x
2878 Return @code{#t} if @var{x} is a pair; otherwise return
2882 The two parts of a pair are traditionally called @emph{car} and
2883 @emph{cdr}. They can be retrieved with procedures of the same name
2884 (@code{car} and @code{cdr}), and can be modified with the procedures
2885 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
2886 Scheme programs is to access the car of a pair, or the car of the cdr of
2887 a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
2888 are also predefined.
2892 @deffn primitive car pair
2893 @deffnx primitive cdr pair
2894 Return the car or the cdr of @var{pair}, respectively.
2897 @deffn primitive caar pair
2898 @deffnx primitive cadr pair @dots{}
2899 @deffnx primitive cdddar pair
2900 @deffnx primitive cddddr pair
2901 These procedures are compositions of @code{car} and @code{cdr}, where
2902 for example @code{caddr} could be defined by
2905 (define caddr (lambda (x) (car (cdr (cdr x)))))
2910 @deffn primitive set-car! pair value
2911 Stores @var{value} in the car field of @var{pair}. The value returned
2912 by @code{set-car!} is unspecified.
2916 @deffn primitive set-cdr! pair value
2917 Stores @var{value} in the cdr field of @var{pair}. The value returned
2918 by @code{set-cdr!} is unspecified.
2926 @c FIXME::martin: Review me!
2928 A very important data type in Scheme---as well as in all other Lisp
2929 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
2930 Scheme does not have a real datatype @emph{list}. Lists are made up of
2931 chained @emph{pairs}, and only exist by definition---a list is a chain
2932 of pairs which looks like a list.}
2934 This is the short definition of what a list is:
2938 Either the empty list @code{()},
2941 or a pair which has a list in its cdr.
2944 @c FIXME::martin: Describe the pair chaining in more detail.
2946 @c FIXME::martin: What is a proper, what an improper list?
2947 @c What is a circular list?
2949 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
2953 * List Syntax:: Writing literal lists.
2954 * List Predicates:: Testing lists.
2955 * List Constructors:: Creating new lists.
2956 * List Selection:: Selecting from lists, getting their length.
2957 * Append/Reverse:: Appending and reversing lists.
2958 * List Modifification:: Modifying list structure.
2959 * List Searching:: Searching for list elements
2960 * List Mapping:: Applying procedures to lists.
2964 @subsection List Read Syntax
2966 @c FIXME::martin: Review me!
2968 The syntax for lists is an opening parentheses, then all the elements of
2969 the list (separated by whitespace) and finally a closing
2970 parentheses.@footnote{Note that there is no separation character between
2971 the list elements, like a comma or a semicolon.}.
2974 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
2975 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
2976 () ; @r{the empty list}
2979 The last example needs a bit more explanation. A list with no elements,
2980 called the @dfn{empty list}, is special in some ways. It is used for
2981 terminating lists by storing it into the cdr of the last pair that makes
2982 up a list. An example will clear that up:
2993 This example also shows that lists have to be quoted (REFFIXME) when
2994 written, because they would otherwise be mistakingly taken as procedure
2995 applications (@pxref{Simple Invocation}).
2998 @node List Predicates
2999 @subsection List Predicates
3001 @c FIXME::martin: Review me!
3003 Often it is useful to test whether a given Scheme object is a list or
3004 not. List-processing procedures could use this information to test
3005 whether their input is valid, or they could do different things
3006 depending on the datatype of their arguments.
3009 @deffn primitive list? x
3010 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
3013 The predicate @code{null?} is often used in list-processing code to
3014 tell whether a given list has run out of elements. That is, a loop
3015 somehow deals with the elements of a list until the list satisfies
3016 @code{null?}. Then, teh algorithm terminates.
3019 @deffn primitive null? x
3020 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
3023 @node List Constructors
3024 @subsection List Constructors
3026 This section describes the procedures for constructing new lists.
3027 @code{list} simply returns a list where the elements are the arguments,
3028 @code{cons*} is similar, but the last argument is stored in the cdr of
3029 the last pair of the list.
3032 @deffn primitive list arg1 @dots{}
3033 Return a list containing @var{objs}, the arguments to
3037 @deffn primitive cons* arg1 arg2 @dots{}
3038 Like @code{list}, but the last arg provides the tail of the
3039 constructed list, returning @code{(cons @var{arg1} (cons
3040 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
3041 argument. If given one argument, that argument is returned as
3042 result. This function is called @code{list*} in some other
3043 Schemes and in Common LISP.
3046 @deffn primitive list-copy lst
3047 Return a (newly-created) copy of @var{lst}.
3050 @deffn procedure make-list n [init]
3051 Create a list containing of @var{n} elements, where each element is
3052 initialized to @var{init}. @var{init} defaults to the empty list
3053 @code{()} if not given.
3056 Note that @code{list-copy} only makes a copy of the pairs which make up
3057 the spine of the lists. The list elements are not copied, which means
3058 that modifying the elements of the new list also modyfies the elements
3059 of the old list. On the other hand, applying procedures like
3060 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
3061 list. If you also need to copy the list elements (making a deep copy),
3062 use the procedure @code{copy-tree} (@pxref{Copying}).
3064 @node List Selection
3065 @subsection List Selection
3067 @c FIXME::martin: Review me!
3069 These procedures are used to get some information about a list, or to
3070 retrieve one or more elements of a list.
3073 @deffn primitive length lst
3074 Return the number of elements in list @var{lst}.
3077 @deffn primitive last-pair lst
3078 Return a pointer to the last pair in @var{lst}, signalling an error if
3079 @var{lst} is circular.
3083 @deffn primitive list-ref list k
3084 Return the @var{k}th element from @var{list}.
3088 @deffn primitive list-tail lst k
3089 @deffnx primitive list-cdr-ref lst k
3090 Return the "tail" of @var{lst} beginning with its @var{k}th element.
3091 The first element of the list is considered to be element 0.
3093 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
3094 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
3095 or returning the results of cdring @var{k} times down @var{lst}.
3098 @deffn primitive list-head lst k
3099 Copy the first @var{k} elements from @var{lst} into a new list, and
3103 @node Append/Reverse
3104 @subsection Append and Reverse
3106 @c FIXME::martin: Review me!
3108 @code{append} and @code{append!} are used to concatenate two or more
3109 lists in order to form a new list. @code{reverse} and @code{reverse!}
3110 return lists with the same elements as their arguments, but in reverse
3111 order. The procedure variants with an @code{!} directly modify the
3112 pairs which form the list, whereas the other procedures create new
3113 pairs. This is why you should be careful when using the side-effecting
3117 @deffn primitive append . args
3118 Return a list consisting of the elements the lists passed as
3121 (append '(x) '(y)) @result{} (x y)
3122 (append '(a) '(b c d)) @result{} (a b c d)
3123 (append '(a (b)) '((c))) @result{} (a (b) (c))
3125 The resulting list is always newly allocated, except that it
3126 shares structure with the last list argument. The last
3127 argument may actually be any object; an improper list results
3128 if the last argument is not a proper list.
3130 (append '(a b) '(c . d)) @result{} (a b c . d)
3131 (append '() 'a) @result{} a
3135 @deffn primitive append! . lists
3136 A destructive version of @code{append} (@pxref{Pairs and
3137 lists,,,r5rs, The Revised^5 Report on Scheme}). The cdr field
3138 of each list's final pair is changed to point to the head of
3139 the next list, so no consing is performed. Return a pointer to
3144 @deffn primitive reverse lst
3145 Return a new list that contains the elements of @var{lst} but
3149 @c NJFIXME explain new_tail
3150 @deffn primitive reverse! lst [new_tail]
3151 A destructive version of @code{reverse} (@pxref{Pairs and lists,,,r5rs,
3152 The Revised^5 Report on Scheme}). The cdr of each cell in @var{lst} is
3153 modified to point to the previous list element. Return a pointer to the
3154 head of the reversed list.
3156 Caveat: because the list is modified in place, the tail of the original
3157 list now becomes its head, and the head of the original list now becomes
3158 the tail. Therefore, the @var{lst} symbol to which the head of the
3159 original list was bound now points to the tail. To ensure that the head
3160 of the modified list is not lost, it is wise to save the return value of
3164 @node List Modifification
3165 @subsection List Modification
3167 @c FIXME::martin: Review me!
3169 The following procedures modify existing list. @code{list-set!} and
3170 @code{list-cdr-set!} change which elements a list contains, the various
3171 deletion procedures @code{delq}, @code{delv} etc.
3173 @deffn primitive list-set! list k val
3174 Set the @var{k}th element of @var{list} to @var{val}.
3177 @deffn primitive list-cdr-set! list k val
3178 Set the @var{k}th cdr of @var{list} to @var{val}.
3181 @deffn primitive delq item lst
3182 Return a newly-created copy of @var{lst} with elements
3183 @code{eq?} to @var{item} removed. This procedure mirrors
3184 @code{memq}: @code{delq} compares elements of @var{lst} against
3185 @var{item} with @code{eq?}.
3188 @deffn primitive delv item lst
3189 Return a newly-created copy of @var{lst} with elements
3190 @code{eqv?} to @var{item} removed. This procedure mirrors
3191 @code{memv}: @code{delv} compares elements of @var{lst} against
3192 @var{item} with @code{eqv?}.
3195 @deffn primitive delete item lst
3196 Return a newly-created copy of @var{lst} with elements
3197 @code{equal?} to @var{item} removed. This procedure mirrors
3198 @code{member}: @code{delete} compares elements of @var{lst}
3199 against @var{item} with @code{equal?}.
3202 @deffn primitive delq! item lst
3203 @deffnx primitive delv! item lst
3204 @deffnx primitive delete! item lst
3205 These procedures are destructive versions of @code{delq}, @code{delv}
3206 and @code{delete}: they modify the pointers in the existing @var{lst}
3207 rather than creating a new list. Caveat evaluator: Like other
3208 destructive list functions, these functions cannot modify the binding of
3209 @var{lst}, and so cannot be used to delete the first element of
3210 @var{lst} destructively.
3213 @deffn primitive delq1! item lst
3214 Like @code{delq!}, but only deletes the first occurrence of
3215 @var{item} from @var{lst}. Tests for equality using
3216 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
3219 @deffn primitive delv1! item lst
3220 Like @code{delv!}, but only deletes the first occurrence of
3221 @var{item} from @var{lst}. Tests for equality using
3222 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
3225 @deffn primitive delete1! item lst
3226 Like @code{delete!}, but only deletes the first occurrence of
3227 @var{item} from @var{lst}. Tests for equality using
3228 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
3231 @node List Searching
3232 @subsection List Searching
3234 @c FIXME::martin: Review me!
3236 The following procedures search lists for particular elements. They use
3237 different comparison predicates for comparing list elements with the
3238 object to be seached. When they fail, they return @code{#f}, otherwise
3239 they return the sublist whose car is equal to the search object, where
3240 equality depends on the equality predicate used.
3243 @deffn primitive memq x lst
3244 Return the first sublist of @var{lst} whose car is @code{eq?}
3245 to @var{x} where the sublists of @var{lst} are the non-empty
3246 lists returned by @code{(list-tail @var{lst} @var{k})} for
3247 @var{k} less than the length of @var{lst}. If @var{x} does not
3248 occur in @var{lst}, then @code{#f} (not the empty list) is
3253 @deffn primitive memv x lst
3254 Return the first sublist of @var{lst} whose car is @code{eqv?}
3255 to @var{x} where the sublists of @var{lst} are the non-empty
3256 lists returned by @code{(list-tail @var{lst} @var{k})} for
3257 @var{k} less than the length of @var{lst}. If @var{x} does not
3258 occur in @var{lst}, then @code{#f} (not the empty list) is
3263 @deffn primitive member x lst
3264 Return the first sublist of @var{lst} whose car is
3265 @code{equal?} to @var{x} where the sublists of @var{lst} are
3266 the non-empty lists returned by @code{(list-tail @var{lst}
3267 @var{k})} for @var{k} less than the length of @var{lst}. If
3268 @var{x} does not occur in @var{lst}, then @code{#f} (not the
3269 empty list) is returned.
3272 [FIXME: is there any reason to have the `sloppy' functions available at
3273 high level at all? Maybe these docs should be relegated to a "Guile
3274 Internals" node or something. -twp]
3276 @deffn primitive sloppy-memq x lst
3277 This procedure behaves like @code{memq}, but does no type or error checking.
3278 Its use is recommended only in writing Guile internals,
3279 not for high-level Scheme programs.
3282 @deffn primitive sloppy-memv x lst
3283 This procedure behaves like @code{memv}, but does no type or error checking.
3284 Its use is recommended only in writing Guile internals,
3285 not for high-level Scheme programs.
3288 @deffn primitive sloppy-member x lst
3289 This procedure behaves like @code{member}, but does no type or error checking.
3290 Its use is recommended only in writing Guile internals,
3291 not for high-level Scheme programs.
3295 @subsection List Mapping
3297 @c FIXME::martin: Review me!
3299 List processing is very convenient in Scheme because the process of
3300 iterating over the elements of a list can be highly abstracted. The
3301 procedures in this section are the most basic iterating procedures for
3302 lists. They take a procedure and one or more lists as arguments, and
3303 apply the procedure to each element of the list. They differ in what
3304 the result of the invocation is.
3307 @c begin (texi-doc-string "guile" "map")
3308 @deffn primitive map proc arg1 arg2 @dots{}
3309 @deffnx primitive map-in-order proc arg1 arg2 @dots{}
3310 Apply @var{proc} to each element of the list @var{arg1} (if only two
3311 arguments are given), or to the corresponding elements of the argument
3312 lists (if more than two arguments are given). The result(s) of the
3313 procedure applications are saved and returned in a list. For
3314 @code{map}, the order of procedure applications is not specified,
3315 @code{map-in-order} applies the procedure from left to right to the list
3320 @c begin (texi-doc-string "guile" "for-each")
3321 @deffn primitive for-each proc arg1 arg2 @dots{}
3322 Like @code{map}, but the procedure is always applied from left to right,
3323 and the result(s) of the procedure applications are thrown away. The
3324 return value is not specified.
3332 @c FIXME::martin: Review me!
3334 @c FIXME::martin: Should the subsections of this section be nodes
3335 @c of their own, or are the resulting nodes too short, then?
3337 Vectors are sequences of Scheme objects. Unlike lists, the length of a
3338 vector, once the vector is created, cannot be changed. The advantage of
3339 vectors over lists is that the time required to access one element of a
3340 vector is constant, whereas lists have an access time linear to the
3341 index of the accessed element in the list.
3343 Note that the vectors documented in this section can contain any kind of
3344 Scheme object, it is even possible to have different types of objects in
3347 @subsection Vector Read Syntax
3349 Vectors can literally be entered in source code, just like strings,
3350 characters or some of the other data types. The read syntax for vectors
3351 is as follows: A sharp sign (@code{#}), followed by an opening
3352 parentheses, all elements of the vector in their respective read syntax,
3353 and finally a closing parentheses. The following are examples of the
3354 read syntax for vectors; where the first vector only contains numbers
3355 and the second three different object types: a string, a symbol and a
3356 number in hexidecimal notation.
3360 #("Hello" foo #xdeadbeef)
3363 @subsection Vector Predicates
3366 @deffn primitive vector? obj
3367 Return @code{#t} if @var{obj} is a vector, otherwise return
3371 @subsection Vector Constructors
3373 @rnindex make-vector
3374 @deffn primitive make-vector k [fill]
3375 Return a newly allocated vector of @var{k} elements. If a
3376 second argument is given, then each element is initialized to
3377 @var{fill}. Otherwise the initial contents of each element is
3382 @rnindex list->vector
3383 @deffn primitive vector . l
3384 @deffnx primitive list->vector l
3385 Return a newly allocated vector whose elements contain the
3386 given arguments. Analogous to @code{list}.
3389 (vector 'a 'b 'c) @result{} #(a b c)
3393 @rnindex vector->list
3394 @deffn primitive vector->list v
3395 Return a newly allocated list of the objects contained in the
3396 elements of @var{vector}.
3399 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
3400 (list->vector '(dididit dah)) @result{} #(dididit dah)
3404 @subsection Vector Modification
3406 A vector created by any of the vector constructor procedures
3407 (@pxref{Vectors}) documented above can be modified using the
3408 following procedures.
3410 According to R5RS, using any of these procedures on literally entered
3411 vectors is an error, because these vectors are considered to be
3412 constant, although Guile currently does not detect this error.
3414 @rnindex vector-set!
3415 @deffn primitive vector-set! vector k obj
3416 @var{k} must be a valid index of @var{vector}.
3417 @code{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
3418 The value returned by @samp{vector-set!} is unspecified.
3420 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
3421 (vector-set! vec 1 '("Sue" "Sue"))
3422 vec) @result{} #(0 ("Sue" "Sue") "Anna")
3423 (vector-set! '#(0 1 2) 1 "doe") @result{} @emph{error} ; constant vector
3427 @rnindex vector-fill!
3428 @deffn primitive vector-fill! v fill
3429 Store @var{fill} in every element of @var{vector}. The value
3430 returned by @code{vector-fill!} is unspecified.
3433 @deffn primitive vector-move-left! vec1 start1 end1 vec2 start2
3434 Vector version of @code{substring-move-left!}.
3437 @deffn primitive vector-move-right! vec1 start1 end1 vec2 start2
3438 Vector version of @code{substring-move-right!}.
3441 @subsection Vector Selection
3443 These procedures return information about a given vector, such as the
3444 size or what elements are contained in the vector.
3446 @rnindex vector-length
3447 @deffn primitive vector-length vector
3448 Returns the number of elements in @var{vector} as an exact integer.
3452 @deffn primitive vector-ref vector k
3453 @var{k} must be a valid index of @var{vector}.
3454 @samp{Vector-ref} returns the contents of element @var{k} of
3457 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
3458 (vector-ref '#(1 1 2 3 5 8 13 21)
3459 (let ((i (round (* 2 (acos -1)))))
3470 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3473 A @dfn{record type} is a first class object representing a user-defined
3474 data type. A @dfn{record} is an instance of a record type.
3476 @deffn procedure record? obj
3477 Returns @code{#t} if @var{obj} is a record of any type and @code{#f}
3480 Note that @code{record?} may be true of any Scheme value; there is no
3481 promise that records are disjoint with other Scheme types.
3484 @deffn procedure make-record-type type-name field-names
3485 Returns a @dfn{record-type descriptor}, a value representing a new data
3486 type disjoint from all others. The @var{type-name} argument must be a
3487 string, but is only used for debugging purposes (such as the printed
3488 representation of a record of the new type). The @var{field-names}
3489 argument is a list of symbols naming the @dfn{fields} of a record of the
3490 new type. It is an error if the list contains any duplicates. It is
3491 unspecified how record-type descriptors are represented.@refill
3494 @deffn procedure record-constructor rtd [field-names]
3495 Returns a procedure for constructing new members of the type represented
3496 by @var{rtd}. The returned procedure accepts exactly as many arguments
3497 as there are symbols in the given list, @var{field-names}; these are
3498 used, in order, as the initial values of those fields in a new record,
3499 which is returned by the constructor procedure. The values of any
3500 fields not named in that list are unspecified. The @var{field-names}
3501 argument defaults to the list of field names in the call to
3502 @code{make-record-type} that created the type represented by @var{rtd};
3503 if the @var{field-names} argument is provided, it is an error if it
3504 contains any duplicates or any symbols not in the default list.@refill
3507 @deffn procedure record-predicate rtd
3508 Returns a procedure for testing membership in the type represented by
3509 @var{rtd}. The returned procedure accepts exactly one argument and
3510 returns a true value if the argument is a member of the indicated record
3511 type; it returns a false value otherwise.@refill
3514 @deffn procedure record-accessor rtd field-name
3515 Returns a procedure for reading the value of a particular field of a
3516 member of the type represented by @var{rtd}. The returned procedure
3517 accepts exactly one argument which must be a record of the appropriate
3518 type; it returns the current value of the field named by the symbol
3519 @var{field-name} in that record. The symbol @var{field-name} must be a
3520 member of the list of field-names in the call to @code{make-record-type}
3521 that created the type represented by @var{rtd}.@refill
3524 @deffn procedure record-modifier rtd field-name
3525 Returns a procedure for writing the value of a particular field of a
3526 member of the type represented by @var{rtd}. The returned procedure
3527 accepts exactly two arguments: first, a record of the appropriate type,
3528 and second, an arbitrary Scheme value; it modifies the field named by
3529 the symbol @var{field-name} in that record to contain the given value.
3530 The returned value of the modifier procedure is unspecified. The symbol
3531 @var{field-name} must be a member of the list of field-names in the call
3532 to @code{make-record-type} that created the type represented by
3536 @deffn procedure record-type-descriptor record
3537 Returns a record-type descriptor representing the type of the given
3538 record. That is, for example, if the returned descriptor were passed to
3539 @code{record-predicate}, the resulting predicate would return a true
3540 value when passed the given record. Note that it is not necessarily the
3541 case that the returned descriptor is the one that was passed to
3542 @code{record-constructor} in the call that created the constructor
3543 procedure that created the given record.@refill
3546 @deffn procedure record-type-name rtd
3547 Returns the type-name associated with the type represented by rtd. The
3548 returned value is @code{eqv?} to the @var{type-name} argument given in
3549 the call to @code{make-record-type} that created the type represented by
3553 @deffn procedure record-type-fields rtd
3554 Returns a list of the symbols naming the fields in members of the type
3555 represented by @var{rtd}. The returned value is @code{equal?} to the
3556 field-names argument given in the call to @code{make-record-type} that
3557 created the type represented by @var{rtd}.@refill
3565 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3568 A @dfn{structure type} is a first class user-defined data type. A
3569 @dfn{structure} is an instance of a structure type. A structure type is
3572 Structures are less abstract and more general than traditional records.
3573 In fact, in Guile Scheme, records are implemented using structures.
3576 * Structure Concepts:: The structure of Structures
3577 * Structure Layout:: Defining the layout of structure types
3578 * Structure Basics:: make-, -ref and -set! procedures for structs
3579 * Vtables:: Accessing type-specific data
3582 @node Structure Concepts
3583 @subsection Structure Concepts
3585 A structure object consists of a handle, structure data, and a vtable.
3586 The handle is a Scheme value which points to both the vtable and the
3587 structure's data. Structure data is a dynamically allocated region of
3588 memory, private to the structure, divided up into typed fields. A
3589 vtable is another structure used to hold type-specific data. Multiple
3590 structures can share a common vtable.
3592 Three concepts are key to understanding structures.
3595 @item @dfn{layout specifications}
3597 Layout specifications determine how memory allocated to structures is
3598 divided up into fields. Programmers must write a layout specification
3599 whenever a new type of structure is defined.
3601 @item @dfn{structural accessors}
3603 Structure access is by field number. There is only one set of
3604 accessors common to all structure objects.
3608 Vtables, themselves structures, are first class representations of
3609 disjoint sub-types of structures in general. In most cases, when a
3610 new structure is created, programmers must specifiy a vtable for the
3611 new structure. Each vtable has a field describing the layout of its
3612 instances. Vtables can have additional, user-defined fields as well.
3617 @node Structure Layout
3618 @subsection Structure Layout
3620 When a structure is created, a region of memory is allocated to hold its
3621 state. The @dfn{layout} of the structure's type determines how that
3622 memory is divided into fields.
3624 Each field has a specified type. There are only three types allowed, each
3625 corresponding to a one letter code. The allowed types are:
3628 @item 'u' -- unprotected
3630 The field holds binary data that is not GC protected.
3632 @item 'p' -- protected
3634 The field holds a Scheme value and is GC protected.
3638 The field holds a Scheme value and is GC protected. When a structure is
3639 created with this type of field, the field is initialized to refer to
3640 the structure's own handle. This kind of field is mainly useful when
3641 mixing Scheme and C code in which the C code may need to compute a
3642 structure's handle given only the address of its malloced data.
3646 Each field also has an associated access protection. There are only
3647 three kinds of protection, each corresponding to a one letter code.
3648 The allowed protections are:
3651 @item 'w' -- writable
3653 The field can be read and written.
3655 @item 'r' -- readable
3657 The field can be read, but not written.
3661 The field can be neither read nor written. This kind
3662 of protection is for fields useful only to built-in routines.
3665 A layout specification is described by stringing together pairs
3666 of letters: one to specify a field type and one to specify a field
3667 protection. For example, a traditional cons pair type object could
3671 ; cons pairs have two writable fields of Scheme data
3675 A pair object in which the first field is held constant could be:
3681 Binary fields, (fields of type "u"), hold one @emph{word} each. The
3682 size of a word is a machine dependent value defined to be equal to the
3683 value of the C expression: @code{sizeof (long)}.
3685 The last field of a structure layout may specify a tail array.
3686 A tail array is indicated by capitalizing the field's protection
3687 code ('W', 'R' or 'O'). A tail-array field is replaced by
3688 a read-only binary data field containing an array size. The array
3689 size is determined at the time the structure is created. It is followed
3690 by a corresponding number of fields of the type specified for the
3691 tail array. For example, a conventional Scheme vector can be
3695 ; A vector is an arbitrary number of writable fields holding Scheme
3700 In the above example, field 0 contains the size of the vector and
3701 fields beginning at 1 contain the vector elements.
3703 A kind of tagged vector (a constant tag followed by conventioal
3704 vector elements) might be:
3711 Structure layouts are represented by specially interned symbols whose
3712 name is a string of type and protection codes. To create a new
3713 structure layout, use this procedure:
3715 @deffn primitive make-struct-layout fields
3716 Return a new structure layout object.
3718 @var{fields} must be a string made up of pairs of characters
3719 strung together. The first character of each pair describes a field
3720 type, the second a field protection. Allowed types are 'p' for
3721 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
3722 a field that points to the structure itself. Allowed protections
3723 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
3724 fields. The last field protection specification may be capitalized to
3725 indicate that the field is a tail-array.
3730 @node Structure Basics
3731 @subsection Structure Basics
3733 This section describes the basic procedures for creating and accessing
3736 @deffn primitive make-struct vtable tail_array_size . init
3737 Create a new structure.
3739 @var{type} must be a vtable structure (@pxref{Vtables}).
3741 @var{tail-elts} must be a non-negative integer. If the layout
3742 specification indicated by @var{type} includes a tail-array,
3743 this is the number of elements allocated to that array.
3745 The @var{init1}, @dots{} are optional arguments describing how
3746 successive fields of the structure should be initialized. Only fields
3747 with protection 'r' or 'w' can be initialized, except for fields of
3748 type 's', which are automatically initialized to point to the new
3749 structure itself; fields with protection 'o' can not be initialized by
3752 If fewer optional arguments than initializable fields are supplied,
3753 fields of type 'p' get default value #f while fields of type 'u' are
3756 Structs are currently the basic representation for record-like data
3757 structures in Guile. The plan is to eventually replace them with a
3758 new representation which will at the same time be easier to use and
3761 For more information, see the documentation for @code{make-vtable-vtable}.
3764 @deffn primitive struct? x
3765 Return @code{#t} iff @var{obj} is a structure object, else
3770 @deffn primitive struct-ref handle pos
3771 @deffnx primitive struct-set! struct n value
3772 Access (or modify) the @var{n}th field of @var{struct}.
3774 If the field is of type 'p', then it can be set to an arbitrary value.
3776 If the field is of type 'u', then it can only be set to a non-negative
3777 integer value small enough to fit in one machine word.
3785 Vtables are structures that are used to represent structure types. Each
3786 vtable contains a layout specification in field
3787 @code{vtable-index-layout} -- instances of the type are laid out
3788 according to that specification. Vtables contain additional fields
3789 which are used only internally to libguile. The variable
3790 @code{vtable-offset-user} is bound to a field number. Vtable fields
3791 at that position or greater are user definable.
3793 @deffn primitive struct-vtable handle
3794 Return the vtable structure that describes the type of @var{struct}.
3797 @deffn primitive struct-vtable? x
3798 Return @code{#t} iff obj is a vtable structure.
3801 If you have a vtable structure, @code{V}, you can create an instance of
3802 the type it describes by using @code{(make-struct V ...)}. But where
3803 does @code{V} itself come from? One possibility is that @code{V} is an
3804 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
3805 created by using @code{(make-struct V' ...)}. Another possibility is
3806 that @code{V} is an instance of the type it itself describes. Vtable
3807 structures of the second sort are created by this procedure:
3809 @deffn primitive make-vtable-vtable user_fields tail_array_size . init
3810 Return a new, self-describing vtable structure.
3812 @var{user-fields} is a string describing user defined fields of the
3813 vtable beginning at index @code{vtable-offset-user}
3814 (see @code{make-struct-layout}).
3816 @var{tail-size} specifies the size of the tail-array (if any) of
3819 @var{init1}, @dots{} are the optional initializers for the fields of
3822 Vtables have one initializable system field---the struct printer.
3823 This field comes before the user fields in the initializers passed
3824 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
3825 a third optional argument to @code{make-vtable-vtable} and a fourth to
3826 @code{make-struct} when creating vtables:
3828 If the value is a procedure, it will be called instead of the standard
3829 printer whenever a struct described by this vtable is printed.
3830 The procedure will be called with arguments STRUCT and PORT.
3832 The structure of a struct is described by a vtable, so the vtable is
3833 in essence the type of the struct. The vtable is itself a struct with
3834 a vtable. This could go on forever if it weren't for the
3835 vtable-vtables which are self-describing vtables, and thus terminate
3838 There are several potential ways of using structs, but the standard
3839 one is to use three kinds of structs, together building up a type
3840 sub-system: one vtable-vtable working as the root and one or several
3841 "types", each with a set of "instances". (The vtable-vtable should be
3842 compared to the class <class> which is the class of itself.)
3845 (define ball-root (make-vtable-vtable "pr" 0))
3847 (define (make-ball-type ball-color)
3848 (make-struct ball-root 0
3849 (make-struct-layout "pw")
3851 (format port "#<a ~A ball owned by ~A>"
3855 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
3856 (define (owner ball) (struct-ref ball 0))
3858 (define red (make-ball-type 'red))
3859 (define green (make-ball-type 'green))
3861 (define (make-ball type owner) (make-struct type 0 owner))
3863 (define ball (make-ball green 'Nisse))
3864 ball @result{} #<a green ball owned by Nisse>
3868 @deffn primitive struct-vtable-name vtable
3869 Return the name of the vtable @var{vtable}.
3872 @deffn primitive set-struct-vtable-name! vtable name
3873 Set the name of the vtable @var{vtable} to @var{name}.
3876 @deffn primitive struct-vtable-tag handle
3877 Return the vtable tag of the structure @var{handle}.
3886 * Conventional Arrays:: Arrays with arbitrary data.
3887 * Array Mapping:: Applying a procedure to the contents of an array.
3888 * Uniform Arrays:: Arrays with data of a single type.
3889 * Bit Vectors:: Vectors of bits.
3892 @node Conventional Arrays
3893 @subsection Conventional Arrays
3895 @dfn{Conventional arrays} are a collection of cells organised into an
3896 arbitrary number of dimensions. Each cell can hold any kind of Scheme
3897 value and can be accessed in constant time by supplying an index for
3898 each dimension. This contrasts with uniform arrays, which use memory
3899 more efficiently but can hold data of only a single type, and lists
3900 where inserting and deleting cells is more efficient, but more time
3901 is usually required to access a particular cell.
3903 A conventional array is displayed as @code{#} followed by the @dfn{rank}
3904 (number of dimensions) followed by the cells, organised into dimensions
3905 using parentheses. The nesting depth of the parentheses is equal to
3908 When an array is created, the number of dimensions and range of each
3909 dimension must be specified, e.g., to create a 2x3 array with a
3913 (make-array 'ho 2 3) @result{}
3914 #2((ho ho ho) (ho ho ho))
3917 The range of each dimension can also be given explicitly, e.g., another
3918 way to create the same array:
3921 (make-array 'ho '(0 1) '(0 2)) @result{}
3922 #2((ho ho ho) (ho ho ho))
3925 A conventional array with one dimension based at zero is identical to
3929 (make-array 'ho 3) @result{}
3933 The following procedures can be used with conventional arrays (or vectors).
3935 @deffn primitive array? v [prot]
3936 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
3937 not. The @var{prototype} argument is used with uniform arrays
3938 and is described elsewhere.
3941 @deffn procedure make-array initial-value bound1 bound2 @dots{}
3942 Creates and returns an array that has as many dimensions as there are
3943 @var{bound}s and fills it with @var{initial-value}.
3946 @c array-ref's type is `compiled-closure'. There's some weird stuff
3947 @c going on in array.c, too. Let's call it a primitive. -twp
3949 @deffn primitive uniform-vector-ref v args
3950 @deffnx primitive array-ref v . args
3951 Return the element at the @code{(index1, index2)} element in
3955 @deffn primitive array-in-bounds? v . args
3956 Return @code{#t} if its arguments would be acceptable to
3960 @deffn primitive array-set! v obj . args
3961 @deffnx primitive uniform-array-set1! v obj args
3962 Sets the element at the @code{(index1, index2)} element in @var{array} to
3963 @var{new-value}. The value returned by array-set! is unspecified.
3966 @deffn primitive make-shared-array oldra mapfunc . dims
3967 @code{make-shared-array} can be used to create shared subarrays of other
3968 arrays. The @var{mapper} is a function that translates coordinates in
3969 the new array into coordinates in the old array. A @var{mapper} must be
3970 linear, and its range must stay within the bounds of the old array, but
3971 it can be otherwise arbitrary. A simple example:
3973 (define fred (make-array #f 8 8))
3974 (define freds-diagonal
3975 (make-shared-array fred (lambda (i) (list i i)) 8))
3976 (array-set! freds-diagonal 'foo 3)
3977 (array-ref fred 3 3) @result{} foo
3978 (define freds-center
3979 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
3980 (array-ref freds-center 0 0) @result{} foo
3984 @deffn primitive shared-array-increments ra
3985 For each dimension, return the distance between elements in the root vector.
3988 @deffn primitive shared-array-offset ra
3989 Return the root vector index of the first element in the array.
3992 @deffn primitive shared-array-root ra
3993 Return the root vector of a shared array.
3996 @deffn primitive transpose-array ra . args
3997 Return an array sharing contents with @var{array}, but with
3998 dimensions arranged in a different order. There must be one
3999 @var{dim} argument for each dimension of @var{array}.
4000 @var{dim0}, @var{dim1}, @dots{} should be integers between 0
4001 and the rank of the array to be returned. Each integer in that
4002 range must appear at least once in the argument list.
4004 The values of @var{dim0}, @var{dim1}, @dots{} correspond to
4005 dimensions in the array to be returned, their positions in the
4006 argument list to dimensions of @var{array}. Several @var{dim}s
4007 may have the same value, in which case the returned array will
4008 have smaller rank than @var{array}.
4011 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
4012 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
4013 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
4014 #2((a 4) (b 5) (c 6))
4018 @deffn primitive enclose-array ra . axes
4019 @var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
4020 the rank of @var{array}. @var{enclose-array} returns an array
4021 resembling an array of shared arrays. The dimensions of each shared
4022 array are the same as the @var{dim}th dimensions of the original array,
4023 the dimensions of the outer array are the same as those of the original
4024 array that did not match a @var{dim}.
4026 An enclosed array is not a general Scheme array. Its elements may not
4027 be set using @code{array-set!}. Two references to the same element of
4028 an enclosed array will be @code{equal?} but will not in general be
4029 @code{eq?}. The value returned by @var{array-prototype} when given an
4030 enclosed array is unspecified.
4034 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
4035 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
4037 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
4038 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
4042 @deffn procedure array-shape array
4043 Returns a list of inclusive bounds of integers.
4045 (array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
4049 @deffn primitive array-dimensions ra
4050 @code{Array-dimensions} is similar to @code{array-shape} but replaces
4051 elements with a @code{0} minimum with one greater than the maximum. So:
4053 (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
4057 @deffn primitive array-rank ra
4058 Return the number of dimensions of @var{obj}. If @var{obj} is
4059 not an array, @code{0} is returned.
4062 @deffn primitive array->list v
4063 Return a list consisting of all the elements, in order, of
4067 @deffn primitive array-copy! src dst
4068 @deffnx primitive array-copy-in-order! src dst
4069 Copies every element from vector or array @var{source} to the
4070 corresponding element of @var{destination}. @var{destination} must have
4071 the same rank as @var{source}, and be at least as large in each
4072 dimension. The order is unspecified.
4075 @deffn primitive array-fill! ra fill
4076 Stores @var{fill} in every element of @var{array}. The value returned
4080 @c begin (texi-doc-string "guile" "array-equal?")
4081 @deffn primitive array-equal? ra0 ra1
4082 Returns @code{#t} iff all arguments are arrays with the same shape, the
4083 same type, and have corresponding elements which are either
4084 @code{equal?} or @code{array-equal?}. This function differs from
4085 @code{equal?} in that a one dimensional shared array may be
4086 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
4089 @deffn primitive array-contents ra [strict]
4090 @deffnx primitive array-contents array strict
4091 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
4092 without changing their order (last subscript changing fastest), then
4093 @code{array-contents} returns that shared array, otherwise it returns
4094 @code{#f}. All arrays made by @var{make-array} and
4095 @var{make-uniform-array} may be unrolled, some arrays made by
4096 @var{make-shared-array} may not be.
4098 If the optional argument @var{strict} is provided, a shared array will
4099 be returned only if its elements are stored internally contiguous in
4104 @subsection Array Mapping
4106 @deffn primitive array-map! ra0 proc . lra
4107 @deffnx primitive array-map-in-order! ra0 proc . lra
4108 @var{array1}, @dots{} must have the same number of dimensions as
4109 @var{array0} and have a range for each index which includes the range
4110 for the corresponding index in @var{array0}. @var{proc} is applied to
4111 each tuple of elements of @var{array1} @dots{} and the result is stored
4112 as the corresponding element in @var{array0}. The value returned is
4113 unspecified. The order of application is unspecified.
4116 @deffn primitive array-for-each proc ra0 . lra
4117 @var{proc} is applied to each tuple of elements of @var{array0} @dots{}
4118 in row-major order. The value returned is unspecified.
4121 @deffn primitive array-index-map! ra proc
4122 applies @var{proc} to the indices of each element of @var{array} in
4123 turn, storing the result in the corresponding element. The value
4124 returned and the order of application are unspecified.
4126 One can implement @var{array-indexes} as
4128 (define (array-indexes array)
4129 (let ((ra (apply make-array #f (array-shape array))))
4130 (array-index-map! ra (lambda x x))
4135 (define (apl:index-generator n)
4136 (let ((v (make-uniform-vector n 1)))
4137 (array-index-map! v (lambda (i) i))
4142 @node Uniform Arrays
4143 @subsection Uniform Arrays
4144 @tpindex Uniform Arrays
4147 @dfn{Uniform arrays} have elements all of the
4148 same type and occupy less storage than conventional
4149 arrays. Uniform arrays with a single zero-based dimension
4150 are also known as @dfn{uniform vectors}. The procedures in
4151 this section can also be used on conventional arrays, vectors,
4152 bit-vectors and strings.
4155 When creating a uniform array, the type of data to be stored
4156 is indicated with a @var{prototype} argument. The following table
4157 lists the types available and example prototypes:
4160 prototype type printing character
4162 #t boolean (bit-vector) b
4164 #\nul byte (integer) y
4165 's short (integer) h
4166 1 unsigned long (integer) u
4167 -1 signed long (integer) e
4168 'l signed long long (integer) l
4169 1.0 float (single precision) s
4170 1/3 double (double precision float) i
4171 0+i complex (double precision) c
4172 () conventional vector
4176 Unshared uniform arrays of characters with a single zero-based dimension
4177 are identical to strings:
4180 (make-uniform-array #\a 3) @result{}
4185 Unshared uniform arrays of booleans with a single zero-based dimension
4186 are identical to @ref{Bit Vectors, bit-vectors}.
4189 (make-uniform-array #t 3) @result{}
4194 Other uniform vectors are written in a form similar to that of vectors,
4195 except that a single character from the above table is put between
4196 @code{#} and @code{(}. For example, a uniform vector of signed
4197 long integers is displayed in the form @code{'#e(3 5 9)}.
4199 @deffn primitive array? v [prot]
4200 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
4202 The @var{prototype} argument is used with uniform arrays and is described
4206 @deffn procedure make-uniform-array prototype bound1 bound2 @dots{}
4207 Creates and returns a uniform array of type corresponding to
4208 @var{prototype} that has as many dimensions as there are @var{bound}s
4209 and fills it with @var{prototype}.
4212 @deffn primitive array-prototype ra
4213 Return an object that would produce an array of the same type
4214 as @var{array}, if used as the @var{prototype} for
4215 @code{make-uniform-array}.
4218 @deffn primitive list->uniform-array ndim prot lst
4219 @deffnx procedure list->uniform-vector prot lst
4220 Return a uniform array of the type indicated by prototype
4221 @var{prot} with elements the same as those of @var{lst}.
4222 Elements must be of the appropriate type, no coercions are
4226 @deffn primitive uniform-vector-fill! uve fill
4227 Stores @var{fill} in every element of @var{uve}. The value returned is
4231 @deffn primitive uniform-vector-length v
4232 Return the number of elements in @var{uve}.
4235 @deffn primitive dimensions->uniform-array dims prot [fill]
4236 @deffnx primitive make-uniform-vector length prototype [fill]
4237 Create and return a uniform array or vector of type
4238 corresponding to @var{prototype} with dimensions @var{dims} or
4239 length @var{length}. If @var{fill} is supplied, it's used to
4240 fill the array, otherwise @var{prototype} is used.
4243 @c Another compiled-closure. -twp
4245 @deffn primitive uniform-array-read! ra [port_or_fd [start [end]]]
4246 @deffnx primitive uniform-vector-read! uve [port-or-fdes] [start] [end]
4247 Attempts to read all elements of @var{ura}, in lexicographic order, as
4248 binary objects from @var{port-or-fdes}.
4249 If an end of file is encountered during
4250 uniform-array-read! the objects up to that point only are put into @var{ura}
4251 (starting at the beginning) and the remainder of the array is
4254 The optional arguments @var{start} and @var{end} allow
4255 a specified region of a vector (or linearized array) to be read,
4256 leaving the remainder of the vector unchanged.
4258 @code{uniform-array-read!} returns the number of objects read.
4259 @var{port-or-fdes} may be omitted, in which case it defaults to the value
4260 returned by @code{(current-input-port)}.
4263 @deffn primitive uniform-array-write v [port_or_fd [start [end]]]
4264 @deffnx primitive uniform-vector-write uve [port-or-fdes] [start] [end]
4265 Writes all elements of @var{ura} as binary objects to
4268 The optional arguments @var{start}
4270 a specified region of a vector (or linearized array) to be written.
4272 The number of objects actually written is returned.
4273 @var{port-or-fdes} may be
4274 omitted, in which case it defaults to the value returned by
4275 @code{(current-output-port)}.
4279 @subsection Bit Vectors
4282 Bit vectors are a specific type of uniform array: an array of booleans
4283 with a single zero-based index.
4286 They are displayed as a sequence of @code{0}s and
4287 @code{1}s prefixed by @code{#*}, e.g.,
4290 (make-uniform-vector 8 #t #f) @result{}
4293 #b(#t #f #t) @result{}
4297 @deffn primitive bit-count b bitvector
4298 Return the number of occurrences of the boolean @var{b} in
4302 @deffn primitive bit-position item v k
4303 Return the minimum index of an occurrence of @var{bool} in
4304 @var{bv} which is at least @var{k}. If no @var{bool} occurs
4305 within the specified range @code{#f} is returned.
4308 @deffn primitive bit-invert! v
4309 Modifies @var{bv} by replacing each element with its negation.
4312 @deffn primitive bit-set*! v kv obj
4313 If uve is a bit-vector @var{bv} and uve must be of the same
4314 length. If @var{bool} is @code{#t}, uve is OR'ed into
4315 @var{bv}; If @var{bool} is @code{#f}, the inversion of uve is
4316 AND'ed into @var{bv}.
4318 If uve is a unsigned long integer vector all the elements of uve
4319 must be between 0 and the @code{length} of @var{bv}. The bits
4320 of @var{bv} corresponding to the indexes in uve are set to
4321 @var{bool}. The return value is unspecified.
4324 @deffn primitive bit-count* v kv obj
4327 (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
4329 @var{bv} is not modified.
4333 @node Association Lists and Hash Tables
4334 @section Association Lists and Hash Tables
4336 This chapter discusses dictionary objects: data structures that are
4337 useful for organizing and indexing large bodies of information.
4340 * Dictionary Types:: About dictionary types; what they're good for.
4341 * Association Lists:: List-based dictionaries.
4342 * Hash Tables:: Table-based dictionaries.
4345 @node Dictionary Types
4346 @subsection Dictionary Types
4348 A @dfn{dictionary} object is a data structure used to index
4349 information in a user-defined way. In standard Scheme, the main
4350 aggregate data types are lists and vectors. Lists are not really
4351 indexed at all, and vectors are indexed only by number
4352 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
4353 to index your data on some other type; for example, in a library
4354 catalog you might want to look up a book by the name of its
4355 author. Dictionaries are used to help you organize information in
4358 An @dfn{association list} (or @dfn{alist} for short) is a list of
4359 key-value pairs. Each pair represents a single quantity or
4360 object; the @code{car} of the pair is a key which is used to
4361 identify the object, and the @code{cdr} is the object's value.
4363 A @dfn{hash table} also permits you to index objects with
4364 arbitrary keys, but in a way that makes looking up any one object
4365 extremely fast. A well-designed hash system makes hash table
4366 lookups almost as fast as conventional array or vector references.
4368 Alists are popular among Lisp programmers because they use only
4369 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
4370 and the equality primitives). No changes to the language core are
4371 necessary. Therefore, with Scheme's built-in list manipulation
4372 facilities, it is very convenient to handle data stored in an
4373 association list. Also, alists are highly portable and can be
4374 easily implemented on even the most minimal Lisp systems.
4376 However, alists are inefficient, especially for storing large
4377 quantities of data. Because we want Guile to be useful for large
4378 software systems as well as small ones, Guile provides a rich set
4379 of tools for using either association lists or hash tables.
4381 @node Association Lists
4382 @subsection Association Lists
4383 @tpindex Association Lists
4386 @cindex Association List
4390 An association list is a conventional data structure that is often used
4391 to implement simple key-value databases. It consists of a list of
4392 entries in which each entry is a pair. The @dfn{key} of each entry is
4393 the @code{car} of the pair and the @dfn{value} of each entry is the
4397 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
4405 Association lists are also known, for short, as @dfn{alists}.
4407 The structure of an association list is just one example of the infinite
4408 number of possible structures that can be built using pairs and lists.
4409 As such, the keys and values in an association list can be manipulated
4410 using the general list structure procedures @code{cons}, @code{car},
4411 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
4412 because association lists are so useful, Guile also provides specific
4413 procedures for manipulating them.
4416 * Alist Key Equality::
4417 * Adding or Setting Alist Entries::
4418 * Retrieving Alist Entries::
4419 * Removing Alist Entries::
4420 * Sloppy Alist Functions::
4424 @node Alist Key Equality
4425 @subsubsection Alist Key Equality
4427 All of Guile's dedicated association list procedures, apart from
4428 @code{acons}, come in three flavours, depending on the level of equality
4429 that is required to decide whether an existing key in the association
4430 list is the same as the key that the procedure call uses to identify the
4435 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
4439 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
4443 Procedures with @dfn{assoc} in their name use @code{equal?} to
4444 determine key equality.
4447 @code{acons} is an exception because it is used to build association
4448 lists which do not require their entries' keys to be unique.
4450 @node Adding or Setting Alist Entries
4451 @subsubsection Adding or Setting Alist Entries
4453 @code{acons} adds a new entry to an association list and returns the
4454 combined association list. The combined alist is formed by consing the
4455 new entry onto the head of the alist specified in the @code{acons}
4456 procedure call. So the specified alist is not modified, but its
4457 contents become shared with the tail of the combined alist that
4458 @code{acons} returns.
4460 In the most common usage of @code{acons}, a variable holding the
4461 original association list is updated with the combined alist:
4464 (set! address-list (acons name address address-list))
4467 In such cases, it doesn't matter that the old and new values of
4468 @code{address-list} share some of their contents, since the old value is
4469 usually no longer independently accessible.
4471 Note that @code{acons} adds the specified new entry regardless of
4472 whether the alist may already contain entries with keys that are, in
4473 some sense, the same as that of the new entry. Thus @code{acons} is
4474 ideal for building alists where there is no concept of key uniqueness.
4477 (set! task-list (acons 3 "pay gas bill" '()))
4480 ((3 . "pay gas bill"))
4482 (set! task-list (acons 3 "tidy bedroom" task-list))
4485 ((3 . "tidy bedroom") (3 . "pay gas bill"))
4488 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
4489 or replace an entry in an association list where there @emph{is} a
4490 concept of key uniqueness. If the specified association list already
4491 contains an entry whose key is the same as that specified in the
4492 procedure call, the existing entry is replaced by the new one.
4493 Otherwise, the new entry is consed onto the head of the old association
4494 list to create the combined alist. In all cases, these procedures
4495 return the combined alist.
4497 @code{assq-set!} and friends @emph{may} destructively modify the
4498 structure of the old association list in such a way that an existing
4499 variable is correctly updated without having to @code{set!} it to the
4505 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
4507 (assoc-set! address-list "james" "1a London Road")
4509 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4513 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4519 (assoc-set! address-list "bob" "11 Newington Avenue")
4521 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4522 ("james" . "1a London Road"))
4526 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4529 The only safe way to update an association list variable when adding or
4530 replacing an entry like this is to @code{set!} the variable to the
4535 (assoc-set! address-list "bob" "11 Newington Avenue"))
4538 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4539 ("james" . "1a London Road"))
4542 Because of this slight inconvenience, you may find it more convenient to
4543 use hash tables to store dictionary data. If your application will not
4544 be modifying the contents of an alist very often, this may not make much
4547 If you need to keep the old value of an association list in a form
4548 independent from the list that results from modification by
4549 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
4550 use @code{list-copy} to copy the old association list before modifying
4553 @deffn primitive acons key value alist
4554 Adds a new key-value pair to @var{alist}. A new pair is
4555 created whose car is @var{key} and whose cdr is @var{value}, and the
4556 pair is consed onto @var{alist}, and the new list is returned. This
4557 function is @emph{not} destructive; @var{alist} is not modified.
4560 @deffn primitive assq-set! alist key val
4561 @deffnx primitive assv-set! alist key value
4562 @deffnx primitive assoc-set! alist key value
4563 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
4564 @var{alist} entry for @var{key} and associate it with the new
4565 @var{value}. If @var{alist} does not contain an entry for @var{key},
4566 add a new one. Return the (possibly new) alist.
4568 These functions do not attempt to verify the structure of @var{alist},
4569 and so may cause unusual results if passed an object that is not an
4573 @node Retrieving Alist Entries
4574 @subsubsection Retrieving Alist Entries
4579 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
4580 arguments and return the entry for that key if an entry exists, or
4581 @code{#f} if there is no entry for that key. Note that, in the cases
4582 where an entry exists, these procedures return the complete entry, that
4583 is @code{(KEY . VALUE)}, not just the value.
4585 @deffn primitive assq key alist
4586 @deffnx primitive assv key alist
4587 @deffnx primitive assoc key alist
4588 Fetches the entry in @var{alist} that is associated with @var{key}. To
4589 decide whether the argument @var{key} matches a particular entry in
4590 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
4591 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
4592 cannot be found in @var{alist} (according to whichever equality
4593 predicate is in use), then @code{#f} is returned. These functions
4594 return the entire alist entry found (i.e. both the key and the value).
4597 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
4598 hand, take an alist and a key and return @emph{just the value} for that
4599 key, if an entry exists. If there is no entry for the specified key,
4600 these procedures return @code{#f}.
4602 This creates an ambiguity: if the return value is @code{#f}, it means
4603 either that there is no entry with the specified key, or that there
4604 @emph{is} an entry for the specified key, with value @code{#f}.
4605 Consequently, @code{assq-ref} and friends should only be used where it
4606 is known that an entry exists, or where the ambiguity doesn't matter
4607 for some other reason.
4609 @deffn primitive assq-ref alist key
4610 @deffnx primitive assv-ref alist key
4611 @deffnx primitive assoc-ref alist key
4612 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
4613 value associated with @var{key} in @var{alist} is returned. These
4614 functions are equivalent to
4617 (let ((ent (@var{associator} @var{key} @var{alist})))
4618 (and ent (cdr ent)))
4621 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
4624 @node Removing Alist Entries
4625 @subsubsection Removing Alist Entries
4627 To remove the element from an association list whose key matches a
4628 specified key, use @code{assq-remove!}, @code{assv-remove!} or
4629 @code{assoc-remove!} (depending, as usual, on the level of equality
4630 required between the key that you specify and the keys in the
4633 As with @code{assq-set!} and friends, the specified alist may or may not
4634 be modified destructively, and the only safe way to update a variable
4635 containing the alist is to @code{set!} it to the value that
4636 @code{assq-remove!} and friends return.
4641 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4642 ("james" . "1a London Road"))
4644 (set! address-list (assoc-remove! address-list "mary"))
4647 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
4650 Note that, when @code{assq/v/oc-remove!} is used to modify an
4651 association list that has been constructed only using the corresponding
4652 @code{assq/v/oc-set!}, there can be at most one matching entry in the
4653 alist, so the question of multiple entries being removed in one go does
4654 not arise. If @code{assq/v/oc-remove!} is applied to an association
4655 list that has been constructed using @code{acons}, or an
4656 @code{assq/v/oc-set!} with a different level of equality, or any mixture
4657 of these, it removes only the first matching entry from the alist, even
4658 if the alist might contain further matching entries. For example:
4661 (define address-list '())
4662 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
4663 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
4666 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
4668 (set! address-list (assoc-remove! address-list "mary"))
4671 (("mary" . "11 Elm Street"))
4674 In this example, the two instances of the string "mary" are not the same
4675 when compared using @code{eq?}, so the two @code{assq-set!} calls add
4676 two distinct entries to @code{address-list}. When compared using
4677 @code{equal?}, both "mary"s in @code{address-list} are the same as the
4678 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
4679 after removing the first matching entry that it finds, and so one of the
4680 "mary" entries is left in place.
4682 @deffn primitive assq-remove! alist key
4683 @deffnx primitive assv-remove! alist key
4684 @deffnx primitive assoc-remove! alist key
4685 Delete the first entry in @var{alist} associated with @var{key}, and return
4686 the resulting alist.
4689 @node Sloppy Alist Functions
4690 @subsubsection Sloppy Alist Functions
4692 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
4693 like the corresponding non-@code{sloppy-} procedures, except that they
4694 return @code{#f} when the specified association list is not well-formed,
4695 where the non-@code{sloppy-} versions would signal an error.
4697 Specifically, there are two conditions for which the non-@code{sloppy-}
4698 procedures signal an error, which the @code{sloppy-} procedures handle
4699 instead by returning @code{#f}. Firstly, if the specified alist as a
4700 whole is not a proper list:
4703 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4705 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
4706 ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
4707 ABORT: (wrong-type-arg)
4709 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4715 Secondly, if one of the entries in the specified alist is not a pair:
4718 (assoc 2 '((1 . 1) 2 (3 . 9)))
4720 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
4721 ERROR: Wrong type argument in position 2 (expecting CONSP): 2
4722 ABORT: (wrong-type-arg)
4724 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
4729 Unless you are explicitly working with badly formed association lists,
4730 it is much safer to use the non-@code{sloppy-} procedures, because they
4731 help to highlight coding and data errors that the @code{sloppy-}
4732 versions would silently cover up.
4734 @deffn primitive sloppy-assq key alist
4735 Behaves like @code{assq} but does not do any error checking.
4736 Recommended only for use in Guile internals.
4739 @deffn primitive sloppy-assv key alist
4740 Behaves like @code{assv} but does not do any error checking.
4741 Recommended only for use in Guile internals.
4744 @deffn primitive sloppy-assoc key alist
4745 Behaves like @code{assoc} but does not do any error checking.
4746 Recommended only for use in Guile internals.
4750 @subsubsection Alist Example
4752 Here is a longer example of how alists may be used in practice.
4755 (define capitals '(("New York" . "Albany")
4756 ("Oregon" . "Salem")
4757 ("Florida" . "Miami")))
4759 ;; What's the capital of Oregon?
4760 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
4761 (assoc-ref capitals "Oregon") @result{} "Salem"
4763 ;; We left out South Dakota.
4765 (assoc-set! capitals "South Dakota" "Bismarck"))
4767 @result{} (("South Dakota" . "Bismarck")
4768 ("New York" . "Albany")
4769 ("Oregon" . "Salem")
4770 ("Florida" . "Miami"))
4772 ;; And we got Florida wrong.
4774 (assoc-set! capitals "Florida" "Tallahassee"))
4776 @result{} (("South Dakota" . "Bismarck")
4777 ("New York" . "Albany")
4778 ("Oregon" . "Salem")
4779 ("Florida" . "Tallahassee"))
4781 ;; After Oregon secedes, we can remove it.
4783 (assoc-remove! capitals "Oregon"))
4785 @result{} (("South Dakota" . "Bismarck")
4786 ("New York" . "Albany")
4787 ("Florida" . "Tallahassee"))
4791 @subsection Hash Tables
4792 @tpindex Hash Tables
4794 @c FIXME::martin: Review me!
4796 Hash tables are dictionaries which offer similar functionality as
4797 association lists: They provide a mapping from keys to values. The
4798 difference is that association lists need time linear in the size of
4799 elements when searching for entries, whereas hash tables can normally
4800 search in constant time. The drawback is that hash tables require a
4801 little bit more memory, and that you can not use the normal list
4802 procedures (@pxref{Lists}) for working with them.
4805 * Hash Table Examples:: Demonstration of hash table usage.
4806 * Hash Table Reference:: Hash table procedure descriptions.
4810 @node Hash Table Examples
4811 @subsubsection Hash Table Examples
4813 @c FIXME::martin: Review me!
4815 For demonstration purposes, this section gives a few usage examples of
4816 some hash table procedures, together with some explanation what they do.
4818 First we start by creating a new hash table with 31 slots, and
4819 populate it with two key/value pairs.
4822 (define h (make-hash-table 31))
4824 (hashq-create-handle! h 'foo "bar")
4828 (hashq-create-handle! h 'braz "zonk")
4832 (hashq-create-handle! h 'frob #f)
4837 You can get the value for a given key with the procedure
4838 @code{hashq-ref}, but the problem with this procedure is that you
4839 cannot reliably determine whether a key does exists in the table. The
4840 reason is that the procedure returns @code{#f} if the key is not in
4841 the table, but it will return the same value if the key is in the
4842 table and just happens to have the value @code{#f}, as you can see in
4843 the following examples.
4854 (hashq-ref h 'not-there)
4859 Better is to use the procedure @code{hashq-get-handle}, which makes a
4860 distinction between the two cases. Just like @code{assq}, this
4861 procedure returns a key/value-pair on success, and @code{#f} if the
4865 (hashq-get-handle h 'foo)
4869 (hashq-get-handle h 'not-there)
4874 There is no procedure for calculating the number of key/value-pairs in
4875 a hash table, but @code{hash-fold} can be used for doing exactly that.
4878 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
4883 @node Hash Table Reference
4884 @subsubsection Hash Table Reference
4886 Like the association list functions, the hash table functions come
4887 in several varieties: @code{hashq}, @code{hashv}, and @code{hash}.
4888 The @code{hashq} functions use @code{eq?} to determine whether two
4889 keys match. The @code{hashv} functions use @code{eqv?}, and the
4890 @code{hash} functions use @code{equal?}.
4892 In each of the functions that follow, the @var{table} argument
4893 must be a vector. The @var{key} and @var{value} arguments may be
4896 @deffn procedure make-hash-table size
4897 Create a new hash table of @var{size} slots. Note that the number of
4898 slots does not limit the size of the table, it just tells how large
4899 the underlying vector will be. The @var{size} should be similar to
4900 the expected number of elements which will be added to the table, but
4901 they need not match. For good performance, it might be a good idea to
4902 use a prime number as the @var{size}.
4905 @deffn primitive hashq-ref table key [dflt]
4906 Look up @var{key} in the hash table @var{table}, and return the
4907 value (if any) associated with it. If @var{key} is not found,
4908 return @var{default} (or @code{#f} if no @var{default} argument
4909 is supplied). Uses @code{eq?} for equality testing.
4912 @deffn primitive hashv-ref table key [dflt]
4913 Look up @var{key} in the hash table @var{table}, and return the
4914 value (if any) associated with it. If @var{key} is not found,
4915 return @var{default} (or @code{#f} if no @var{default} argument
4916 is supplied). Uses @code{eqv?} for equality testing.
4919 @deffn primitive hash-ref table key [dflt]
4920 Look up @var{key} in the hash table @var{table}, and return the
4921 value (if any) associated with it. If @var{key} is not found,
4922 return @var{default} (or @code{#f} if no @var{default} argument
4923 is supplied). Uses @code{equal?} for equality testing.
4926 @deffn primitive hashq-set! table key val
4927 Find the entry in @var{table} associated with @var{key}, and
4928 store @var{value} there. Uses @code{eq?} for equality testing.
4931 @deffn primitive hashv-set! table key val
4932 Find the entry in @var{table} associated with @var{key}, and
4933 store @var{value} there. Uses @code{eqv?} for equality testing.
4936 @deffn primitive hash-set! table key val
4937 Find the entry in @var{table} associated with @var{key}, and
4938 store @var{value} there. Uses @code{equal?} for equality
4942 @deffn primitive hashq-remove! table key
4943 Remove @var{key} (and any value associated with it) from
4944 @var{table}. Uses @code{eq?} for equality tests.
4947 @deffn primitive hashv-remove! table key
4948 Remove @var{key} (and any value associated with it) from
4949 @var{table}. Uses @code{eqv?} for equality tests.
4952 @deffn primitive hash-remove! table key
4953 Remove @var{key} (and any value associated with it) from
4954 @var{table}. Uses @code{equal?} for equality tests.
4957 The standard hash table functions may be too limited for some
4958 applications. For example, you may want a hash table to store
4959 strings in a case-insensitive manner, so that references to keys
4960 named ``foobar'', ``FOOBAR'' and ``FooBaR'' will all yield the
4961 same item. Guile provides you with @dfn{extended} hash tables
4962 that permit you to specify a hash function and associator function
4963 of your choosing. The functions described in the rest of this section
4964 can be used to implement such custom hash table structures.
4966 If you are unfamiliar with the inner workings of hash tables, then
4967 this facility will probably be a little too abstract for you to
4968 use comfortably. If you are interested in learning more, see an
4969 introductory textbook on data structures or algorithms for an
4970 explanation of how hash tables are implemented.
4972 @deffn primitive hashq key size
4973 Determine a hash value for @var{key} that is suitable for
4974 lookups in a hashtable of size @var{size}, where @code{eq?} is
4975 used as the equality predicate. The function returns an
4976 integer in the range 0 to @var{size} - 1. Note that
4977 @code{hashq} may use internal addresses. Thus two calls to
4978 hashq where the keys are @code{eq?} are not guaranteed to
4979 deliver the same value if the key object gets garbage collected
4980 in between. This can happen, for example with symbols:
4981 @code{(hashq 'foo n) (gc) (hashq 'foo n)} may produce two
4982 different values, since @code{foo} will be garbage collected.
4985 @deffn primitive hashv key size
4986 Determine a hash value for @var{key} that is suitable for
4987 lookups in a hashtable of size @var{size}, where @code{eqv?} is
4988 used as the equality predicate. The function returns an
4989 integer in the range 0 to @var{size} - 1. Note that
4990 @code{(hashv key)} may use internal addresses. Thus two calls
4991 to hashv where the keys are @code{eqv?} are not guaranteed to
4992 deliver the same value if the key object gets garbage collected
4993 in between. This can happen, for example with symbols:
4994 @code{(hashv 'foo n) (gc) (hashv 'foo n)} may produce two
4995 different values, since @code{foo} will be garbage collected.
4998 @deffn primitive hash key size
4999 Determine a hash value for @var{key} that is suitable for
5000 lookups in a hashtable of size @var{size}, where @code{equal?}
5001 is used as the equality predicate. The function returns an
5002 integer in the range 0 to @var{size} - 1.
5005 @deffn primitive hashx-ref hash assoc table key [dflt]
5006 This behaves the same way as the corresponding @code{ref}
5007 function, but uses @var{hash} as a hash function and
5008 @var{assoc} to compare keys. @code{hash} must be a function
5009 that takes two arguments, a key to be hashed and a table size.
5010 @code{assoc} must be an associator function, like @code{assoc},
5011 @code{assq} or @code{assv}.
5013 By way of illustration, @code{hashq-ref table key} is
5014 equivalent to @code{hashx-ref hashq assq table key}.
5017 @deffn primitive hashx-set! hash assoc table key val
5018 This behaves the same way as the corresponding @code{set!}
5019 function, but uses @var{hash} as a hash function and
5020 @var{assoc} to compare keys. @code{hash} must be a function
5021 that takes two arguments, a key to be hashed and a table size.
5022 @code{assoc} must be an associator function, like @code{assoc},
5023 @code{assq} or @code{assv}.
5025 By way of illustration, @code{hashq-set! table key} is
5026 equivalent to @code{hashx-set! hashq assq table key}.
5029 @deffn primitive hashq-get-handle table key
5030 This procedure returns the @code{(key . value)} pair from the
5031 hash table @var{table}. If @var{table} does not hold an
5032 associated value for @var{key}, @code{#f} is returned.
5033 Uses @code{eq?} for equality testing.
5036 @deffn primitive hashv-get-handle table key
5037 This procedure returns the @code{(key . value)} pair from the
5038 hash table @var{table}. If @var{table} does not hold an
5039 associated value for @var{key}, @code{#f} is returned.
5040 Uses @code{eqv?} for equality testing.
5043 @deffn primitive hash-get-handle table key
5044 This procedure returns the @code{(key . value)} pair from the
5045 hash table @var{table}. If @var{table} does not hold an
5046 associated value for @var{key}, @code{#f} is returned.
5047 Uses @code{equal?} for equality testing.
5050 @deffn primitive hashx-get-handle hash assoc table key
5051 This behaves the same way as the corresponding
5052 @code{-get-handle} function, but uses @var{hash} as a hash
5053 function and @var{assoc} to compare keys. @code{hash} must be
5054 a function that takes two arguments, a key to be hashed and a
5055 table size. @code{assoc} must be an associator function, like
5056 @code{assoc}, @code{assq} or @code{assv}.
5059 @deffn primitive hashq-create-handle! table key init
5060 This function looks up @var{key} in @var{table} and returns its handle.
5061 If @var{key} is not already present, a new handle is created which
5062 associates @var{key} with @var{init}.
5065 @deffn primitive hashv-create-handle! table key init
5066 This function looks up @var{key} in @var{table} and returns its handle.
5067 If @var{key} is not already present, a new handle is created which
5068 associates @var{key} with @var{init}.
5071 @deffn primitive hash-create-handle! table key init
5072 This function looks up @var{key} in @var{table} and returns its handle.
5073 If @var{key} is not already present, a new handle is created which
5074 associates @var{key} with @var{init}.
5077 @deffn primitive hashx-create-handle! hash assoc table key init
5078 This behaves the same way as the corresponding
5079 @code{-create-handle} function, but uses @var{hash} as a hash
5080 function and @var{assoc} to compare keys. @code{hash} must be
5081 a function that takes two arguments, a key to be hashed and a
5082 table size. @code{assoc} must be an associator function, like
5083 @code{assoc}, @code{assq} or @code{assv}.
5086 @deffn primitive hash-fold proc init table
5087 An iterator over hash-table elements.
5088 Accumulates and returns a result by applying PROC successively.
5089 The arguments to PROC are "(key value prior-result)" where key
5090 and value are successive pairs from the hash table TABLE, and
5091 prior-result is either INIT (for the first application of PROC)
5092 or the return value of the previous application of PROC.
5093 For example, @code{(hash-fold acons '() tab)} will convert a hash
5094 table into an a-list of key-value pairs.
5102 @c FIXME::martin: Review me!
5104 A hook is basically a list of procedures to be called at well defined
5105 points in time. Hooks are used internally for several debugging
5106 facilities, but they can be used in user code, too.
5108 Hooks are created with @code{make-hook}, then procedures can be added to
5109 a hook with @code{add-hook!} or removed with @code{remove-hook!} or
5110 @code{reset-hook!}. The procedures stored in a hook can be invoked with
5114 * Hook Examples:: Hook usage by example.
5115 * Hook Reference:: Reference of all hook procedures.
5119 @subsection Hook Examples
5121 Hook usage is shown by some examples in this section. First, we will
5122 define a hook of arity 2 --- that is, the procedures stored in the hook
5123 will have to accept two arguments.
5126 (define hook (make-hook 2))
5128 @result{} #<hook 2 40286c90>
5131 Now we are ready to add some procedures to the newly created hook with
5132 @code{add-hook!}. In the following example, two procedures are added,
5133 which print different messages and do different things with their
5134 arguments. When the procedures have been added, we can invoke them
5135 using @code{run-hook}.
5138 (add-hook! hook (lambda (x y)
5142 (add-hook! hook (lambda (x y)
5151 Note that the procedures are called in reverse order than they were
5152 added. This can be changed by providing the optional third argument
5153 on the second call to @code{add-hook!}.
5156 (add-hook! hook (lambda (x y)
5160 (add-hook! hook (lambda (x y)
5164 #t) ; @r{<- Change here!}
5170 @node Hook Reference
5171 @subsection Hook Reference
5173 When a hook is created with @code{make-hook}, you can supply the arity
5174 of the procedures which can be added to the hook. The arity defaults to
5175 zero. All procedures of a hook must have the same arity, and when the
5176 procedures are invoked using @code{run-hook}, the number of arguments
5177 must match the arity of the procedures.
5179 The order in which procedures are added to a hook matters. If the third
5180 parameter to @var{add-hook!} is omitted or is equal to @code{#f}, the
5181 procedure is added in front of the procedures which might already be on
5182 that hook, otherwise the procedure is added at the end. The procedures
5183 are always called from first to last when they are invoked via
5186 When calling @code{hook->list}, the procedures in the resulting list are
5187 in the same order as they would have been called by @code{run-hook}.
5189 @deffn primitive make-hook [n_args]
5190 Create a hook for storing procedure of arity @var{n_args}.
5191 @var{n_args} defaults to zero. The returned value is a hook
5192 object to be used with the other hook procedures.
5195 @deffn primitive hook? x
5196 Return @code{#t} if @var{x} is a hook, @code{#f} otherwise.
5199 @deffn primitive hook-empty? hook
5200 Return @code{#t} if @var{hook} is an empty hook, @code{#f}
5204 @deffn primitive add-hook! hook proc [append_p]
5205 Add the procedure @var{proc} to the hook @var{hook}. The
5206 procedure is added to the end if @var{append_p} is true,
5207 otherwise it is added to the front. The return value of this
5208 procedure is not specified.
5211 @deffn primitive remove-hook! hook proc
5212 Remove the procedure @var{proc} from the hook @var{hook}. The
5213 return value of this procedure is not specified.
5216 @deffn primitive reset-hook! hook
5217 Remove all procedures from the hook @var{hook}. The return
5218 value of this procedure is not specified.
5221 @deffn primitive run-hook hook . args
5222 Apply all procedures from the hook @var{hook} to the arguments
5223 @var{args}. The order of the procedure application is first to
5224 last. The return value of this procedure is not specified.
5227 @deffn primitive hook->list hook
5228 Convert the procedure list of @var{hook} to a list.
5232 @node Other Data Types
5233 @section Other Core Guile Data Types
5236 @c TeX-master: "guile.texi"