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.
57 * Association Lists and Hash Tables::
59 * Hooks:: User-customizable event lists.
60 * Other Data Types:: Data types that are documented elsewhere.
67 The two boolean values are @code{#t} for true and @code{#f} for false.
69 Boolean values are returned by predicate procedures, such as the general
70 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
71 (@pxref{Equality}) and numerical and string comparison operators like
72 @code{string=?} (REFFIXME) and @code{<=} (REFFIXME).
83 (equal? "house" "houses")
92 In test condition contexts like @code{if} (REFFIXME) and @code{cond}
93 (REFFIXME), where a group of subexpressions will be evaluated only if a
94 @var{condition} expression evaluates to ``true'', ``true'' means any
95 value at all except @code{#f}.
111 A result of this asymmetry is that typical Scheme source code more often
112 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
113 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
114 not necessary to represent an @code{if} or @code{cond} true value.
116 It is important to note that @code{#f} is @strong{not} equivalent to any
117 other Scheme value. In particular, @code{#f} is not the same as the
118 number 0 (like in C and C++), and not the same as the ``empty list''
119 (like in some Lisp dialects).
121 The @code{not} procedure returns the boolean inverse of its argument:
124 @c docstring begin (texi-doc-string "guile" "not")
125 @deffn primitive not x
126 Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
129 The @code{boolean?} procedure is a predicate that returns @code{#t} if
130 its argument is one of the boolean values, otherwise @code{#f}.
133 @c docstring begin (texi-doc-string "guile" "boolean?")
134 @deffn primitive boolean? obj
135 Return @code{#t} iff @var{obj} is either @code{#t} or @code{#f}.
140 @section Numerical data types
142 Guile supports a rich ``tower'' of numerical types --- integer,
143 rational, real and complex --- and provides an extensive set of
144 mathematical and scientific functions for operating on numerical
145 data. This section of the manual documents those types and functions.
147 You may also find it illuminating to read R5RS's presentation of numbers
148 in Scheme, which is particularly clear and accessible: see
149 @xref{Numbers,,,r5rs}.
152 * Numerical Tower:: Scheme's numerical "tower".
153 * Integers:: Whole numbers.
154 * Reals and Rationals:: Real and rational numbers.
155 * Complex Numbers:: Complex numbers.
156 * Exactness:: Exactness and inexactness.
157 * Number Syntax:: Read syntax for numerical data.
158 * Integer Operations:: Operations on integer values.
159 * Comparison:: Comparison predicates.
160 * Conversion:: Converting numbers to and from strings.
161 * Complex:: Complex number operations.
162 * Arithmetic:: Arithmetic functions.
163 * Scientific:: Scientific functions.
164 * Primitive Numerics:: Primitive numeric functions.
165 * Bitwise Operations:: Logical AND, OR, NOT, and so on.
166 * Random:: Random number generation.
170 @node Numerical Tower
171 @subsection Scheme's Numerical ``Tower''
174 Scheme's numerical ``tower'' consists of the following categories of
179 integers (whole numbers)
182 rationals (the set of numbers that can be expressed as P/Q where P and Q
186 real numbers (the set of numbers that describes all possible positions
187 along a one dimensional line)
190 complex numbers (the set of numbers that describes all possible
191 positions in a two dimensional space)
194 It is called a tower because each category ``sits on'' the one that
195 follows it, in the sense that every integer is also a rational, every
196 rational is also real, and every real number is also a complex number
197 (but with zero imaginary part).
199 Of these, Guile implements integers, reals and complex numbers as
200 distinct types. Rationals are implemented as regards the read syntax
201 for rational numbers that is specified by R5RS, but are immediately
202 converted by Guile to the corresponding real number.
204 The @code{number?} predicate may be applied to any Scheme value to
205 discover whether the value is any of the supported numerical types.
207 @c docstring begin (texi-doc-string "guile" "number?")
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
237 Integers are whole numbers, that is numbers with no fractional part,
238 such as 2, 83 and -3789.
240 Integers in Guile can be arbitrarily big, as shown by the following
244 (define (factorial n)
245 (let loop ((n n) (product 1))
248 (loop (- n 1) (* product n)))))
260 -119622220865480194561963161495657715064383733760000000000
263 Readers whose background is in programming languages where integers are
264 limited by the need to fit into just 4 or 8 bytes of memory may find
265 this surprising, or suspect that Guile's representation of integers is
266 inefficient. In fact, Guile achieves a near optimal balance of
267 convenience and efficiency by using the host computer's native
268 representation of integers where possible, and a more general
269 representation where the required number does not fit in the native
270 form. Conversion between these two representations is automatic and
271 completely invisible to the Scheme level programmer.
273 @c REFFIXME Maybe point here to discussion of handling immediates/bignums
274 @c on the C level, where the conversion is not so automatic - NJ
276 @c docstring begin (texi-doc-string "guile" "integer?")
277 @deffn primitive integer? x
278 Return @code{#t} if @var{x} is an integer number, @code{#f} else.
292 @node Reals and Rationals
293 @subsection Real and Rational Numbers
297 Mathematically, the real numbers are the set of numbers that describe
298 all possible points along a continuous, infinite, one-dimensional line.
299 The rational numbers are the set of all numbers that can be written as
300 fractions P/Q, where P and Q are integers. All rational numbers are
301 also real, but there are real numbers that are not rational, for example
302 the square root of 2, and pi.
304 Guile represents both real and rational numbers approximately using a
305 floating point encoding with limited precision. Even though the actual
306 encoding is in binary, it may be helpful to think of it as a decimal
307 number with a limited number of significant figures and a decimal point
308 somewhere, since this corresponds to the standard notation for non-whole
309 numbers. For example:
314 -5648394822220000000000.0
318 The limited precision of Guile's encoding means that any ``real'' number
319 in Guile can be written in a rational form, by multiplying and then dividing
320 by sufficient powers of 10 (or in fact, 2). For example,
321 @code{-0.00000142857931198} is the same as @code{142857931198} divided by
322 @code{100000000000000000}. In Guile's current incarnation, therefore,
323 the @code{rational?} and @code{real?} predicates are equivalent.
325 Another aspect of this equivalence is that Guile currently does not
326 preserve the exactness that is possible with rational arithmetic.
327 If such exactness is needed, it is of course possible to implement
328 exact rational arithmetic at the Scheme level using Guile's arbitrary
331 A planned future revision of Guile's numerical tower will make it
332 possible to implement exact representations and arithmetic for both
333 rational numbers and real irrational numbers such as square roots,
334 and in such a way that the new kinds of number integrate seamlessly
335 with those that are already implemented.
337 @c docstring begin (texi-doc-string "guile" "real?")
338 @deffn primitive real? obj
339 Return @code{#t} if @var{obj} is a real number, @code{#f} else.
340 Note that the sets of integer and rational values form subsets
341 of the set of real numbers, so the predicate will also be fulfilled
342 if @var{obj} is an integer number or a rational number.
345 @c docstring begin (texi-doc-string "guile" "rational?")
346 @deffn primitive rational? x
347 Return @code{#t} if @var{x} is a rational number, @code{#f}
348 else. Note that the set of integer values forms a subset of
349 the set of rational numbers, i. e. the predicate will also be
350 fulfilled if @var{x} is an integer number. Real numbers
351 will also satisfy this predicate, because of their limited
356 @node Complex Numbers
357 @subsection Complex Numbers
360 Complex numbers are the set of numbers that describe all possible points
361 in a two-dimensional space. The two coordinates of a particular point
362 in this space are known as the @dfn{real} and @dfn{imaginary} parts of
363 the complex number that describes that point.
365 In Guile, complex numbers are written in rectangular form as the sum of
366 their real and imaginary parts, using the symbol @code{i} to indicate
379 Guile represents a complex number as a pair of numbers both of which are
380 real, so the real and imaginary parts of a complex number have the same
381 properties of inexactness and limited precision as single real numbers.
383 @c docstring begin (texi-doc-string "guile" "complex?")
384 @deffn primitive complex? x
385 Return @code{#t} if @var{x} is a complex number, @code{#f}
386 else. Note that the sets of real, rational and integer
387 values form subsets of the set of complex numbers, i. e. the
388 predicate will also be fulfilled if @var{x} is a real,
389 rational or integer number.
394 @subsection Exact and Inexact Numbers
397 @rnindex exact->inexact
398 @rnindex inexact->exact
400 R5RS requires that a calculation involving inexact numbers always
401 produces an inexact result. To meet this requirement, Guile
402 distinguishes between an exact integer value such as @code{5} and the
403 corresponding inexact real value which, to the limited precision
404 available, has no fractional part, and is printed as @code{5.0}. Guile
405 will only convert the latter value to the former when forced to do so by
406 an invocation of the @code{inexact->exact} procedure.
408 @c docstring begin (texi-doc-string "guile" "exact?")
409 @deffn primitive exact? x
410 Return @code{#t} if @var{x} is an exact number, @code{#f}
414 @c docstring begin (texi-doc-string "guile" "inexact?")
415 @deffn primitive inexact? x
416 Return @code{#t} if @var{x} is an inexact number, @code{#f}
420 @c docstring begin (texi-doc-string "guile" "inexact->exact")
421 @deffn primitive inexact->exact z
422 Return an exact number that is numerically closest to @var{z}.
425 @c begin (texi-doc-string "guile" "exact->inexact")
426 @deffn primitive exact->inexact z
427 Convert the number @var{z} to its inexact representation.
432 @subsection Read Syntax for Numerical Data
434 The read syntax for integers is a string of digits, optionally
435 preceded by a minus or plus character, a code indicating the
436 base in which the integer is encoded, and a code indicating whether
437 the number is exact or inexact. The supported base codes are:
441 @code{#b}, @code{#B} --- the integer is written in binary (base 2)
444 @code{#o}, @code{#O} --- the integer is written in octal (base 8)
447 @code{#d}, @code{#D} --- the integer is written in decimal (base 10)
450 @code{#x}, @code{#X} --- the integer is written in hexadecimal (base 16).
453 If the base code is omitted, the integer is assumed to be decimal. The
454 following examples show how these base codes are used.
478 The codes for indicating exactness (which can, incidentally, be applied
479 to all numerical values) are:
483 @code{#e}, @code{#E} --- the number is exact
486 @code{#i}, @code{#I} --- the number is inexact.
489 If the exactness indicator is omitted, the integer is assumed to be exact,
490 since Guile's internal representation for integers is always exact.
491 Real numbers have limited precision similar to the precision of the
492 @code{double} type in C. A consequence of the limited precision is that
493 all real numbers in Guile are also rational, since any number R with a
494 limited number of decimal places, say N, can be made into an integer by
498 @node Integer Operations
499 @subsection Operations on Integer Values
508 @c docstring begin (texi-doc-string "guile" "odd?")
509 @deffn primitive odd? n
510 Return @code{#t} if @var{n} is an odd number, @code{#f}
514 @c docstring begin (texi-doc-string "guile" "even?")
515 @deffn primitive even? n
516 Return @code{#t} if @var{n} is an even number, @code{#f}
520 @c begin (texi-doc-string "guile" "quotient")
521 @deffn primitive quotient
522 Return the quotient of the numbers @var{x} and @var{y}.
525 @c begin (texi-doc-string "guile" "remainder")
526 @deffn primitive remainder
527 Return the remainder of the numbers @var{x} and @var{y}.
529 (remainder 13 4) @result{} 1
530 (remainder -13 4) @result{} -1
534 @c begin (texi-doc-string "guile" "modulo")
535 @deffn primitive modulo
536 Return the modulo of the numbers @var{x} and @var{y}.
538 (modulo 13 4) @result{} 1
539 (modulo -13 4) @result{} 3
543 @c begin (texi-doc-string "guile" "gcd")
545 Return the greatest common divisor of all arguments.
546 If called without arguments, 0 is returned.
549 @c begin (texi-doc-string "guile" "lcm")
551 Return the least common multiple of the arguments.
552 If called without arguments, 1 is returned.
557 @subsection Comparison Predicates
562 @c begin (texi-doc-string "guile" "=")
564 Return @code{#t} if all parameters are numerically equal.
567 @c begin (texi-doc-string "guile" "<")
569 Return @code{#t} if the list of parameters is monotonically
573 @c begin (texi-doc-string "guile" ">")
575 Return @code{#t} if the list of parameters is monotonically
579 @c begin (texi-doc-string "guile" "<=")
581 Return @code{#t} if the list of parameters is monotonically
585 @c begin (texi-doc-string "guile" ">=")
587 Return @code{#t} if the list of parameters is monotonically
591 @c begin (texi-doc-string "guile" "zero?")
592 @deffn primitive zero?
593 Return @code{#t} if @var{z} is an exact or inexact number equal to
597 @c begin (texi-doc-string "guile" "positive?")
598 @deffn primitive positive?
599 Return @code{#t} if @var{x} is an exact or inexact number greater than
603 @c begin (texi-doc-string "guile" "negative?")
604 @deffn primitive negative?
605 Return @code{#t} if @var{x} is an exact or inexact number less than
611 @subsection Converting Numbers To and From Strings
612 @rnindex number->string
613 @rnindex string->number
615 @c docstring begin (texi-doc-string "guile" "number->string")
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 @c docstring begin (texi-doc-string "guile" "string->number")
623 @deffn primitive string->number string [radix]
624 Return a number of the maximally precise representation
625 expressed by the given @var{string}. @var{radix} must be an
626 exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
627 is a default radix that may be overridden by an explicit radix
628 prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
629 supplied, then the default radix is 10. If string is not a
630 syntactically valid notation for a number, then
631 @code{string->number} returns @code{#f}.
636 @subsection Complex Number Operations
637 @rnindex make-rectangular
644 @c docstring begin (texi-doc-string "guile" "make-rectangular")
645 @deffn primitive make-rectangular real imaginary
646 Return a complex number constructed of the given @var{real} and
647 @var{imaginary} parts.
650 @c docstring begin (texi-doc-string "guile" "make-polar")
651 @deffn primitive make-polar x y
652 Return the complex number @var{x} * e^(i * @var{y}).
655 @c begin (texi-doc-string "guile" "real-part")
656 @deffn primitive real-part
657 Return the real part of the number @var{z}.
660 @c begin (texi-doc-string "guile" "imag-part")
661 @deffn primitive imag-part
662 Return the imaginary part of the number @var{z}.
665 @c begin (texi-doc-string "guile" "magnitude")
666 @deffn primitive magnitude
667 Return the magnitude of the number @var{z}. This is the same as
668 @code{abs} for real arguments, but also allows complex numbers.
671 @c begin (texi-doc-string "guile" "angle")
672 @deffn primitive angle
673 Return the angle of the complex number @var{z}.
678 @subsection Arithmetic Functions
691 @c begin (texi-doc-string "guile" "+")
692 @deffn primitive + z1 @dots{}
693 Return the sum of all parameter values. Return 0 if called without any
697 @c begin (texi-doc-string "guile" "-")
698 @deffn primitive - z1 z2 @dots{}
699 If called without arguments, 0 is returned. Otherwise the sum of all but
700 the first argument are subtracted from the first argument.
703 @c begin (texi-doc-string "guile" "*")
704 @deffn primitive * z1 @dots{}
705 Return the product of all arguments. If called without arguments, 1 is
709 @c begin (texi-doc-string "guile" "/")
710 @deffn primitive / z1 z2 @dots{}
711 Divide the first argument by the product of the remaining arguments.
714 @c begin (texi-doc-string "guile" "abs")
715 @deffn primitive abs x
716 Return the absolute value of @var{x}.
719 @c begin (texi-doc-string "guile" "max")
720 @deffn primitive max x1 x2 @dots{}
721 Return the maximum of all parameter values.
724 @c begin (texi-doc-string "guile" "min")
725 @deffn primitive min x1 x2 @dots{}
726 Return the minium of all parameter values.
729 @c begin (texi-doc-string "guile" "truncate")
730 @deffn primitive truncate
731 Round the inexact number @var{x} towards zero.
734 @c begin (texi-doc-string "guile" "round")
735 @deffn primitive round x
736 Round the inexact number @var{x} towards zero.
739 @c begin (texi-doc-string "guile" "floor")
740 @deffn primitive floor x
741 Round the number @var{x} towards minus infinity.
744 @c begin (texi-doc-string "guile" "ceiling")
745 @deffn primitive ceiling x
746 Round the number @var{x} towards infinity.
751 @subsection Scientific Functions
763 The following procedures accept any kind of number as arguments,
764 including complex numbers.
766 @c begin (texi-doc-string "guile" "sqrt")
767 @deffn procedure sqrt z
768 Return the square root of @var{z}.
771 @c begin (texi-doc-string "guile" "expt")
772 @deffn procedure expt z1 z2
773 Return @var{z1} raised to the power of @var{z2}.
776 @c begin (texi-doc-string "guile" "sin")
777 @deffn procedure sin z
778 Return the sine of @var{z}.
781 @c begin (texi-doc-string "guile" "cos")
782 @deffn procedure cos z
783 Return the cosine of @var{z}.
786 @c begin (texi-doc-string "guile" "tan")
787 @deffn procedure tan z
788 Return the tangent of @var{z}.
791 @c begin (texi-doc-string "guile" "asin")
792 @deffn procedure asin z
793 Return the arcsine of @var{z}.
796 @c begin (texi-doc-string "guile" "acos")
797 @deffn procedure acos z
798 Return the arccosine of @var{z}.
801 @c begin (texi-doc-string "guile" "atan")
802 @deffn procedure atan z
803 Return the arctangent of @var{z}.
806 @c begin (texi-doc-string "guile" "exp")
807 @deffn procedure exp z
808 Return e to the power of @var{z}, where e is the base of natural
809 logarithms (2.71828@dots{}).
812 @c begin (texi-doc-string "guile" "log")
813 @deffn procedure log z
814 Return the natural logarithm of @var{z}.
817 @c begin (texi-doc-string "guile" "log10")
818 @deffn procedure log10 z
819 Return the base 10 logarithm of @var{z}.
822 @c begin (texi-doc-string "guile" "sinh")
823 @deffn procedure sinh z
824 Return the hyperbolic sine of @var{z}.
827 @c begin (texi-doc-string "guile" "cosh")
828 @deffn procedure cosh z
829 Return the hyperbolic cosine of @var{z}.
832 @c begin (texi-doc-string "guile" "tanh")
833 @deffn procedure tanh z
834 Return the hyperbolic tangent of @var{z}.
837 @c begin (texi-doc-string "guile" "asinh")
838 @deffn procedure asinh z
839 Return the hyperbolic arcsine of @var{z}.
842 @c begin (texi-doc-string "guile" "acosh")
843 @deffn procedure acosh z
844 Return the hyperbolic arccosine of @var{z}.
847 @c begin (texi-doc-string "guile" "atanh")
848 @deffn procedure atanh z
849 Return the hyperbolic arctangent of @var{z}.
853 @node Primitive Numerics
854 @subsection Primitive Numeric Functions
856 Many of Guile's numeric procedures which accept any kind of numbers as
857 arguments, including complex numbers, are implemented as Scheme
858 procedures that use the following real number-based primitives. These
859 primitives signal an error if they are called with complex arguments.
861 @c begin (texi-doc-string "guile" "$abs")
862 @deffn primitive $abs x
863 Return the absolute value of @var{x}.
866 @c begin (texi-doc-string "guile" "$sqrt")
867 @deffn primitive $sqrt x
868 Return the square root of @var{x}.
871 @c docstring begin (texi-doc-string "guile" "$expt")
872 @deffn primitive $expt x y
873 Return @var{x} raised to the power of @var{y}. This
874 procedure does not accept complex arguments.
877 @c begin (texi-doc-string "guile" "$sin")
878 @deffn primitive $sin x
879 Return the sine of @var{x}.
882 @c begin (texi-doc-string "guile" "$cos")
883 @deffn primitive $cos x
884 Return the cosine of @var{x}.
887 @c begin (texi-doc-string "guile" "$tan")
888 @deffn primitive $tan x
889 Return the tangent of @var{x}.
892 @c begin (texi-doc-string "guile" "$asin")
893 @deffn primitive $asin x
894 Return the arcsine of @var{x}.
897 @c begin (texi-doc-string "guile" "$acos")
898 @deffn primitive $acos x
899 Return the arccosine of @var{x}.
902 @c begin (texi-doc-string "guile" "$atan")
903 @deffn primitive $atan x
904 Return the arctangent of @var{x} in the range -PI/2 to PI/2.
907 @c docstring begin (texi-doc-string "guile" "$atan2")
908 @deffn primitive $atan2 x y
909 Return the arc tangent of the two arguments @var{x} and
910 @var{y}. This is similar to calculating the arc tangent of
911 @var{x} / @var{y}, except that the signs of both arguments
912 are used to determine the quadrant of the result. This
913 procedure does not accept complex arguments.
916 @c begin (texi-doc-string "guile" "$exp")
917 @deffn primitive $exp x
918 Return e to the power of @var{x}, where e is the base of natural
919 logarithms (2.71828@dots{}).
922 @c begin (texi-doc-string "guile" "$log")
923 @deffn primitive $log x
924 Return the natural logarithm of @var{x}.
927 @c begin (texi-doc-string "guile" "$sinh")
928 @deffn primitive $sinh x
929 Return the hyperbolic sine of @var{x}.
932 @c begin (texi-doc-string "guile" "$cosh")
933 @deffn primitive $cosh x
934 Return the hyperbolic cosine of @var{x}.
937 @c begin (texi-doc-string "guile" "$tanh")
938 @deffn primitive $tanh x
939 Return the hyperbolic tangent of @var{x}.
942 @c begin (texi-doc-string "guile" "$asinh")
943 @deffn primitive $asinh x
944 Return the hyperbolic arcsine of @var{x}.
947 @c begin (texi-doc-string "guile" "$acosh")
948 @deffn primitive $acosh x
949 Return the hyperbolic arccosine of @var{x}.
952 @c begin (texi-doc-string "guile" "$atanh")
953 @deffn primitive $atanh x
954 Return the hyperbolic arctangent of @var{x}.
958 @node Bitwise Operations
959 @subsection Bitwise Operations
961 @c docstring begin (texi-doc-string "guile" "logand")
962 @deffn primitive logand n1 n2
963 Return the integer which is the bit-wise AND of the two integer
966 (number->string (logand #b1100 #b1010) 2)
971 @c docstring begin (texi-doc-string "guile" "logior")
972 @deffn primitive logior n1 n2
973 Return the integer which is the bit-wise OR of the two integer
976 (number->string (logior #b1100 #b1010) 2)
981 @c docstring begin (texi-doc-string "guile" "logxor")
982 @deffn primitive logxor n1 n2
983 Return the integer which is the bit-wise XOR of the two integer
986 (number->string (logxor #b1100 #b1010) 2)
991 @c docstring begin (texi-doc-string "guile" "lognot")
992 @deffn primitive lognot n
993 Return the integer which is the 2s-complement of the integer
996 (number->string (lognot #b10000000) 2)
997 @result{} "-10000001"
998 (number->string (lognot #b0) 2)
1003 @c docstring begin (texi-doc-string "guile" "logtest")
1004 @deffn primitive logtest j k
1006 (logtest j k) @equiv{} (not (zero? (logand j k)))
1008 (logtest #b0100 #b1011) @result{} #f
1009 (logtest #b0100 #b0111) @result{} #t
1013 @c docstring begin (texi-doc-string "guile" "logbit?")
1014 @deffn primitive logbit? index j
1016 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1018 (logbit? 0 #b1101) @result{} #t
1019 (logbit? 1 #b1101) @result{} #f
1020 (logbit? 2 #b1101) @result{} #t
1021 (logbit? 3 #b1101) @result{} #t
1022 (logbit? 4 #b1101) @result{} #f
1026 @c docstring begin (texi-doc-string "guile" "ash")
1027 @deffn primitive ash n cnt
1028 The function ash performs an arithmetic shift left by @var{cnt}
1029 bits (or shift right, if @var{cnt} is negative). 'Arithmetic'
1030 means, that the function does not guarantee to keep the bit
1031 structure of @var{n}, but rather guarantees that the result
1032 will always be rounded towards minus infinity. Therefore, the
1033 results of ash and a corresponding bitwise shift will differ if
1034 @var{n} is negative.
1035 Formally, the function returns an integer equivalent to
1036 @code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
1038 (number->string (ash #b1 3) 2) @result{} "1000"
1039 (number->string (ash #b1010 -1) 2) @result{} "101"
1043 @c docstring begin (texi-doc-string "guile" "logcount")
1044 @deffn primitive logcount n
1045 Return the number of bits in integer @var{n}. If integer is
1046 positive, the 1-bits in its binary representation are counted.
1047 If negative, the 0-bits in its two's-complement binary
1048 representation are counted. If 0, 0 is returned.
1050 (logcount #b10101010)
1059 @c docstring begin (texi-doc-string "guile" "integer-length")
1060 @deffn primitive integer-length n
1061 Return the number of bits neccessary to represent @var{n}.
1063 (integer-length #b10101010)
1067 (integer-length #b1111)
1072 @c docstring begin (texi-doc-string "guile" "integer-expt")
1073 @deffn primitive integer-expt n k
1074 Return @var{n} raised to the non-negative integer exponent
1084 @c docstring begin (texi-doc-string "guile" "bit-extract")
1085 @deffn primitive bit-extract n start end
1086 Return the integer composed of the @var{start} (inclusive)
1087 through @var{end} (exclusive) bits of @var{n}. The
1088 @var{start}th bit becomes the 0-th bit in the result.
1090 (number->string (bit-extract #b1101101010 0 4) 2)
1092 (number->string (bit-extract #b1101101010 4 9) 2)
1099 @subsection Random Number Generation
1101 @c docstring begin (texi-doc-string "guile" "copy-random-state")
1102 @deffn primitive copy-random-state [state]
1103 Return a copy of the random state @var{state}.
1106 @c docstring begin (texi-doc-string "guile" "random")
1107 @deffn primitive random n [state]
1108 Return a number in [0,N).
1109 Accepts a positive integer or real n and returns a
1110 number of the same type between zero (inclusive) and
1111 N (exclusive). The values returned have a uniform
1113 The optional argument @var{state} must be of the type produced
1114 by @code{seed->random-state}. It defaults to the value of the
1115 variable @var{*random-state*}. This object is used to maintain
1116 the state of the pseudo-random-number generator and is altered
1117 as a side effect of the random operation.
1120 @c docstring begin (texi-doc-string "guile" "random:exp")
1121 @deffn primitive random:exp [state]
1122 Return an inexact real in an exponential distribution with mean
1123 1. For an exponential distribution with mean u use (* u
1127 @c docstring begin (texi-doc-string "guile" "random:hollow-sphere!")
1128 @deffn primitive random:hollow-sphere! v [state]
1129 Fills vect with inexact real random numbers
1130 the sum of whose squares is equal to 1.0.
1131 Thinking of vect as coordinates in space of
1132 dimension n = (vector-length vect), the coordinates
1133 are uniformly distributed over the surface of the
1137 @c docstring begin (texi-doc-string "guile" "random:normal")
1138 @deffn primitive random:normal [state]
1139 Return an inexact real in a normal distribution. The
1140 distribution used has mean 0 and standard deviation 1. For a
1141 normal distribution with mean m and standard deviation d use
1142 @code{(+ m (* d (random:normal)))}.
1145 @c docstring begin (texi-doc-string "guile" "random:normal-vector!")
1146 @deffn primitive random:normal-vector! v [state]
1147 Fills vect with inexact real random numbers that are
1148 independent and standard normally distributed
1149 (i.e., with mean 0 and variance 1).
1152 @c docstring begin (texi-doc-string "guile" "random:solid-sphere!")
1153 @deffn primitive random:solid-sphere! v [state]
1154 Fills vect with inexact real random numbers
1155 the sum of whose squares is less than 1.0.
1156 Thinking of vect as coordinates in space of
1157 dimension n = (vector-length vect), the coordinates
1158 are uniformly distributed within the unit n-shere.
1159 The sum of the squares of the numbers is returned.
1162 @c docstring begin (texi-doc-string "guile" "random:uniform")
1163 @deffn primitive random:uniform [state]
1164 Return a uniformly distributed inexact real random number in
1168 @c docstring begin (texi-doc-string "guile" "seed->random-state")
1169 @deffn primitive seed->random-state seed
1170 Return a new random state using @var{seed}.
1182 @rnindex char-alphabetic?
1183 @rnindex char-numeric?
1184 @rnindex char-whitespace?
1185 @rnindex char-upper-case?
1186 @rnindex char-lower-case?
1187 @rnindex char->integer
1188 @rnindex integer->char
1189 @rnindex char-upcase
1190 @rnindex char-downcase
1193 Most of the characters in the ASCII character set may be referred to by
1194 name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and so on.
1195 The following table describes the ASCII names for each character.
1197 @multitable @columnfractions .25 .25 .25 .25
1198 @item 0 = @code{#\nul}
1199 @tab 1 = @code{#\soh}
1200 @tab 2 = @code{#\stx}
1201 @tab 3 = @code{#\etx}
1202 @item 4 = @code{#\eot}
1203 @tab 5 = @code{#\enq}
1204 @tab 6 = @code{#\ack}
1205 @tab 7 = @code{#\bel}
1206 @item 8 = @code{#\bs}
1207 @tab 9 = @code{#\ht}
1208 @tab 10 = @code{#\nl}
1209 @tab 11 = @code{#\vt}
1210 @item 12 = @code{#\np}
1211 @tab 13 = @code{#\cr}
1212 @tab 14 = @code{#\so}
1213 @tab 15 = @code{#\si}
1214 @item 16 = @code{#\dle}
1215 @tab 17 = @code{#\dc1}
1216 @tab 18 = @code{#\dc2}
1217 @tab 19 = @code{#\dc3}
1218 @item 20 = @code{#\dc4}
1219 @tab 21 = @code{#\nak}
1220 @tab 22 = @code{#\syn}
1221 @tab 23 = @code{#\etb}
1222 @item 24 = @code{#\can}
1223 @tab 25 = @code{#\em}
1224 @tab 26 = @code{#\sub}
1225 @tab 27 = @code{#\esc}
1226 @item 28 = @code{#\fs}
1227 @tab 29 = @code{#\gs}
1228 @tab 30 = @code{#\rs}
1229 @tab 31 = @code{#\us}
1230 @item 32 = @code{#\sp}
1233 The @code{delete} character (octal 177) may be referred to with the name
1236 Several characters have more than one name:
1255 @c docstring begin (texi-doc-string "guile" "char?")
1256 @deffn primitive char? x
1257 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1260 @c docstring begin (texi-doc-string "guile" "char=?")
1261 @deffn primitive char=? x y
1262 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1265 @c docstring begin (texi-doc-string "guile" "char<?")
1266 @deffn primitive char<? x y
1267 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence,
1271 @c docstring begin (texi-doc-string "guile" "char<=?")
1272 @deffn primitive char<=? x y
1273 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1274 ASCII sequence, else @code{#f}.
1277 @c docstring begin (texi-doc-string "guile" "char>?")
1278 @deffn primitive char>? x y
1279 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1280 sequence, else @code{#f}.
1283 @c docstring begin (texi-doc-string "guile" "char>=?")
1284 @deffn primitive char>=? x y
1285 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1286 ASCII sequence, else @code{#f}.
1289 @c docstring begin (texi-doc-string "guile" "char-ci=?")
1290 @deffn primitive char-ci=? x y
1291 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1292 case, else @code{#f}.
1295 @c docstring begin (texi-doc-string "guile" "char-ci<?")
1296 @deffn primitive char-ci<? x y
1297 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence
1298 ignoring case, else @code{#f}.
1301 @c docstring begin (texi-doc-string "guile" "char-ci<=?")
1302 @deffn primitive char-ci<=? x y
1303 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1304 ASCII sequence ignoring case, else @code{#f}.
1307 @c docstring begin (texi-doc-string "guile" "char-ci>?")
1308 @deffn primitive char-ci>? x y
1309 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1310 sequence ignoring case, else @code{#f}.
1313 @c docstring begin (texi-doc-string "guile" "char-ci>=?")
1314 @deffn primitive char-ci>=? x y
1315 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1316 ASCII sequence ignoring case, else @code{#f}.
1319 @c docstring begin (texi-doc-string "guile" "char-alphabetic?")
1320 @deffn primitive char-alphabetic? chr
1321 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1322 Alphabetic means the same thing as the isalpha C library function.
1325 @c docstring begin (texi-doc-string "guile" "char-numeric?")
1326 @deffn primitive char-numeric? chr
1327 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1328 Numeric means the same thing as the isdigit C library function.
1331 @c docstring begin (texi-doc-string "guile" "char-whitespace?")
1332 @deffn primitive char-whitespace? chr
1333 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1334 Whitespace means the same thing as the isspace C library function.
1337 @c docstring begin (texi-doc-string "guile" "char-upper-case?")
1338 @deffn primitive char-upper-case? chr
1339 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1340 Uppercase means the same thing as the isupper C library function.
1343 @c docstring begin (texi-doc-string "guile" "char-lower-case?")
1344 @deffn primitive char-lower-case? chr
1345 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1346 Lowercase means the same thing as the islower C library function.
1349 @c docstring begin (texi-doc-string "guile" "char-is-both?")
1350 @deffn primitive char-is-both? chr
1351 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else @code{#f}.
1352 Uppercase and lowercase are as defined by the isupper and islower
1353 C library functions.
1356 @c docstring begin (texi-doc-string "guile" "char->integer")
1357 @deffn primitive char->integer chr
1358 Return the number corresponding to ordinal position of @var{chr} in the
1362 @c docstring begin (texi-doc-string "guile" "integer->char")
1363 @deffn primitive integer->char n
1364 Return the character at position @var{n} in the ASCII sequence.
1367 @c docstring begin (texi-doc-string "guile" "char-upcase")
1368 @deffn primitive char-upcase chr
1369 Return the uppercase character version of @var{chr}.
1372 @c docstring begin (texi-doc-string "guile" "char-downcase")
1373 @deffn primitive char-downcase chr
1374 Return the lowercase character version of @var{chr}.
1381 Strings are fixed--length sequences of characters. They can be created
1382 by calling constructor procedures, but they can also literally get
1383 entered at the REPL or in Scheme source files.
1385 Guile provides a rich set of string processing procedures, because text
1386 handling is very important when Guile is used as a scripting language.
1388 Strings always carry the information about how many characters they are
1389 composed of with them, so there is no special end--of--string character,
1390 like in C. That means that Scheme strings can contain any character,
1391 even the NUL character @code{'\0'}. But note: Since most operating
1392 system calls dealing with strings (such as for file operations) expect
1393 strings to be zero--terminated, they might do unexpected things when
1394 called with string containing unusal characters.
1397 * String Syntax:: Read syntax for strings.
1398 * String Predicates:: Testing strings for certain properties.
1399 * String Constructors:: Creating new string objects.
1400 * List/String Conversion:: Converting from/to lists of characters.
1401 * String Selection:: Select portions from strings.
1402 * String Modification:: Modify parts or whole strings.
1403 * String Comparison:: Lexicographic ordering predicates.
1404 * String Searching:: Searching in strings.
1405 * Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1406 * Appending Strings:: Appending strings to form a new string.
1407 * String Miscellanea:: Miscellaneous string procedures.
1408 * Shared Substrings:: Strings which share memory with each other.
1409 * Read Only Strings:: Treating certain non-strings as strings.
1413 @subsection String Read Syntax
1415 The read syntax for strings is an arbitrarily long sequence of characters
1416 enclosed in double quotes (@code{"}). @footnote{Actually, the current
1417 implementation restricts strings to a length of 2^24 characters.} If
1418 you want to insert a double quote character into a string literal, it
1419 must be prefixed with a backslash @code{\} character (called an
1420 @emph{escape character}).
1422 The following are examples of string literals:
1431 @c FIXME::martin: What about escape sequences like \r, \n etc.?
1433 @node String Predicates
1434 @subsection String Predicates
1436 The following procedures can be used to check whether a given string
1437 fulfills some specified property.
1440 @c docstring begin (texi-doc-string "guile" "string?")
1441 @deffn primitive string? obj
1442 Return @code{#t} iff @var{obj} is a string, else returns
1446 @c docstring begin (texi-doc-string "guile" "string-null?")
1447 @deffn primitive string-null? str
1448 Return @code{#t} if @var{str}'s length is nonzero, and
1449 @code{#f} otherwise.
1451 (string-null? "") @result{} #t
1453 (string-null? y) @result{} #f
1457 @node String Constructors
1458 @subsection String Constructors
1460 The string constructor procedures create new string objects, possibly
1461 initializing them with some specified character data.
1463 @c FIXME::martin: list->string belongs into `List/String Conversion'
1466 @rnindex list->string
1467 @c docstring begin (texi-doc-string "guile" "string")
1468 @c docstring begin (texi-doc-string "guile" "list->string")
1469 @deffn primitive string . chrs
1470 @deffnx primitive list->string chrs
1471 Return a newly allocated string composed of the arguments,
1475 @rnindex make-string
1476 @c docstring begin (texi-doc-string "guile" "make-string")
1477 @deffn primitive make-string k [chr]
1478 Return a newly allocated string of
1479 length @var{k}. If @var{chr} is given, then all elements of
1480 the string are initialized to @var{chr}, otherwise the contents
1481 of the @var{string} are unspecified.
1484 @node List/String Conversion
1485 @subsection List/String conversion
1487 When processing strings, it is often convenient to first convert them
1488 into a list representation by using the procedure @code{string->list},
1489 work with the resulting list, and then convert it back into a string.
1490 These procedures are useful for similar tasks.
1492 @rnindex string->list
1493 @c docstring begin (texi-doc-string "guile" "string->list")
1494 @deffn primitive string->list str
1495 Return a newly allocated list of the characters that make up
1496 the given string @var{str}. @code{string->list} and
1497 @code{list->string} are inverses as far as @samp{equal?} is
1501 @node String Selection
1502 @subsection String Selection
1504 Portions of strings can be extracted by these procedures.
1505 @code{string-ref} delivers individual characters whereas
1506 @code{substring} can be used to extract substrings from longer strings.
1508 @rnindex string-length
1509 @c docstring begin (texi-doc-string "guile" "string-length")
1510 @deffn primitive string-length string
1511 Return the number of characters in @var{string}.
1515 @c docstring begin (texi-doc-string "guile" "string-ref")
1516 @deffn primitive string-ref str k
1517 Return character @var{k} of @var{str} using zero-origin
1518 indexing. @var{k} must be a valid index of @var{str}.
1521 @rnindex string-copy
1522 @c docstring begin (texi-doc-string "guile" "string-copy")
1523 @deffn primitive string-copy str
1524 Return a newly allocated copy of the given @var{string}.
1528 @c docstring begin (texi-doc-string "guile" "substring")
1529 @deffn primitive substring str start [end]
1530 Return a newly allocated string formed from the characters
1531 of @var{str} beginning with index @var{start} (inclusive) and
1532 ending with index @var{end} (exclusive).
1533 @var{str} must be a string, @var{start} and @var{end} must be
1534 exact integers satisfying:
1536 0 <= @var{start} <= @var{end} <= (string-length @var{str}).
1539 @node String Modification
1540 @subsection String Modification
1542 These procedures are for modifying strings in--place. That means, that
1543 not a new string is the result of a string operation, but that the
1544 actual memory representation of a string is modified.
1546 @rnindex string-set!
1547 @c docstring begin (texi-doc-string "guile" "string-set!")
1548 @deffn primitive string-set! str k chr
1549 Store @var{chr} in element @var{k} of @var{str} and return
1550 an unspecified value. @var{k} must be a valid index of
1554 @rnindex string-fill!
1555 @c docstring begin (texi-doc-string "guile" "string-fill!")
1556 @deffn primitive string-fill! str chr
1557 Store @var{char} in every element of the given @var{string} and
1558 return an unspecified value.
1561 @c docstring begin (texi-doc-string "guile" "substring-fill!")
1562 @deffn primitive substring-fill! str start end fill
1563 Change every character in @var{str} between @var{start} and
1564 @var{end} to @var{fill}.
1566 (define y "abcdefg")
1567 (substring-fill! y 1 3 #\r)
1573 @c docstring begin (texi-doc-string "guile" "substring-move!")
1574 @c docstring begin (texi-doc-string "guile" "substring-move-left!")
1575 @c docstring begin (texi-doc-string "guile" "substring-move-right!")
1576 @deffn primitive substring-move! str1 start1 end1 str2 start2
1577 @deffnx primitive substring-move-left! str1 start1 end1 str2 start2
1578 @deffnx primitive substring-move-right! str1 start1 end1 str2 start2
1579 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1580 into @var{str2} beginning at position @var{end2}.
1581 @code{substring-move-right!} begins copying from the rightmost character
1582 and moves left, and @code{substring-move-left!} copies from the leftmost
1583 character moving right.
1585 It is useful to have two functions that copy in different directions so
1586 that substrings can be copied back and forth within a single string. If
1587 you wish to copy text from the left-hand side of a string to the
1588 right-hand side of the same string, and the source and destination
1589 overlap, you must be careful to copy the rightmost characters of the
1590 text first, to avoid clobbering your data. Hence, when @var{str1} and
1591 @var{str2} are the same string, you should use
1592 @code{substring-move-right!} when moving text from left to right, and
1593 @code{substring-move-left!} otherwise. If @code{str1} and @samp{str2}
1594 are different strings, it does not matter which function you use.
1597 @deffn primitive substring-move-left! str1 start1 end1 str2 start2
1599 @deftypefn {C Function} SCM scm_substring_move_left_x (SCM @var{str1}, SCM @var{start1}, SCM @var{end1}, SCM @var{str2}, SCM @var{start2})
1600 [@strong{Note:} this is only valid if you've applied the strop patch].
1602 Moves a substring of @var{str1}, from @var{start1} to @var{end1}
1603 (@var{end1} is exclusive), into @var{str2}, starting at
1604 @var{start2}. Allows overlapping strings.
1607 (define x (make-string 10 #\a))
1609 (substring-move-left! x 2 5 y 0)
1614 @result{} "aaaaaaaaaa"
1617 (substring-move-left! x 2 5 y 0)
1621 (define y "abcdefg")
1622 (substring-move-left! y 2 5 y 3)
1628 @deffn substring-move-right! str1 start1 end1 str2 start2
1630 @deftypefn {C Function} SCM scm_substring_move_right_x (SCM @var{str1}, SCM @var{start1}, SCM @var{end1}, SCM @var{str2}, SCM @var{start2})
1631 [@strong{Note:} this is only valid if you've applied the strop patch, if
1632 it hasn't made it into the guile tree].
1634 Does much the same thing as @code{substring-move-left!}, except it
1635 starts moving at the end of the sequence, rather than the beginning.
1637 (define y "abcdefg")
1638 (substring-move-right! y 2 5 y 0)
1642 (define y "abcdefg")
1643 (substring-move-right! y 2 5 y 3)
1650 @node String Comparison
1651 @subsection String Comparison
1653 The procedures in this section are similar to the character ordering
1654 predicates (REFFIXME), but are defined on character sequences. They all
1655 return @code{#t} on success and @code{#f} on failure. The predicates
1656 ending in @code{-ci} ignore the character case when comparing strings.
1660 @c docstring begin (texi-doc-string "guile" "string=?")
1661 @deffn primitive string=? s1 s2
1662 Lexicographic equality predicate; return @code{#t} if the two
1663 strings are the same length and contain the same characters in
1664 the same positions, otherwise return @code{#f}.
1665 The procedure @code{string-ci=?} treats upper and lower case
1666 letters as though they were the same character, but
1667 @code{string=?} treats upper and lower case as distinct
1672 @c docstring begin (texi-doc-string "guile" "string<?")
1673 @deffn primitive string<? s1 s2
1674 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1675 is lexicographically less than @var{s2}.
1679 @c docstring begin (texi-doc-string "guile" "string<=?")
1680 @deffn primitive string<=? s1 s2
1681 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1682 is lexicographically less than or equal to @var{s2}.
1686 @c docstring begin (texi-doc-string "guile" "string>?")
1687 @deffn primitive string>? s1 s2
1688 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1689 is lexicographically greater than @var{s2}.
1693 @c docstring begin (texi-doc-string "guile" "string>=?")
1694 @deffn primitive string>=? s1 s2
1695 Lexicographic ordering predicate; return @code{#t} if @var{s1}
1696 is lexicographically greater than or equal to @var{s2}.
1699 @rnindex string-ci=?
1700 @c docstring begin (texi-doc-string "guile" "string-ci=?")
1701 @deffn primitive string-ci=? s1 s2
1702 Case-insensitive string equality predicate; return @code{#t} if
1703 the two strings are the same length and their component
1704 characters match (ignoring case) at each position; otherwise
1709 @c docstring begin (texi-doc-string "guile" "string-ci<?")
1710 @deffn primitive string-ci<? s1 s2
1711 Case insensitive lexicographic ordering predicate; return
1712 @code{#t} if @var{s1} is lexicographically less than @var{s2}
1717 @c docstring begin (texi-doc-string "guile" "string-ci<=?")
1718 @deffn primitive string-ci<=? s1 s2
1719 Case insensitive lexicographic ordering predicate; return
1720 @code{#t} if @var{s1} is lexicographically less than or equal
1721 to @var{s2} regardless of case.
1724 @rnindex string-ci>?
1725 @c docstring begin (texi-doc-string "guile" "string-ci>?")
1726 @deffn primitive string-ci>? s1 s2
1727 Case insensitive lexicographic ordering predicate; return
1728 @code{#t} if @var{s1} is lexicographically greater than
1729 @var{s2} regardless of case.
1732 @rnindex string-ci>=?
1733 @c docstring begin (texi-doc-string "guile" "string-ci>=?")
1734 @deffn primitive string-ci>=? s1 s2
1735 Case insensitive lexicographic ordering predicate; return
1736 @code{#t} if @var{s1} is lexicographically greater than or
1737 equal to @var{s2} regardless of case.
1741 @node String Searching
1742 @subsection String Searching
1744 When searching the index of a character in a string, these procedures
1747 @c docstring begin (texi-doc-string "guile" "string-index")
1748 @deffn primitive string-index str chr [frm [to]]
1749 Return the index of the first occurrence of @var{chr} in
1750 @var{str}. The optional integer arguments @var{frm} and
1751 @var{to} limit the search to a portion of the string. This
1752 procedure essentially implements the @code{index} or
1753 @code{strchr} functions from the C library.
1755 (string-index "weiner" #\e)
1758 (string-index "weiner" #\e 2)
1761 (string-index "weiner" #\e 2 4)
1766 @c docstring begin (texi-doc-string "guile" "string-rindex")
1767 @deffn primitive string-rindex str chr [frm [to]]
1768 Like @code{string-index}, but search from the right of the
1769 string rather than from the left. This procedure essentially
1770 implements the @code{rindex} or @code{strrchr} functions from
1773 (string-rindex "weiner" #\e)
1776 (string-rindex "weiner" #\e 2 4)
1779 (string-rindex "weiner" #\e 2 5)
1784 @node Alphabetic Case Mapping
1785 @subsection Alphabetic Case Mapping
1787 These are procedures for mapping strings to their upper-- or lower--case
1788 equivalents, respectively, or for capitalizing strings.
1790 @c docstring begin (texi-doc-string "guile" "string-upcase")
1791 @deffn primitive string-upcase str
1792 Return a freshly allocated string containing the characters of
1793 @var{str} in upper case.
1796 @c docstring begin (texi-doc-string "guile" "string-upcase!")
1797 @deffn primitive string-upcase! str
1798 Destructively upcase every character in @var{str} and return
1801 y @result{} "arrdefg"
1802 (string-upcase! y) @result{} "ARRDEFG"
1803 y @result{} "ARRDEFG"
1807 @c docstring begin (texi-doc-string "guile" "string-downcase")
1808 @deffn primitive string-downcase str
1809 Return a freshly allocation string containing the characters in
1810 @var{str} in lower case.
1813 @c docstring begin (texi-doc-string "guile" "string-downcase!")
1814 @deffn primitive string-downcase! str
1815 Destructively downcase every character in @var{str} and return
1818 y @result{} "ARRDEFG"
1819 (string-downcase! y) @result{} "arrdefg"
1820 y @result{} "arrdefg"
1824 @c docstring begin (texi-doc-string "guile" "string-capitalize")
1825 @deffn primitive string-capitalize str
1826 Return a freshly allocated string with the characters in
1827 @var{str}, where the first character of every word is
1831 @c docstring begin (texi-doc-string "guile" "string-capitalize!")
1832 @deffn primitive string-capitalize! str
1833 Upcase the first character of every word in @var{str}
1834 destructively and return @var{str}.
1836 y @result{} "hello world"
1837 (string-capitalize! y) @result{} "Hello World"
1838 y @result{} "Hello World"
1843 @node Appending Strings
1844 @subsection Appending Strings
1846 The procedure @code{string-append} appends several strings together to
1847 form a longer result string.
1849 @rnindex string-append
1850 @c docstring begin (texi-doc-string "guile" "string-append")
1851 @deffn primitive string-append . args
1852 Return a newly allocated string whose characters form the
1853 concatenation of the given strings, @var{args}.
1857 @node String Miscellanea
1858 @subsection String Miscellanea
1860 This section contains several remaining string procedures.
1862 @c docstring begin (texi-doc-string "guile" "string-ci->symbol")
1863 @deffn primitive string-ci->symbol str
1864 Return the symbol whose name is @var{str}. @var{str} is
1865 converted to lowercase before the conversion is done, if Guile
1866 is currently reading symbols case--insensitively.
1870 @node Shared Substrings
1871 @subsection Shared Substrings
1873 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
1876 @c FIXME::martin: Shared substrings are gone, so this section should die.
1878 Whenever you extract a substring using @code{substring}, the Scheme
1879 interpreter allocates a new string and copies data from the old string.
1880 This is expensive, but @code{substring} is so convenient for
1881 manipulating text that programmers use it often.
1883 Guile Scheme provides the concept of the @dfn{shared substring} to
1884 improve performance of many substring-related operations. A shared
1885 substring is an object that mostly behaves just like an ordinary
1886 substring, except that it actually shares storage space with its parent
1889 @c docstring begin (texi-doc-string "guile" "make-shared-substring")
1890 @deffn primitive make-shared-substring str [start [end]]
1891 Return a shared substring of @var{str}. The semantics are the
1892 same as for the @code{substring} function: the shared substring
1893 returned includes all of the text from @var{str} between
1894 indexes @var{start} (inclusive) and @var{end} (exclusive). If
1895 @var{end} is omitted, it defaults to the end of @var{str}. The
1896 shared substring returned by @code{make-shared-substring}
1897 occupies the same storage space as @var{str}.
1903 (define foo "the quick brown fox")
1904 (define bar (make-shared-substring some-string 4 9))
1906 foo => "t h e q u i c k b r o w n f o x"
1907 bar =========> |---------|
1910 The shared substring @var{bar} is not given its own storage space.
1911 Instead, the Guile interpreter notes internally that @var{bar} points to
1912 a portion of the memory allocated to @var{foo}. However, @var{bar}
1913 behaves like an ordinary string in most respects: it may be used with
1914 string primitives like @code{string-length}, @code{string-ref},
1915 @code{string=?}. Guile makes the necessary translation between indices
1916 of @var{bar} and indices of @var{foo} automatically.
1919 (string-length? bar) @result{} 5 ; bar only extends from indices 4 to 9
1920 (string-ref bar 3) @result{} #\c ; same as (string-ref foo 7)
1921 (make-shared-substring bar 2)
1922 @result{} "ick" ; can even make a shared substring!
1925 Because creating a shared substring does not require allocating new
1926 storage from the heap, it is a very fast operation. However, because it
1927 shares memory with its parent string, a change to the contents of the
1928 parent string will implicitly change the contents of its shared
1932 (string-set! foo 7 #\r)
1933 bar @result{} "quirk"
1936 Guile considers shared substrings to be immutable. This is because
1937 programmers might not always be aware that a given string is really a
1938 shared substring, and might innocently try to mutate it without
1939 realizing that the change would affect its parent string. (We are
1940 currently considering a "copy-on-write" strategy that would permit
1941 modifying shared substrings without affecting the parent string.)
1943 In general, shared substrings are useful in circumstances where it is
1944 important to divide a string into smaller portions, but you do not
1945 expect to change the contents of any of the strings involved.
1947 @node Read Only Strings
1948 @subsection Read Only Strings
1950 @c FIXME::martin: Read-only strings are gone, too, so this section should
1953 Type-checking in Guile primitives distinguishes between mutable strings
1954 and read only strings. Mutable strings answer @code{#t} to
1955 @code{string?} while read only strings may or may not. All kinds of
1956 strings, whether or not they are mutable return #t to this:
1958 @c docstring begin (texi-doc-string "guile" "read-only-string?")
1959 @deffn primitive read-only-string? obj
1960 Return true if @var{obj} can be read as a string,
1962 This illustrates the difference between @code{string?} and
1963 @code{read-only-string?}:
1966 (string? "a string") @result{} #t
1967 (string? 'a-symbol) @result{} #f
1969 (read-only-string? "a string") @result{} #t
1970 (read-only-string? 'a-symbol) @result{} #t
1974 "Read-only" refers to how the string will be used, not how the string is
1975 permitted to be used. In particular, all strings are "read-only
1976 strings" even if they are mutable, because a function that only reads
1977 from a string can certainly operate on even a mutable string.
1979 Symbols are an example of read-only strings. Many string functions,
1980 such as @code{string-append} are happy to operate on symbols. Many
1981 functions that expect a string argument, such as @code{open-file}, will
1982 accept a symbol as well.
1984 Shared substrings, discussed in the previous chapter, also happen to be
1988 @node Regular Expressions
1989 @section Regular Expressions
1991 @cindex regular expressions
1993 @cindex emacs regexp
1995 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
1996 describes a whole class of strings. A full description of regular
1997 expressions and their syntax is beyond the scope of this manual;
1998 an introduction can be found in the Emacs manual (@pxref{Regexps,
1999 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, or
2000 in many general Unix reference books.
2002 If your system does not include a POSIX regular expression library, and
2003 you have not linked Guile with a third-party regexp library such as Rx,
2004 these functions will not be available. You can tell whether your Guile
2005 installation includes regular expression support by checking whether the
2006 @code{*features*} list includes the @code{regex} symbol.
2009 * Regexp Functions:: Functions that create and match regexps.
2010 * Match Structures:: Finding what was matched by a regexp.
2011 * Backslash Escapes:: Removing the special meaning of regexp metacharacters.
2012 * Rx Interface:: Tom Lord's Rx library does things differently.
2015 [FIXME: it may be useful to include an Examples section. Parts of this
2016 interface are bewildering on first glance.]
2018 @node Regexp Functions
2019 @subsection Regexp Functions
2021 By default, Guile supports POSIX extended regular expressions.
2022 That means that the characters @samp{(}, @samp{)}, @samp{+} and
2023 @samp{?} are special, and must be escaped if you wish to match the
2026 This regular expression interface was modeled after that
2027 implemented by SCSH, the Scheme Shell. It is intended to be
2028 upwardly compatible with SCSH regular expressions.
2030 @c begin (scm-doc-string "regex.scm" "string-match")
2031 @deffn procedure string-match pattern str [start]
2032 Compile the string @var{pattern} into a regular expression and compare
2033 it with @var{str}. The optional numeric argument @var{start} specifies
2034 the position of @var{str} at which to begin matching.
2036 @code{string-match} returns a @dfn{match structure} which
2037 describes what, if anything, was matched by the regular
2038 expression. @xref{Match Structures}. If @var{str} does not match
2039 @var{pattern} at all, @code{string-match} returns @code{#f}.
2042 Each time @code{string-match} is called, it must compile its
2043 @var{pattern} argument into a regular expression structure. This
2044 operation is expensive, which makes @code{string-match} inefficient if
2045 the same regular expression is used several times (for example, in a
2046 loop). For better performance, you can compile a regular expression in
2047 advance and then match strings against the compiled regexp.
2049 @c docstring begin (texi-doc-string "guile" "make-regexp")
2050 @deffn primitive make-regexp pat . flags
2051 Compile the regular expression described by @var{pat}, and
2052 return the compiled regexp structure. If @var{pat} does not
2053 describe a legal regular expression, @code{make-regexp} throws
2054 a @code{regular-expression-syntax} error.
2055 The @var{flags} arguments change the behavior of the compiled
2056 regular expression. The following flags may be supplied:
2059 Consider uppercase and lowercase letters to be the same when
2061 @item regexp/newline
2062 If a newline appears in the target string, then permit the
2063 @samp{^} and @samp{$} operators to match immediately after or
2064 immediately before the newline, respectively. Also, the
2065 @samp{.} and @samp{[^...]} operators will never match a newline
2066 character. The intent of this flag is to treat the target
2067 string as a buffer containing many lines of text, and the
2068 regular expression as a pattern that may match a single one of
2071 Compile a basic (``obsolete'') regexp instead of the extended
2072 (``modern'') regexps that are the default. Basic regexps do
2073 not consider @samp{|}, @samp{+} or @samp{?} to be special
2074 characters, and require the @samp{@{...@}} and @samp{(...)}
2075 metacharacters to be backslash-escaped (@pxref{Backslash
2076 Escapes}). There are several other differences between basic
2077 and extended regular expressions, but these are the most
2079 @item regexp/extended
2080 Compile an extended regular expression rather than a basic
2081 regexp. This is the default behavior; this flag will not
2082 usually be needed. If a call to @code{make-regexp} includes
2083 both @code{regexp/basic} and @code{regexp/extended} flags, the
2084 one which comes last will override the earlier one.
2088 @c docstring begin (texi-doc-string "guile" "regexp-exec")
2089 @deffn primitive regexp-exec rx str [start [flags]]
2090 Match the compiled regular expression @var{rx} against
2091 @code{str}. If the optional integer @var{start} argument is
2092 provided, begin matching from that position in the string.
2093 Return a match structure describing the results of the match,
2094 or @code{#f} if no match could be found.
2097 @c docstring begin (texi-doc-string "guile" "regexp?")
2098 @deffn primitive regexp? obj
2099 Return @code{#t} if @var{obj} is a compiled regular expression,
2100 or @code{#f} otherwise.
2103 Regular expressions are commonly used to find patterns in one string and
2104 replace them with the contents of another string.
2106 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2107 @deffn procedure regexp-substitute port match [item@dots{}]
2108 Write to the output port @var{port} selected contents of the match
2109 structure @var{match}. Each @var{item} specifies what should be
2110 written, and may be one of the following arguments:
2114 A string. String arguments are written out verbatim.
2117 An integer. The submatch with that number is written.
2120 The symbol @samp{pre}. The portion of the matched string preceding
2121 the regexp match is written.
2124 The symbol @samp{post}. The portion of the matched string following
2125 the regexp match is written.
2128 @var{port} may be @code{#f}, in which case nothing is written; instead,
2129 @code{regexp-substitute} constructs a string from the specified
2130 @var{item}s and returns that.
2133 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2134 @deffn procedure regexp-substitute/global port regexp target [item@dots{}]
2135 Similar to @code{regexp-substitute}, but can be used to perform global
2136 substitutions on @var{str}. Instead of taking a match structure as an
2137 argument, @code{regexp-substitute/global} takes two string arguments: a
2138 @var{regexp} string describing a regular expression, and a @var{target}
2139 string which should be matched against this regular expression.
2141 Each @var{item} behaves as in @var{regexp-substitute}, with the
2142 following exceptions:
2146 A function may be supplied. When this function is called, it will be
2147 passed one argument: a match structure for a given regular expression
2148 match. It should return a string to be written out to @var{port}.
2151 The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
2152 on the unmatched portion of @var{str}. This @emph{must} be supplied in
2153 order to perform global search-and-replace on @var{str}; if it is not
2154 present among the @var{item}s, then @code{regexp-substitute/global} will
2155 return after processing a single match.
2159 @node Match Structures
2160 @subsection Match Structures
2162 @cindex match structures
2164 A @dfn{match structure} is the object returned by @code{string-match} and
2165 @code{regexp-exec}. It describes which portion of a string, if any,
2166 matched the given regular expression. Match structures include: a
2167 reference to the string that was checked for matches; the starting and
2168 ending positions of the regexp match; and, if the regexp included any
2169 parenthesized subexpressions, the starting and ending positions of each
2172 In each of the regexp match functions described below, the @code{match}
2173 argument must be a match structure returned by a previous call to
2174 @code{string-match} or @code{regexp-exec}. Most of these functions
2175 return some information about the original target string that was
2176 matched against a regular expression; we will call that string
2177 @var{target} for easy reference.
2179 @c begin (scm-doc-string "regex.scm" "regexp-match?")
2180 @deffn procedure regexp-match? obj
2181 Return @code{#t} if @var{obj} is a match structure returned by a
2182 previous call to @code{regexp-exec}, or @code{#f} otherwise.
2185 @c begin (scm-doc-string "regex.scm" "match:substring")
2186 @deffn procedure match:substring match [n]
2187 Return the portion of @var{target} matched by subexpression number
2188 @var{n}. Submatch 0 (the default) represents the entire regexp match.
2189 If the regular expression as a whole matched, but the subexpression
2190 number @var{n} did not match, return @code{#f}.
2193 @c begin (scm-doc-string "regex.scm" "match:start")
2194 @deffn procedure match:start match [n]
2195 Return the starting position of submatch number @var{n}.
2198 @c begin (scm-doc-string "regex.scm" "match:end")
2199 @deffn procedure match:end match [n]
2200 Return the ending position of submatch number @var{n}.
2203 @c begin (scm-doc-string "regex.scm" "match:prefix")
2204 @deffn procedure match:prefix match
2205 Return the unmatched portion of @var{target} preceding the regexp match.
2208 @c begin (scm-doc-string "regex.scm" "match:suffix")
2209 @deffn procedure match:suffix match
2210 Return the unmatched portion of @var{target} following the regexp match.
2213 @c begin (scm-doc-string "regex.scm" "match:count")
2214 @deffn procedure match:count match
2215 Return the number of parenthesized subexpressions from @var{match}.
2216 Note that the entire regular expression match itself counts as a
2217 subexpression, and failed submatches are included in the count.
2220 @c begin (scm-doc-string "regex.scm" "match:string")
2221 @deffn procedure match:string match
2222 Return the original @var{target} string.
2225 @node Backslash Escapes
2226 @subsection Backslash Escapes
2228 Sometimes you will want a regexp to match characters like @samp{*} or
2229 @samp{$} exactly. For example, to check whether a particular string
2230 represents a menu entry from an Info node, it would be useful to match
2231 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2232 because the asterisk is a metacharacter, it won't match the @samp{*} at
2233 the beginning of the string. In this case, we want to make the first
2236 You can do this by preceding the metacharacter with a backslash
2237 character @samp{\}. (This is also called @dfn{quoting} the
2238 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2239 sees a backslash in a regular expression, it considers the following
2240 glyph to be an ordinary character, no matter what special meaning it
2241 would ordinarily have. Therefore, we can make the above example work by
2242 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2243 the regular expression engine to match only a single asterisk in the
2246 Since the backslash is itself a metacharacter, you may force a regexp to
2247 match a backslash in the target string by preceding the backslash with
2248 itself. For example, to find variable references in a @TeX{} program,
2249 you might want to find occurrences of the string @samp{\let\} followed
2250 by any number of alphabetic characters. The regular expression
2251 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2252 regexp each match a single backslash in the target string.
2254 @c begin (scm-doc-string "regex.scm" "regexp-quote")
2255 @deffn procedure regexp-quote str
2256 Quote each special character found in @var{str} with a backslash, and
2257 return the resulting string.
2260 @strong{Very important:} Using backslash escapes in Guile source code
2261 (as in Emacs Lisp or C) can be tricky, because the backslash character
2262 has special meaning for the Guile reader. For example, if Guile
2263 encounters the character sequence @samp{\n} in the middle of a string
2264 while processing Scheme code, it replaces those characters with a
2265 newline character. Similarly, the character sequence @samp{\t} is
2266 replaced by a horizontal tab. Several of these @dfn{escape sequences}
2267 are processed by the Guile reader before your code is executed.
2268 Unrecognized escape sequences are ignored: if the characters @samp{\*}
2269 appear in a string, they will be translated to the single character
2272 This translation is obviously undesirable for regular expressions, since
2273 we want to be able to include backslashes in a string in order to
2274 escape regexp metacharacters. Therefore, to make sure that a backslash
2275 is preserved in a string in your Guile program, you must use @emph{two}
2276 consecutive backslashes:
2279 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2282 The string in this example is preprocessed by the Guile reader before
2283 any code is executed. The resulting argument to @code{make-regexp} is
2284 the string @samp{^\* [^:]*}, which is what we really want.
2286 This also means that in order to write a regular expression that matches
2287 a single backslash character, the regular expression string in the
2288 source code must include @emph{four} backslashes. Each consecutive pair
2289 of backslashes gets translated by the Guile reader to a single
2290 backslash, and the resulting double-backslash is interpreted by the
2291 regexp engine as matching a single backslash character. Hence:
2294 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2297 The reason for the unwieldiness of this syntax is historical. Both
2298 regular expression pattern matchers and Unix string processing systems
2299 have traditionally used backslashes with the special meanings
2300 described above. The POSIX regular expression specification and ANSI C
2301 standard both require these semantics. Attempting to abandon either
2302 convention would cause other kinds of compatibility problems, possibly
2303 more severe ones. Therefore, without extending the Scheme reader to
2304 support strings with different quoting conventions (an ungainly and
2305 confusing extension when implemented in other languages), we must adhere
2306 to this cumbersome escape syntax.
2309 @subsection Rx Interface
2311 [FIXME: this is taken from Gary and Mark's quick summaries and should be
2312 reviewed and expanded. Rx is pretty stable, so could already be done!]
2315 @cindex finite automaton
2317 Guile includes an interface to Tom Lord's Rx library (currently only to
2318 POSIX regular expressions). Use of the library requires a two step
2319 process: compile a regular expression into an efficient structure, then
2320 use the structure in any number of string comparisons.
2322 For example, given the
2323 regular expression @samp{abc.} (which matches any string containing
2324 @samp{abc} followed by any single character):
2327 guile> @kbd{(define r (regcomp "abc."))}
2330 guile> @kbd{(regexec r "abc")}
2332 guile> @kbd{(regexec r "abcd")}
2337 The definitions of @code{regcomp} and @code{regexec} are as follows:
2339 @c NJFIXME not in libguile!
2340 @deffn primitive regcomp pattern [flags]
2341 Compile the regular expression pattern using POSIX rules. Flags is
2342 optional and should be specified using symbolic names:
2343 @defvar REG_EXTENDED
2344 use extended POSIX syntax
2347 use case-insensitive matching
2350 allow anchors to match after newline characters in the
2351 string and prevents @code{.} or @code{[^...]} from matching newlines.
2354 The @code{logior} procedure can be used to combine multiple flags.
2355 The default is to use
2356 POSIX basic syntax, which makes @code{+} and @code{?} literals and @code{\+}
2358 operators. Backslashes in @var{pattern} must be escaped if specified in a
2359 literal string e.g., @code{"\\(a\\)\\?"}.
2362 @c NJFIXME not in libguile!
2363 @deffn primitive regexec regex string [match-pick] [flags]
2365 Match @var{string} against the compiled POSIX regular expression
2367 @var{match-pick} and @var{flags} are optional. Possible flags (which can be
2368 combined using the logior procedure) are:
2371 The beginning of line operator won't match the beginning of
2372 @var{string} (presumably because it's not the beginning of a line)
2376 Similar to REG_NOTBOL, but prevents the end of line operator
2377 from matching the end of @var{string}.
2380 If no match is possible, regexec returns #f. Otherwise @var{match-pick}
2381 determines the return value:
2383 @code{#t} or unspecified: a newly-allocated vector is returned,
2384 containing pairs with the indices of the matched part of @var{string} and any
2387 @code{""}: a list is returned: the first element contains a nested list
2388 with the matched part of @var{string} surrounded by the the unmatched parts.
2389 Remaining elements are matched substrings (if any). All returned
2390 substrings share memory with @var{string}.
2392 @code{#f}: regexec returns #t if a match is made, otherwise #f.
2394 vector: the supplied vector is returned, with the first element replaced
2395 by a pair containing the indices of the matched portion of @var{string} and
2396 further elements replaced by pairs containing the indices of matched
2397 substrings (if any).
2399 list: a list will be returned, with each member of the list
2400 specified by a code in the corresponding position of the supplied list:
2402 a number: the numbered matching substring (0 for the entire match).
2404 @code{#\<}: the beginning of @var{string} to the beginning of the part matched
2407 @code{#\>}: the end of the matched part of @var{string} to the end of
2410 @code{#\c}: the "final tag", which seems to be associated with the "cut
2411 operator", which doesn't seem to be available through the posix
2414 e.g., @code{(list #\< 0 1 #\>)}. The returned substrings share memory with
2418 Here are some other procedures that might be used when using regular
2421 @c NJFIXME not in libguile!
2422 @deffn primitive compiled-regexp? obj
2423 Test whether obj is a compiled regular expression.
2426 @c NJFIXME not in libguile!
2427 @deffn primitive regexp->dfa regex [flags]
2430 @c NJFIXME not in libguile!
2431 @deffn primitive dfa-fork dfa
2434 @c NJFIXME not in libguile!
2435 @deffn primitive reset-dfa! dfa
2438 @c NJFIXME not in libguile!
2439 @deffn primitive dfa-final-tag dfa
2442 @c NJFIXME not in libguile!
2443 @deffn primitive dfa-continuable? dfa
2446 @c NJFIXME not in libguile!
2447 @deffn primitive advance-dfa! dfa string
2451 @node Symbols and Variables
2452 @section Symbols and Variables
2455 Guile symbol tables are hash tables. Each hash table, also called an
2456 @dfn{obarray} (for `object array'), is a vector of association lists.
2457 Each entry in the alists is a pair (@var{SYMBOL} . @var{VALUE}). To
2458 @dfn{intern} a symbol in a symbol table means to return its
2459 (@var{SYMBOL} . @var{VALUE}) pair, adding a new entry to the symbol
2460 table (with an undefined value) if none is yet present.
2462 @c FIXME::martin: According to NEWS, removed. Remove here too, or
2463 @c leave for compatibility?
2464 @c @c docstring begin (texi-doc-string "guile" "builtin-bindings")
2465 @c @deffn primitive builtin-bindings
2466 @c Create and return a copy of the global symbol table, removing all
2470 @c docstring begin (texi-doc-string "guile" "gensym")
2471 @deffn primitive gensym [prefix]
2472 Create a new symbol with a name constructed from a prefix and
2473 a counter value. The string @var{prefix} can be specified as
2474 an optional argument. Default prefix is @code{g}. The counter
2475 is increased by 1 at each call. There is no provision for
2476 resetting the counter.
2479 @c docstring begin (texi-doc-string "guile" "gentemp")
2480 @deffn primitive gentemp [prefix [obarray]]
2481 Create a new symbol with a name unique in an obarray.
2482 The name is constructed from an optional string @var{prefix}
2483 and a counter value. The default prefix is @code{t}. The
2484 @var{obarray} is specified as a second optional argument.
2485 Default is the system obarray where all normal symbols are
2486 interned. The counter is increased by 1 at each
2487 call. There is no provision for resetting the counter.
2490 @c docstring begin (texi-doc-string "guile" "intern-symbol")
2491 @deffn primitive intern-symbol obarray string
2492 Add a new symbol to @var{obarray} with name @var{string}, bound to an
2493 unspecified initial value. The symbol table is not modified if a symbol
2494 with this name is already present.
2497 @c docstring begin (texi-doc-string "guile" "string->obarray-symbol")
2498 @deffn primitive string->obarray-symbol obarray string [soft?]
2499 Intern a new symbol in @var{obarray}, a symbol table, with name
2502 If @var{obarray} is @code{#f}, use the default system symbol table. If
2503 @var{obarray} is @code{#t}, the symbol should not be interned in any
2504 symbol table; merely return the pair (@var{symbol}
2505 . @var{#<undefined>}).
2507 The @var{soft?} argument determines whether new symbol table entries
2508 should be created when the specified symbol is not already present in
2509 @var{obarray}. If @var{soft?} is specified and is a true value, then
2510 new entries should not be added for symbols not already present in the
2511 table; instead, simply return @code{#f}.
2514 @rnindex string->symbol
2515 @c docstring begin (texi-doc-string "guile" "string->symbol")
2516 @deffn primitive string->symbol string
2517 Return the symbol whose name is @var{string}. This procedure
2518 can create symbols with names containing special characters or
2519 letters in the non-standard case, but it is usually a bad idea
2520 to create such symbols because in some implementations of
2521 Scheme they cannot be read as themselves. See
2522 @code{symbol->string}.
2523 The following examples assume that the implementation's
2524 standard case is lower case:
2526 (eq? 'mISSISSIppi 'mississippi) @result{} #t
2527 (string->symbol "mISSISSIppi") @result{} @r{the symbol with name "mISSISSIppi"}
2528 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
2530 (string->symbol (symbol->string 'JollyWog))) @result{} #t
2531 (string=? "K. Harper, M.D."
2533 (string->symbol "K. Harper, M.D."))) @result{}#t
2537 @rnindex symbol->string
2538 @c docstring begin (texi-doc-string "guile" "symbol->string")
2539 @deffn primitive symbol->string s
2540 Return the name of @var{symbol} as a string. If the symbol was
2541 part of an object returned as the value of a literal expression
2542 (section @pxref{Literal expressions,,,r4rs, The Revised^4
2543 Report on Scheme}) or by a call to the @code{read} procedure,
2544 and its name contains alphabetic characters, then the string
2545 returned will contain characters in the implementation's
2546 preferred standard case---some implementations will prefer
2547 upper case, others lower case. If the symbol was returned by
2548 @code{string->symbol}, the case of characters in the string
2549 returned will be the same as the case in the string that was
2550 passed to @code{string->symbol}. It is an error to apply
2551 mutation procedures like @code{string-set!} to strings returned
2553 The following examples assume that the implementation's
2554 standard case is lower case:
2556 (symbol->string 'flying-fish) @result{} "flying-fish"
2557 (symbol->string 'Martin) @result{} "martin"
2559 (string->symbol "Malvina")) @result{} "Malvina"
2563 @c docstring begin (texi-doc-string "guile" "symbol-binding")
2564 @deffn primitive symbol-binding obarray string
2565 Look up in @var{obarray} the symbol whose name is @var{string}, and
2566 return the value to which it is bound. If @var{obarray} is @code{#f},
2567 use the global symbol table. If @var{string} is not interned in
2568 @var{obarray}, an error is signalled.
2571 @c docstring begin (texi-doc-string "guile" "symbol-bound?")
2572 @deffn primitive symbol-bound? obarray string
2573 Return @code{#t} if @var{obarray} contains a symbol with name
2574 @var{string} bound to a defined value. This differs from
2575 @var{symbol-interned?} in that the mere mention of a symbol
2576 usually causes it to be interned; @code{symbol-bound?}
2577 determines whether a symbol has been given any meaningful
2581 @c docstring begin (texi-doc-string "guile" "symbol-fref")
2582 @deffn primitive symbol-fref symbol
2583 Return the contents of @var{symbol}'s @dfn{function slot}.
2586 @c docstring begin (texi-doc-string "guile" "symbol-fset!")
2587 @deffn primitive symbol-fset! symbol value
2588 Change the binding of @var{symbol}'s function slot.
2591 @c docstring begin (texi-doc-string "guile" "symbol-hash")
2592 @deffn primitive symbol-hash symbol
2593 Return a hash value for @var{symbol}.
2596 @c docstring begin (texi-doc-string "guile" "symbol-interned?")
2597 @deffn primitive symbol-interned? obarray string
2598 Return @code{#t} if @var{obarray} contains a symbol with name
2599 @var{string}, and @code{#f} otherwise.
2602 @c docstring begin (texi-doc-string "guile" "symbol-pref")
2603 @deffn primitive symbol-pref symbol
2604 Return the @dfn{property list} currently associated with @var{symbol}.
2607 @c docstring begin (texi-doc-string "guile" "symbol-pset!")
2608 @deffn primitive symbol-pset! symbol value
2609 Change the binding of @var{symbol}'s property slot.
2612 @c docstring begin (texi-doc-string "guile" "symbol-set!")
2613 @deffn primitive symbol-set! obarray string value
2614 Find the symbol in @var{obarray} whose name is @var{string}, and rebind
2615 it to @var{value}. An error is signalled if @var{string} is not present
2620 @c docstring begin (texi-doc-string "guile" "symbol?")
2621 @deffn primitive symbol? obj
2622 Return @code{#t} if @var{obj} is a symbol, otherwise return
2626 @c docstring begin (texi-doc-string "guile" "unintern-symbol")
2627 @deffn primitive unintern-symbol obarray string
2628 Remove the symbol with name @var{string} from @var{obarray}. This
2629 function returns @code{#t} if the symbol was present and @code{#f}
2633 @c docstring begin (texi-doc-string "guile" "builtin-variable")
2634 @deffn primitive builtin-variable name
2635 Return the built-in variable with the name @var{name}.
2636 @var{name} must be a symbol (not a string).
2637 Then use @code{variable-ref} to access its value.
2640 @c docstring begin (texi-doc-string "guile" "make-undefined-variable")
2641 @deffn primitive make-undefined-variable [name-hint]
2642 Return a variable object initialized to an undefined value.
2643 If given, uses @var{name-hint} as its internal (debugging)
2644 name, otherwise just treat it as an anonymous variable.
2645 Remember, of course, that multiple bindings to the same
2646 variable may exist, so @var{name-hint} is just that---a hint.
2649 @c docstring begin (texi-doc-string "guile" "make-variable")
2650 @deffn primitive make-variable init [name-hint]
2651 Return a variable object initialized to value @var{init}.
2652 If given, uses @var{name-hint} as its internal (debugging)
2653 name, otherwise just treat it as an anonymous variable.
2654 Remember, of course, that multiple bindings to the same
2655 variable may exist, so @var{name-hint} is just that---a hint.
2658 @c docstring begin (texi-doc-string "guile" "variable-bound?")
2659 @deffn primitive variable-bound? var
2660 Return @code{#t} iff @var{var} is bound to a value.
2661 Throws an error if @var{var} is not a variable object.
2664 @c docstring begin (texi-doc-string "guile" "variable-ref")
2665 @deffn primitive variable-ref var
2666 Dereference @var{var} and return its value.
2667 @var{var} must be a variable object; see @code{make-variable}
2668 and @code{make-undefined-variable}.
2671 @c docstring begin (texi-doc-string "guile" "variable-set!")
2672 @deffn primitive variable-set! var val
2673 Set the value of the variable @var{var} to @var{val}.
2674 @var{var} must be a variable object, @var{val} can be any
2675 value. Return an unspecified value.
2678 @c docstring begin (texi-doc-string "guile" "variable?")
2679 @deffn primitive variable? obj
2680 Return @code{#t} iff @var{obj} is a variable object, else
2688 Keywords are self-evaluating objects with a convenient read syntax that
2689 makes them easy to type.
2691 Guile's keyword support conforms to R4RS, and adds a (switchable) read
2692 syntax extension to permit keywords to begin with @code{:} as well as
2696 * Why Use Keywords?:: Motivation for keyword usage.
2697 * Coding With Keywords:: How to use keywords.
2698 * Keyword Read Syntax:: Read syntax for keywords.
2699 * Keyword Primitives:: Procedures for dealing with keywords.
2702 @node Why Use Keywords?
2703 @subsection Why Use Keywords?
2705 Keywords are useful in contexts where a program or procedure wants to be
2706 able to accept a large number of optional arguments without making its
2707 interface unmanageable.
2709 To illustrate this, consider a hypothetical @code{make-window}
2710 procedure, which creates a new window on the screen for drawing into
2711 using some graphical toolkit. There are many parameters that the caller
2712 might like to specify, but which could also be sensibly defaulted, for
2717 colour depth -- Default: the colour depth for the screen
2720 background colour -- Default: white
2723 width -- Default: 600
2726 height -- Default: 400
2729 If @code{make-window} did not use keywords, the caller would have to
2730 pass in a value for each possible argument, remembering the correct
2731 argument order and using a special value to indicate the default value
2735 (make-window 'default ;; Colour depth
2736 'default ;; Background colour
2739 @dots{}) ;; More make-window arguments
2742 With keywords, on the other hand, defaulted arguments are omitted, and
2743 non-default arguments are clearly tagged by the appropriate keyword. As
2744 a result, the invocation becomes much clearer:
2747 (make-window #:width 800 #:height 100)
2750 On the other hand, for a simpler procedure with few arguments, the use
2751 of keywords would be a hindrance rather than a help. The primitive
2752 procedure @code{cons}, for example, would not be improved if it had to
2756 (cons #:car x #:cdr y)
2759 So the decision whether to use keywords or not is purely pragmatic: use
2760 them if they will clarify the procedure invocation at point of call.
2762 @node Coding With Keywords
2763 @subsection Coding With Keywords
2765 If a procedure wants to support keywords, it should take a rest argument
2766 and then use whatever means is convenient to extract keywords and their
2767 corresponding arguments from the contents of that rest argument.
2769 The following example illustrates the principle: the code for
2770 @code{make-window} uses a helper procedure called
2771 @code{get-keyword-value} to extract individual keyword arguments from
2775 (define (get-keyword-value args keyword default)
2776 (let ((kv (memq keyword args)))
2777 (if (and kv (>= (length kv) 2))
2781 (define (make-window . args)
2782 (let ((depth (get-keyword-value args #:depth screen-depth))
2783 (bg (get-keyword-value args #:bg "white"))
2784 (width (get-keyword-value args #:width 800))
2785 (height (get-keyword-value args #:height 100))
2790 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
2791 optargs)} module provides a set of powerful macros that you can use to
2792 implement keyword-supporting procedures like this:
2795 (use-modules (ice-9 optargs))
2797 (define (make-window . args)
2798 (let-keywords args #f ((depth screen-depth)
2806 Or, even more economically, like this:
2809 (use-modules (ice-9 optargs))
2811 (define* (make-window #:key (depth screen-depth)
2818 For further details on @code{let-keywords}, @code{define*} and other
2819 facilities provided by the @code{(ice-9 optargs)} module, @ref{Optional
2823 @node Keyword Read Syntax
2824 @subsection Keyword Read Syntax
2826 Guile, by default, only recognizes the keyword syntax specified by R5RS.
2827 A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
2828 as a Scheme symbol, is the external representation of the keyword named
2829 @code{NAME}. Keyword objects print using this syntax as well, so values
2830 containing keyword objects can be read back into Guile. When used in an
2831 expression, keywords are self-quoting objects.
2833 If the @code{keyword} read option is set to @code{'prefix}, Guile also
2834 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
2835 of the form @code{:NAME} are read as symbols, as required by R4RS.
2837 To enable and disable the alternative non-R4RS keyword syntax, you use
2838 the @code{read-options} procedure documented in @ref{General option
2839 interface} and @ref{Reader options}.
2842 (read-set! keywords 'prefix)
2852 (read-set! keywords #f)
2860 ERROR: In expression :type:
2861 ERROR: Unbound variable: :type
2862 ABORT: (unbound-variable)
2865 @node Keyword Primitives
2866 @subsection Keyword Primitives
2868 Internally, a keyword is implemented as something like a tagged symbol,
2869 where the tag identifies the keyword as being self-evaluating, and the
2870 symbol, known as the keyword's @dfn{dash symbol} has the same name as
2871 the keyword name but prefixed by a single dash. For example, the
2872 keyword @code{#:name} has the corresponding dash symbol @code{-name}.
2874 Most keyword objects are constructed automatically by the reader when it
2875 reads a token beginning with @code{#:}. However, if you need to
2876 construct a keyword object programmatically, you can do so by calling
2877 @code{make-keyword-from-dash-symbol} with the corresponding dash symbol
2878 (as the reader does). The dash symbol for a keyword object can be
2879 retrieved using the @code{keyword-dash-symbol} procedure.
2881 @c docstring begin (texi-doc-string "guile" "make-keyword-from-dash-symbol")
2882 @deffn primitive make-keyword-from-dash-symbol symbol
2883 Make a keyword object from a @var{symbol} that starts with a dash.
2886 @c docstring begin (texi-doc-string "guile" "keyword?")
2887 @deffn primitive keyword? obj
2888 Return @code{#t} if the argument @var{obj} is a keyword, else
2892 @c docstring begin (texi-doc-string "guile" "keyword-dash-symbol")
2893 @deffn primitive keyword-dash-symbol keyword
2894 Return the dash symbol for @var{keyword}.
2895 This is the inverse of @code{make-keyword-from-dash-symbol}.
2902 @c FIXME::martin: Review me!
2904 Pairs are used to combine two Scheme objects into one compound object.
2905 Hence the name: A pair stores a pair of objects.
2907 The data type @emph{pair} is extremely important in Scheme, just like in
2908 any other Lisp dialect. The reason is that pairs are not only used to
2909 make two values available as one object, but that pairs are used for
2910 constructing lists of values. Because lists are so important in Scheme,
2911 they are described in a section of their own (@pxref{Lists}).
2913 Pairs can literally get entered in source code or at the REPL, in the
2914 so-called @dfn{dotted list} syntax. This syntax consists of an opening
2915 parentheses, the first element of the pair, a dot, the second element
2916 and a closing parentheses. The following example shows how a pair
2917 consisting of the two numbers 1 and 2, and a pair containing the symbols
2918 @code{foo} and @code{bar} can be entered. It is very important to write
2919 the whitespace before and after the dot, because otherwise the Scheme
2920 parser whould not be able to figure out where to split the tokens.
2927 But beware, if you want to try out these examples, you have to
2928 @dfn{quote} the expressions. More information about quotation is
2929 available in the section (REFFIXME). The correct way to try these
2930 examples is as follows.
2941 A new pair is made by calling the procedure @code{cons} with two
2942 arguments. Then the argument values are stored into a newly allocated
2943 pair, and the pair is returned. The name @code{cons} stands for
2944 @emph{construct}. Use the procedure @code{pair?} to test whether a
2945 given Scheme object is a pair or not.
2948 @c docstring begin (texi-doc-string "guile" "cons")
2949 @deffn primitive cons x y
2950 Return a newly allocated pair whose car is @var{x} and whose
2951 cdr is @var{y}. The pair is guaranteed to be different (in the
2952 sense of @code{eq?}) from every previously existing object.
2956 @c docstring begin (texi-doc-string "guile" "pair?")
2957 @deffn primitive pair? x
2958 Return @code{#t} if @var{x} is a pair; otherwise return
2962 The two parts of a pair are traditionally called @emph{car} and
2963 @emph{cdr}. They can be retrieved with procedures of the same name
2964 (@code{car} and @code{cdr}), and can be modified with the procedures
2965 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
2966 Scheme programs is to access the car of a pair, or the car of the cdr of
2967 a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
2968 are also predefined.
2972 @deffn primitive car pair
2973 @deffnx primitive cdr pair
2974 Return the car or the cdr of @var{pair}, respectively.
2977 @deffn primitive caar pair
2978 @deffnx primitive cadr pair @dots{}
2979 @deffnx primitive cdddar pair
2980 @deffnx primitive cddddr pair
2981 These procedures are compositions of @code{car} and @code{cdr}, where
2982 for example @code{caddr} could be defined by
2985 (define caddr (lambda (x) (car (cdr (cdr x)))))
2990 @c docstring begin (texi-doc-string "guile" "set-car!")
2991 @deffn primitive set-car! pair value
2992 Stores @var{value} in the car field of @var{pair}. The value returned
2993 by @code{set-car!} is unspecified.
2997 @c docstring begin (texi-doc-string "guile" "set-cdr!")
2998 @deffn primitive set-cdr! pair value
2999 Stores @var{value} in the cdr field of @var{pair}. The value returned
3000 by @code{set-cdr!} is unspecified.
3007 A very important datatype in Scheme---as well as in all other Lisp
3008 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
3009 Scheme does not have a real datatype @emph{list}. Lists are made up of
3010 chained @emph{pairs}, and only exist by definition --- A list is a chain
3011 of pairs which looks like a list.}
3013 This is the short definition of what a list is:
3016 @item Either the empty list @code{()},
3017 @item or a pair which has a list in its cdr.
3020 @c FIXME::martin: Describe the pair chaining in more detail.
3022 @c FIXME::martin: What is a proper, what an improper list?
3023 @c What is a circular list?
3025 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
3029 * List Syntax:: Writing literal lists.
3030 * List Predicates:: Testing lists.
3031 * List Constructors:: Creating new lists.
3032 * List Selection:: Selecting from lists, getting their length.
3033 * Append/Reverse:: Appending and reversing lists.
3034 * List Modifification:: Modifying list structure.
3035 * List Searching:: Searching for list elements
3036 * List Mapping:: Applying procedures to lists.
3040 @subsection List Read Syntax
3042 The syntax for lists is an opening parentheses, then all the elements of
3043 the list (separated by whitespace) and finally a closing
3044 parentheses.@footnote{Note that there is no separation character between
3045 the list elements, like a comma or a semicolon.}.
3048 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
3049 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
3050 () ; @r{the empty list}
3053 The last example needs a bit more explanation. A list with no elements,
3054 called the @dfn{empty list}, is special in some ways. It is used for
3055 terminating lists by storing it into the cdr of the last pair that makes
3056 up a list. An example will clear that up:
3067 This example also shows that lists have to be quoted (REFFIXME) when
3068 written, because they would otherwise be mistakingly taken as procedure
3069 applications (REFFIXME).
3072 @node List Predicates
3073 @subsection List Predicates
3075 Often it is useful to test whether a given Scheme object is a list or
3076 not. List--processing procedures could use this information to test
3077 whether their input is valid, or they could do different things
3078 depending on the datatype of their arguments.
3081 @c docstring begin (texi-doc-string "guile" "list?")
3082 @deffn primitive list? x
3083 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
3086 The predicate @code{null?} is often used in list--processing code to
3087 tell whether a given list has run out of elements. That is, a loop
3088 somehow deals with the elements of a list until the list satisfies
3089 @code{null?}. Then, teh algorithm terminates.
3092 @c docstring begin (texi-doc-string "guile" "null?")
3093 @deffn primitive null? x
3094 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
3097 @node List Constructors
3098 @subsection List Constructors
3100 This section describes the procedures for constructing new lists.
3101 @code{list} simply returns a list where the elements are the arguments,
3102 @code{cons*} is similar, but the last argument is stored in the cdr of
3103 the last pair of the list.
3106 @c docstring begin (texi-doc-string "guile" "list")
3107 @deffn primitive list arg1 @dots{}
3108 Return a list containing @var{objs}, the arguments to
3112 @c docstring begin (texi-doc-string "guile" "cons*")
3113 @deffn primitive cons* arg1 arg2 @dots{}
3114 Like @code{list}, but the last arg provides the tail of the
3115 constructed list, returning @code{(cons @var{arg1} (cons
3116 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
3117 argument. If given one argument, that argument is returned as
3118 result. This function is called @code{list*} in some other
3119 Schemes and in Common LISP.
3122 @c docstring begin (texi-doc-string "guile" "list-copy")
3123 @deffn primitive list-copy lst
3124 Return a (newly-created) copy of @var{lst}.
3127 Note that @code{list-copy} only makes a copy of the pairs which make up
3128 the spine of the lists. The list elements are not copied, which means
3129 that modifying the elements of the new list also modyfies the elements
3130 of the old list. On the other hand, applying procedures like
3131 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
3132 list. If you also need to copy the list elements (making a deep copy),
3133 use the procedure @code{copy-tree} (REFFIXME).
3135 @node List Selection
3136 @subsection List Selection
3138 These procedures are used to get some information about a list, or to
3139 retrieve one or more elements of a list.
3142 @c docstring begin (texi-doc-string "guile" "length")
3143 @deffn primitive length lst
3144 Return the number of elements in list @var{lst}.
3147 @c docstring begin (texi-doc-string "guile" "last-pair")
3148 @deffn primitive last-pair lst
3149 Return a pointer to the last pair in @var{lst}, signalling an error if
3150 @var{lst} is circular.
3154 @c docstring begin (texi-doc-string "guile" "list-ref")
3155 @deffn primitive list-ref list k
3156 Return the @var{k}th element from @var{list}.
3160 @c docstring begin (texi-doc-string "guile" "list-tail")
3161 @c docstring begin (texi-doc-string "guile" "list-cdr-ref")
3162 @deffn primitive list-tail lst k
3163 @deffnx primitive list-cdr-ref lst k
3164 Return the "tail" of @var{lst} beginning with its @var{k}th element.
3165 The first element of the list is considered to be element 0.
3167 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
3168 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
3169 or returning the results of cdring @var{k} times down @var{lst}.
3172 @c docstring begin (texi-doc-string "guile" "list-head")
3173 @deffn primitive list-head lst k
3174 Copy the first @var{k} elements from @var{lst} into a new list, and
3178 @node Append/Reverse
3179 @subsection Append and Reverse
3181 @code{append} and @code{append!} are used to concatenate two or more
3182 lists in order to form a new list. @code{reverse} and @code{reverse!}
3183 return lists with the same elements as their arguments, but in reverse
3184 order. The procedure variants with an @code{!} directly modify the
3185 pairs which form the list, whereas the other procedures create new
3186 pairs. This is why you should be careful when using the side--effecting
3190 @c docstring begin (texi-doc-string "guile" "append")
3191 @deffn primitive append . args
3192 Return a list consisting of the elements the lists passed as
3195 (append '(x) '(y)) @result{} (x y)
3196 (append '(a) '(b c d)) @result{} (a b c d)
3197 (append '(a (b)) '((c))) @result{} (a (b) (c))
3199 The resulting list is always newly allocated, except that it
3200 shares structure with the last list argument. The last
3201 argument may actually be any object; an improper list results
3202 if the last argument is not a proper list.
3204 (append '(a b) '(c . d)) @result{} (a b c . d)
3205 (append '() 'a) @result{} a
3209 @c docstring begin (texi-doc-string "guile" "append!")
3210 @deffn primitive append! . lists
3211 A destructive version of @code{append} (@pxref{Pairs and
3212 Lists,,,r4rs, The Revised^4 Report on Scheme}). The cdr field
3213 of each list's final pair is changed to point to the head of
3214 the next list, so no consing is performed. Return a pointer to
3219 @c docstring begin (texi-doc-string "guile" "reverse")
3220 @deffn primitive reverse lst
3221 Return a new list that contains the elements of @var{lst} but
3225 @c NJFIXME explain new_tail
3226 @c docstring begin (texi-doc-string "guile" "reverse!")
3227 @deffn primitive reverse! lst [new_tail]
3228 A destructive version of @code{reverse} (@pxref{Pairs and Lists,,,r4rs,
3229 The Revised^4 Report on Scheme}). The cdr of each cell in @var{lst} is
3230 modified to point to the previous list element. Return a pointer to the
3231 head of the reversed list.
3233 Caveat: because the list is modified in place, the tail of the original
3234 list now becomes its head, and the head of the original list now becomes
3235 the tail. Therefore, the @var{lst} symbol to which the head of the
3236 original list was bound now points to the tail. To ensure that the head
3237 of the modified list is not lost, it is wise to save the return value of
3241 @node List Modifification
3242 @subsection List Modification
3244 The following procedures modify existing list. @code{list-set!} and
3245 @code{list-cdr-set!} change which elements a list contains, the various
3246 deletion procedures @code{delq}, @code{delv} etc.
3248 @c docstring begin (texi-doc-string "guile" "list-set!")
3249 @deffn primitive list-set! list k val
3250 Set the @var{k}th element of @var{list} to @var{val}.
3253 @c docstring begin (texi-doc-string "guile" "list-cdr-set!")
3254 @deffn primitive list-cdr-set! list k val
3255 Set the @var{k}th cdr of @var{list} to @var{val}.
3258 @c docstring begin (texi-doc-string "guile" "delq")
3259 @deffn primitive delq item lst
3260 Return a newly-created copy of @var{lst} with elements
3261 @code{eq?} to @var{item} removed. This procedure mirrors
3262 @code{memq}: @code{delq} compares elements of @var{lst} against
3263 @var{item} with @code{eq?}.
3266 @c docstring begin (texi-doc-string "guile" "delv")
3267 @deffn primitive delv item lst
3268 Return a newly-created copy of @var{lst} with elements
3269 @code{eqv?} to @var{item} removed. This procedure mirrors
3270 @code{memv}: @code{delv} compares elements of @var{lst} against
3271 @var{item} with @code{eqv?}.
3274 @c docstring begin (texi-doc-string "guile" "delete")
3275 @deffn primitive delete item lst
3276 Return a newly-created copy of @var{lst} with elements
3277 @code{equal?} to @var{item} removed. This procedure mirrors
3278 @code{member}: @code{delete} compares elements of @var{lst}
3279 against @var{item} with @code{equal?}.
3282 @c docstring begin (texi-doc-string "guile" "delq!")
3283 @c docstring begin (texi-doc-string "guile" "delv!")
3284 @c docstring begin (texi-doc-string "guile" "delete!")
3285 @deffn primitive delq! item lst
3286 @deffnx primitive delv! item lst
3287 @deffnx primitive delete! item lst
3288 These procedures are destructive versions of @code{delq}, @code{delv}
3289 and @code{delete}: they modify the pointers in the existing @var{lst}
3290 rather than creating a new list. Caveat evaluator: Like other
3291 destructive list functions, these functions cannot modify the binding of
3292 @var{lst}, and so cannot be used to delete the first element of
3293 @var{lst} destructively.
3296 @c docstring begin (texi-doc-string "guile" "delq1!")
3297 @deffn primitive delq1! item lst
3298 Like @code{delq!}, but only deletes the first occurrence of
3299 @var{item} from @var{lst}. Tests for equality using
3300 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
3303 @c docstring begin (texi-doc-string "guile" "delv1!")
3304 @deffn primitive delv1! item lst
3305 Like @code{delv!}, but only deletes the first occurrence of
3306 @var{item} from @var{lst}. Tests for equality using
3307 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
3310 @c docstring begin (texi-doc-string "guile" "delete1!")
3311 @deffn primitive delete1! item lst
3312 Like @code{delete!}, but only deletes the first occurrence of
3313 @var{item} from @var{lst}. Tests for equality using
3314 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
3317 @node List Searching
3318 @subsection List Searching
3320 The following procedures search lists for particular elements. They use
3321 different comparison predicates for comparing list elements with the
3322 object to be seached. When they fail, they return @code{#f}, otherwise
3323 they return the sublist whose car is equal to the search object, where
3324 equality depends on the equality predicate used.
3327 @c docstring begin (texi-doc-string "guile" "memq")
3328 @deffn primitive memq x lst
3329 Return the first sublist of @var{lst} whose car is @code{eq?}
3330 to @var{x} where the sublists of @var{lst} are the non-empty
3331 lists returned by @code{(list-tail @var{lst} @var{k})} for
3332 @var{k} less than the length of @var{lst}. If @var{x} does not
3333 occur in @var{lst}, then @code{#f} (not the empty list) is
3338 @c docstring begin (texi-doc-string "guile" "memv")
3339 @deffn primitive memv x lst
3340 Return the first sublist of @var{lst} whose car is @code{eqv?}
3341 to @var{x} where the sublists of @var{lst} are the non-empty
3342 lists returned by @code{(list-tail @var{lst} @var{k})} for
3343 @var{k} less than the length of @var{lst}. If @var{x} does not
3344 occur in @var{lst}, then @code{#f} (not the empty list) is
3349 @c docstring begin (texi-doc-string "guile" "member")
3350 @deffn primitive member x lst
3351 Return the first sublist of @var{lst} whose car is
3352 @code{equal?} to @var{x} where the sublists of @var{lst} are
3353 the non-empty lists returned by @code{(list-tail @var{lst}
3354 @var{k})} for @var{k} less than the length of @var{lst}. If
3355 @var{x} does not occur in @var{lst}, then @code{#f} (not the
3356 empty list) is returned.
3359 [FIXME: is there any reason to have the `sloppy' functions available at
3360 high level at all? Maybe these docs should be relegated to a "Guile
3361 Internals" node or something. -twp]
3363 @c docstring begin (texi-doc-string "guile" "sloppy-memq")
3364 @deffn primitive sloppy-memq x lst
3365 This procedure behaves like @code{memq}, but does no type or error checking.
3366 Its use is recommended only in writing Guile internals,
3367 not for high-level Scheme programs.
3370 @c docstring begin (texi-doc-string "guile" "sloppy-memv")
3371 @deffn primitive sloppy-memv x lst
3372 This procedure behaves like @code{memv}, but does no type or error checking.
3373 Its use is recommended only in writing Guile internals,
3374 not for high-level Scheme programs.
3377 @c docstring begin (texi-doc-string "guile" "sloppy-member")
3378 @deffn primitive sloppy-member x lst
3379 This procedure behaves like @code{member}, but does no type or error checking.
3380 Its use is recommended only in writing Guile internals,
3381 not for high-level Scheme programs.
3385 @subsection List Mapping
3387 List processing is very convenient in Scheme because the process of
3388 iterating over the elements of a list can be highly abstracted. The
3389 procedures in this section are the most basic iterating procedures for
3390 lists. They take a procedure and one or more lists as arguments, and
3391 apply the procedure to each element of the list. They differ in what
3392 the result of the invocation is.
3395 @c begin (texi-doc-string "guile" "map")
3396 @c docstring begin (texi-doc-string "guile" "map-in-order")
3397 @deffn primitive map proc arg1 arg2 @dots{}
3398 @deffnx primitive map-in-order proc arg1 arg2 @dots{}
3399 Apply @var{proc} to each element of the list @var{arg1} (if only two
3400 arguments are given), or to the corresponding elements of the argument
3401 lists (if more than two arguments are given). The result(s) of the
3402 procedure applications are saved and returned in a list. For
3403 @code{map}, the order of procedure applications is not specified,
3404 @code{map-in-order} applies the procedure from left to right to the list
3409 @c begin (texi-doc-string "guile" "for-each")
3410 @deffn primitive for-each proc arg1 arg2 @dots{}
3411 Like @code{map}, but the procedure is always applied from left to right,
3412 and the result(s) of the procedure applications are thrown away. The
3413 return value is not specified.
3420 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3423 A @dfn{record type} is a first class object representing a user-defined
3424 data type. A @dfn{record} is an instance of a record type.
3426 @deffn procedure record? obj
3427 Returns @code{#t} if @var{obj} is a record of any type and @code{#f}
3430 Note that @code{record?} may be true of any Scheme value; there is no
3431 promise that records are disjoint with other Scheme types.
3434 @deffn procedure make-record-type type-name field-names
3435 Returns a @dfn{record-type descriptor}, a value representing a new data
3436 type disjoint from all others. The @var{type-name} argument must be a
3437 string, but is only used for debugging purposes (such as the printed
3438 representation of a record of the new type). The @var{field-names}
3439 argument is a list of symbols naming the @dfn{fields} of a record of the
3440 new type. It is an error if the list contains any duplicates. It is
3441 unspecified how record-type descriptors are represented.@refill
3444 @deffn procedure record-constructor rtd [field-names]
3445 Returns a procedure for constructing new members of the type represented
3446 by @var{rtd}. The returned procedure accepts exactly as many arguments
3447 as there are symbols in the given list, @var{field-names}; these are
3448 used, in order, as the initial values of those fields in a new record,
3449 which is returned by the constructor procedure. The values of any
3450 fields not named in that list are unspecified. The @var{field-names}
3451 argument defaults to the list of field names in the call to
3452 @code{make-record-type} that created the type represented by @var{rtd};
3453 if the @var{field-names} argument is provided, it is an error if it
3454 contains any duplicates or any symbols not in the default list.@refill
3457 @deffn procedure record-predicate rtd
3458 Returns a procedure for testing membership in the type represented by
3459 @var{rtd}. The returned procedure accepts exactly one argument and
3460 returns a true value if the argument is a member of the indicated record
3461 type; it returns a false value otherwise.@refill
3464 @deffn procedure record-accessor rtd field-name
3465 Returns a procedure for reading the value of a particular field of a
3466 member of the type represented by @var{rtd}. The returned procedure
3467 accepts exactly one argument which must be a record of the appropriate
3468 type; it returns the current value of the field named by the symbol
3469 @var{field-name} in that record. The symbol @var{field-name} must be a
3470 member of the list of field-names in the call to @code{make-record-type}
3471 that created the type represented by @var{rtd}.@refill
3474 @deffn procedure record-modifier rtd field-name
3475 Returns a procedure for writing the value of a particular field of a
3476 member of the type represented by @var{rtd}. The returned procedure
3477 accepts exactly two arguments: first, a record of the appropriate type,
3478 and second, an arbitrary Scheme value; it modifies the field named by
3479 the symbol @var{field-name} in that record to contain the given value.
3480 The returned value of the modifier procedure is unspecified. The symbol
3481 @var{field-name} must be a member of the list of field-names in the call
3482 to @code{make-record-type} that created the type represented by
3486 @deffn procedure record-type-descriptor record
3487 Returns a record-type descriptor representing the type of the given
3488 record. That is, for example, if the returned descriptor were passed to
3489 @code{record-predicate}, the resulting predicate would return a true
3490 value when passed the given record. Note that it is not necessarily the
3491 case that the returned descriptor is the one that was passed to
3492 @code{record-constructor} in the call that created the constructor
3493 procedure that created the given record.@refill
3496 @deffn procedure record-type-name rtd
3497 Returns the type-name associated with the type represented by rtd. The
3498 returned value is @code{eqv?} to the @var{type-name} argument given in
3499 the call to @code{make-record-type} that created the type represented by
3503 @deffn procedure record-type-fields rtd
3504 Returns a list of the symbols naming the fields in members of the type
3505 represented by @var{rtd}. The returned value is @code{equal?} to the
3506 field-names argument given in the call to @code{make-record-type} that
3507 created the type represented by @var{rtd}.@refill
3514 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3517 A @dfn{structure type} is a first class user-defined data type. A
3518 @dfn{structure} is an instance of a structure type. A structure type is
3521 Structures are less abstract and more general than traditional records.
3522 In fact, in Guile Scheme, records are implemented using structures.
3525 * Structure Concepts:: The structure of Structures
3526 * Structure Layout:: Defining the layout of structure types
3527 * Structure Basics:: make-, -ref and -set! procedures for structs
3528 * Vtables:: Accessing type-specific data
3531 @node Structure Concepts
3532 @subsection Structure Concepts
3534 A structure object consists of a handle, structure data, and a vtable.
3535 The handle is a Scheme value which points to both the vtable and the
3536 structure's data. Structure data is a dynamically allocated region of
3537 memory, private to the structure, divided up into typed fields. A
3538 vtable is another structure used to hold type-specific data. Multiple
3539 structures can share a common vtable.
3541 Three concepts are key to understanding structures.
3544 @item @dfn{layout specifications}
3546 Layout specifications determine how memory allocated to structures is
3547 divided up into fields. Programmers must write a layout specification
3548 whenever a new type of structure is defined.
3550 @item @dfn{structural accessors}
3552 Structure access is by field number. There is only one set of
3553 accessors common to all structure objects.
3557 Vtables, themselves structures, are first class representations of
3558 disjoint sub-types of structures in general. In most cases, when a
3559 new structure is created, programmers must specifiy a vtable for the
3560 new structure. Each vtable has a field describing the layout of its
3561 instances. Vtables can have additional, user-defined fields as well.
3566 @node Structure Layout
3567 @subsection Structure Layout
3569 When a structure is created, a region of memory is allocated to hold its
3570 state. The @dfn{layout} of the structure's type determines how that
3571 memory is divided into fields.
3573 Each field has a specified type. There are only three types allowed, each
3574 corresponding to a one letter code. The allowed types are:
3577 @item 'u' -- unprotected
3579 The field holds binary data that is not GC protected.
3581 @item 'p' -- protected
3583 The field holds a Scheme value and is GC protected.
3587 The field holds a Scheme value and is GC protected. When a structure is
3588 created with this type of field, the field is initialized to refer to
3589 the structure's own handle. This kind of field is mainly useful when
3590 mixing Scheme and C code in which the C code may need to compute a
3591 structure's handle given only the address of its malloced data.
3595 Each field also has an associated access protection. There are only
3596 three kinds of protection, each corresponding to a one letter code.
3597 The allowed protections are:
3600 @item 'w' -- writable
3602 The field can be read and written.
3604 @item 'r' -- readable
3606 The field can be read, but not written.
3610 The field can be neither read nor written. This kind
3611 of protection is for fields useful only to built-in routines.
3614 A layout specification is described by stringing together pairs
3615 of letters: one to specify a field type and one to specify a field
3616 protection. For example, a traditional cons pair type object could
3620 ; cons pairs have two writable fields of Scheme data
3624 A pair object in which the first field is held constant could be:
3630 Binary fields, (fields of type "u"), hold one @emph{word} each. The
3631 size of a word is a machine dependent value defined to be equal to the
3632 value of the C expression: @code{sizeof (long)}.
3634 The last field of a structure layout may specify a tail array.
3635 A tail array is indicated by capitalizing the field's protection
3636 code ('W', 'R' or 'O'). A tail-array field is replaced by
3637 a read-only binary data field containing an array size. The array
3638 size is determined at the time the structure is created. It is followed
3639 by a corresponding number of fields of the type specified for the
3640 tail array. For example, a conventional Scheme vector can be
3644 ; A vector is an arbitrary number of writable fields holding Scheme
3649 In the above example, field 0 contains the size of the vector and
3650 fields beginning at 1 contain the vector elements.
3652 A kind of tagged vector (a constant tag followed by conventioal
3653 vector elements) might be:
3660 Structure layouts are represented by specially interned symbols whose
3661 name is a string of type and protection codes. To create a new
3662 structure layout, use this procedure:
3664 @c docstring begin (texi-doc-string "guile" "make-struct-layout")
3665 @deffn primitive make-struct-layout fields
3666 Return a new structure layout object.
3668 @var{fields} must be a string made up of pairs of characters
3669 strung together. The first character of each pair describes a field
3670 type, the second a field protection. Allowed types are 'p' for
3671 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
3672 a field that points to the structure itself. Allowed protections
3673 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
3674 fields. The last field protection specification may be capitalized to
3675 indicate that the field is a tail-array.
3680 @node Structure Basics
3681 @subsection Structure Basics
3683 This section describes the basic procedures for creating and accessing
3686 @c docstring begin (texi-doc-string "guile" "make-struct")
3687 @deffn primitive make-struct vtable tail_array_size . init
3688 Create a new structure.
3690 @var{type} must be a vtable structure (@pxref{Vtables}).
3692 @var{tail-elts} must be a non-negative integer. If the layout
3693 specification indicated by @var{type} includes a tail-array,
3694 this is the number of elements allocated to that array.
3696 The @var{init1}, @dots{} are optional arguments describing how
3697 successive fields of the structure should be initialized. Only fields
3698 with protection 'r' or 'w' can be initialized, except for fields of
3699 type 's', which are automatically initialized to point to the new
3700 structure itself; fields with protection 'o' can not be initialized by
3703 If fewer optional arguments than initializable fields are supplied,
3704 fields of type 'p' get default value #f while fields of type 'u' are
3707 Structs are currently the basic representation for record-like data
3708 structures in Guile. The plan is to eventually replace them with a
3709 new representation which will at the same time be easier to use and
3712 For more information, see the documentation for @code{make-vtable-vtable}.
3715 @c docstring begin (texi-doc-string "guile" "struct?")
3716 @deffn primitive struct? x
3717 Return @code{#t} iff @var{obj} is a structure object, else
3722 @c docstring begin (texi-doc-string "guile" "struct-ref")
3723 @c docstring begin (texi-doc-string "guile" "struct-set!")
3724 @deffn primitive struct-ref handle pos
3725 @deffnx primitive struct-set! struct n value
3726 Access (or modify) the @var{n}th field of @var{struct}.
3728 If the field is of type 'p', then it can be set to an arbitrary value.
3730 If the field is of type 'u', then it can only be set to a non-negative
3731 integer value small enough to fit in one machine word.
3739 Vtables are structures that are used to represent structure types. Each
3740 vtable contains a layout specification in field
3741 @code{vtable-index-layout} -- instances of the type are laid out
3742 according to that specification. Vtables contain additional fields
3743 which are used only internally to libguile. The variable
3744 @code{vtable-offset-user} is bound to a field number. Vtable fields
3745 at that position or greater are user definable.
3747 @c docstring begin (texi-doc-string "guile" "struct-vtable")
3748 @deffn primitive struct-vtable handle
3749 Return the vtable structure that describes the type of @var{struct}.
3752 @c docstring begin (texi-doc-string "guile" "struct-vtable?")
3753 @deffn primitive struct-vtable? x
3754 Return @code{#t} iff obj is a vtable structure.
3757 If you have a vtable structure, @code{V}, you can create an instance of
3758 the type it describes by using @code{(make-struct V ...)}. But where
3759 does @code{V} itself come from? One possibility is that @code{V} is an
3760 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
3761 created by using @code{(make-struct V' ...)}. Another possibility is
3762 that @code{V} is an instance of the type it itself describes. Vtable
3763 structures of the second sort are created by this procedure:
3765 @c docstring begin (texi-doc-string "guile" "make-vtable-vtable")
3766 @deffn primitive make-vtable-vtable user_fields tail_array_size . init
3767 Return a new, self-describing vtable structure.
3769 @var{user-fields} is a string describing user defined fields of the
3770 vtable beginning at index @code{vtable-offset-user}
3771 (see @code{make-struct-layout}).
3773 @var{tail-size} specifies the size of the tail-array (if any) of
3776 @var{init1}, @dots{} are the optional initializers for the fields of
3779 Vtables have one initializable system field---the struct printer.
3780 This field comes before the user fields in the initializers passed
3781 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
3782 a third optional argument to @code{make-vtable-vtable} and a fourth to
3783 @code{make-struct} when creating vtables:
3785 If the value is a procedure, it will be called instead of the standard
3786 printer whenever a struct described by this vtable is printed.
3787 The procedure will be called with arguments STRUCT and PORT.
3789 The structure of a struct is described by a vtable, so the vtable is
3790 in essence the type of the struct. The vtable is itself a struct with
3791 a vtable. This could go on forever if it weren't for the
3792 vtable-vtables which are self-describing vtables, and thus terminate
3795 There are several potential ways of using structs, but the standard
3796 one is to use three kinds of structs, together building up a type
3797 sub-system: one vtable-vtable working as the root and one or several
3798 "types", each with a set of "instances". (The vtable-vtable should be
3799 compared to the class <class> which is the class of itself.)
3802 (define ball-root (make-vtable-vtable "pr" 0))
3804 (define (make-ball-type ball-color)
3805 (make-struct ball-root 0
3806 (make-struct-layout "pw")
3808 (format port "#<a ~A ball owned by ~A>"
3812 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
3813 (define (owner ball) (struct-ref ball 0))
3815 (define red (make-ball-type 'red))
3816 (define green (make-ball-type 'green))
3818 (define (make-ball type owner) (make-struct type 0 owner))
3820 (define ball (make-ball green 'Nisse))
3821 ball @result{} #<a green ball owned by Nisse>
3825 @c docstring begin (texi-doc-string "guile" "struct-vtable-name")
3826 @deffn primitive struct-vtable-name vtable
3827 Return the name of the vtable @var{vtable}.
3830 @c docstring begin (texi-doc-string "guile" "set-struct-vtable-name!")
3831 @deffn primitive set-struct-vtable-name! vtable name
3832 Set the name of the vtable @var{vtable} to @var{name}.
3835 @c docstring begin (texi-doc-string "guile" "struct-vtable-tag")
3836 @deffn primitive struct-vtable-tag handle
3837 Return the vtable tag of the structure @var{handle}.
3845 * Conventional Arrays:: Arrays with arbitrary data.
3846 * Array Mapping:: Applying a procedure to the contents of an array.
3847 * Uniform Arrays:: Arrays with data of a single type.
3848 * Bit Vectors:: Vectors of bits.
3851 @node Conventional Arrays
3852 @subsection Conventional Arrays
3854 @dfn{Conventional arrays} are a collection of cells organised into an
3855 arbitrary number of dimensions. Each cell can hold any kind of Scheme
3856 value and can be accessed in constant time by supplying an index for
3857 each dimension. This contrasts with uniform arrays, which use memory
3858 more efficiently but can hold data of only a single type, and lists
3859 where inserting and deleting cells is more efficient, but more time
3860 is usually required to access a particular cell.
3862 A conventional array is displayed as @code{#} followed by the @dfn{rank}
3863 (number of dimensions) followed by the cells, organised into dimensions
3864 using parentheses. The nesting depth of the parentheses is equal to
3867 When an array is created, the number of dimensions and range of each
3868 dimension must be specified, e.g., to create a 2x3 array with a
3872 (make-array 'ho 2 3) @result{}
3873 #2((ho ho ho) (ho ho ho))
3876 The range of each dimension can also be given explicitly, e.g., another
3877 way to create the same array:
3880 (make-array 'ho '(0 1) '(0 2)) @result{}
3881 #2((ho ho ho) (ho ho ho))
3884 A conventional array with one dimension based at zero is identical to
3888 (make-array 'ho 3) @result{}
3892 The following procedures can be used with conventional arrays (or vectors).
3894 @c docstring begin (texi-doc-string "guile" "array?")
3895 @deffn primitive array? v [prot]
3896 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
3897 not. The @var{prototype} argument is used with uniform arrays
3898 and is described elsewhere.
3901 @deffn procedure make-array initial-value bound1 bound2 @dots{}
3902 Creates and returns an array that has as many dimensions as there are
3903 @var{bound}s and fills it with @var{initial-value}.
3906 @c array-ref's type is `compiled-closure'. There's some weird stuff
3907 @c going on in array.c, too. Let's call it a primitive. -twp
3909 @c docstring begin (texi-doc-string "guile" "uniform-vector-ref")
3910 @c docstring begin (texi-doc-string "guile" "array-ref")
3911 @deffn primitive uniform-vector-ref v args
3912 @deffnx primitive array-ref v . args
3913 Return the element at the @code{(index1, index2)} element in
3917 @c docstring begin (texi-doc-string "guile" "array-in-bounds?")
3918 @deffn primitive array-in-bounds? v . args
3919 Return @code{#t} if its arguments would be acceptable to
3923 @c docstring begin (texi-doc-string "guile" "array-set!")
3924 @c docstring begin (texi-doc-string "guile" "uniform-array-set1!")
3925 @deffn primitive array-set! v obj . args
3926 @deffnx primitive uniform-array-set1! v obj args
3927 Sets the element at the @code{(index1, index2)} element in @var{array} to
3928 @var{new-value}. The value returned by array-set! is unspecified.
3931 @c docstring begin (texi-doc-string "guile" "make-shared-array")
3932 @deffn primitive make-shared-array oldra mapfunc . dims
3933 @code{make-shared-array} can be used to create shared subarrays of other
3934 arrays. The @var{mapper} is a function that translates coordinates in
3935 the new array into coordinates in the old array. A @var{mapper} must be
3936 linear, and its range must stay within the bounds of the old array, but
3937 it can be otherwise arbitrary. A simple example:
3939 (define fred (make-array #f 8 8))
3940 (define freds-diagonal
3941 (make-shared-array fred (lambda (i) (list i i)) 8))
3942 (array-set! freds-diagonal 'foo 3)
3943 (array-ref fred 3 3) @result{} foo
3944 (define freds-center
3945 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
3946 (array-ref freds-center 0 0) @result{} foo
3950 @c docstring begin (texi-doc-string "guile" "shared-array-increments")
3951 @deffn primitive shared-array-increments ra
3952 For each dimension, return the distance between elements in the root vector.
3955 @c docstring begin (texi-doc-string "guile" "shared-array-offset")
3956 @deffn primitive shared-array-offset ra
3957 Return the root vector index of the first element in the array.
3960 @c docstring begin (texi-doc-string "guile" "shared-array-root")
3961 @deffn primitive shared-array-root ra
3962 Return the root vector of a shared array.
3965 @c docstring begin (texi-doc-string "guile" "transpose-array")
3966 @deffn primitive transpose-array ra . args
3967 Return an array sharing contents with @var{array}, but with
3968 dimensions arranged in a different order. There must be one
3969 @var{dim} argument for each dimension of @var{array}.
3970 @var{dim0}, @var{dim1}, @dots{} should be integers between 0
3971 and the rank of the array to be returned. Each integer in that
3972 range must appear at least once in the argument list.
3973 The values of @var{dim0}, @var{dim1}, @dots{} correspond to
3974 dimensions in the array to be returned, their positions in the
3975 argument list to dimensions of @var{array}. Several @var{dim}s
3976 may have the same value, in which case the returned array will
3977 have smaller rank than @var{array}.
3979 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
3980 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
3981 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
3982 #2((a 4) (b 5) (c 6))
3986 @c docstring begin (texi-doc-string "guile" "enclose-array")
3987 @deffn primitive enclose-array ra . axes
3988 @var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
3989 the rank of @var{array}. @var{enclose-array} returns an array
3990 resembling an array of shared arrays. The dimensions of each shared
3991 array are the same as the @var{dim}th dimensions of the original array,
3992 the dimensions of the outer array are the same as those of the original
3993 array that did not match a @var{dim}.
3995 An enclosed array is not a general Scheme array. Its elements may not
3996 be set using @code{array-set!}. Two references to the same element of
3997 an enclosed array will be @code{equal?} but will not in general be
3998 @code{eq?}. The value returned by @var{array-prototype} when given an
3999 enclosed array is unspecified.
4003 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
4004 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
4006 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
4007 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
4011 @deffn procedure array-shape array
4012 Returns a list of inclusive bounds of integers.
4014 (array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
4018 @c docstring begin (texi-doc-string "guile" "array-dimensions")
4019 @deffn primitive array-dimensions ra
4020 @code{Array-dimensions} is similar to @code{array-shape} but replaces
4021 elements with a @code{0} minimum with one greater than the maximum. So:
4023 (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
4027 @c docstring begin (texi-doc-string "guile" "array-rank")
4028 @deffn primitive array-rank ra
4029 Return the number of dimensions of @var{obj}. If @var{obj} is
4030 not an array, @code{0} is returned.
4033 @c docstring begin (texi-doc-string "guile" "array->list")
4034 @deffn primitive array->list v
4035 Return a list consisting of all the elements, in order, of
4039 @c docstring begin (texi-doc-string "guile" "array-copy!")
4040 @c docstring begin (texi-doc-string "guile" "array-copy-in-order!")
4041 @deffn primitive array-copy! src dst
4042 @deffnx primitive array-copy-in-order! src dst
4043 Copies every element from vector or array @var{source} to the
4044 corresponding element of @var{destination}. @var{destination} must have
4045 the same rank as @var{source}, and be at least as large in each
4046 dimension. The order is unspecified.
4049 @c docstring begin (texi-doc-string "guile" "array-fill!")
4050 @deffn primitive array-fill! ra fill
4051 Stores @var{fill} in every element of @var{array}. The value returned
4055 @c begin (texi-doc-string "guile" "array-equal?")
4056 @deffn primitive array-equal? ra0 ra1
4057 Returns @code{#t} iff all arguments are arrays with the same shape, the
4058 same type, and have corresponding elements which are either
4059 @code{equal?} or @code{array-equal?}. This function differs from
4060 @code{equal?} in that a one dimensional shared array may be
4061 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
4064 @c docstring begin (texi-doc-string "guile" "array-contents")
4065 @deffn primitive array-contents ra [strict]
4066 @deffnx primitive array-contents array strict
4067 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
4068 without changing their order (last subscript changing fastest), then
4069 @code{array-contents} returns that shared array, otherwise it returns
4070 @code{#f}. All arrays made by @var{make-array} and
4071 @var{make-uniform-array} may be unrolled, some arrays made by
4072 @var{make-shared-array} may not be.
4074 If the optional argument @var{strict} is provided, a shared array will
4075 be returned only if its elements are stored internally contiguous in
4080 @subsection Array Mapping
4082 @c docstring begin (texi-doc-string "guile" "array-map!")
4083 @c docstring begin (texi-doc-string "guile" "array-map-in-order!")
4084 @deffn primitive array-map! ra0 proc . lra
4085 @deffnx primitive array-map-in-order! ra0 proc . lra
4086 @var{array1}, @dots{} must have the same number of dimensions as
4087 @var{array0} and have a range for each index which includes the range
4088 for the corresponding index in @var{array0}. @var{proc} is applied to
4089 each tuple of elements of @var{array1} @dots{} and the result is stored
4090 as the corresponding element in @var{array0}. The value returned is
4091 unspecified. The order of application is unspecified.
4094 @c docstring begin (texi-doc-string "guile" "array-for-each")
4095 @deffn primitive array-for-each proc ra0 . lra
4096 @var{proc} is applied to each tuple of elements of @var{array0} @dots{}
4097 in row-major order. The value returned is unspecified.
4100 @c docstring begin (texi-doc-string "guile" "array-index-map!")
4101 @deffn primitive array-index-map! ra proc
4102 applies @var{proc} to the indices of each element of @var{array} in
4103 turn, storing the result in the corresponding element. The value
4104 returned and the order of application are unspecified.
4106 One can implement @var{array-indexes} as
4108 (define (array-indexes array)
4109 (let ((ra (apply make-array #f (array-shape array))))
4110 (array-index-map! ra (lambda x x))
4115 (define (apl:index-generator n)
4116 (let ((v (make-uniform-vector n 1)))
4117 (array-index-map! v (lambda (i) i))
4122 @node Uniform Arrays
4123 @subsection Uniform Arrays
4126 @dfn{Uniform arrays} have elements all of the
4127 same type and occupy less storage than conventional
4128 arrays. Uniform arrays with a single zero-based dimension
4129 are also known as @dfn{uniform vectors}. The procedures in
4130 this section can also be used on conventional arrays, vectors,
4131 bit-vectors and strings.
4134 When creating a uniform array, the type of data to be stored
4135 is indicated with a @var{prototype} argument. The following table
4136 lists the types available and example prototypes:
4139 prototype type printing character
4141 #t boolean (bit-vector) b
4143 #\nul byte (integer) y
4144 's short (integer) h
4145 1 unsigned long (integer) u
4146 -1 signed long (integer) e
4147 'l signed long long (integer) l
4148 1.0 float (single precision) s
4149 1/3 double (double precision float) i
4150 0+i complex (double precision) c
4151 () conventional vector
4155 Unshared uniform arrays of characters with a single zero-based dimension
4156 are identical to strings:
4159 (make-uniform-array #\a 3) @result{}
4164 Unshared uniform arrays of booleans with a single zero-based dimension
4165 are identical to @ref{Bit Vectors, bit-vectors}.
4168 (make-uniform-array #t 3) @result{}
4173 Other uniform vectors are written in a form similar to that of vectors,
4174 except that a single character from the above table is put between
4175 @code{#} and @code{(}. For example, a uniform vector of signed
4176 long integers is displayed in the form @code{'#e(3 5 9)}.
4178 @c docstring begin (texi-doc-string "guile" "array?")
4179 @deffn primitive array? v [prot]
4180 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
4182 The @var{prototype} argument is used with uniform arrays and is described
4186 @deffn procedure make-uniform-array prototype bound1 bound2 @dots{}
4187 Creates and returns a uniform array of type corresponding to
4188 @var{prototype} that has as many dimensions as there are @var{bound}s
4189 and fills it with @var{prototype}.
4192 @c docstring begin (texi-doc-string "guile" "array-prototype")
4193 @deffn primitive array-prototype ra
4194 Return an object that would produce an array of the same type
4195 as @var{array}, if used as the @var{prototype} for
4196 @code{make-uniform-array}.
4199 @c docstring begin (texi-doc-string "guile" "list->uniform-array")
4200 @deffn primitive list->uniform-array ndim prot lst
4201 @deffnx procedure list->uniform-vector prot lst
4202 Return a uniform array of the type indicated by prototype
4203 @var{prot} with elements the same as those of @var{lst}.
4204 Elements must be of the appropriate type, no coercions are
4208 @deffn primitive uniform-vector-fill! uve fill
4209 Stores @var{fill} in every element of @var{uve}. The value returned is
4213 @c docstring begin (texi-doc-string "guile" "uniform-vector-length")
4214 @deffn primitive uniform-vector-length v
4215 Return the number of elements in @var{uve}.
4218 @c docstring begin (texi-doc-string "guile" "dimensions->uniform-array")
4219 @deffn primitive dimensions->uniform-array dims prot [fill]
4220 @deffnx primitive make-uniform-vector length prototype [fill]
4221 Create and return a uniform array or vector of type
4222 corresponding to @var{prototype} with dimensions @var{dims} or
4223 length @var{length}. If @var{fill} is supplied, it's used to
4224 fill the array, otherwise @var{prototype} is used.
4227 @c Another compiled-closure. -twp
4229 @c docstring begin (texi-doc-string "guile" "uniform-array-read!")
4230 @deffn primitive uniform-array-read! ra [port_or_fd [start [end]]]
4231 @deffnx primitive uniform-vector-read! uve [port-or-fdes] [start] [end]
4232 Attempts to read all elements of @var{ura}, in lexicographic order, as
4233 binary objects from @var{port-or-fdes}.
4234 If an end of file is encountered during
4235 uniform-array-read! the objects up to that point only are put into @var{ura}
4236 (starting at the beginning) and the remainder of the array is
4239 The optional arguments @var{start} and @var{end} allow
4240 a specified region of a vector (or linearized array) to be read,
4241 leaving the remainder of the vector unchanged.
4243 @code{uniform-array-read!} returns the number of objects read.
4244 @var{port-or-fdes} may be omitted, in which case it defaults to the value
4245 returned by @code{(current-input-port)}.
4248 @c docstring begin (texi-doc-string "guile" "uniform-array-write")
4249 @deffn primitive uniform-array-write v [port_or_fd [start [end]]]
4250 @deffnx primitive uniform-vector-write uve [port-or-fdes] [start] [end]
4251 Writes all elements of @var{ura} as binary objects to
4254 The optional arguments @var{start}
4256 a specified region of a vector (or linearized array) to be written.
4258 The number of objects actually written is returned.
4259 @var{port-or-fdes} may be
4260 omitted, in which case it defaults to the value returned by
4261 @code{(current-output-port)}.
4265 @subsection Bit Vectors
4268 Bit vectors are a specific type of uniform array: an array of booleans
4269 with a single zero-based index.
4272 They are displayed as a sequence of @code{0}s and
4273 @code{1}s prefixed by @code{#*}, e.g.,
4276 (make-uniform-vector 8 #t #f) @result{}
4279 #b(#t #f #t) @result{}
4283 @c docstring begin (texi-doc-string "guile" "bit-count")
4284 @deffn primitive bit-count b bitvector
4285 Return the number of occurrences of the boolean @var{b} in
4289 @c docstring begin (texi-doc-string "guile" "bit-position")
4290 @deffn primitive bit-position item v k
4291 Return the minimum index of an occurrence of @var{bool} in
4292 @var{bv} which is at least @var{k}. If no @var{bool} occurs
4293 within the specified range @code{#f} is returned.
4296 @c docstring begin (texi-doc-string "guile" "bit-invert!")
4297 @deffn primitive bit-invert! v
4298 Modifies @var{bv} by replacing each element with its negation.
4301 @c docstring begin (texi-doc-string "guile" "bit-set*!")
4302 @deffn primitive bit-set*! v kv obj
4303 If uve is a bit-vector @var{bv} and uve must be of the same
4304 length. If @var{bool} is @code{#t}, uve is OR'ed into
4305 @var{bv}; If @var{bool} is @code{#f}, the inversion of uve is
4306 AND'ed into @var{bv}.
4308 If uve is a unsigned integer vector all the elements of uve
4309 must be between 0 and the @code{length} of @var{bv}. The bits
4310 of @var{bv} corresponding to the indexes in uve are set to
4311 @var{bool}. The return value is unspecified.
4314 @c docstring begin (texi-doc-string "guile" "bit-count*")
4315 @deffn primitive bit-count* v kv obj
4318 (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
4320 @var{bv} is not modified.
4324 @node Association Lists and Hash Tables
4325 @section Association Lists and Hash Tables
4327 This chapter discusses dictionary objects: data structures that are
4328 useful for organizing and indexing large bodies of information.
4331 * Dictionary Types:: About dictionary types; what they're good for.
4332 * Association Lists::
4336 @node Dictionary Types
4337 @subsection Dictionary Types
4339 A @dfn{dictionary} object is a data structure used to index
4340 information in a user-defined way. In standard Scheme, the main
4341 aggregate data types are lists and vectors. Lists are not really
4342 indexed at all, and vectors are indexed only by number
4343 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
4344 to index your data on some other type; for example, in a library
4345 catalog you might want to look up a book by the name of its
4346 author. Dictionaries are used to help you organize information in
4349 An @dfn{association list} (or @dfn{alist} for short) is a list of
4350 key-value pairs. Each pair represents a single quantity or
4351 object; the @code{car} of the pair is a key which is used to
4352 identify the object, and the @code{cdr} is the object's value.
4354 A @dfn{hash table} also permits you to index objects with
4355 arbitrary keys, but in a way that makes looking up any one object
4356 extremely fast. A well-designed hash system makes hash table
4357 lookups almost as fast as conventional array or vector references.
4359 Alists are popular among Lisp programmers because they use only
4360 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
4361 and the equality primitives). No changes to the language core are
4362 necessary. Therefore, with Scheme's built-in list manipulation
4363 facilities, it is very convenient to handle data stored in an
4364 association list. Also, alists are highly portable and can be
4365 easily implemented on even the most minimal Lisp systems.
4367 However, alists are inefficient, especially for storing large
4368 quantities of data. Because we want Guile to be useful for large
4369 software systems as well as small ones, Guile provides a rich set
4370 of tools for using either association lists or hash tables.
4372 @node Association Lists
4373 @subsection Association Lists
4374 @cindex Association List
4378 An association list is a conventional data structure that is often used
4379 to implement simple key-value databases. It consists of a list of
4380 entries in which each entry is a pair. The @dfn{key} of each entry is
4381 the @code{car} of the pair and the @dfn{value} of each entry is the
4385 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
4393 Association lists are also known, for short, as @dfn{alists}.
4395 The structure of an association list is just one example of the infinite
4396 number of possible structures that can be built using pairs and lists.
4397 As such, the keys and values in an association list can be manipulated
4398 using the general list structure procedures @code{cons}, @code{car},
4399 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
4400 because association lists are so useful, Guile also provides specific
4401 procedures for manipulating them.
4404 * Alist Key Equality::
4405 * Adding or Setting Alist Entries::
4406 * Retrieving Alist Entries::
4407 * Removing Alist Entries::
4408 * Sloppy Alist Functions::
4412 @node Alist Key Equality
4413 @subsubsection Alist Key Equality
4415 All of Guile's dedicated association list procedures, apart from
4416 @code{acons}, come in three flavours, depending on the level of equality
4417 that is required to decide whether an existing key in the association
4418 list is the same as the key that the procedure call uses to identify the
4423 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
4427 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
4431 Procedures with @dfn{assoc} in their name use @code{equal?} to
4432 determine key equality.
4435 @code{acons} is an exception because it is used to build association
4436 lists which do not require their entries' keys to be unique.
4438 @node Adding or Setting Alist Entries
4439 @subsubsection Adding or Setting Alist Entries
4441 @code{acons} adds a new entry to an association list and returns the
4442 combined association list. The combined alist is formed by consing the
4443 new entry onto the head of the alist specified in the @code{acons}
4444 procedure call. So the specified alist is not modified, but its
4445 contents become shared with the tail of the combined alist that
4446 @code{acons} returns.
4448 In the most common usage of @code{acons}, a variable holding the
4449 original association list is updated with the combined alist:
4452 (set! address-list (acons name address address-list))
4455 In such cases, it doesn't matter that the old and new values of
4456 @code{address-list} share some of their contents, since the old value is
4457 usually no longer independently accessible.
4459 Note that @code{acons} adds the specified new entry regardless of
4460 whether the alist may already contain entries with keys that are, in
4461 some sense, the same as that of the new entry. Thus @code{acons} is
4462 ideal for building alists where there is no concept of key uniqueness.
4465 (set! task-list (acons 3 "pay gas bill" '()))
4468 ((3 . "pay gas bill"))
4470 (set! task-list (acons 3 "tidy bedroom" task-list))
4473 ((3 . "tidy bedroom") (3 . "pay gas bill"))
4476 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
4477 or replace an entry in an association list where there @emph{is} a
4478 concept of key uniqueness. If the specified association list already
4479 contains an entry whose key is the same as that specified in the
4480 procedure call, the existing entry is replaced by the new one.
4481 Otherwise, the new entry is consed onto the head of the old association
4482 list to create the combined alist. In all cases, these procedures
4483 return the combined alist.
4485 @code{assq-set!} and friends @emph{may} destructively modify the
4486 structure of the old association list in such a way that an existing
4487 variable is correctly updated without having to @code{set!} it to the
4493 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
4495 (assoc-set! address-list "james" "1a London Road")
4497 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4501 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4507 (assoc-set! address-list "bob" "11 Newington Avenue")
4509 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4510 ("james" . "1a London Road"))
4514 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4517 The only safe way to update an association list variable when adding or
4518 replacing an entry like this is to @code{set!} the variable to the
4523 (assoc-set! address-list "bob" "11 Newington Avenue"))
4526 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4527 ("james" . "1a London Road"))
4530 Because of this slight inconvenience, you may find it more convenient to
4531 use hash tables to store dictionary data. If your application will not
4532 be modifying the contents of an alist very often, this may not make much
4535 If you need to keep the old value of an association list in a form
4536 independent from the list that results from modification by
4537 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
4538 use @code{list-copy} to copy the old association list before modifying
4541 @c docstring begin (texi-doc-string "guile" "acons")
4542 @deffn primitive acons key value alist
4543 Adds a new key-value pair to @var{alist}. A new pair is
4544 created whose car is @var{key} and whose cdr is @var{value}, and the
4545 pair is consed onto @var{alist}, and the new list is returned. This
4546 function is @emph{not} destructive; @var{alist} is not modified.
4549 @c docstring begin (texi-doc-string "guile" "assq-set!")
4550 @c docstring begin (texi-doc-string "guile" "assv-set!")
4551 @c docstring begin (texi-doc-string "guile" "assoc-set!")
4552 @deffn primitive assq-set! alist key val
4553 @deffnx primitive assv-set! alist key value
4554 @deffnx primitive assoc-set! alist key value
4555 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
4556 @var{alist} entry for @var{key} and associate it with the new
4557 @var{value}. If @var{alist} does not contain an entry for @var{key},
4558 add a new one. Return the (possibly new) alist.
4560 These functions do not attempt to verify the structure of @var{alist},
4561 and so may cause unusual results if passed an object that is not an
4565 @node Retrieving Alist Entries
4566 @subsubsection Retrieving Alist Entries
4571 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
4572 arguments and return the entry for that key if an entry exists, or
4573 @code{#f} if there is no entry for that key. Note that, in the cases
4574 where an entry exists, these procedures return the complete entry, that
4575 is @code{(KEY . VALUE)}, not just the value.
4577 @c docstring begin (texi-doc-string "guile" "assq")
4578 @c docstring begin (texi-doc-string "guile" "assv")
4579 @c docstring begin (texi-doc-string "guile" "assoc")
4580 @deffn primitive assq key alist
4581 @deffnx primitive assv key alist
4582 @deffnx primitive assoc key alist
4583 Fetches the entry in @var{alist} that is associated with @var{key}. To
4584 decide whether the argument @var{key} matches a particular entry in
4585 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
4586 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
4587 cannot be found in @var{alist} (according to whichever equality
4588 predicate is in use), then @code{#f} is returned. These functions
4589 return the entire alist entry found (i.e. both the key and the value).
4592 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
4593 hand, take an alist and a key and return @emph{just the value} for that
4594 key, if an entry exists. If there is no entry for the specified key,
4595 these procedures return @code{#f}.
4597 This creates an ambiguity: if the return value is @code{#f}, it means
4598 either that there is no entry with the specified key, or that there
4599 @emph{is} an entry for the specified key, with value @code{#f}.
4600 Consequently, @code{assq-ref} and friends should only be used where it
4601 is known that an entry exists, or where the ambiguity doesn't matter
4602 for some other reason.
4604 @c docstring begin (texi-doc-string "guile" "assq-ref")
4605 @c docstring begin (texi-doc-string "guile" "assv-ref")
4606 @c docstring begin (texi-doc-string "guile" "assoc-ref")
4607 @deffn primitive assq-ref alist key
4608 @deffnx primitive assv-ref alist key
4609 @deffnx primitive assoc-ref alist key
4610 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
4611 value associated with @var{key} in @var{alist} is returned. These
4612 functions are equivalent to
4615 (let ((ent (@var{associator} @var{key} @var{alist})))
4616 (and ent (cdr ent)))
4619 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
4622 @node Removing Alist Entries
4623 @subsubsection Removing Alist Entries
4625 To remove the element from an association list whose key matches a
4626 specified key, use @code{assq-remove!}, @code{assv-remove!} or
4627 @code{assoc-remove!} (depending, as usual, on the level of equality
4628 required between the key that you specify and the keys in the
4631 As with @code{assq-set!} and friends, the specified alist may or may not
4632 be modified destructively, and the only safe way to update a variable
4633 containing the alist is to @code{set!} it to the value that
4634 @code{assq-remove!} and friends return.
4639 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4640 ("james" . "1a London Road"))
4642 (set! address-list (assoc-remove! address-list "mary"))
4645 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
4648 Note that, when @code{assq/v/oc-remove!} is used to modify an
4649 association list that has been constructed only using the corresponding
4650 @code{assq/v/oc-set!}, there can be at most one matching entry in the
4651 alist, so the question of multiple entries being removed in one go does
4652 not arise. If @code{assq/v/oc-remove!} is applied to an association
4653 list that has been constructed using @code{acons}, or an
4654 @code{assq/v/oc-set!} with a different level of equality, or any mixture
4655 of these, it removes only the first matching entry from the alist, even
4656 if the alist might contain further matching entries. For example:
4659 (define address-list '())
4660 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
4661 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
4664 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
4666 (set! address-list (assoc-remove! address-list "mary"))
4669 (("mary" . "11 Elm Street"))
4672 In this example, the two instances of the string "mary" are not the same
4673 when compared using @code{eq?}, so the two @code{assq-set!} calls add
4674 two distinct entries to @code{address-list}. When compared using
4675 @code{equal?}, both "mary"s in @code{address-list} are the same as the
4676 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
4677 after removing the first matching entry that it finds, and so one of the
4678 "mary" entries is left in place.
4680 @c docstring begin (texi-doc-string "guile" "assq-remove!")
4681 @c docstring begin (texi-doc-string "guile" "assv-remove!")
4682 @c docstring begin (texi-doc-string "guile" "assoc-remove!")
4683 @deffn primitive assq-remove! alist key
4684 @deffnx primitive assv-remove! alist key
4685 @deffnx primitive assoc-remove! alist key
4686 Delete the first entry in @var{alist} associated with @var{key}, and return
4687 the resulting alist.
4690 @node Sloppy Alist Functions
4691 @subsubsection Sloppy Alist Functions
4693 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
4694 like the corresponding non-@code{sloppy-} procedures, except that they
4695 return @code{#f} when the specified association list is not well-formed,
4696 where the non-@code{sloppy-} versions would signal an error.
4698 Specifically, there are two conditions for which the non-@code{sloppy-}
4699 procedures signal an error, which the @code{sloppy-} procedures handle
4700 instead by returning @code{#f}. Firstly, if the specified alist as a
4701 whole is not a proper list:
4704 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4706 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
4707 ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
4708 ABORT: (wrong-type-arg)
4710 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4716 Secondly, if one of the entries in the specified alist is not a pair:
4719 (assoc 2 '((1 . 1) 2 (3 . 9)))
4721 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
4722 ERROR: Wrong type argument in position 2 (expecting CONSP): 2
4723 ABORT: (wrong-type-arg)
4725 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
4730 Unless you are explicitly working with badly formed association lists,
4731 it is much safer to use the non-@code{sloppy-} procedures, because they
4732 help to highlight coding and data errors that the @code{sloppy-}
4733 versions would silently cover up.
4735 @c docstring begin (texi-doc-string "guile" "sloppy-assq")
4736 @deffn primitive sloppy-assq key alist
4737 Behaves like @code{assq} but does not do any error checking.
4738 Recommended only for use in Guile internals.
4741 @c docstring begin (texi-doc-string "guile" "sloppy-assv")
4742 @deffn primitive sloppy-assv key alist
4743 Behaves like @code{assv} but does not do any error checking.
4744 Recommended only for use in Guile internals.
4747 @c docstring begin (texi-doc-string "guile" "sloppy-assoc")
4748 @deffn primitive sloppy-assoc key alist
4749 Behaves like @code{assoc} but does not do any error checking.
4750 Recommended only for use in Guile internals.
4754 @subsubsection Alist Example
4756 Here is a longer example of how alists may be used in practice.
4759 (define capitals '(("New York" . "Albany")
4760 ("Oregon" . "Salem")
4761 ("Florida" . "Miami")))
4763 ;; What's the capital of Oregon?
4764 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
4765 (assoc-ref capitals "Oregon") @result{} "Salem"
4767 ;; We left out South Dakota.
4769 (assoc-set! capitals "South Dakota" "Bismarck"))
4771 @result{} (("South Dakota" . "Bismarck")
4772 ("New York" . "Albany")
4773 ("Oregon" . "Salem")
4774 ("Florida" . "Miami"))
4776 ;; And we got Florida wrong.
4778 (assoc-set! capitals "Florida" "Tallahassee"))
4780 @result{} (("South Dakota" . "Bismarck")
4781 ("New York" . "Albany")
4782 ("Oregon" . "Salem")
4783 ("Florida" . "Tallahassee"))
4785 ;; After Oregon secedes, we can remove it.
4787 (assoc-remove! capitals "Oregon"))
4789 @result{} (("South Dakota" . "Bismarck")
4790 ("New York" . "Albany")
4791 ("Florida" . "Tallahassee"))
4795 @subsection Hash Tables
4797 Like the association list functions, the hash table functions come
4798 in several varieties: @code{hashq}, @code{hashv}, and @code{hash}.
4799 The @code{hashq} functions use @code{eq?} to determine whether two
4800 keys match. The @code{hashv} functions use @code{eqv?}, and the
4801 @code{hash} functions use @code{equal?}.
4803 In each of the functions that follow, the @var{table} argument
4804 must be a vector. The @var{key} and @var{value} arguments may be
4807 @c docstring begin (texi-doc-string "guile" "hashq-ref")
4808 @deffn primitive hashq-ref table key [dflt]
4809 Look up @var{key} in the hash table @var{table}, and return the
4810 value (if any) associated with it. If @var{key} is not found,
4811 return @var{default} (or @code{#f} if no @var{default} argument
4812 is supplied). Uses @code{eq?} for equality testing.
4815 @c docstring begin (texi-doc-string "guile" "hashv-ref")
4816 @deffn primitive hashv-ref table key [dflt]
4817 Look up @var{key} in the hash table @var{table}, and return the
4818 value (if any) associated with it. If @var{key} is not found,
4819 return @var{default} (or @code{#f} if no @var{default} argument
4820 is supplied). Uses @code{eqv?} for equality testing.
4823 @c docstring begin (texi-doc-string "guile" "hash-ref")
4824 @deffn primitive hash-ref table key [dflt]
4825 Look up @var{key} in the hash table @var{table}, and return the
4826 value (if any) associated with it. If @var{key} is not found,
4827 return @var{default} (or @code{#f} if no @var{default} argument
4828 is supplied). Uses @code{equal?} for equality testing.
4831 @c docstring begin (texi-doc-string "guile" "hashq-set!")
4832 @deffn primitive hashq-set! table key val
4833 Find the entry in @var{table} associated with @var{key}, and
4834 store @var{value} there. Uses @code{eq?} for equality testing.
4837 @c docstring begin (texi-doc-string "guile" "hashv-set!")
4838 @deffn primitive hashv-set! table key val
4839 Find the entry in @var{table} associated with @var{key}, and
4840 store @var{value} there. Uses @code{eqv?} for equality testing.
4843 @c docstring begin (texi-doc-string "guile" "hash-set!")
4844 @deffn primitive hash-set! table key val
4845 Find the entry in @var{table} associated with @var{key}, and
4846 store @var{value} there. Uses @code{equal?} for equality
4850 @c docstring begin (texi-doc-string "guile" "hashq-remove!")
4851 @deffn primitive hashq-remove! table key
4852 Remove @var{key} (and any value associated with it) from
4853 @var{table}. Uses @code{eq?} for equality tests.
4856 @c docstring begin (texi-doc-string "guile" "hashv-remove!")
4857 @deffn primitive hashv-remove! table key
4858 Remove @var{key} (and any value associated with it) from
4859 @var{table}. Uses @code{eqv?} for equality tests.
4862 @c docstring begin (texi-doc-string "guile" "hash-remove!")
4863 @deffn primitive hash-remove! table key
4864 Remove @var{key} (and any value associated with it) from
4865 @var{table}. Uses @code{equal?} for equality tests.
4868 The standard hash table functions may be too limited for some
4869 applications. For example, you may want a hash table to store
4870 strings in a case-insensitive manner, so that references to keys
4871 named ``foobar'', ``FOOBAR'' and ``FooBaR'' will all yield the
4872 same item. Guile provides you with @dfn{extended} hash tables
4873 that permit you to specify a hash function and associator function
4874 of your choosing. The functions described in the rest of this section
4875 can be used to implement such custom hash table structures.
4877 If you are unfamiliar with the inner workings of hash tables, then
4878 this facility will probably be a little too abstract for you to
4879 use comfortably. If you are interested in learning more, see an
4880 introductory textbook on data structures or algorithms for an
4881 explanation of how hash tables are implemented.
4883 @c docstring begin (texi-doc-string "guile" "hashq")
4884 @deffn primitive hashq key size
4885 Determine a hash value for @var{key} that is suitable for
4886 lookups in a hashtable of size @var{size}, where @code{eq?} is
4887 used as the equality predicate. The function returns an
4888 integer in the range 0 to @var{size} - 1. Note that
4889 @code{hashq} may use internal addresses. Thus two calls to
4890 hashq where the keys are @code{eq?} are not guaranteed to
4891 deliver the same value if the key object gets garbage collected
4892 in between. This can happen, for example with symbols:
4893 @code{(hashq 'foo n) (gc) (hashq 'foo n)} may produce two
4894 different values, since @code{foo} will be garbage collected.
4897 @c docstring begin (texi-doc-string "guile" "hashv")
4898 @deffn primitive hashv key size
4899 Determine a hash value for @var{key} that is suitable for
4900 lookups in a hashtable of size @var{size}, where @code{eqv?} is
4901 used as the equality predicate. The function returns an
4902 integer in the range 0 to @var{size} - 1. Note that
4903 @code{(hashv key)} may use internal addresses. Thus two calls
4904 to hashv where the keys are @code{eqv?} are not guaranteed to
4905 deliver the same value if the key object gets garbage collected
4906 in between. This can happen, for example with symbols:
4907 @code{(hashv 'foo n) (gc) (hashv 'foo n)} may produce two
4908 different values, since @code{foo} will be garbage collected.
4911 @c docstring begin (texi-doc-string "guile" "hash")
4912 @deffn primitive hash key size
4913 Determine a hash value for @var{key} that is suitable for
4914 lookups in a hashtable of size @var{size}, where @code{equal?}
4915 is used as the equality predicate. The function returns an
4916 integer in the range 0 to @var{size} - 1.
4919 @c docstring begin (texi-doc-string "guile" "hashx-ref")
4920 @deffn primitive hashx-ref hash assoc table key [dflt]
4921 This behaves the same way as the corresponding @code{ref}
4922 function, but uses @var{hash} as a hash function and
4923 @var{assoc} to compare keys. @code{hash} must be a function
4924 that takes two arguments, a key to be hashed and a table size.
4925 @code{assoc} must be an associator function, like @code{assoc},
4926 @code{assq} or @code{assv}.
4927 By way of illustration, @code{hashq-ref table key} is
4928 equivalent to @code{hashx-ref hashq assq table key}.
4931 @c docstring begin (texi-doc-string "guile" "hashx-set!")
4932 @deffn primitive hashx-set! hash assoc table key val
4933 This behaves the same way as the corresponding @code{set!}
4934 function, but uses @var{hash} as a hash function and
4935 @var{assoc} to compare keys. @code{hash} must be a function
4936 that takes two arguments, a key to be hashed and a table size.
4937 @code{assoc} must be an associator function, like @code{assoc},
4938 @code{assq} or @code{assv}.
4939 By way of illustration, @code{hashq-set! table key} is
4940 equivalent to @code{hashx-set! hashq assq table key}.
4943 @c docstring begin (texi-doc-string "guile" "hashq-get-handle")
4944 @deffn primitive hashq-get-handle table key
4945 This procedure returns the @code{(key . value)} pair from the
4946 hash table @var{table}. If @var{table} does not hold an
4947 associated value for @var{key}, @code{#f} is returned.
4948 Uses @code{eq?} for equality testing.
4951 @c docstring begin (texi-doc-string "guile" "hashv-get-handle")
4952 @deffn primitive hashv-get-handle table key
4953 This procedure returns the @code{(key . value)} pair from the
4954 hash table @var{table}. If @var{table} does not hold an
4955 associated value for @var{key}, @code{#f} is returned.
4956 Uses @code{eqv?} for equality testing.
4959 @c docstring begin (texi-doc-string "guile" "hash-get-handle")
4960 @deffn primitive hash-get-handle table key
4961 This procedure returns the @code{(key . value)} pair from the
4962 hash table @var{table}. If @var{table} does not hold an
4963 associated value for @var{key}, @code{#f} is returned.
4964 Uses @code{equal?} for equality testing.
4967 @c docstring begin (texi-doc-string "guile" "hashx-get-handle")
4968 @deffn primitive hashx-get-handle hash assoc table key
4969 This behaves the same way as the corresponding
4970 @code{-get-handle} function, but uses @var{hash} as a hash
4971 function and @var{assoc} to compare keys. @code{hash} must be
4972 a function that takes two arguments, a key to be hashed and a
4973 table size. @code{assoc} must be an associator function, like
4974 @code{assoc}, @code{assq} or @code{assv}.
4977 @c docstring begin (texi-doc-string "guile" "hashq-create-handle!")
4978 @deffn primitive hashq-create-handle! table key init
4979 This function looks up @var{key} in @var{table} and returns its handle.
4980 If @var{key} is not already present, a new handle is created which
4981 associates @var{key} with @var{init}.
4984 @c docstring begin (texi-doc-string "guile" "hashv-create-handle!")
4985 @deffn primitive hashv-create-handle! table key init
4986 This function looks up @var{key} in @var{table} and returns its handle.
4987 If @var{key} is not already present, a new handle is created which
4988 associates @var{key} with @var{init}.
4991 @c docstring begin (texi-doc-string "guile" "hash-create-handle!")
4992 @deffn primitive hash-create-handle! table key init
4993 This function looks up @var{key} in @var{table} and returns its handle.
4994 If @var{key} is not already present, a new handle is created which
4995 associates @var{key} with @var{init}.
4998 @c docstring begin (texi-doc-string "guile" "hashx-create-handle!")
4999 @deffn primitive hashx-create-handle! hash assoc table key init
5000 This behaves the same way as the corresponding
5001 @code{-create-handle} function, but uses @var{hash} as a hash
5002 function and @var{assoc} to compare keys. @code{hash} must be
5003 a function that takes two arguments, a key to be hashed and a
5004 table size. @code{assoc} must be an associator function, like
5005 @code{assoc}, @code{assq} or @code{assv}.
5008 @c docstring begin (texi-doc-string "guile" "hash-fold")
5009 @deffn primitive hash-fold proc init table
5010 An iterator over hash-table elements.
5011 Accumulates and returns a result by applying PROC successively.
5012 The arguments to PROC are "(key value prior-result)" where key
5013 and value are successive pairs from the hash table TABLE, and
5014 prior-result is either INIT (for the first application of PROC)
5015 or the return value of the previous application of PROC.
5016 For example, @code{(hash-fold acons () tab)} will convert a hash
5017 table into an a-list of key-value pairs.
5024 @c FIXME::martin: Review me!
5026 @c FIXME::martin: This node should come before the non-standard data types.
5028 @c FIXME::martin: Should the subsections of this section be nodes
5029 @c of their own, or are the resulting nodes too short, then?
5031 Vectors are sequences of Scheme objects. Unlike lists, the length of a
5032 vector, once the vector is created, cannot be changed. The advantage of
5033 vectors over lists is that the time required to access one element of a
5034 vector is constant, whereas lists have an access time linear to the
5035 index of the accessed element in the list.
5037 Note that the vectors documented in this section can contain any kind of
5038 Scheme object, it is even possible to have different types of objects in
5041 @subsection Vector Read Syntax
5043 Vectors can literally be entered in source code, just like strings,
5044 characters or some of the other data types. The read syntax for vectors
5045 is as follows: A sharp sign (@code{#}), followed by an opening
5046 parentheses, all elements of the vector in their respective read syntax,
5047 and finally a closing parentheses. The following are examples of the
5048 read syntax for vectors; where the first vector only contains numbers
5049 and the second three different object types: a string, a symbol and a
5050 number in hexidecimal notation.
5054 #("Hello" foo #xdeadbeef)
5057 @subsection Vector Predicates
5060 @c docstring begin (texi-doc-string "guile" "vector?")
5061 @deffn primitive vector? obj
5062 Return @code{#t} if @var{obj} is a vector, otherwise return
5066 @subsection Vector Constructors
5068 @rnindex make-vector
5069 @c docstring begin (texi-doc-string "guile" "make-vector")
5070 @deffn primitive make-vector k [fill]
5071 Return a newly allocated vector of @var{k} elements. If a
5072 second argument is given, then each element is initialized to
5073 @var{fill}. Otherwise the initial contents of each element is
5078 @rnindex list->vector
5079 @c docstring begin (texi-doc-string "guile" "vector")
5080 @c docstring begin (texi-doc-string "guile" "list->vector")
5081 @deffn primitive vector . l
5082 @deffnx primitive list->vector l
5083 Return a newly allocated vector whose elements contain the
5084 given arguments. Analogous to @code{list}.
5086 (vector 'a 'b 'c) @result{} #(a b c)
5090 @rnindex vector->list
5091 @c docstring begin (texi-doc-string "guile" "vector->list")
5092 @deffn primitive vector->list v
5093 Return a newly allocated list of the objects contained in the
5094 elements of @var{vector}.
5096 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
5097 (list->vector '(dididit dah)) @result{} #(dididit dah)
5101 @subsection Vector Modification
5103 A vector created by any of the vector constructor procedures (REFFIXME)
5104 documented above can be modified using the following procedures.
5106 According to R5RS, using any of these procedures on literally entered
5107 vectors is an error, because these vectors are considered to be
5108 constant, although Guile currently does not detect this error.
5110 @rnindex vector-set!
5111 @deffn primitive vector-set! vector k obj
5112 @var{k} must be a valid index of @var{vector}.
5113 @code{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
5114 The value returned by @samp{vector-set!} is unspecified.
5116 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
5117 (vector-set! vec 1 '("Sue" "Sue"))
5118 vec) @result{} #(0 ("Sue" "Sue") "Anna")
5119 (vector-set! '#(0 1 2) 1 "doe") @result{} @emph{error} ; constant vector
5123 @rnindex vector-fill!
5124 @c docstring begin (texi-doc-string "guile" "vector-fill!")
5125 @deffn primitive vector-fill! v fill
5126 Store @var{fill} in every element of @var{vector}. The value
5127 returned by @code{vector-fill!} is unspecified.
5130 @c docstring begin (texi-doc-string "guile" "vector-move-left!")
5131 @deffn primitive vector-move-left! vec1 start1 end1 vec2 start2
5132 Vector version of @code{substring-move-left!}.
5135 @c docstring begin (texi-doc-string "guile" "vector-move-right!")
5136 @deffn primitive vector-move-right! vec1 start1 end1 vec2 start2
5137 Vector version of @code{substring-move-right!}.
5140 @subsection Vector Selection
5142 These procedures return information about a given vector, such as the
5143 size or what elements are contained in the vector.
5145 @rnindex vector-length
5146 @deffn primitive vector-length vector
5147 Returns the number of elements in @var{vector} as an exact integer.
5151 @deffn primitive vector-ref vector k
5152 @var{k} must be a valid index of @var{vector}.
5153 @samp{Vector-ref} returns the contents of element @var{k} of
5156 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
5157 (vector-ref '#(1 1 2 3 5 8 13 21)
5158 (let ((i (round (* 2 (acos -1)))))
5168 @c FIXME::martin: Review me!
5170 A hook is basically a list of procedures to be called at well defined
5171 points in time. Hooks are used internally for several debugging
5172 facilities, but they can be used in user code, too.
5174 Hooks are created with @code{make-hook}, then procedures can be added to
5175 a hook with @code{add-hook!} or removed with @code{remove-hook!} or
5176 @code{reset-hook!}. The procedures stored in a hook can be invoked with
5180 * Hook Examples:: Hook usage by example.
5181 * Hook Reference:: Reference of all hook procedures.
5185 @subsection Hook Examples
5187 Hook usage is shown by some examples in this section. First, we will
5188 define a hook of arity 2---that is, the procedures stored in the hook
5189 will have to accept two arguments.
5192 (define hook (make-hook 2))
5194 @result{} #<hook 2 40286c90>
5197 Now we are ready to add some procedures to the newly created hook with
5198 @code{add-hook!}. In the following example, two procedures are added,
5199 which print different messages and do different things with their
5200 arguments. When the procedures have been added, we can invoke them
5201 using @code{run-hook}.
5204 (add-hook! hook (lambda (x y)
5208 (add-hook! hook (lambda (x y)
5217 Note that the procedures are called in reverse order than they were
5218 added. This can be changed by providing the optional third argument
5219 on the second call to @code{add-hook!}.
5222 (add-hook! hook (lambda (x y)
5226 (add-hook! hook (lambda (x y)
5230 #t) ; <- Change here!
5236 @node Hook Reference
5237 @subsection Hook Reference
5239 When a hook is created with @code{make-hook}, you can supply the arity
5240 of the procedures which can be added to the hook. The arity defaults to
5241 zero. All procedures of a hook must have the same arity, and when the
5242 procedures are invoked using @code{run-hook}, the number of arguments
5243 must match the arity of the procedures.
5245 The order in which procedures are added to a hook matters. If the third
5246 parameter to @var{add-hook!} is omitted or is equal to @code{#f}, the
5247 procedure is added in front of the procedures which might already be on
5248 that hook, otherwise the procedure is added at the end. The procedures
5249 are always called from first to last when they are invoked via
5252 When calling @code{hook->list}, the procedures in the resulting list are
5253 in the same order as they would have been called by @code{run-hook}.
5255 @c docstring begin (texi-doc-string "guile" "make-hook-with-name")
5256 @deffn primitive make-hook-with-name name [n_args]
5257 Create a named hook with the name @var{name} for storing
5258 procedures of arity @var{n_args}. @var{n_args} defaults to
5262 @c docstring begin (texi-doc-string "guile" "make-hook")
5263 @deffn primitive make-hook [n_args]
5264 Create a hook for storing procedure of arity
5265 @var{n_args}. @var{n_args} defaults to zero.
5268 @c docstring begin (texi-doc-string "guile" "hook?")
5269 @deffn primitive hook? x
5270 Return @code{#t} if @var{x} is a hook, @code{#f} otherwise.
5273 @c docstring begin (texi-doc-string "guile" "hook-empty?")
5274 @deffn primitive hook-empty? hook
5275 Return @code{#t} if @var{hook} is an empty hook, @code{#f}
5279 @c docstring begin (texi-doc-string "guile" "add-hook!")
5280 @deffn primitive add-hook! hook proc [append_p]
5281 Add the procedure @var{proc} to the hook @var{hook}. The
5282 procedure is added to the end if @var{append_p} is true,
5283 otherwise it is added to the front.
5286 @c docstring begin (texi-doc-string "guile" "remove-hook!")
5287 @deffn primitive remove-hook! hook proc
5288 Remove the procedure @var{proc} from the hook @var{hook}.
5291 @c docstring begin (texi-doc-string "guile" "reset-hook!")
5292 @deffn primitive reset-hook! hook
5293 Remove all procedures from the hook @var{hook}.
5296 @c docstring begin (texi-doc-string "guile" "run-hook")
5297 @deffn primitive run-hook hook . args
5298 Apply all procedures from the hook @var{hook} to the arguments
5299 @var{args}. The order of the procedure application is first to
5303 @c docstring begin (texi-doc-string "guile" "hook->list")
5304 @deffn primitive hook->list hook
5305 Convert the procedure list of @var{hook} to a list.
5309 @node Other Data Types
5310 @section Other Core Guile Data Types
5314 @c TeX-master: "guile.texi"