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.
69 The two boolean values are @code{#t} for true and @code{#f} for false.
71 Boolean values are returned by predicate procedures, such as the general
72 equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
73 (@pxref{Equality}) and numerical and string comparison operators like
74 @code{string=?} (REFFIXME) and @code{<=} (REFFIXME).
85 (equal? "house" "houses")
94 In test condition contexts like @code{if} (REFFIXME) and @code{cond}
95 (REFFIXME), where a group of subexpressions will be evaluated only if a
96 @var{condition} expression evaluates to ``true'', ``true'' means any
97 value at all except @code{#f}.
113 A result of this asymmetry is that typical Scheme source code more often
114 uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
115 represent an @code{if} or @code{cond} false value, whereas @code{#t} is
116 not necessary to represent an @code{if} or @code{cond} true value.
118 It is important to note that @code{#f} is @strong{not} equivalent to any
119 other Scheme value. In particular, @code{#f} is not the same as the
120 number 0 (like in C and C++), and not the same as the ``empty list''
121 (like in some Lisp dialects).
123 The @code{not} procedure returns the boolean inverse of its argument:
125 @c docstring begin (texi-doc-string "guile" "not")
126 @deffn primitive not x
127 Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
130 The @code{boolean?} procedure is a predicate that returns @code{#t} if
131 its argument is one of the boolean values, otherwise @code{#f}.
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 @r5index exact->inexact
398 @r5index 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 Returns 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 @r5index number->string
613 @r5index 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 Returns 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 @r5index 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 Returns the integer which is the bit-wise AND of the two integer
968 (number->string (logand #b1100 #b1010) 2)
973 @c docstring begin (texi-doc-string "guile" "logior")
974 @deffn primitive logior n1 n2
975 Returns the integer which is the bit-wise OR of the two integer
980 (number->string (logior #b1100 #b1010) 2)
985 @c docstring begin (texi-doc-string "guile" "logxor")
986 @deffn primitive logxor n1 n2
987 Returns the integer which is the bit-wise XOR of the two integer
992 (number->string (logxor #b1100 #b1010) 2)
997 @c docstring begin (texi-doc-string "guile" "lognot")
998 @deffn primitive lognot n
999 Returns the integer which is the 2s-complement of the integer argument.
1003 (number->string (lognot #b10000000) 2)
1004 @result{} "-10000001"
1005 (number->string (lognot #b0) 2)
1010 @c ARGFIXME j/n1 k/n2
1011 @c docstring begin (texi-doc-string "guile" "logtest")
1012 @deffn primitive logtest n1 n2
1014 (logtest j k) @equiv{} (not (zero? (logand j k)))
1016 (logtest #b0100 #b1011) @result{} #f
1017 (logtest #b0100 #b0111) @result{} #t
1021 @c docstring begin (texi-doc-string "guile" "logbit?")
1022 @deffn primitive logbit? index j
1024 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1026 (logbit? 0 #b1101) @result{} #t
1027 (logbit? 1 #b1101) @result{} #f
1028 (logbit? 2 #b1101) @result{} #t
1029 (logbit? 3 #b1101) @result{} #t
1030 (logbit? 4 #b1101) @result{} #f
1034 @c ARGFIXME n/int cnt/count
1035 @c docstring begin (texi-doc-string "guile" "ash")
1036 @deffn primitive ash n cnt
1037 The function ash performs an arithmetic shift left by @var{CNT}
1038 bits (or shift right, if @var{cnt} is negative).
1039 'Arithmetic' means, that the function does not guarantee to
1040 keep the bit structure of @var{n}, but rather guarantees that
1041 the result will always be rounded towards minus infinity.
1042 Therefore, the results of ash and a corresponding bitwise
1043 shift will differ if N is negative.
1045 Formally, the function returns an integer equivalent to
1046 @code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
1050 (number->string (ash #b1 3) 2)
1052 (number->string (ash #b1010 -1) 2)
1057 @c docstring begin (texi-doc-string "guile" "logcount")
1058 @deffn primitive logcount n
1059 Returns the number of bits in integer @var{n}. If integer is positive,
1060 the 1-bits in its binary representation are counted. If negative, the
1061 0-bits in its two's-complement binary representation are counted. If 0,
1066 (logcount #b10101010)
1075 @c docstring begin (texi-doc-string "guile" "integer-length")
1076 @deffn primitive integer-length n
1077 Returns the number of bits neccessary to represent @var{n}.
1081 (integer-length #b10101010)
1085 (integer-length #b1111)
1090 @c docstring begin (texi-doc-string "guile" "integer-expt")
1091 @deffn primitive integer-expt n k
1092 Returns @var{n} raised to the non-negative integer exponent @var{k}.
1103 @c docstring begin (texi-doc-string "guile" "bit-extract")
1104 @deffn primitive bit-extract n start end
1105 Returns the integer composed of the @var{start} (inclusive) through
1106 @var{end} (exclusive) bits of @var{n}. The @var{start}th bit becomes
1107 the 0-th bit in the result.@refill
1111 (number->string (bit-extract #b1101101010 0 4) 2)
1113 (number->string (bit-extract #b1101101010 4 9) 2)
1120 @subsection Random Number Generation
1122 @c docstring begin (texi-doc-string "guile" "copy-random-state")
1123 @deffn primitive copy-random-state [state]
1124 Return a copy of the random state @var{state}.
1127 @c docstring begin (texi-doc-string "guile" "random")
1128 @deffn primitive random n [state]
1129 Return a number in [0,N).
1130 Accepts a positive integer or real n and returns a
1131 number of the same type between zero (inclusive) and
1132 N (exclusive). The values returned have a uniform
1134 The optional argument @var{state} must be of the type produced
1135 by @code{seed->random-state}. It defaults to the value of the
1136 variable @var{*random-state*}. This object is used to maintain
1137 the state of the pseudo-random-number generator and is altered
1138 as a side effect of the random operation.
1141 @c docstring begin (texi-doc-string "guile" "random:exp")
1142 @deffn primitive random:exp [state]
1143 Returns an inexact real in an exponential distribution with mean 1.
1144 For an exponential distribution with mean u use (* u (random:exp)).
1147 @c docstring begin (texi-doc-string "guile" "random:hollow-sphere!")
1148 @deffn primitive random:hollow-sphere! v [state]
1149 Fills vect with inexact real random numbers
1150 the sum of whose squares is equal to 1.0.
1151 Thinking of vect as coordinates in space of
1152 dimension n = (vector-length vect), the coordinates
1153 are uniformly distributed over the surface of the
1157 @c docstring begin (texi-doc-string "guile" "random:normal")
1158 @deffn primitive random:normal [state]
1159 Returns an inexact real in a normal distribution.
1160 The distribution used has mean 0 and standard deviation 1.
1161 For a normal distribution with mean m and standard deviation
1162 d use @code{(+ m (* d (random:normal)))}.
1165 @c docstring begin (texi-doc-string "guile" "random:normal-vector!")
1166 @deffn primitive random:normal-vector! v [state]
1167 Fills vect with inexact real random numbers that are
1168 independent and standard normally distributed
1169 (i.e., with mean 0 and variance 1).
1172 @c docstring begin (texi-doc-string "guile" "random:solid-sphere!")
1173 @deffn primitive random:solid-sphere! v [state]
1174 Fills vect with inexact real random numbers
1175 the sum of whose squares is less than 1.0.
1176 Thinking of vect as coordinates in space of
1177 dimension n = (vector-length vect), the coordinates
1178 are uniformly distributed within the unit n-shere.
1179 The sum of the squares of the numbers is returned.
1182 @c docstring begin (texi-doc-string "guile" "random:uniform")
1183 @deffn primitive random:uniform [state]
1184 Returns a uniformly distributed inexact real random number in [0,1).
1187 @c docstring begin (texi-doc-string "guile" "seed->random-state")
1188 @deffn primitive seed->random-state seed
1189 Return a new random state using @var{seed}.
1201 @r5index char-alphabetic?
1202 @r5index char-numeric?
1203 @r5index char-whitespace?
1204 @r5index char-upper-case?
1205 @r5index char-lower-case?
1206 @r5index char->integer
1207 @r5index integer->char
1208 @r5index char-upcase
1209 @r5index char-downcase
1212 Most of the characters in the ASCII character set may be referred to by
1213 name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and so on.
1214 The following table describes the ASCII names for each character.
1216 @multitable @columnfractions .25 .25 .25 .25
1217 @item 0 = @code{#\nul}
1218 @tab 1 = @code{#\soh}
1219 @tab 2 = @code{#\stx}
1220 @tab 3 = @code{#\etx}
1221 @item 4 = @code{#\eot}
1222 @tab 5 = @code{#\enq}
1223 @tab 6 = @code{#\ack}
1224 @tab 7 = @code{#\bel}
1225 @item 8 = @code{#\bs}
1226 @tab 9 = @code{#\ht}
1227 @tab 10 = @code{#\nl}
1228 @tab 11 = @code{#\vt}
1229 @item 12 = @code{#\np}
1230 @tab 13 = @code{#\cr}
1231 @tab 14 = @code{#\so}
1232 @tab 15 = @code{#\si}
1233 @item 16 = @code{#\dle}
1234 @tab 17 = @code{#\dc1}
1235 @tab 18 = @code{#\dc2}
1236 @tab 19 = @code{#\dc3}
1237 @item 20 = @code{#\dc4}
1238 @tab 21 = @code{#\nak}
1239 @tab 22 = @code{#\syn}
1240 @tab 23 = @code{#\etb}
1241 @item 24 = @code{#\can}
1242 @tab 25 = @code{#\em}
1243 @tab 26 = @code{#\sub}
1244 @tab 27 = @code{#\esc}
1245 @item 28 = @code{#\fs}
1246 @tab 29 = @code{#\gs}
1247 @tab 30 = @code{#\rs}
1248 @tab 31 = @code{#\us}
1249 @item 32 = @code{#\sp}
1252 The @code{delete} character (octal 177) may be referred to with the name
1255 Several characters have more than one name:
1274 @c docstring begin (texi-doc-string "guile" "char?")
1275 @deffn primitive char? x
1276 Return @code{#t} iff @var{x} is a character, else @code{#f}.
1279 @c docstring begin (texi-doc-string "guile" "char=?")
1280 @deffn primitive char=? x y
1281 Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1284 @c docstring begin (texi-doc-string "guile" "char<?")
1285 @deffn primitive char<? x y
1286 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence,
1290 @c docstring begin (texi-doc-string "guile" "char<=?")
1291 @deffn primitive char<=? x y
1292 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1293 ASCII sequence, else @code{#f}.
1296 @c docstring begin (texi-doc-string "guile" "char>?")
1297 @deffn primitive char>? x y
1298 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1299 sequence, else @code{#f}.
1302 @c docstring begin (texi-doc-string "guile" "char>=?")
1303 @deffn primitive char>=? x y
1304 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1305 ASCII sequence, else @code{#f}.
1308 @c docstring begin (texi-doc-string "guile" "char-ci=?")
1309 @deffn primitive char-ci=? x y
1310 Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1311 case, else @code{#f}.
1314 @c docstring begin (texi-doc-string "guile" "char-ci<?")
1315 @deffn primitive char-ci<? x y
1316 Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence
1317 ignoring case, else @code{#f}.
1320 @c docstring begin (texi-doc-string "guile" "char-ci<=?")
1321 @deffn primitive char-ci<=? x y
1322 Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1323 ASCII sequence ignoring case, else @code{#f}.
1326 @c docstring begin (texi-doc-string "guile" "char-ci>?")
1327 @deffn primitive char-ci>? x y
1328 Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1329 sequence ignoring case, else @code{#f}.
1332 @c docstring begin (texi-doc-string "guile" "char-ci>=?")
1333 @deffn primitive char-ci>=? x y
1334 Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1335 ASCII sequence ignoring case, else @code{#f}.
1338 @c docstring begin (texi-doc-string "guile" "char-alphabetic?")
1339 @deffn primitive char-alphabetic? chr
1340 Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1341 Alphabetic means the same thing as the isalpha C library function.
1344 @c docstring begin (texi-doc-string "guile" "char-numeric?")
1345 @deffn primitive char-numeric? chr
1346 Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1347 Numeric means the same thing as the isdigit C library function.
1350 @c docstring begin (texi-doc-string "guile" "char-whitespace?")
1351 @deffn primitive char-whitespace? chr
1352 Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1353 Whitespace means the same thing as the isspace C library function.
1356 @c docstring begin (texi-doc-string "guile" "char-upper-case?")
1357 @deffn primitive char-upper-case? chr
1358 Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1359 Uppercase means the same thing as the isupper C library function.
1362 @c docstring begin (texi-doc-string "guile" "char-lower-case?")
1363 @deffn primitive char-lower-case? chr
1364 Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1365 Lowercase means the same thing as the islower C library function.
1368 @c docstring begin (texi-doc-string "guile" "char-is-both?")
1369 @deffn primitive char-is-both? chr
1370 Return @code{#t} iff @var{chr} is either uppercase or lowercase, else @code{#f}.
1371 Uppercase and lowercase are as defined by the isupper and islower
1372 C library functions.
1375 @c docstring begin (texi-doc-string "guile" "char->integer")
1376 @deffn primitive char->integer chr
1377 Return the number corresponding to ordinal position of @var{chr} in the
1381 @c docstring begin (texi-doc-string "guile" "integer->char")
1382 @deffn primitive integer->char n
1383 Return the character at position @var{n} in the ASCII sequence.
1386 @c docstring begin (texi-doc-string "guile" "char-upcase")
1387 @deffn primitive char-upcase chr
1388 Return the uppercase character version of @var{chr}.
1391 @c docstring begin (texi-doc-string "guile" "char-downcase")
1392 @deffn primitive char-downcase chr
1393 Return the lowercase character version of @var{chr}.
1400 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
1403 For the sake of efficiency, two special kinds of strings are available
1404 in Guile: shared substrings and the misleadingly named ``read-only''
1405 strings. It is not necessary to know about these to program in Guile,
1406 but you are likely to run into one or both of these special string types
1407 eventually, and it will be helpful to know how they work.
1410 * String Fun:: New functions for manipulating strings.
1411 * Shared Substrings:: Strings which share memory with each other.
1412 * Read Only Strings:: Treating certain non-strings as strings.
1416 @subsection String Fun
1419 @r5index list->string
1420 @c docstring begin (texi-doc-string "guile" "string")
1421 @c docstring begin (texi-doc-string "guile" "list->string")
1422 @deffn primitive string . chrs
1423 @deffnx primitive list->string chrs
1424 Returns a newly allocated string composed of the arguments,
1428 @r5index make-string
1429 @c docstring begin (texi-doc-string "guile" "make-string")
1430 @deffn primitive make-string k [chr]
1431 Return a newly allocated string of
1432 length @var{k}. If @var{chr} is given, then all elements of
1433 the string are initialized to @var{chr}, otherwise the contents
1434 of the @var{string} are unspecified.
1437 @r5index string-append
1438 @c docstring begin (texi-doc-string "guile" "string-append")
1439 @deffn primitive string-append . args
1440 Return a newly allocated string whose characters form the
1441 concatenation of the given strings, @var{args}.
1444 @r5index string-length
1445 @c docstring begin (texi-doc-string "guile" "string-length")
1446 @deffn primitive string-length string
1447 Return the number of characters in @var{string}.
1451 @c docstring begin (texi-doc-string "guile" "string-ref")
1452 @deffn primitive string-ref str k
1453 Return character @var{k} of @var{str} using zero-origin
1454 indexing. @var{k} must be a valid index of @var{str}.
1457 @r5index string-set!
1458 @c docstring begin (texi-doc-string "guile" "string-set!")
1459 @deffn primitive string-set! str k chr
1460 Store @var{chr} in element @var{k} of @var{str} and return
1461 an unspecified value. @var{k} must be a valid index of
1466 @c docstring begin (texi-doc-string "guile" "string?")
1467 @deffn primitive string? obj
1468 Returns @code{#t} iff @var{obj} is a string, else returns
1473 @c docstring begin (texi-doc-string "guile" "substring")
1474 @deffn primitive substring str start [end]
1475 Return a newly allocated string formed from the characters
1476 of @var{str} beginning with index @var{start} (inclusive) and
1477 ending with index @var{end} (exclusive).
1478 @var{str} must be a string, @var{start} and @var{end} must be
1479 exact integers satisfying:
1481 0 <= @var{start} <= @var{end} <= (string-length @var{str}).
1484 @c docstring begin (texi-doc-string "guile" "string-index")
1485 @deffn primitive string-index str chr [frm [to]]
1486 Return the index of the first occurrence of @var{chr} in @var{str}. The
1487 optional integer arguments @var{frm} and @var{to} limit the search to
1488 a portion of the string. This procedure essentially implements the
1489 @code{index} or @code{strchr} functions from the C library.
1491 (qdocs:) Returns the index of @var{char} in @var{str}, or @code{#f} if the
1492 @var{char} isn't in @var{str}. If @var{frm} is given and not @code{#f},
1493 it is used as the starting index; if @var{to} is given and not @code{#f},
1494 it is used as the ending index (exclusive).
1497 (string-index "weiner" #\e)
1500 (string-index "weiner" #\e 2)
1503 (string-index "weiner" #\e 2 4)
1508 @c docstring begin (texi-doc-string "guile" "string-rindex")
1509 @deffn primitive string-rindex str chr [frm [to]]
1510 Like @code{string-index}, but search from the right of the string rather
1511 than from the left. This procedure essentially implements the
1512 @code{rindex} or @code{strrchr} functions from the C library.
1514 (qdocs:) The same as @code{string-index}, except it gives the rightmost occurance
1515 of @var{char} in the range [@var{frm}, @var{to}-1], which defaults to
1519 (string-rindex "weiner" #\e)
1522 (string-rindex "weiner" #\e 2 4)
1525 (string-rindex "weiner" #\e 2 5)
1530 @c docstring begin (texi-doc-string "guile" "substring-move!")
1531 @c docstring begin (texi-doc-string "guile" "substring-move-left!")
1532 @c docstring begin (texi-doc-string "guile" "substring-move-right!")
1533 @deffn primitive substring-move! str1 start1 end1 str2 start2
1534 @deffnx primitive substring-move-left! str1 start1 end1 str2 start2
1535 @deffnx primitive substring-move-right! str1 start1 end1 str2 start2
1536 Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1537 into @var{str2} beginning at position @var{end2}.
1538 @code{substring-move-right!} begins copying from the rightmost character
1539 and moves left, and @code{substring-move-left!} copies from the leftmost
1540 character moving right.
1542 It is useful to have two functions that copy in different directions so
1543 that substrings can be copied back and forth within a single string. If
1544 you wish to copy text from the left-hand side of a string to the
1545 right-hand side of the same string, and the source and destination
1546 overlap, you must be careful to copy the rightmost characters of the
1547 text first, to avoid clobbering your data. Hence, when @var{str1} and
1548 @var{str2} are the same string, you should use
1549 @code{substring-move-right!} when moving text from left to right, and
1550 @code{substring-move-left!} otherwise. If @code{str1} and @samp{str2}
1551 are different strings, it does not matter which function you use.
1554 @deffn primitive substring-move-left! str1 start1 end1 str2 start2
1556 @deftypefn {C Function} SCM scm_substring_move_left_x (SCM @var{str1}, SCM @var{start1}, SCM @var{end1}, SCM @var{str2}, SCM @var{start2})
1557 [@strong{Note:} this is only valid if you've applied the strop patch].
1559 Moves a substring of @var{str1}, from @var{start1} to @var{end1}
1560 (@var{end1} is exclusive), into @var{str2}, starting at
1561 @var{start2}. Allows overlapping strings.
1564 (define x (make-string 10 #\a))
1566 (substring-move-left! x 2 5 y 0)
1571 @result{} "aaaaaaaaaa"
1574 (substring-move-left! x 2 5 y 0)
1578 (define y "abcdefg")
1579 (substring-move-left! y 2 5 y 3)
1585 @deffn substring-move-right! str1 start1 end1 str2 start2
1587 @deftypefn {C Function} SCM scm_substring_move_right_x (SCM @var{str1}, SCM @var{start1}, SCM @var{end1}, SCM @var{str2}, SCM @var{start2})
1588 [@strong{Note:} this is only valid if you've applied the strop patch, if
1589 it hasn't made it into the guile tree].
1591 Does much the same thing as @code{substring-move-left!}, except it
1592 starts moving at the end of the sequence, rather than the beginning.
1594 (define y "abcdefg")
1595 (substring-move-right! y 2 5 y 0)
1599 (define y "abcdefg")
1600 (substring-move-right! y 2 5 y 3)
1606 @c docstring begin (texi-doc-string "guile" "vector-move-left!")
1607 @deffn primitive vector-move-left! vec1 start1 end1 vec2 start2
1608 Vector version of @code{substring-move-left!}.
1611 @c docstring begin (texi-doc-string "guile" "vector-move-right!")
1612 @deffn primitive vector-move-right! vec1 start1 end1 vec2 start2
1613 Vector version of @code{substring-move-right!}.
1616 @c ARGFIXME fill/fill-char
1617 @c docstring begin (texi-doc-string "guile" "substring-fill!")
1618 @deffn primitive substring-fill! str start end fill
1619 Change every character in @var{str} between @var{start} and @var{end} to
1622 (qdocs:) Destructively fills @var{str}, from @var{start} to @var{end}, with @var{fill}.
1625 (define y "abcdefg")
1626 (substring-fill! y 1 3 #\r)
1632 @c docstring begin (texi-doc-string "guile" "string-null?")
1633 @deffn primitive string-null? str
1634 Return @code{#t} if @var{str}'s length is nonzero, and @code{#f}
1637 (qdocs:) Returns @code{#t} if @var{str} is empty, else returns @code{#f}.
1649 @c docstring begin (texi-doc-string "guile" "string-upcase!")
1650 @deffn primitive string-upcase! str
1651 Destructively upcase every character in @code{str}.
1653 (qdocs:) Converts each element in @var{str} to upper case.
1664 @c docstring begin (texi-doc-string "guile" "string-upcase")
1665 @deffn primitive string-upcase str
1666 Upcase every character in @code{str}.
1670 @c docstring begin (texi-doc-string "guile" "string-downcase!")
1671 @deffn primitive string-downcase! str
1672 Destructively downcase every character in @code{str}.
1674 (qdocs:) Converts each element in @var{str} to lower case.
1680 (string-downcase! y)
1688 @c docstring begin (texi-doc-string "guile" "string-downcase")
1689 @deffn primitive string-downcase str
1690 Downcase every character in @code{str}.
1693 @c docstring begin (texi-doc-string "guile" "string-capitalize!")
1694 @deffn primitive string-capitalize! str
1695 Destructively capitalize every character in @code{str}.
1698 @c docstring begin (texi-doc-string "guile" "string-capitalize")
1699 @deffn primitive string-capitalize str
1700 Capitalize every character in @code{str}.
1704 @c docstring begin (texi-doc-string "guile" "string-ci<=?")
1705 @deffn primitive string-ci<=? s1 s2
1706 Case insensitive lexicographic ordering predicate;
1707 returns @code{#t} if @var{s1} is lexicographically less than
1708 or equal to @var{s2} regardless of case. (r5rs)
1712 @c docstring begin (texi-doc-string "guile" "string-ci<?")
1713 @deffn primitive string-ci<? s1 s2
1714 Case insensitive lexicographic ordering predicate;
1715 returns @code{#t} if @var{s1} is lexicographically less than
1716 @var{s2} regardless of case. (r5rs)
1719 @r5index string-ci=?
1720 @c docstring begin (texi-doc-string "guile" "string-ci=?")
1721 @deffn primitive string-ci=? s1 s2
1722 Case-insensitive string equality predicate; returns @code{#t}
1723 if the two strings are the same length and their component
1724 characters match (ignoring case) at each position; otherwise
1725 returns @code{#f}. (r5rs)
1728 @r5index string-ci>=?
1729 @c docstring begin (texi-doc-string "guile" "string-ci>=?")
1730 @deffn primitive string-ci>=? s1 s2
1731 Case insensitive lexicographic ordering predicate;
1732 returns @code{#t} if @var{s1} is lexicographically greater
1733 than or equal to @var{s2} regardless of case. (r5rs)
1736 @r5index string-ci>?
1737 @c docstring begin (texi-doc-string "guile" "string-ci>?")
1738 @deffn primitive string-ci>? s1 s2
1739 Case insensitive lexicographic ordering predicate;
1740 returns @code{#t} if @var{s1} is lexicographically greater
1741 than @var{s2} regardless of case. (r5rs)
1745 @c docstring begin (texi-doc-string "guile" "string<=?")
1746 @deffn primitive string<=? s1 s2
1747 Lexicographic ordering predicate; returns @code{#t} if
1748 @var{s1} is lexicographically less than or equal to @var{s2}.
1753 @c docstring begin (texi-doc-string "guile" "string<?")
1754 @deffn primitive string<? s1 s2
1755 Lexicographic ordering predicate; returns @code{#t} if
1756 @var{s1} is lexicographically less than @var{s2}. (r5rs)
1760 @c docstring begin (texi-doc-string "guile" "string=?")
1761 @deffn primitive string=? s1 s2
1762 Lexicographic equality predicate;
1763 Returns @code{#t} if the two strings are the same length and
1764 contain the same characters in the same positions, otherwise
1765 returns @code{#f}. (r5rs)
1767 The procedure @code{string-ci=?} treats upper and lower case
1768 letters as though they were the same character, but
1769 @code{string=?} treats upper and lower case as distinct
1774 @c docstring begin (texi-doc-string "guile" "string>=?")
1775 @deffn primitive string>=? s1 s2
1776 Lexicographic ordering predicate; returns @code{#t} if
1777 @var{s1} is lexicographically greater than or equal to
1782 @c docstring begin (texi-doc-string "guile" "string>?")
1783 @deffn primitive string>? s1 s2
1784 Lexicographic ordering predicate; returns @code{#t} if
1785 @var{s1} is lexicographically greater than @var{s2}. (r5rs)
1788 @r5index string->list
1789 @c docstring begin (texi-doc-string "guile" "string->list")
1790 @deffn primitive string->list str
1791 @samp{String->list} returns a newly allocated list of the
1792 characters that make up the given string. @samp{List->string}
1793 returns a newly allocated string formed from the characters in the list
1794 @var{list}, which must be a list of characters. @samp{String->list}
1795 and @samp{list->string} are
1796 inverses so far as @samp{equal?} is concerned. (r5rs)
1799 @c docstring begin (texi-doc-string "guile" "string-ci->symbol")
1800 @deffn primitive string-ci->symbol str
1801 Return the symbol whose name is @var{str}, downcased in necessary(???).
1804 @r5index string-copy
1805 @c docstring begin (texi-doc-string "guile" "string-copy")
1806 @deffn primitive string-copy str
1807 Returns a newly allocated copy of the given @var{string}. (r5rs)
1810 @r5index string-fill!
1811 @c docstring begin (texi-doc-string "guile" "string-fill!")
1812 @deffn primitive string-fill! str chr
1813 Stores @var{char} in every element of the given @var{string} and returns an
1814 unspecified value. (r5rs)
1818 @node Shared Substrings
1819 @subsection Shared Substrings
1821 Whenever you extract a substring using @code{substring}, the Scheme
1822 interpreter allocates a new string and copies data from the old string.
1823 This is expensive, but @code{substring} is so convenient for
1824 manipulating text that programmers use it often.
1826 Guile Scheme provides the concept of the @dfn{shared substring} to
1827 improve performance of many substring-related operations. A shared
1828 substring is an object that mostly behaves just like an ordinary
1829 substring, except that it actually shares storage space with its parent
1832 @c ARGFIXME frm/start to/end
1833 @c docstring begin (texi-doc-string "guile" "make-shared-substring")
1834 @deffn primitive make-shared-substring str [frm [to]]
1835 Return a shared substring of @var{str}. The semantics are the same as
1836 for the @code{substring} function: the shared substring returned
1837 includes all of the text from @var{str} between indexes @var{start}
1838 (inclusive) and @var{end} (exclusive). If @var{end} is omitted, it
1839 defaults to the end of @var{str}. The shared substring returned by
1840 @code{make-shared-substring} occupies the same storage space as
1847 (define foo "the quick brown fox")
1848 (define bar (make-shared-substring some-string 4 9))
1850 foo => "t h e q u i c k b r o w n f o x"
1851 bar =========> |---------|
1854 The shared substring @var{bar} is not given its own storage space.
1855 Instead, the Guile interpreter notes internally that @var{bar} points to
1856 a portion of the memory allocated to @var{foo}. However, @var{bar}
1857 behaves like an ordinary string in most respects: it may be used with
1858 string primitives like @code{string-length}, @code{string-ref},
1859 @code{string=?}. Guile makes the necessary translation between indices
1860 of @var{bar} and indices of @var{foo} automatically.
1863 (string-length? bar) @result{} 5 ; bar only extends from indices 4 to 9
1864 (string-ref bar 3) @result{} #\c ; same as (string-ref foo 7)
1865 (make-shared-substring bar 2)
1866 @result{} "ick" ; can even make a shared substring!
1869 Because creating a shared substring does not require allocating new
1870 storage from the heap, it is a very fast operation. However, because it
1871 shares memory with its parent string, a change to the contents of the
1872 parent string will implicitly change the contents of its shared
1876 (string-set! foo 7 #\r)
1877 bar @result{} "quirk"
1880 Guile considers shared substrings to be immutable. This is because
1881 programmers might not always be aware that a given string is really a
1882 shared substring, and might innocently try to mutate it without
1883 realizing that the change would affect its parent string. (We are
1884 currently considering a "copy-on-write" strategy that would permit
1885 modifying shared substrings without affecting the parent string.)
1887 In general, shared substrings are useful in circumstances where it is
1888 important to divide a string into smaller portions, but you do not
1889 expect to change the contents of any of the strings involved.
1891 @node Read Only Strings
1892 @subsection Read Only Strings
1894 Type-checking in Guile primitives distinguishes between mutable strings
1895 and read only strings. Mutable strings answer @code{#t} to
1896 @code{string?} while read only strings may or may not. All kinds of
1897 strings, whether or not they are mutable return #t to this:
1900 @c docstring begin (texi-doc-string "guile" "read-only-string?")
1901 @deffn primitive read-only-string? obj
1902 Return true if @var{obj} can be read as a string,
1904 This illustrates the difference between @code{string?} and
1905 @code{read-only-string?}:
1908 (string? "a string") @result{} #t
1909 (string? 'a-symbol) @result{} #f
1911 (read-only-string? "a string") @result{} #t
1912 (read-only-string? 'a-symbol) @result{} #t
1916 "Read-only" refers to how the string will be used, not how the string is
1917 permitted to be used. In particular, all strings are "read-only
1918 strings" even if they are mutable, because a function that only reads
1919 from a string can certainly operate on even a mutable string.
1921 Symbols are an example of read-only strings. Many string functions,
1922 such as @code{string-append} are happy to operate on symbols. Many
1923 functions that expect a string argument, such as @code{open-file}, will
1924 accept a symbol as well.
1926 Shared substrings, discussed in the previous chapter, also happen to be
1930 @node Regular Expressions
1931 @section Regular Expressions
1933 @cindex regular expressions
1935 @cindex emacs regexp
1937 A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
1938 describes a whole class of strings. A full description of regular
1939 expressions and their syntax is beyond the scope of this manual;
1940 an introduction can be found in the Emacs manual (@pxref{Regexps,
1941 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, or
1942 in many general Unix reference books.
1944 If your system does not include a POSIX regular expression library, and
1945 you have not linked Guile with a third-party regexp library such as Rx,
1946 these functions will not be available. You can tell whether your Guile
1947 installation includes regular expression support by checking whether the
1948 @code{*features*} list includes the @code{regex} symbol.
1951 * Regexp Functions:: Functions that create and match regexps.
1952 * Match Structures:: Finding what was matched by a regexp.
1953 * Backslash Escapes:: Removing the special meaning of regexp metacharacters.
1954 * Rx Interface:: Tom Lord's Rx library does things differently.
1957 [FIXME: it may be useful to include an Examples section. Parts of this
1958 interface are bewildering on first glance.]
1960 @node Regexp Functions
1961 @subsection Regexp Functions
1963 By default, Guile supports POSIX extended regular expressions.
1964 That means that the characters @samp{(}, @samp{)}, @samp{+} and
1965 @samp{?} are special, and must be escaped if you wish to match the
1968 This regular expression interface was modeled after that
1969 implemented by SCSH, the Scheme Shell. It is intended to be
1970 upwardly compatible with SCSH regular expressions.
1972 @c begin (scm-doc-string "regex.scm" "string-match")
1973 @deffn procedure string-match pattern str [start]
1974 Compile the string @var{pattern} into a regular expression and compare
1975 it with @var{str}. The optional numeric argument @var{start} specifies
1976 the position of @var{str} at which to begin matching.
1978 @code{string-match} returns a @dfn{match structure} which
1979 describes what, if anything, was matched by the regular
1980 expression. @xref{Match Structures}. If @var{str} does not match
1981 @var{pattern} at all, @code{string-match} returns @code{#f}.
1984 Each time @code{string-match} is called, it must compile its
1985 @var{pattern} argument into a regular expression structure. This
1986 operation is expensive, which makes @code{string-match} inefficient if
1987 the same regular expression is used several times (for example, in a
1988 loop). For better performance, you can compile a regular expression in
1989 advance and then match strings against the compiled regexp.
1991 @c ARGFIXME pat/str flags/flag
1992 @c docstring begin (texi-doc-string "guile" "make-regexp")
1993 @deffn primitive make-regexp pat . flags
1994 Compile the regular expression described by @var{str}, and return the
1995 compiled regexp structure. If @var{str} does not describe a legal
1996 regular expression, @code{make-regexp} throws a
1997 @code{regular-expression-syntax} error.
1999 The @var{flag} arguments change the behavior of the compiled regexp.
2000 The following flags may be supplied:
2004 Consider uppercase and lowercase letters to be the same when matching.
2006 @item regexp/newline
2007 If a newline appears in the target string, then permit the @samp{^} and
2008 @samp{$} operators to match immediately after or immediately before the
2009 newline, respectively. Also, the @samp{.} and @samp{[^...]} operators
2010 will never match a newline character. The intent of this flag is to
2011 treat the target string as a buffer containing many lines of text, and
2012 the regular expression as a pattern that may match a single one of those
2016 Compile a basic (``obsolete'') regexp instead of the extended
2017 (``modern'') regexps that are the default. Basic regexps do not
2018 consider @samp{|}, @samp{+} or @samp{?} to be special characters, and
2019 require the @samp{@{...@}} and @samp{(...)} metacharacters to be
2020 backslash-escaped (@pxref{Backslash Escapes}). There are several other
2021 differences between basic and extended regular expressions, but these
2022 are the most significant.
2024 @item regexp/extended
2025 Compile an extended regular expression rather than a basic regexp. This
2026 is the default behavior; this flag will not usually be needed. If a
2027 call to @code{make-regexp} includes both @code{regexp/basic} and
2028 @code{regexp/extended} flags, the one which comes last will override
2033 @c ARGFIXME rx/regexp
2034 @c docstring begin (texi-doc-string "guile" "regexp-exec")
2035 @deffn primitive regexp-exec rx str [start [flags]]
2036 Match the compiled regular expression @var{regexp} against @code{str}.
2037 If the optional integer @var{start} argument is provided, begin matching
2038 from that position in the string. Return a match structure describing
2039 the results of the match, or @code{#f} if no match could be found.
2043 @c docstring begin (texi-doc-string "guile" "regexp?")
2044 @deffn primitive regexp? x
2045 Return @code{#t} if @var{obj} is a compiled regular expression, or
2046 @code{#f} otherwise.
2049 Regular expressions are commonly used to find patterns in one string and
2050 replace them with the contents of another string.
2052 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2053 @deffn procedure regexp-substitute port match [item@dots{}]
2054 Write to the output port @var{port} selected contents of the match
2055 structure @var{match}. Each @var{item} specifies what should be
2056 written, and may be one of the following arguments:
2060 A string. String arguments are written out verbatim.
2063 An integer. The submatch with that number is written.
2066 The symbol @samp{pre}. The portion of the matched string preceding
2067 the regexp match is written.
2070 The symbol @samp{post}. The portion of the matched string following
2071 the regexp match is written.
2074 @var{port} may be @code{#f}, in which case nothing is written; instead,
2075 @code{regexp-substitute} constructs a string from the specified
2076 @var{item}s and returns that.
2079 @c begin (scm-doc-string "regex.scm" "regexp-substitute")
2080 @deffn procedure regexp-substitute/global port regexp target [item@dots{}]
2081 Similar to @code{regexp-substitute}, but can be used to perform global
2082 substitutions on @var{str}. Instead of taking a match structure as an
2083 argument, @code{regexp-substitute/global} takes two string arguments: a
2084 @var{regexp} string describing a regular expression, and a @var{target}
2085 string which should be matched against this regular expression.
2087 Each @var{item} behaves as in @var{regexp-substitute}, with the
2088 following exceptions:
2092 A function may be supplied. When this function is called, it will be
2093 passed one argument: a match structure for a given regular expression
2094 match. It should return a string to be written out to @var{port}.
2097 The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
2098 on the unmatched portion of @var{str}. This @emph{must} be supplied in
2099 order to perform global search-and-replace on @var{str}; if it is not
2100 present among the @var{item}s, then @code{regexp-substitute/global} will
2101 return after processing a single match.
2105 @node Match Structures
2106 @subsection Match Structures
2108 @cindex match structures
2110 A @dfn{match structure} is the object returned by @code{string-match} and
2111 @code{regexp-exec}. It describes which portion of a string, if any,
2112 matched the given regular expression. Match structures include: a
2113 reference to the string that was checked for matches; the starting and
2114 ending positions of the regexp match; and, if the regexp included any
2115 parenthesized subexpressions, the starting and ending positions of each
2118 In each of the regexp match functions described below, the @code{match}
2119 argument must be a match structure returned by a previous call to
2120 @code{string-match} or @code{regexp-exec}. Most of these functions
2121 return some information about the original target string that was
2122 matched against a regular expression; we will call that string
2123 @var{target} for easy reference.
2125 @c begin (scm-doc-string "regex.scm" "regexp-match?")
2126 @deffn procedure regexp-match? obj
2127 Return @code{#t} if @var{obj} is a match structure returned by a
2128 previous call to @code{regexp-exec}, or @code{#f} otherwise.
2131 @c begin (scm-doc-string "regex.scm" "match:substring")
2132 @deffn procedure match:substring match [n]
2133 Return the portion of @var{target} matched by subexpression number
2134 @var{n}. Submatch 0 (the default) represents the entire regexp match.
2135 If the regular expression as a whole matched, but the subexpression
2136 number @var{n} did not match, return @code{#f}.
2139 @c begin (scm-doc-string "regex.scm" "match:start")
2140 @deffn procedure match:start match [n]
2141 Return the starting position of submatch number @var{n}.
2144 @c begin (scm-doc-string "regex.scm" "match:end")
2145 @deffn procedure match:end match [n]
2146 Return the ending position of submatch number @var{n}.
2149 @c begin (scm-doc-string "regex.scm" "match:prefix")
2150 @deffn procedure match:prefix match
2151 Return the unmatched portion of @var{target} preceding the regexp match.
2154 @c begin (scm-doc-string "regex.scm" "match:suffix")
2155 @deffn procedure match:suffix match
2156 Return the unmatched portion of @var{target} following the regexp match.
2159 @c begin (scm-doc-string "regex.scm" "match:count")
2160 @deffn procedure match:count match
2161 Return the number of parenthesized subexpressions from @var{match}.
2162 Note that the entire regular expression match itself counts as a
2163 subexpression, and failed submatches are included in the count.
2166 @c begin (scm-doc-string "regex.scm" "match:string")
2167 @deffn procedure match:string match
2168 Return the original @var{target} string.
2171 @node Backslash Escapes
2172 @subsection Backslash Escapes
2174 Sometimes you will want a regexp to match characters like @samp{*} or
2175 @samp{$} exactly. For example, to check whether a particular string
2176 represents a menu entry from an Info node, it would be useful to match
2177 it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2178 because the asterisk is a metacharacter, it won't match the @samp{*} at
2179 the beginning of the string. In this case, we want to make the first
2182 You can do this by preceding the metacharacter with a backslash
2183 character @samp{\}. (This is also called @dfn{quoting} the
2184 metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2185 sees a backslash in a regular expression, it considers the following
2186 glyph to be an ordinary character, no matter what special meaning it
2187 would ordinarily have. Therefore, we can make the above example work by
2188 changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2189 the regular expression engine to match only a single asterisk in the
2192 Since the backslash is itself a metacharacter, you may force a regexp to
2193 match a backslash in the target string by preceding the backslash with
2194 itself. For example, to find variable references in a @TeX{} program,
2195 you might want to find occurrences of the string @samp{\let\} followed
2196 by any number of alphabetic characters. The regular expression
2197 @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2198 regexp each match a single backslash in the target string.
2200 @c begin (scm-doc-string "regex.scm" "regexp-quote")
2201 @deffn procedure regexp-quote str
2202 Quote each special character found in @var{str} with a backslash, and
2203 return the resulting string.
2206 @strong{Very important:} Using backslash escapes in Guile source code
2207 (as in Emacs Lisp or C) can be tricky, because the backslash character
2208 has special meaning for the Guile reader. For example, if Guile
2209 encounters the character sequence @samp{\n} in the middle of a string
2210 while processing Scheme code, it replaces those characters with a
2211 newline character. Similarly, the character sequence @samp{\t} is
2212 replaced by a horizontal tab. Several of these @dfn{escape sequences}
2213 are processed by the Guile reader before your code is executed.
2214 Unrecognized escape sequences are ignored: if the characters @samp{\*}
2215 appear in a string, they will be translated to the single character
2218 This translation is obviously undesirable for regular expressions, since
2219 we want to be able to include backslashes in a string in order to
2220 escape regexp metacharacters. Therefore, to make sure that a backslash
2221 is preserved in a string in your Guile program, you must use @emph{two}
2222 consecutive backslashes:
2225 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2228 The string in this example is preprocessed by the Guile reader before
2229 any code is executed. The resulting argument to @code{make-regexp} is
2230 the string @samp{^\* [^:]*}, which is what we really want.
2232 This also means that in order to write a regular expression that matches
2233 a single backslash character, the regular expression string in the
2234 source code must include @emph{four} backslashes. Each consecutive pair
2235 of backslashes gets translated by the Guile reader to a single
2236 backslash, and the resulting double-backslash is interpreted by the
2237 regexp engine as matching a single backslash character. Hence:
2240 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2243 The reason for the unwieldiness of this syntax is historical. Both
2244 regular expression pattern matchers and Unix string processing systems
2245 have traditionally used backslashes with the special meanings
2246 described above. The POSIX regular expression specification and ANSI C
2247 standard both require these semantics. Attempting to abandon either
2248 convention would cause other kinds of compatibility problems, possibly
2249 more severe ones. Therefore, without extending the Scheme reader to
2250 support strings with different quoting conventions (an ungainly and
2251 confusing extension when implemented in other languages), we must adhere
2252 to this cumbersome escape syntax.
2255 @subsection Rx Interface
2257 [FIXME: this is taken from Gary and Mark's quick summaries and should be
2258 reviewed and expanded. Rx is pretty stable, so could already be done!]
2261 @cindex finite automaton
2263 Guile includes an interface to Tom Lord's Rx library (currently only to
2264 POSIX regular expressions). Use of the library requires a two step
2265 process: compile a regular expression into an efficient structure, then
2266 use the structure in any number of string comparisons.
2268 For example, given the
2269 regular expression @samp{abc.} (which matches any string containing
2270 @samp{abc} followed by any single character):
2273 guile> @kbd{(define r (regcomp "abc."))}
2276 guile> @kbd{(regexec r "abc")}
2278 guile> @kbd{(regexec r "abcd")}
2283 The definitions of @code{regcomp} and @code{regexec} are as follows:
2285 @c NJFIXME not in libguile!
2286 @deffn primitive regcomp pattern [flags]
2287 Compile the regular expression pattern using POSIX rules. Flags is
2288 optional and should be specified using symbolic names:
2289 @defvar REG_EXTENDED
2290 use extended POSIX syntax
2293 use case-insensitive matching
2296 allow anchors to match after newline characters in the
2297 string and prevents @code{.} or @code{[^...]} from matching newlines.
2300 The @code{logior} procedure can be used to combine multiple flags.
2301 The default is to use
2302 POSIX basic syntax, which makes @code{+} and @code{?} literals and @code{\+}
2304 operators. Backslashes in @var{pattern} must be escaped if specified in a
2305 literal string e.g., @code{"\\(a\\)\\?"}.
2308 @c NJFIXME not in libguile!
2309 @deffn primitive regexec regex string [match-pick] [flags]
2311 Match @var{string} against the compiled POSIX regular expression
2313 @var{match-pick} and @var{flags} are optional. Possible flags (which can be
2314 combined using the logior procedure) are:
2317 The beginning of line operator won't match the beginning of
2318 @var{string} (presumably because it's not the beginning of a line)
2322 Similar to REG_NOTBOL, but prevents the end of line operator
2323 from matching the end of @var{string}.
2326 If no match is possible, regexec returns #f. Otherwise @var{match-pick}
2327 determines the return value:
2329 @code{#t} or unspecified: a newly-allocated vector is returned,
2330 containing pairs with the indices of the matched part of @var{string} and any
2333 @code{""}: a list is returned: the first element contains a nested list
2334 with the matched part of @var{string} surrounded by the the unmatched parts.
2335 Remaining elements are matched substrings (if any). All returned
2336 substrings share memory with @var{string}.
2338 @code{#f}: regexec returns #t if a match is made, otherwise #f.
2340 vector: the supplied vector is returned, with the first element replaced
2341 by a pair containing the indices of the matched portion of @var{string} and
2342 further elements replaced by pairs containing the indices of matched
2343 substrings (if any).
2345 list: a list will be returned, with each member of the list
2346 specified by a code in the corresponding position of the supplied list:
2348 a number: the numbered matching substring (0 for the entire match).
2350 @code{#\<}: the beginning of @var{string} to the beginning of the part matched
2353 @code{#\>}: the end of the matched part of @var{string} to the end of
2356 @code{#\c}: the "final tag", which seems to be associated with the "cut
2357 operator", which doesn't seem to be available through the posix
2360 e.g., @code{(list #\< 0 1 #\>)}. The returned substrings share memory with
2364 Here are some other procedures that might be used when using regular
2367 @c NJFIXME not in libguile!
2368 @deffn primitive compiled-regexp? obj
2369 Test whether obj is a compiled regular expression.
2372 @c NJFIXME not in libguile!
2373 @deffn primitive regexp->dfa regex [flags]
2376 @c NJFIXME not in libguile!
2377 @deffn primitive dfa-fork dfa
2380 @c NJFIXME not in libguile!
2381 @deffn primitive reset-dfa! dfa
2384 @c NJFIXME not in libguile!
2385 @deffn primitive dfa-final-tag dfa
2388 @c NJFIXME not in libguile!
2389 @deffn primitive dfa-continuable? dfa
2392 @c NJFIXME not in libguile!
2393 @deffn primitive advance-dfa! dfa string
2397 @node Symbols and Variables
2398 @section Symbols and Variables
2400 @r5index symbol->string
2401 @r5index string->symbol
2404 Guile symbol tables are hash tables. Each hash table, also called an
2405 @dfn{obarray} (for `object array'), is a vector of association lists.
2406 Each entry in the alists is a pair (@var{SYMBOL} . @var{VALUE}). To
2407 @dfn{intern} a symbol in a symbol table means to return its
2408 (@var{SYMBOL} . @var{VALUE}) pair, adding a new entry to the symbol
2409 table (with an undefined value) if none is yet present.
2411 @c FIXME::martin: According to NEWS, removed. Remove here too, or
2412 @c leave for compatibility?
2413 @c @c docstring begin (texi-doc-string "guile" "builtin-bindings")
2414 @c @deffn primitive builtin-bindings
2415 @c Create and return a copy of the global symbol table, removing all
2419 @c docstring begin (texi-doc-string "guile" "gensym")
2420 @deffn primitive gensym [prefix]
2421 Create a new symbol with a name constructed from a prefix and
2422 a counter value. The string @var{prefix} can be specified as
2423 an optional argument. Default prefix is @code{g}. The counter
2424 is increased by 1 at each call. There is no provision for
2425 resetting the counter.
2428 @c docstring begin (texi-doc-string "guile" "gentemp")
2429 @deffn primitive gentemp [prefix [obarray]]
2430 Create a new symbol with a name unique in an obarray.
2431 The name is constructed from an optional string @var{prefix}
2432 and a counter value. The default prefix is @code{t}. The
2433 @var{obarray} is specified as a second optional argument.
2434 Default is the system obarray where all normal symbols are
2435 interned. The counter is increased by 1 at each
2436 call. There is no provision for resetting the counter.
2439 @c docstring begin (texi-doc-string "guile" "intern-symbol")
2440 @deffn primitive intern-symbol obarray string
2441 Add a new symbol to @var{obarray} with name @var{string}, bound to an
2442 unspecified initial value. The symbol table is not modified if a symbol
2443 with this name is already present.
2446 @c docstring begin (texi-doc-string "guile" "string->obarray-symbol")
2447 @deffn primitive string->obarray-symbol obarray string [soft?]
2448 Intern a new symbol in @var{obarray}, a symbol table, with name
2451 If @var{obarray} is @code{#f}, use the default system symbol table. If
2452 @var{obarray} is @code{#t}, the symbol should not be interned in any
2453 symbol table; merely return the pair (@var{symbol}
2454 . @var{#<undefined>}).
2456 The @var{soft?} argument determines whether new symbol table entries
2457 should be created when the specified symbol is not already present in
2458 @var{obarray}. If @var{soft?} is specified and is a true value, then
2459 new entries should not be added for symbols not already present in the
2460 table; instead, simply return @code{#f}.
2463 @c docstring begin (texi-doc-string "guile" "string->symbol")
2464 @deffn primitive string->symbol string
2465 Returns the symbol whose name is @var{string}. This procedure can
2466 create symbols with names containing special characters or letters in
2467 the non-standard case, but it is usually a bad idea to create such
2468 symbols because in some implementations of Scheme they cannot be read as
2469 themselves. See @code{symbol->string}.
2471 The following examples assume that the implementation's
2472 standard case is lower case:
2475 (eq? 'mISSISSIppi 'mississippi) @result{} #t
2476 (string->symbol "mISSISSIppi") @result{} @r{the symbol with name "mISSISSIppi"}
2477 (eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
2479 (string->symbol (symbol->string 'JollyWog))) @result{} #t
2480 (string=? "K. Harper, M.D."
2482 (string->symbol "K. Harper, M.D."))) @result{}#t
2486 @c docstring begin (texi-doc-string "guile" "symbol->string")
2487 @deffn primitive symbol->string s
2488 Returns the name of @var{symbol} as a string. If the symbol
2489 was part of an object returned as the value of a literal
2490 expression (section @pxref{Literal expressions,,,r4rs, The
2491 Revised^4 Report on Scheme}) or by a call to the @code{read}
2492 procedure, and its name contains alphabetic characters, then
2493 the string returned will contain characters in the
2494 implementation's preferred standard case---some implementations
2495 will prefer upper case, others lower case. If the symbol was
2496 returned by @code{string->symbol}, the case of characters in
2497 the string returned will be the same as the case in the string
2498 that was passed to @code{string->symbol}. It is an error to
2499 apply mutation procedures like @code{string-set!} to strings
2500 returned by this procedure. (r5rs)
2502 The following examples assume that the implementation's
2503 standard case is lower case:
2506 (symbol->string 'flying-fish) @result{} "flying-fish"
2507 (symbol->string 'Martin) @result{} "martin"
2509 (string->symbol "Malvina")) @result{} "Malvina"
2513 @c docstring begin (texi-doc-string "guile" "symbol-binding")
2514 @deffn primitive symbol-binding obarray string
2515 Look up in @var{obarray} the symbol whose name is @var{string}, and
2516 return the value to which it is bound. If @var{obarray} is @code{#f},
2517 use the global symbol table. If @var{string} is not interned in
2518 @var{obarray}, an error is signalled.
2521 @c docstring begin (texi-doc-string "guile" "symbol-bound?")
2522 @deffn primitive symbol-bound? obarray string
2523 Return @code{#t} if @var{obarray} contains a symbol with name
2524 @var{string} bound to a defined value. This differs from
2525 @var{symbol-interned?} in that the mere mention of a symbol
2526 usually causes it to be interned; @code{symbol-bound?}
2527 determines whether a symbol has been given any meaningful
2531 @c docstring begin (texi-doc-string "guile" "symbol-fref")
2532 @deffn primitive symbol-fref symbol
2533 Return the contents of @var{symbol}'s @dfn{function slot}.
2536 @c docstring begin (texi-doc-string "guile" "symbol-fset!")
2537 @deffn primitive symbol-fset! symbol value
2538 Change the binding of @var{symbol}'s function slot.
2541 @c docstring begin (texi-doc-string "guile" "symbol-hash")
2542 @deffn primitive symbol-hash symbol
2543 Return a hash value for @var{symbol}.
2546 @c docstring begin (texi-doc-string "guile" "symbol-interned?")
2547 @deffn primitive symbol-interned? obarray string
2548 Return @code{#t} if @var{obarray} contains a symbol with name
2549 @var{string}, and @code{#f} otherwise.
2552 @c docstring begin (texi-doc-string "guile" "symbol-pref")
2553 @deffn primitive symbol-pref symbol
2554 Return the @dfn{property list} currently associated with @var{symbol}.
2557 @c docstring begin (texi-doc-string "guile" "symbol-pset!")
2558 @deffn primitive symbol-pset! symbol value
2559 Change the binding of @var{symbol}'s property slot.
2562 @c docstring begin (texi-doc-string "guile" "symbol-set!")
2563 @deffn primitive symbol-set! obarray string value
2564 Find the symbol in @var{obarray} whose name is @var{string}, and rebind
2565 it to @var{value}. An error is signalled if @var{string} is not present
2569 @c docstring begin (texi-doc-string "guile" "symbol?")
2570 @deffn primitive symbol? obj
2571 Returns @code{#t} if @var{obj} is a symbol, otherwise returns
2575 @c docstring begin (texi-doc-string "guile" "unintern-symbol")
2576 @deffn primitive unintern-symbol obarray string
2577 Remove the symbol with name @var{string} from @var{obarray}. This
2578 function returns @code{#t} if the symbol was present and @code{#f}
2582 @c docstring begin (texi-doc-string "guile" "builtin-variable")
2583 @deffn primitive builtin-variable name
2584 Return the built-in variable with the name @var{name}.
2585 @var{name} must be a symbol (not a string).
2586 Then use @code{variable-ref} to access its value.
2589 @c docstring begin (texi-doc-string "guile" "make-undefined-variable")
2590 @deffn primitive make-undefined-variable [name-hint]
2591 Return a variable object initialized to an undefined value.
2592 If given, uses @var{name-hint} as its internal (debugging)
2593 name, otherwise just treat it as an anonymous variable.
2594 Remember, of course, that multiple bindings to the same
2595 variable may exist, so @var{name-hint} is just that---a hint.
2598 @c docstring begin (texi-doc-string "guile" "make-variable")
2599 @deffn primitive make-variable init [name-hint]
2600 Return a variable object initialized to value @var{init}.
2601 If given, uses @var{name-hint} as its internal (debugging)
2602 name, otherwise just treat it as an anonymous variable.
2603 Remember, of course, that multiple bindings to the same
2604 variable may exist, so @var{name-hint} is just that---a hint.
2607 @c docstring begin (texi-doc-string "guile" "variable-bound?")
2608 @deffn primitive variable-bound? var
2609 Return @code{#t} iff @var{var} is bound to a value.
2610 Throws an error if @var{var} is not a variable object.
2613 @c docstring begin (texi-doc-string "guile" "variable-ref")
2614 @deffn primitive variable-ref var
2615 Dereference @var{var} and return its value.
2616 @var{var} must be a variable object; see @code{make-variable}
2617 and @code{make-undefined-variable}.
2620 @c docstring begin (texi-doc-string "guile" "variable-set!")
2621 @deffn primitive variable-set! var val
2622 Set the value of the variable @var{var} to @var{val}.
2623 @var{var} must be a variable object, @var{val} can be any
2624 value. Return an unspecified value.
2627 @c docstring begin (texi-doc-string "guile" "variable?")
2628 @deffn primitive variable? obj
2629 Return @code{#t} iff @var{obj} is a variable object, else
2637 Keywords are self-evaluating objects with a convenient read syntax that
2638 makes them easy to type.
2640 Guile's keyword support conforms to R4RS, and adds a (switchable) read
2641 syntax extension to permit keywords to begin with @code{:} as well as
2645 * Why Use Keywords?::
2646 * Coding With Keywords::
2647 * Keyword Read Syntax::
2648 * Keyword Primitives::
2651 @node Why Use Keywords?
2652 @subsection Why Use Keywords?
2654 Keywords are useful in contexts where a program or procedure wants to be
2655 able to accept a large number of optional arguments without making its
2656 interface unmanageable.
2658 To illustrate this, consider a hypothetical @code{make-window}
2659 procedure, which creates a new window on the screen for drawing into
2660 using some graphical toolkit. There are many parameters that the caller
2661 might like to specify, but which could also be sensibly defaulted, for
2666 colour depth -- Default: the colour depth for the screen
2669 background colour -- Default: white
2672 width -- Default: 600
2675 height -- Default: 400
2678 If @code{make-window} did not use keywords, the caller would have to
2679 pass in a value for each possible argument, remembering the correct
2680 argument order and using a special value to indicate the default value
2684 (make-window 'default ;; Colour depth
2685 'default ;; Background colour
2688 @dots{}) ;; More make-window arguments
2691 With keywords, on the other hand, defaulted arguments are omitted, and
2692 non-default arguments are clearly tagged by the appropriate keyword. As
2693 a result, the invocation becomes much clearer:
2696 (make-window #:width 800 #:height 100)
2699 On the other hand, for a simpler procedure with few arguments, the use
2700 of keywords would be a hindrance rather than a help. The primitive
2701 procedure @code{cons}, for example, would not be improved if it had to
2705 (cons #:car x #:cdr y)
2708 So the decision whether to use keywords or not is purely pragmatic: use
2709 them if they will clarify the procedure invocation at point of call.
2711 @node Coding With Keywords
2712 @subsection Coding With Keywords
2714 If a procedure wants to support keywords, it should take a rest argument
2715 and then use whatever means is convenient to extract keywords and their
2716 corresponding arguments from the contents of that rest argument.
2718 The following example illustrates the principle: the code for
2719 @code{make-window} uses a helper procedure called
2720 @code{get-keyword-value} to extract individual keyword arguments from
2724 (define (get-keyword-value args keyword default)
2725 (let ((kv (memq keyword args)))
2726 (if (and kv (>= (length kv) 2))
2730 (define (make-window . args)
2731 (let ((depth (get-keyword-value args #:depth screen-depth))
2732 (bg (get-keyword-value args #:bg "white"))
2733 (width (get-keyword-value args #:width 800))
2734 (height (get-keyword-value args #:height 100))
2739 But you don't need to write @code{get-keyword-value}. The @code{(ice-9
2740 optargs)} module provides a set of powerful macros that you can use to
2741 implement keyword-supporting procedures like this:
2744 (use-modules (ice-9 optargs))
2746 (define (make-window . args)
2747 (let-keywords args #f ((depth screen-depth)
2755 Or, even more economically, like this:
2758 (use-modules (ice-9 optargs))
2760 (define* (make-window #:key (depth screen-depth)
2767 For further details on @code{let-keywords}, @code{define*} and other
2768 facilities provided by the @code{(ice-9 optargs)} module, @ref{Optional
2772 @node Keyword Read Syntax
2773 @subsection Keyword Read Syntax
2775 Guile, by default, only recognizes the keyword syntax specified by R5RS.
2776 A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
2777 as a Scheme symbol, is the external representation of the keyword named
2778 @code{NAME}. Keyword objects print using this syntax as well, so values
2779 containing keyword objects can be read back into Guile. When used in an
2780 expression, keywords are self-quoting objects.
2782 If the @code{keyword} read option is set to @code{'prefix}, Guile also
2783 recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
2784 of the form @code{:NAME} are read as symbols, as required by R4RS.
2786 To enable and disable the alternative non-R4RS keyword syntax, you use
2787 the @code{read-options} procedure documented in @ref{General option
2788 interface} and @ref{Reader options}.
2791 (read-set! keywords 'prefix)
2801 (read-set! keywords #f)
2809 ERROR: In expression :type:
2810 ERROR: Unbound variable: :type
2811 ABORT: (unbound-variable)
2814 @node Keyword Primitives
2815 @subsection Keyword Primitives
2817 Internally, a keyword is implemented as something like a tagged symbol,
2818 where the tag identifies the keyword as being self-evaluating, and the
2819 symbol, known as the keyword's @dfn{dash symbol} has the same name as
2820 the keyword name but prefixed by a single dash. For example, the
2821 keyword @code{#:name} has the corresponding dash symbol @code{-name}.
2823 Most keyword objects are constructed automatically by the reader when it
2824 reads a token beginning with @code{#:}. However, if you need to
2825 construct a keyword object programmatically, you can do so by calling
2826 @code{make-keyword-from-dash-symbol} with the corresponding dash symbol
2827 (as the reader does). The dash symbol for a keyword object can be
2828 retrieved using the @code{keyword-dash-symbol} procedure.
2830 @c docstring begin (texi-doc-string "guile" "make-keyword-from-dash-symbol")
2831 @deffn primitive make-keyword-from-dash-symbol symbol
2832 Make a keyword object from a @var{symbol} that starts with a dash.
2835 @c docstring begin (texi-doc-string "guile" "keyword?")
2836 @deffn primitive keyword? obj
2837 Returns @code{#t} if the argument @var{obj} is a keyword, else @code{#f}.
2840 @c docstring begin (texi-doc-string "guile" "keyword-dash-symbol")
2841 @deffn primitive keyword-dash-symbol keyword
2842 Return the dash symbol for @var{keyword}.
2843 This is the inverse of @code{make-keyword-from-dash-symbol}.
2854 @c docstring begin (texi-doc-string "guile" "cons")
2855 @deffn primitive cons x y
2856 Returns a newly allocated pair whose car is @var{x} and whose cdr is
2857 @var{y}. The pair is guaranteed to be different (in the sense of
2858 @code{eqv?}) from every previously existing object.
2861 @c docstring begin (texi-doc-string "guile" "pair?")
2862 @deffn primitive pair? x
2863 Returns @code{#t} if @var{x} is a pair; otherwise returns @code{#f}.
2868 @deffn primitive car pair
2869 @deffnx primitive cdr pair
2870 Return the car or the cdr of @var{pair}, respectively.
2873 @deffn primitive caar pair
2874 @deffnx primitive cadr pair @dots{}
2875 @deffnx primitive cdddar pair
2876 @deffnx primitive cddddr pair
2877 These procedures are compositions of @code{car} and @code{cdr}, where
2878 for example @code{caddr} could be defined by
2881 (define caddr (lambda (x) (car (cdr (cdr x)))))
2885 @c docstring begin (texi-doc-string "guile" "set-car!")
2886 @deffn primitive set-car! pair value
2887 Stores @var{value} in the car field of @var{pair}. The value returned
2888 by @code{set-car!} is unspecified.
2891 @c docstring begin (texi-doc-string "guile" "set-cdr!")
2892 @deffn primitive set-cdr! pair value
2893 Stores @var{value} in the cdr field of @var{pair}. The value returned
2894 by @code{set-cdr!} is unspecified.
2913 @c docstring begin (texi-doc-string "guile" "list")
2914 @deffn primitive list . objs
2915 Return a list containing @var{objs}, the arguments to
2919 @c docstring begin (texi-doc-string "guile" "cons*")
2920 @deffn primitive cons* arg . rest
2921 Like @code{list}, but the last arg provides the tail of the
2922 constructed list, returning @code{(cons @var{arg1} (cons
2923 @var{arg2} (cons @dots{} @var{argn}))). Requires at least one
2924 argument. If given one argument, that argument is returned as
2925 result. This function is called @code{list*} in some other
2926 Schemes and in Common LISP.
2929 @c docstring begin (texi-doc-string "guile" "list?")
2930 @deffn primitive list? x
2931 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
2934 @c docstring begin (texi-doc-string "guile" "null?")
2935 @deffn primitive null? x
2936 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
2939 @c docstring begin (texi-doc-string "guile" "length")
2940 @deffn primitive length lst
2941 Return the number of elements in list @var{lst}.
2944 @c docstring begin (texi-doc-string "guile" "append")
2945 @deffn primitive append . args
2946 Return a list consisting of the elements the lists passed as
2949 (append '(x) '(y)) @result{} (x y)
2950 (append '(a) '(b c d)) @result{} (a b c d)
2951 (append '(a (b)) '((c))) @result{} (a (b) (c))
2953 The resulting list is always newly allocated, except that it
2954 shares structure with the last list argument. The last
2955 argument may actually be any object; an improper list results
2956 if the last argument is not a proper list.
2958 (append '(a b) '(c . d)) @result{} (a b c . d)
2959 (append '() 'a) @result{} a
2964 @c docstring begin (texi-doc-string "guile" "append!")
2965 @deffn primitive append! . args
2966 A destructive version of @code{append} (@pxref{Pairs and Lists,,,r4rs,
2967 The Revised^4 Report on Scheme}). The cdr field of each list's final
2968 pair is changed to point to the head of the next list, so no consing is
2969 performed. Return a pointer to the mutated list.
2972 @c docstring begin (texi-doc-string "guile" "last-pair")
2973 @deffn primitive last-pair lst
2974 Return a pointer to the last pair in @var{lst}, signalling an error if
2975 @var{lst} is circular.
2978 @c docstring begin (texi-doc-string "guile" "reverse")
2979 @deffn primitive reverse lst
2980 Return a new list that contains the elements of @var{lst} but
2984 @c NJFIXME explain new_tail
2985 @c docstring begin (texi-doc-string "guile" "reverse!")
2986 @deffn primitive reverse! lst [new_tail]
2987 A destructive version of @code{reverse} (@pxref{Pairs and Lists,,,r4rs,
2988 The Revised^4 Report on Scheme}). The cdr of each cell in @var{lst} is
2989 modified to point to the previous list element. Return a pointer to the
2990 head of the reversed list.
2992 Caveat: because the list is modified in place, the tail of the original
2993 list now becomes its head, and the head of the original list now becomes
2994 the tail. Therefore, the @var{lst} symbol to which the head of the
2995 original list was bound now points to the tail. To ensure that the head
2996 of the modified list is not lost, it is wise to save the return value of
3000 @c docstring begin (texi-doc-string "guile" "list-ref")
3001 @deffn primitive list-ref list k
3002 Return the @var{k}th element from @var{list}.
3005 @c docstring begin (texi-doc-string "guile" "list-set!")
3006 @deffn primitive list-set! list k val
3007 Set the @var{k}th element of @var{list} to @var{val}.
3010 @c docstring begin (texi-doc-string "guile" "list-tail")
3011 @c docstring begin (texi-doc-string "guile" "list-cdr-ref")
3012 @deffn primitive list-tail lst k
3013 @deffnx primitive list-cdr-ref lst k
3014 Return the "tail" of @var{lst} beginning with its @var{k}th element.
3015 The first element of the list is considered to be element 0.
3017 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
3018 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
3019 or returning the results of cdring @var{k} times down @var{lst}.
3022 @c docstring begin (texi-doc-string "guile" "list-cdr-set!")
3023 @deffn primitive list-cdr-set! list k val
3024 Set the @var{k}th cdr of @var{list} to @var{val}.
3027 @c docstring begin (texi-doc-string "guile" "list-head")
3028 @deffn primitive list-head lst k
3029 Copy the first @var{k} elements from @var{lst} into a new list, and
3033 @c docstring begin (texi-doc-string "guile" "list-copy")
3034 @deffn primitive list-copy lst
3035 Return a (newly-created) copy of @var{lst}.
3038 @c docstring begin (texi-doc-string "guile" "memq")
3039 @deffn primitive memq x lst
3040 Return the first sublist of @var{lst} whose car is @code{eq?}
3041 to @var{x} where the sublists of @var{lst} are the non-empty
3042 lists returned by @code{(list-tail @var{lst} @var{k})} for
3043 @var{k} less than the length of @var{lst}. If @var{x} does not
3044 occur in @var{lst}, then @code{#f} (not the empty list) is
3048 @c docstring begin (texi-doc-string "guile" "memv")
3049 @deffn primitive memv x lst
3050 Return the first sublist of @var{lst} whose car is @code{eqv?}
3051 to @var{x} where the sublists of @var{lst} are the non-empty
3052 lists returned by @code{(list-tail @var{lst} @var{k})} for
3053 @var{k} less than the length of @var{lst}. If @var{x} does not
3054 occur in @var{lst}, then @code{#f} (not the empty list) is
3058 @c docstring begin (texi-doc-string "guile" "member")
3059 @deffn primitive member x lst
3060 Return the first sublist of @var{lst} whose car is
3061 @code{equal?} to @var{x} where the sublists of @var{lst} are
3062 the non-empty lists returned by @code{(list-tail @var{lst}
3063 @var{k})} for @var{k} less than the length of @var{lst}. If
3064 @var{x} does not occur in @var{lst}, then @code{#f} (not the
3065 empty list) is returned.
3068 @c docstring begin (texi-doc-string "guile" "delq")
3069 @deffn primitive delq item lst
3070 Return a newly-created copy of @var{lst} with elements
3071 @code{eq?} to @var{item} removed. This procedure mirrors
3072 @code{memq}: @code{delq} compares elements of @var{lst} against
3073 @var{item} with @code{eq?}.
3076 @c docstring begin (texi-doc-string "guile" "delv")
3077 @deffn primitive delv item lst
3078 Return a newly-created copy of @var{lst} with elements
3079 @code{eqv?} to @var{item} removed. This procedure mirrors
3080 @code{memv}: @code{delv} compares elements of @var{lst} against
3081 @var{item} with @code{eqv?}.
3084 @c docstring begin (texi-doc-string "guile" "delete")
3085 @deffn primitive delete item lst
3086 Return a newly-created copy of @var{lst} with elements
3087 @code{equal?} to @var{item} removed. This procedure mirrors
3088 @code{member}: @code{delete} compares elements of @var{lst}
3089 against @var{item} with @code{equal?}.
3092 @c docstring begin (texi-doc-string "guile" "delq!")
3093 @c docstring begin (texi-doc-string "guile" "delv!")
3094 @c docstring begin (texi-doc-string "guile" "delete!")
3095 @deffn primitive delq! item lst
3096 @deffnx primitive delv! item lst
3097 @deffnx primitive delete! item lst
3098 These procedures are destructive versions of @code{delq}, @code{delv}
3099 and @code{delete}: they modify the pointers in the existing @var{lst}
3100 rather than creating a new list. Caveat evaluator: Like other
3101 destructive list functions, these functions cannot modify the binding of
3102 @var{lst}, and so cannot be used to delete the first element of
3103 @var{lst} destructively.
3106 @c docstring begin (texi-doc-string "guile" "delq1!")
3107 @deffn primitive delq1! item lst
3108 Like @code{delq!}, but only deletes the first occurrence of
3109 @var{item} from @var{lst}. Tests for equality using
3110 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
3113 @c docstring begin (texi-doc-string "guile" "delv1!")
3114 @deffn primitive delv1! item lst
3115 Like @code{delv!}, but only deletes the first occurrence of
3116 @var{item} from @var{lst}. Tests for equality using
3117 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
3120 @c docstring begin (texi-doc-string "guile" "delete1!")
3121 @deffn primitive delete1! item lst
3122 Like @code{delete!}, but only deletes the first occurrence of
3123 @var{item} from @var{lst}. Tests for equality using
3124 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
3127 [FIXME: is there any reason to have the `sloppy' functions available at
3128 high level at all? Maybe these docs should be relegated to a "Guile
3129 Internals" node or something. -twp]
3131 @c docstring begin (texi-doc-string "guile" "sloppy-memq")
3132 @deffn primitive sloppy-memq x lst
3133 This procedure behaves like @code{memq}, but does no type or error checking.
3134 Its use is recommended only in writing Guile internals,
3135 not for high-level Scheme programs.
3138 @c docstring begin (texi-doc-string "guile" "sloppy-memv")
3139 @deffn primitive sloppy-memv x lst
3140 This procedure behaves like @code{memv}, but does no type or error checking.
3141 Its use is recommended only in writing Guile internals,
3142 not for high-level Scheme programs.
3145 @c docstring begin (texi-doc-string "guile" "sloppy-member")
3146 @deffn primitive sloppy-member x lst
3147 This procedure behaves like @code{member}, but does no type or error checking.
3148 Its use is recommended only in writing Guile internals,
3149 not for high-level Scheme programs.
3153 @c begin (texi-doc-string "guile" "map")
3154 @c docstring begin (texi-doc-string "guile" "map-in-order")
3155 @deffn primitive map proc arg1 . args
3156 @deffnx primitive map-in-order proc arg1 . args
3160 @c begin (texi-doc-string "guile" "for-each")
3161 @deffn primitive for-each proc arg1 . args
3168 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3171 A @dfn{record type} is a first class object representing a user-defined
3172 data type. A @dfn{record} is an instance of a record type.
3174 @deffn procedure record? obj
3175 Returns @code{#t} if @var{obj} is a record of any type and @code{#f}
3178 Note that @code{record?} may be true of any Scheme value; there is no
3179 promise that records are disjoint with other Scheme types.
3182 @deffn procedure make-record-type type-name field-names
3183 Returns a @dfn{record-type descriptor}, a value representing a new data
3184 type disjoint from all others. The @var{type-name} argument must be a
3185 string, but is only used for debugging purposes (such as the printed
3186 representation of a record of the new type). The @var{field-names}
3187 argument is a list of symbols naming the @dfn{fields} of a record of the
3188 new type. It is an error if the list contains any duplicates. It is
3189 unspecified how record-type descriptors are represented.@refill
3192 @deffn procedure record-constructor rtd [field-names]
3193 Returns a procedure for constructing new members of the type represented
3194 by @var{rtd}. The returned procedure accepts exactly as many arguments
3195 as there are symbols in the given list, @var{field-names}; these are
3196 used, in order, as the initial values of those fields in a new record,
3197 which is returned by the constructor procedure. The values of any
3198 fields not named in that list are unspecified. The @var{field-names}
3199 argument defaults to the list of field names in the call to
3200 @code{make-record-type} that created the type represented by @var{rtd};
3201 if the @var{field-names} argument is provided, it is an error if it
3202 contains any duplicates or any symbols not in the default list.@refill
3205 @deffn procedure record-predicate rtd
3206 Returns a procedure for testing membership in the type represented by
3207 @var{rtd}. The returned procedure accepts exactly one argument and
3208 returns a true value if the argument is a member of the indicated record
3209 type; it returns a false value otherwise.@refill
3212 @deffn procedure record-accessor rtd field-name
3213 Returns a procedure for reading the value of a particular field of a
3214 member of the type represented by @var{rtd}. The returned procedure
3215 accepts exactly one argument which must be a record of the appropriate
3216 type; it returns the current value of the field named by the symbol
3217 @var{field-name} in that record. The symbol @var{field-name} must be a
3218 member of the list of field-names in the call to @code{make-record-type}
3219 that created the type represented by @var{rtd}.@refill
3222 @deffn procedure record-modifier rtd field-name
3223 Returns a procedure for writing the value of a particular field of a
3224 member of the type represented by @var{rtd}. The returned procedure
3225 accepts exactly two arguments: first, a record of the appropriate type,
3226 and second, an arbitrary Scheme value; it modifies the field named by
3227 the symbol @var{field-name} in that record to contain the given value.
3228 The returned value of the modifier procedure is unspecified. The symbol
3229 @var{field-name} must be a member of the list of field-names in the call
3230 to @code{make-record-type} that created the type represented by
3234 @deffn procedure record-type-descriptor record
3235 Returns a record-type descriptor representing the type of the given
3236 record. That is, for example, if the returned descriptor were passed to
3237 @code{record-predicate}, the resulting predicate would return a true
3238 value when passed the given record. Note that it is not necessarily the
3239 case that the returned descriptor is the one that was passed to
3240 @code{record-constructor} in the call that created the constructor
3241 procedure that created the given record.@refill
3244 @deffn procedure record-type-name rtd
3245 Returns the type-name associated with the type represented by rtd. The
3246 returned value is @code{eqv?} to the @var{type-name} argument given in
3247 the call to @code{make-record-type} that created the type represented by
3251 @deffn procedure record-type-fields rtd
3252 Returns a list of the symbols naming the fields in members of the type
3253 represented by @var{rtd}. The returned value is @code{equal?} to the
3254 field-names argument given in the call to @code{make-record-type} that
3255 created the type represented by @var{rtd}.@refill
3262 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3265 A @dfn{structure type} is a first class user-defined data type. A
3266 @dfn{structure} is an instance of a structure type. A structure type is
3269 Structures are less abstract and more general than traditional records.
3270 In fact, in Guile Scheme, records are implemented using structures.
3273 * Structure Concepts:: The structure of Structures
3274 * Structure Layout:: Defining the layout of structure types
3275 * Structure Basics:: make-, -ref and -set! procedures for structs
3276 * Vtables:: Accessing type-specific data
3279 @node Structure Concepts
3280 @subsection Structure Concepts
3282 A structure object consists of a handle, structure data, and a vtable.
3283 The handle is a Scheme value which points to both the vtable and the
3284 structure's data. Structure data is a dynamically allocated region of
3285 memory, private to the structure, divided up into typed fields. A
3286 vtable is another structure used to hold type-specific data. Multiple
3287 structures can share a common vtable.
3289 Three concepts are key to understanding structures.
3292 @item @dfn{layout specifications}
3294 Layout specifications determine how memory allocated to structures is
3295 divided up into fields. Programmers must write a layout specification
3296 whenever a new type of structure is defined.
3298 @item @dfn{structural accessors}
3300 Structure access is by field number. There is only one set of
3301 accessors common to all structure objects.
3305 Vtables, themselves structures, are first class representations of
3306 disjoint sub-types of structures in general. In most cases, when a
3307 new structure is created, programmers must specifiy a vtable for the
3308 new structure. Each vtable has a field describing the layout of its
3309 instances. Vtables can have additional, user-defined fields as well.
3314 @node Structure Layout
3315 @subsection Structure Layout
3317 When a structure is created, a region of memory is allocated to hold its
3318 state. The @dfn{layout} of the structure's type determines how that
3319 memory is divided into fields.
3321 Each field has a specified type. There are only three types allowed, each
3322 corresponding to a one letter code. The allowed types are:
3325 @item 'u' -- unprotected
3327 The field holds binary data that is not GC protected.
3329 @item 'p' -- protected
3331 The field holds a Scheme value and is GC protected.
3335 The field holds a Scheme value and is GC protected. When a structure is
3336 created with this type of field, the field is initialized to refer to
3337 the structure's own handle. This kind of field is mainly useful when
3338 mixing Scheme and C code in which the C code may need to compute a
3339 structure's handle given only the address of its malloced data.
3343 Each field also has an associated access protection. There are only
3344 three kinds of protection, each corresponding to a one letter code.
3345 The allowed protections are:
3348 @item 'w' -- writable
3350 The field can be read and written.
3352 @item 'r' -- readable
3354 The field can be read, but not written.
3358 The field can be neither read nor written. This kind
3359 of protection is for fields useful only to built-in routines.
3362 A layout specification is described by stringing together pairs
3363 of letters: one to specify a field type and one to specify a field
3364 protection. For example, a traditional cons pair type object could
3368 ; cons pairs have two writable fields of Scheme data
3372 A pair object in which the first field is held constant could be:
3378 Binary fields, (fields of type "u"), hold one @emph{word} each. The
3379 size of a word is a machine dependent value defined to be equal to the
3380 value of the C expression: @code{sizeof (long)}.
3382 The last field of a structure layout may specify a tail array.
3383 A tail array is indicated by capitalizing the field's protection
3384 code ('W', 'R' or 'O'). A tail-array field is replaced by
3385 a read-only binary data field containing an array size. The array
3386 size is determined at the time the structure is created. It is followed
3387 by a corresponding number of fields of the type specified for the
3388 tail array. For example, a conventional Scheme vector can be
3392 ; A vector is an arbitrary number of writable fields holding Scheme
3397 In the above example, field 0 contains the size of the vector and
3398 fields beginning at 1 contain the vector elements.
3400 A kind of tagged vector (a constant tag followed by conventioal
3401 vector elements) might be:
3408 Structure layouts are represented by specially interned symbols whose
3409 name is a string of type and protection codes. To create a new
3410 structure layout, use this procedure:
3412 @c docstring begin (texi-doc-string "guile" "make-struct-layout")
3413 @deffn primitive make-struct-layout fields
3414 Return a new structure layout object.
3416 @var{fields} must be a string made up of pairs of characters
3417 strung together. The first character of each pair describes a field
3418 type, the second a field protection. Allowed types are 'p' for
3419 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
3420 a field that points to the structure itself. Allowed protections
3421 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
3422 fields. The last field protection specification may be capitalized to
3423 indicate that the field is a tail-array.
3428 @node Structure Basics
3429 @subsection Structure Basics
3431 This section describes the basic procedures for creating and accessing
3434 @c docstring begin (texi-doc-string "guile" "make-struct")
3435 @deffn primitive make-struct vtable tail_array_size . init
3436 Create a new structure.
3438 @var{type} must be a vtable structure (@pxref{Vtables}).
3440 @var{tail-elts} must be a non-negative integer. If the layout
3441 specification indicated by @var{type} includes a tail-array,
3442 this is the number of elements allocated to that array.
3444 The @var{init1}, @dots{} are optional arguments describing how
3445 successive fields of the structure should be initialized. Only fields
3446 with protection 'r' or 'w' can be initialized, except for fields of
3447 type 's', which are automatically initialized to point to the new
3448 structure itself; fields with protection 'o' can not be initialized by
3451 If fewer optional arguments than initializable fields are supplied,
3452 fields of type 'p' get default value #f while fields of type 'u' are
3455 Structs are currently the basic representation for record-like data
3456 structures in Guile. The plan is to eventually replace them with a
3457 new representation which will at the same time be easier to use and
3460 For more information, see the documentation for @code{make-vtable-vtable}.
3463 @c docstring begin (texi-doc-string "guile" "struct?")
3464 @deffn primitive struct? x
3465 Return @code{#t} iff @var{obj} is a structure object, else
3470 @c docstring begin (texi-doc-string "guile" "struct-ref")
3471 @c docstring begin (texi-doc-string "guile" "struct-set!")
3472 @deffn primitive struct-ref handle pos
3473 @deffnx primitive struct-set! struct n value
3474 Access (or modify) the @var{n}th field of @var{struct}.
3476 If the field is of type 'p', then it can be set to an arbitrary value.
3478 If the field is of type 'u', then it can only be set to a non-negative
3479 integer value small enough to fit in one machine word.
3487 Vtables are structures that are used to represent structure types. Each
3488 vtable contains a layout specification in field
3489 @code{vtable-index-layout} -- instances of the type are laid out
3490 according to that specification. Vtables contain additional fields
3491 which are used only internally to libguile. The variable
3492 @code{vtable-offset-user} is bound to a field number. Vtable fields
3493 at that position or greater are user definable.
3495 @c docstring begin (texi-doc-string "guile" "struct-vtable")
3496 @deffn primitive struct-vtable handle
3497 Return the vtable structure that describes the type of @var{struct}.
3500 @c docstring begin (texi-doc-string "guile" "struct-vtable?")
3501 @deffn primitive struct-vtable? x
3502 Return @code{#t} iff obj is a vtable structure.
3505 If you have a vtable structure, @code{V}, you can create an instance of
3506 the type it describes by using @code{(make-struct V ...)}. But where
3507 does @code{V} itself come from? One possibility is that @code{V} is an
3508 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
3509 created by using @code{(make-struct V' ...)}. Another possibility is
3510 that @code{V} is an instance of the type it itself describes. Vtable
3511 structures of the second sort are created by this procedure:
3513 @c docstring begin (texi-doc-string "guile" "make-vtable-vtable")
3514 @deffn primitive make-vtable-vtable user_fields tail_array_size . init
3515 Return a new, self-describing vtable structure.
3517 @var{user-fields} is a string describing user defined fields of the
3518 vtable beginning at index @code{vtable-offset-user}
3519 (see @code{make-struct-layout}).
3521 @var{tail-size} specifies the size of the tail-array (if any) of
3524 @var{init1}, @dots{} are the optional initializers for the fields of
3527 Vtables have one initializable system field---the struct printer.
3528 This field comes before the user fields in the initializers passed
3529 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
3530 a third optional argument to @code{make-vtable-vtable} and a fourth to
3531 @code{make-struct} when creating vtables:
3533 If the value is a procedure, it will be called instead of the standard
3534 printer whenever a struct described by this vtable is printed.
3535 The procedure will be called with arguments STRUCT and PORT.
3537 The structure of a struct is described by a vtable, so the vtable is
3538 in essence the type of the struct. The vtable is itself a struct with
3539 a vtable. This could go on forever if it weren't for the
3540 vtable-vtables which are self-describing vtables, and thus terminate
3543 There are several potential ways of using structs, but the standard
3544 one is to use three kinds of structs, together building up a type
3545 sub-system: one vtable-vtable working as the root and one or several
3546 "types", each with a set of "instances". (The vtable-vtable should be
3547 compared to the class <class> which is the class of itself.)
3550 (define ball-root (make-vtable-vtable "pr" 0))
3552 (define (make-ball-type ball-color)
3553 (make-struct ball-root 0
3554 (make-struct-layout "pw")
3556 (format port "#<a ~A ball owned by ~A>"
3560 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
3561 (define (owner ball) (struct-ref ball 0))
3563 (define red (make-ball-type 'red))
3564 (define green (make-ball-type 'green))
3566 (define (make-ball type owner) (make-struct type 0 owner))
3568 (define ball (make-ball green 'Nisse))
3569 ball @result{} #<a green ball owned by Nisse>
3573 @c docstring begin (texi-doc-string "guile" "struct-vtable-name")
3574 @deffn primitive struct-vtable-name vtable
3575 Return the name of the vtable @var{vtable}.
3578 @c docstring begin (texi-doc-string "guile" "set-struct-vtable-name!")
3579 @deffn primitive set-struct-vtable-name! vtable name
3580 Set the name of the vtable @var{vtable} to @var{name}.
3583 @c docstring begin (texi-doc-string "guile" "struct-vtable-tag")
3584 @deffn primitive struct-vtable-tag handle
3585 Return the vtable tag of the structure @var{handle}.
3593 * Conventional Arrays:: Arrays with arbitrary data.
3594 * Array Mapping:: Applying a procedure to the contents of an array.
3595 * Uniform Arrays:: Arrays with data of a single type.
3596 * Bit Vectors:: Vectors of bits.
3599 @node Conventional Arrays
3600 @subsection Conventional Arrays
3602 @dfn{Conventional arrays} are a collection of cells organised into an
3603 arbitrary number of dimensions. Each cell can hold any kind of Scheme
3604 value and can be accessed in constant time by supplying an index for
3605 each dimension. This contrasts with uniform arrays, which use memory
3606 more efficiently but can hold data of only a single type, and lists
3607 where inserting and deleting cells is more efficient, but more time
3608 is usually required to access a particular cell.
3610 A conventional array is displayed as @code{#} followed by the @dfn{rank}
3611 (number of dimensions) followed by the cells, organised into dimensions
3612 using parentheses. The nesting depth of the parentheses is equal to
3615 When an array is created, the number of dimensions and range of each
3616 dimension must be specified, e.g., to create a 2x3 array with a
3620 (make-array 'ho 2 3) @result{}
3621 #2((ho ho ho) (ho ho ho))
3624 The range of each dimension can also be given explicitly, e.g., another
3625 way to create the same array:
3628 (make-array 'ho '(0 1) '(0 2)) @result{}
3629 #2((ho ho ho) (ho ho ho))
3632 A conventional array with one dimension based at zero is identical to
3636 (make-array 'ho 3) @result{}
3640 The following procedures can be used with conventional arrays (or vectors).
3642 @c docstring begin (texi-doc-string "guile" "array?")
3643 @deffn primitive array? v [prot]
3644 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
3646 The @var{prototype} argument is used with uniform arrays and is described
3650 @deffn procedure make-array initial-value bound1 bound2 @dots{}
3651 Creates and returns an array that has as many dimensions as there are
3652 @var{bound}s and fills it with @var{initial-value}.
3655 @c array-ref's type is `compiled-closure'. There's some weird stuff
3656 @c going on in array.c, too. Let's call it a primitive. -twp
3658 @c docstring begin (texi-doc-string "guile" "uniform-vector-ref")
3659 @c docstring begin (texi-doc-string "guile" "array-ref")
3660 @deffn primitive uniform-vector-ref v args
3661 @deffnx primitive array-ref v . args
3662 Returns the element at the @code{(index1, index2)} element in @var{array}.
3665 @c docstring begin (texi-doc-string "guile" "array-in-bounds?")
3666 @deffn primitive array-in-bounds? v . args
3667 Returns @code{#t} if its arguments would be acceptable to array-ref.
3670 @c docstring begin (texi-doc-string "guile" "array-set!")
3671 @c docstring begin (texi-doc-string "guile" "uniform-array-set1!")
3672 @deffn primitive array-set! v obj . args
3673 @deffnx primitive uniform-array-set1! v obj args
3674 Sets the element at the @code{(index1, index2)} element in @var{array} to
3675 @var{new-value}. The value returned by array-set! is unspecified.
3678 @c docstring begin (texi-doc-string "guile" "make-shared-array")
3679 @deffn primitive make-shared-array oldra mapfunc . dims
3680 @code{make-shared-array} can be used to create shared subarrays of other
3681 arrays. The @var{mapper} is a function that translates coordinates in
3682 the new array into coordinates in the old array. A @var{mapper} must be
3683 linear, and its range must stay within the bounds of the old array, but
3684 it can be otherwise arbitrary. A simple example:
3686 (define fred (make-array #f 8 8))
3687 (define freds-diagonal
3688 (make-shared-array fred (lambda (i) (list i i)) 8))
3689 (array-set! freds-diagonal 'foo 3)
3690 (array-ref fred 3 3) @result{} foo
3691 (define freds-center
3692 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
3693 (array-ref freds-center 0 0) @result{} foo
3697 @c docstring begin (texi-doc-string "guile" "shared-array-increments")
3698 @deffn primitive shared-array-increments ra
3699 For each dimension, return the distance between elements in the root vector.
3702 @c docstring begin (texi-doc-string "guile" "shared-array-offset")
3703 @deffn primitive shared-array-offset ra
3704 Return the root vector index of the first element in the array.
3707 @c docstring begin (texi-doc-string "guile" "shared-array-root")
3708 @deffn primitive shared-array-root ra
3709 Return the root vector of a shared array.
3712 @c docstring begin (texi-doc-string "guile" "transpose-array")
3713 @deffn primitive transpose-array ra . args
3714 Returns an array sharing contents with @var{array}, but with dimensions
3715 arranged in a different order. There must be one @var{dim} argument for
3716 each dimension of @var{array}. @var{dim0}, @var{dim1}, @dots{} should
3717 be integers between 0 and the rank of the array to be returned. Each
3718 integer in that range must appear at least once in the argument list.
3720 The values of @var{dim0}, @var{dim1}, @dots{} correspond to dimensions
3721 in the array to be returned, their positions in the argument list to
3722 dimensions of @var{array}. Several @var{dim}s may have the same value,
3723 in which case the returned array will have smaller rank than
3728 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
3729 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
3730 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
3731 #2((a 4) (b 5) (c 6))
3735 @c docstring begin (texi-doc-string "guile" "enclose-array")
3736 @deffn primitive enclose-array ra . axes
3737 @var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
3738 the rank of @var{array}. @var{enclose-array} returns an array
3739 resembling an array of shared arrays. The dimensions of each shared
3740 array are the same as the @var{dim}th dimensions of the original array,
3741 the dimensions of the outer array are the same as those of the original
3742 array that did not match a @var{dim}.
3744 An enclosed array is not a general Scheme array. Its elements may not
3745 be set using @code{array-set!}. Two references to the same element of
3746 an enclosed array will be @code{equal?} but will not in general be
3747 @code{eq?}. The value returned by @var{array-prototype} when given an
3748 enclosed array is unspecified.
3752 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
3753 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
3755 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
3756 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
3760 @deffn procedure array-shape array
3761 Returns a list of inclusive bounds of integers.
3763 (array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
3767 @c docstring begin (texi-doc-string "guile" "array-dimensions")
3768 @deffn primitive array-dimensions ra
3769 @code{Array-dimensions} is similar to @code{array-shape} but replaces
3770 elements with a @code{0} minimum with one greater than the maximum. So:
3772 (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
3776 @c docstring begin (texi-doc-string "guile" "array-rank")
3777 @deffn primitive array-rank ra
3778 Returns the number of dimensions of @var{obj}. If @var{obj} is not an
3779 array, @code{0} is returned.
3782 @c docstring begin (texi-doc-string "guile" "array->list")
3783 @deffn primitive array->list v
3784 Returns a list consisting of all the elements, in order, of @var{array}.
3787 @c docstring begin (texi-doc-string "guile" "array-copy!")
3788 @c docstring begin (texi-doc-string "guile" "array-copy-in-order!")
3789 @deffn primitive array-copy! src dst
3790 @deffnx primitive array-copy-in-order! src dst
3791 Copies every element from vector or array @var{source} to the
3792 corresponding element of @var{destination}. @var{destination} must have
3793 the same rank as @var{source}, and be at least as large in each
3794 dimension. The order is unspecified.
3797 @c docstring begin (texi-doc-string "guile" "array-fill!")
3798 @deffn primitive array-fill! ra fill
3799 Stores @var{fill} in every element of @var{array}. The value returned
3803 @c begin (texi-doc-string "guile" "array-equal?")
3804 @deffn primitive array-equal? ra0 ra1
3805 Returns @code{#t} iff all arguments are arrays with the same shape, the
3806 same type, and have corresponding elements which are either
3807 @code{equal?} or @code{array-equal?}. This function differs from
3808 @code{equal?} in that a one dimensional shared array may be
3809 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
3812 @c docstring begin (texi-doc-string "guile" "array-contents")
3813 @deffn primitive array-contents ra [strict]
3814 @deffnx primitive array-contents array strict
3815 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
3816 without changing their order (last subscript changing fastest), then
3817 @code{array-contents} returns that shared array, otherwise it returns
3818 @code{#f}. All arrays made by @var{make-array} and
3819 @var{make-uniform-array} may be unrolled, some arrays made by
3820 @var{make-shared-array} may not be.
3822 If the optional argument @var{strict} is provided, a shared array will
3823 be returned only if its elements are stored internally contiguous in
3828 @subsection Array Mapping
3830 @c docstring begin (texi-doc-string "guile" "array-map!")
3831 @c docstring begin (texi-doc-string "guile" "array-map-in-order!")
3832 @deffn primitive array-map! ra0 proc . lra
3833 @deffnx primitive array-map-in-order! ra0 proc . lra
3834 @var{array1}, @dots{} must have the same number of dimensions as
3835 @var{array0} and have a range for each index which includes the range
3836 for the corresponding index in @var{array0}. @var{proc} is applied to
3837 each tuple of elements of @var{array1} @dots{} and the result is stored
3838 as the corresponding element in @var{array0}. The value returned is
3839 unspecified. The order of application is unspecified.
3842 @c docstring begin (texi-doc-string "guile" "array-for-each")
3843 @deffn primitive array-for-each proc ra0 . lra
3844 @var{proc} is applied to each tuple of elements of @var{array0} @dots{}
3845 in row-major order. The value returned is unspecified.
3848 @c docstring begin (texi-doc-string "guile" "array-index-map!")
3849 @deffn primitive array-index-map! ra proc
3850 applies @var{proc} to the indices of each element of @var{array} in
3851 turn, storing the result in the corresponding element. The value
3852 returned and the order of application are unspecified.
3854 One can implement @var{array-indexes} as
3856 (define (array-indexes array)
3857 (let ((ra (apply make-array #f (array-shape array))))
3858 (array-index-map! ra (lambda x x))
3863 (define (apl:index-generator n)
3864 (let ((v (make-uniform-vector n 1)))
3865 (array-index-map! v (lambda (i) i))
3870 @node Uniform Arrays
3871 @subsection Uniform Arrays
3874 @dfn{Uniform arrays} have elements all of the
3875 same type and occupy less storage than conventional
3876 arrays. Uniform arrays with a single zero-based dimension
3877 are also known as @dfn{uniform vectors}. The procedures in
3878 this section can also be used on conventional arrays, vectors,
3879 bit-vectors and strings.
3882 When creating a uniform array, the type of data to be stored
3883 is indicated with a @var{prototype} argument. The following table
3884 lists the types available and example prototypes:
3887 prototype type printing character
3889 #t boolean (bit-vector) b
3891 #\nul byte (integer) y
3892 's short (integer) h
3893 1 unsigned long (integer) u
3894 -1 signed long (integer) e
3895 'l signed long long (integer) l
3896 1.0 float (single precision) s
3897 1/3 double (double precision float) i
3898 0+i complex (double precision) c
3899 () conventional vector
3903 Unshared uniform arrays of characters with a single zero-based dimension
3904 are identical to strings:
3907 (make-uniform-array #\a 3) @result{}
3912 Unshared uniform arrays of booleans with a single zero-based dimension
3913 are identical to @ref{Bit Vectors, bit-vectors}.
3916 (make-uniform-array #t 3) @result{}
3921 Other uniform vectors are written in a form similar to that of vectors,
3922 except that a single character from the above table is put between
3923 @code{#} and @code{(}. For example, a uniform vector of signed
3924 long integers is displayed in the form @code{'#e(3 5 9)}.
3926 @c docstring begin (texi-doc-string "guile" "array?")
3927 @deffn primitive array? v [prot]
3928 Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
3930 The @var{prototype} argument is used with uniform arrays and is described
3934 @deffn procedure make-uniform-array prototype bound1 bound2 @dots{}
3935 Creates and returns a uniform array of type corresponding to
3936 @var{prototype} that has as many dimensions as there are @var{bound}s
3937 and fills it with @var{prototype}.
3940 @c docstring begin (texi-doc-string "guile" "array-prototype")
3941 @deffn primitive array-prototype ra
3942 Returns an object that would produce an array of the same type as
3943 @var{array}, if used as the @var{prototype} for
3944 @code{make-uniform-array}.
3947 @c docstring begin (texi-doc-string "guile" "list->uniform-array")
3948 @deffn primitive list->uniform-array ndim prot lst
3949 @deffnx procedure list->uniform-vector prot lst
3950 Returns a uniform array of the type indicated by prototype @var{prot}
3951 with elements the same as those of @var{lst}. Elements must be of the
3952 appropriate type, no coercions are done.
3955 @deffn primitive uniform-vector-fill! uve fill
3956 Stores @var{fill} in every element of @var{uve}. The value returned is
3960 @c docstring begin (texi-doc-string "guile" "uniform-vector-length")
3961 @deffn primitive uniform-vector-length v
3962 Returns the number of elements in @var{uve}.
3965 @c docstring begin (texi-doc-string "guile" "dimensions->uniform-array")
3966 @deffn primitive dimensions->uniform-array dims prot [fill]
3967 @deffnx primitive make-uniform-vector length prototype [fill]
3968 Creates and returns a uniform array or vector of type corresponding to
3969 @var{prototype} with dimensions @var{dims} or length @var{length}. If
3970 @var{fill} is supplied, it's used to fill the array, otherwise
3971 @var{prototype} is used.
3974 @c Another compiled-closure. -twp
3976 @c docstring begin (texi-doc-string "guile" "uniform-array-read!")
3977 @deffn primitive uniform-array-read! ra [port_or_fd [start [end]]]
3978 @deffnx primitive uniform-vector-read! uve [port-or-fdes] [start] [end]
3979 Attempts to read all elements of @var{ura}, in lexicographic order, as
3980 binary objects from @var{port-or-fdes}.
3981 If an end of file is encountered during
3982 uniform-array-read! the objects up to that point only are put into @var{ura}
3983 (starting at the beginning) and the remainder of the array is
3986 The optional arguments @var{start} and @var{end} allow
3987 a specified region of a vector (or linearized array) to be read,
3988 leaving the remainder of the vector unchanged.
3990 @code{uniform-array-read!} returns the number of objects read.
3991 @var{port-or-fdes} may be omitted, in which case it defaults to the value
3992 returned by @code{(current-input-port)}.
3995 @c docstring begin (texi-doc-string "guile" "uniform-array-write")
3996 @deffn primitive uniform-array-write v [port_or_fd [start [end]]]
3997 @deffnx primitive uniform-vector-write uve [port-or-fdes] [start] [end]
3998 Writes all elements of @var{ura} as binary objects to
4001 The optional arguments @var{start}
4003 a specified region of a vector (or linearized array) to be written.
4005 The number of objects actually written is returned.
4006 @var{port-or-fdes} may be
4007 omitted, in which case it defaults to the value returned by
4008 @code{(current-output-port)}.
4012 @subsection Bit Vectors
4015 Bit vectors are a specific type of uniform array: an array of booleans
4016 with a single zero-based index.
4019 They are displayed as a sequence of @code{0}s and
4020 @code{1}s prefixed by @code{#*}, e.g.,
4023 (make-uniform-vector 8 #t #f) @result{}
4026 #b(#t #f #t) @result{}
4030 @c docstring begin (texi-doc-string "guile" "bit-count")
4031 @deffn primitive bit-count b bitvector
4032 Returns the number of occurrences of the boolean @var{b} in
4036 @c docstring begin (texi-doc-string "guile" "bit-position")
4037 @deffn primitive bit-position item v k
4038 Returns the minimum index of an occurrence of @var{bool} in @var{bv}
4039 which is at least @var{k}. If no @var{bool} occurs within the specified
4040 range @code{#f} is returned.
4043 @c docstring begin (texi-doc-string "guile" "bit-invert!")
4044 @deffn primitive bit-invert! v
4045 Modifies @var{bv} by replacing each element with its negation.
4048 @c docstring begin (texi-doc-string "guile" "bit-set*!")
4049 @deffn primitive bit-set*! v kv obj
4050 If uve is a bit-vector @var{bv} and uve must be of the same
4051 length. If @var{bool} is @code{#t}, uve is OR'ed into
4052 @var{bv}; If @var{bool} is @code{#f}, the inversion of uve is
4053 AND'ed into @var{bv}.
4055 If uve is a unsigned integer vector all the elements of uve
4056 must be between 0 and the @code{length} of @var{bv}. The bits
4057 of @var{bv} corresponding to the indexes in uve are set to
4058 @var{bool}. The return value is unspecified.
4061 @c docstring begin (texi-doc-string "guile" "bit-count*")
4062 @deffn primitive bit-count* v kv obj
4065 (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
4067 @var{bv} is not modified.
4071 @node Association Lists and Hash Tables
4072 @section Association Lists and Hash Tables
4074 This chapter discusses dictionary objects: data structures that are
4075 useful for organizing and indexing large bodies of information.
4078 * Dictionary Types:: About dictionary types; what they're good for.
4079 * Association Lists::
4083 @node Dictionary Types
4084 @subsection Dictionary Types
4086 A @dfn{dictionary} object is a data structure used to index
4087 information in a user-defined way. In standard Scheme, the main
4088 aggregate data types are lists and vectors. Lists are not really
4089 indexed at all, and vectors are indexed only by number
4090 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
4091 to index your data on some other type; for example, in a library
4092 catalog you might want to look up a book by the name of its
4093 author. Dictionaries are used to help you organize information in
4096 An @dfn{association list} (or @dfn{alist} for short) is a list of
4097 key-value pairs. Each pair represents a single quantity or
4098 object; the @code{car} of the pair is a key which is used to
4099 identify the object, and the @code{cdr} is the object's value.
4101 A @dfn{hash table} also permits you to index objects with
4102 arbitrary keys, but in a way that makes looking up any one object
4103 extremely fast. A well-designed hash system makes hash table
4104 lookups almost as fast as conventional array or vector references.
4106 Alists are popular among Lisp programmers because they use only
4107 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
4108 and the equality primitives). No changes to the language core are
4109 necessary. Therefore, with Scheme's built-in list manipulation
4110 facilities, it is very convenient to handle data stored in an
4111 association list. Also, alists are highly portable and can be
4112 easily implemented on even the most minimal Lisp systems.
4114 However, alists are inefficient, especially for storing large
4115 quantities of data. Because we want Guile to be useful for large
4116 software systems as well as small ones, Guile provides a rich set
4117 of tools for using either association lists or hash tables.
4119 @node Association Lists
4120 @subsection Association Lists
4121 @cindex Association List
4125 An association list is a conventional data structure that is often used
4126 to implement simple key-value databases. It consists of a list of
4127 entries in which each entry is a pair. The @dfn{key} of each entry is
4128 the @code{car} of the pair and the @dfn{value} of each entry is the
4132 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
4140 Association lists are also known, for short, as @dfn{alists}.
4142 The structure of an association list is just one example of the infinite
4143 number of possible structures that can be built using pairs and lists.
4144 As such, the keys and values in an association list can be manipulated
4145 using the general list structure procedures @code{cons}, @code{car},
4146 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
4147 because association lists are so useful, Guile also provides specific
4148 procedures for manipulating them.
4151 * Alist Key Equality::
4152 * Adding or Setting Alist Entries::
4153 * Retrieving Alist Entries::
4154 * Removing Alist Entries::
4155 * Sloppy Alist Functions::
4159 @node Alist Key Equality
4160 @subsubsection Alist Key Equality
4162 All of Guile's dedicated association list procedures, apart from
4163 @code{acons}, come in three flavours, depending on the level of equality
4164 that is required to decide whether an existing key in the association
4165 list is the same as the key that the procedure call uses to identify the
4170 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
4174 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
4178 Procedures with @dfn{assoc} in their name use @code{equal?} to
4179 determine key equality.
4182 @code{acons} is an exception because it is used to build association
4183 lists which do not require their entries' keys to be unique.
4185 @node Adding or Setting Alist Entries
4186 @subsubsection Adding or Setting Alist Entries
4188 @code{acons} adds a new entry to an association list and returns the
4189 combined association list. The combined alist is formed by consing the
4190 new entry onto the head of the alist specified in the @code{acons}
4191 procedure call. So the specified alist is not modified, but its
4192 contents become shared with the tail of the combined alist that
4193 @code{acons} returns.
4195 In the most common usage of @code{acons}, a variable holding the
4196 original association list is updated with the combined alist:
4199 (set! address-list (acons name address address-list))
4202 In such cases, it doesn't matter that the old and new values of
4203 @code{address-list} share some of their contents, since the old value is
4204 usually no longer independently accessible.
4206 Note that @code{acons} adds the specified new entry regardless of
4207 whether the alist may already contain entries with keys that are, in
4208 some sense, the same as that of the new entry. Thus @code{acons} is
4209 ideal for building alists where there is no concept of key uniqueness.
4212 (set! task-list (acons 3 "pay gas bill" '()))
4215 ((3 . "pay gas bill"))
4217 (set! task-list (acons 3 "tidy bedroom" task-list))
4220 ((3 . "tidy bedroom") (3 . "pay gas bill"))
4223 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
4224 or replace an entry in an association list where there @emph{is} a
4225 concept of key uniqueness. If the specified association list already
4226 contains an entry whose key is the same as that specified in the
4227 procedure call, the existing entry is replaced by the new one.
4228 Otherwise, the new entry is consed onto the head of the old association
4229 list to create the combined alist. In all cases, these procedures
4230 return the combined alist.
4232 @code{assq-set!} and friends @emph{may} destructively modify the
4233 structure of the old association list in such a way that an existing
4234 variable is correctly updated without having to @code{set!} it to the
4240 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
4242 (assoc-set! address-list "james" "1a London Road")
4244 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4248 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4254 (assoc-set! address-list "bob" "11 Newington Avenue")
4256 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4257 ("james" . "1a London Road"))
4261 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4264 The only safe way to update an association list variable when adding or
4265 replacing an entry like this is to @code{set!} the variable to the
4270 (assoc-set! address-list "bob" "11 Newington Avenue"))
4273 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4274 ("james" . "1a London Road"))
4277 Because of this slight inconvenience, you may find it more convenient to
4278 use hash tables to store dictionary data. If your application will not
4279 be modifying the contents of an alist very often, this may not make much
4282 If you need to keep the old value of an association list in a form
4283 independent from the list that results from modification by
4284 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
4285 use @code{list-copy} to copy the old association list before modifying
4288 @c docstring begin (texi-doc-string "guile" "acons")
4289 @deffn primitive acons key value alist
4290 Adds a new key-value pair to @var{alist}. A new pair is
4291 created whose car is @var{key} and whose cdr is @var{value}, and the
4292 pair is consed onto @var{alist}, and the new list is returned. This
4293 function is @emph{not} destructive; @var{alist} is not modified.
4296 @c docstring begin (texi-doc-string "guile" "assq-set!")
4297 @c docstring begin (texi-doc-string "guile" "assv-set!")
4298 @c docstring begin (texi-doc-string "guile" "assoc-set!")
4299 @deffn primitive assq-set! alist key val
4300 @deffnx primitive assv-set! alist key value
4301 @deffnx primitive assoc-set! alist key value
4302 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
4303 @var{alist} entry for @var{key} and associate it with the new
4304 @var{value}. If @var{alist} does not contain an entry for @var{key},
4305 add a new one. Return the (possibly new) alist.
4307 These functions do not attempt to verify the structure of @var{alist},
4308 and so may cause unusual results if passed an object that is not an
4312 @node Retrieving Alist Entries
4313 @subsubsection Retrieving Alist Entries
4318 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
4319 arguments and return the entry for that key if an entry exists, or
4320 @code{#f} if there is no entry for that key. Note that, in the cases
4321 where an entry exists, these procedures return the complete entry, that
4322 is @code{(KEY . VALUE)}, not just the value.
4324 @c docstring begin (texi-doc-string "guile" "assq")
4325 @c docstring begin (texi-doc-string "guile" "assv")
4326 @c docstring begin (texi-doc-string "guile" "assoc")
4327 @deffn primitive assq key alist
4328 @deffnx primitive assv key alist
4329 @deffnx primitive assoc key alist
4330 Fetches the entry in @var{alist} that is associated with @var{key}. To
4331 decide whether the argument @var{key} matches a particular entry in
4332 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
4333 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
4334 cannot be found in @var{alist} (according to whichever equality
4335 predicate is in use), then @code{#f} is returned. These functions
4336 return the entire alist entry found (i.e. both the key and the value).
4339 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
4340 hand, take an alist and a key and return @emph{just the value} for that
4341 key, if an entry exists. If there is no entry for the specified key,
4342 these procedures return @code{#f}.
4344 This creates an ambiguity: if the return value is @code{#f}, it means
4345 either that there is no entry with the specified key, or that there
4346 @emph{is} an entry for the specified key, with value @code{#f}.
4347 Consequently, @code{assq-ref} and friends should only be used where it
4348 is known that an entry exists, or where the ambiguity doesn't matter
4349 for some other reason.
4351 @c docstring begin (texi-doc-string "guile" "assq-ref")
4352 @c docstring begin (texi-doc-string "guile" "assv-ref")
4353 @c docstring begin (texi-doc-string "guile" "assoc-ref")
4354 @deffn primitive assq-ref alist key
4355 @deffnx primitive assv-ref alist key
4356 @deffnx primitive assoc-ref alist key
4357 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
4358 value associated with @var{key} in @var{alist} is returned. These
4359 functions are equivalent to
4362 (let ((ent (@var{associator} @var{key} @var{alist})))
4363 (and ent (cdr ent)))
4366 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
4369 @node Removing Alist Entries
4370 @subsubsection Removing Alist Entries
4372 To remove the element from an association list whose key matches a
4373 specified key, use @code{assq-remove!}, @code{assv-remove!} or
4374 @code{assoc-remove!} (depending, as usual, on the level of equality
4375 required between the key that you specify and the keys in the
4378 As with @code{assq-set!} and friends, the specified alist may or may not
4379 be modified destructively, and the only safe way to update a variable
4380 containing the alist is to @code{set!} it to the value that
4381 @code{assq-remove!} and friends return.
4386 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4387 ("james" . "1a London Road"))
4389 (set! address-list (assoc-remove! address-list "mary"))
4392 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
4395 Note that, when @code{assq/v/oc-remove!} is used to modify an
4396 association list that has been constructed only using the corresponding
4397 @code{assq/v/oc-set!}, there can be at most one matching entry in the
4398 alist, so the question of multiple entries being removed in one go does
4399 not arise. If @code{assq/v/oc-remove!} is applied to an association
4400 list that has been constructed using @code{acons}, or an
4401 @code{assq/v/oc-set!} with a different level of equality, or any mixture
4402 of these, it removes only the first matching entry from the alist, even
4403 if the alist might contain further matching entries. For example:
4406 (define address-list '())
4407 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
4408 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
4411 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
4413 (set! address-list (assoc-remove! address-list "mary"))
4416 (("mary" . "11 Elm Street"))
4419 In this example, the two instances of the string "mary" are not the same
4420 when compared using @code{eq?}, so the two @code{assq-set!} calls add
4421 two distinct entries to @code{address-list}. When compared using
4422 @code{equal?}, both "mary"s in @code{address-list} are the same as the
4423 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
4424 after removing the first matching entry that it finds, and so one of the
4425 "mary" entries is left in place.
4427 @c docstring begin (texi-doc-string "guile" "assq-remove!")
4428 @c docstring begin (texi-doc-string "guile" "assv-remove!")
4429 @c docstring begin (texi-doc-string "guile" "assoc-remove!")
4430 @deffn primitive assq-remove! alist key
4431 @deffnx primitive assv-remove! alist key
4432 @deffnx primitive assoc-remove! alist key
4433 Delete the first entry in @var{alist} associated with @var{key}, and return
4434 the resulting alist.
4437 @node Sloppy Alist Functions
4438 @subsubsection Sloppy Alist Functions
4440 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
4441 like the corresponding non-@code{sloppy-} procedures, except that they
4442 return @code{#f} when the specified association list is not well-formed,
4443 where the non-@code{sloppy-} versions would signal an error.
4445 Specifically, there are two conditions for which the non-@code{sloppy-}
4446 procedures signal an error, which the @code{sloppy-} procedures handle
4447 instead by returning @code{#f}. Firstly, if the specified alist as a
4448 whole is not a proper list:
4451 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4453 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
4454 ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
4455 ABORT: (wrong-type-arg)
4457 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4463 Secondly, if one of the entries in the specified alist is not a pair:
4466 (assoc 2 '((1 . 1) 2 (3 . 9)))
4468 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
4469 ERROR: Wrong type argument in position 2 (expecting CONSP): 2
4470 ABORT: (wrong-type-arg)
4472 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
4477 Unless you are explicitly working with badly formed association lists,
4478 it is much safer to use the non-@code{sloppy-} procedures, because they
4479 help to highlight coding and data errors that the @code{sloppy-}
4480 versions would silently cover up.
4482 @c docstring begin (texi-doc-string "guile" "sloppy-assq")
4483 @deffn primitive sloppy-assq key alist
4484 Behaves like @code{assq} but does not do any error checking.
4485 Recommended only for use in Guile internals.
4488 @c docstring begin (texi-doc-string "guile" "sloppy-assv")
4489 @deffn primitive sloppy-assv key alist
4490 Behaves like @code{assv} but does not do any error checking.
4491 Recommended only for use in Guile internals.
4494 @c docstring begin (texi-doc-string "guile" "sloppy-assoc")
4495 @deffn primitive sloppy-assoc key alist
4496 Behaves like @code{assoc} but does not do any error checking.
4497 Recommended only for use in Guile internals.
4501 @subsubsection Alist Example
4503 Here is a longer example of how alists may be used in practice.
4506 (define capitals '(("New York" . "Albany")
4507 ("Oregon" . "Salem")
4508 ("Florida" . "Miami")))
4510 ;; What's the capital of Oregon?
4511 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
4512 (assoc-ref capitals "Oregon") @result{} "Salem"
4514 ;; We left out South Dakota.
4516 (assoc-set! capitals "South Dakota" "Bismarck"))
4518 @result{} (("South Dakota" . "Bismarck")
4519 ("New York" . "Albany")
4520 ("Oregon" . "Salem")
4521 ("Florida" . "Miami"))
4523 ;; And we got Florida wrong.
4525 (assoc-set! capitals "Florida" "Tallahassee"))
4527 @result{} (("South Dakota" . "Bismarck")
4528 ("New York" . "Albany")
4529 ("Oregon" . "Salem")
4530 ("Florida" . "Tallahassee"))
4532 ;; After Oregon secedes, we can remove it.
4534 (assoc-remove! capitals "Oregon"))
4536 @result{} (("South Dakota" . "Bismarck")
4537 ("New York" . "Albany")
4538 ("Florida" . "Tallahassee"))
4542 @subsection Hash Tables
4544 Like the association list functions, the hash table functions come
4545 in several varieties: @code{hashq}, @code{hashv}, and @code{hash}.
4546 The @code{hashq} functions use @code{eq?} to determine whether two
4547 keys match. The @code{hashv} functions use @code{eqv?}, and the
4548 @code{hash} functions use @code{equal?}.
4550 In each of the functions that follow, the @var{table} argument
4551 must be a vector. The @var{key} and @var{value} arguments may be
4555 @c docstring begin (texi-doc-string "guile" "hashq-ref")
4556 @deffn primitive hashq-ref table obj [dflt]
4557 Look up @var{key} in the hash table @var{table}, and return the
4558 value (if any) associated with it. If @var{key} is not found,
4559 return @var{default} (or @code{#f} if no @var{default} argument
4560 is supplied). Uses @code{eq?} for equality testing.
4564 @c docstring begin (texi-doc-string "guile" "hashv-ref")
4565 @deffn primitive hashv-ref table obj [dflt]
4566 Look up @var{key} in the hash table @var{table}, and return the
4567 value (if any) associated with it. If @var{key} is not found,
4568 return @var{default} (or @code{#f} if no @var{default} argument
4569 is supplied). Uses @code{eqv?} for equality testing.
4573 @c docstring begin (texi-doc-string "guile" "hash-ref")
4574 @deffn primitive hash-ref table obj [dflt]
4575 Look up @var{key} in the hash table @var{table}, and return the
4576 value (if any) associated with it. If @var{key} is not found,
4577 return @var{default} (or @code{#f} if no @var{default} argument
4578 is supplied). Uses @code{equal?} for equality testing.
4582 @c docstring begin (texi-doc-string "guile" "hashq-set!")
4583 @deffn primitive hashq-set! table obj val
4584 Find the entry in @var{table} associated with @var{key}, and
4585 store @var{value} there. Uses @code{eq?} for equality testing.
4589 @c docstring begin (texi-doc-string "guile" "hashv-set!")
4590 @deffn primitive hashv-set! table obj val
4591 Find the entry in @var{table} associated with @var{key}, and
4592 store @var{value} there. Uses @code{eqv?} for equality testing.
4596 @c docstring begin (texi-doc-string "guile" "hash-set!")
4597 @deffn primitive hash-set! table obj val
4598 Find the entry in @var{table} associated with @var{key}, and
4599 store @var{value} there. Uses @code{equal?} for equality
4604 @c docstring begin (texi-doc-string "guile" "hashq-remove!")
4605 @deffn primitive hashq-remove! table obj
4606 Remove @var{key} (and any value associated with it) from
4607 @var{table}. Uses @code{eq?} for equality tests.
4611 @c docstring begin (texi-doc-string "guile" "hashv-remove!")
4612 @deffn primitive hashv-remove! table obj
4613 Remove @var{key} (and any value associated with it) from
4614 @var{table}. Uses @code{eqv?} for equality tests.
4618 @c docstring begin (texi-doc-string "guile" "hash-remove!")
4619 @deffn primitive hash-remove! table obj
4620 Remove @var{key} (and any value associated with it) from
4621 @var{table}. Uses @code{equal?} for equality tests.
4624 The standard hash table functions may be too limited for some
4625 applications. For example, you may want a hash table to store
4626 strings in a case-insensitive manner, so that references to keys
4627 named ``foobar'', ``FOOBAR'' and ``FooBaR'' will all yield the
4628 same item. Guile provides you with @dfn{extended} hash tables
4629 that permit you to specify a hash function and associator function
4630 of your choosing. The functions described in the rest of this section
4631 can be used to implement such custom hash table structures.
4633 If you are unfamiliar with the inner workings of hash tables, then
4634 this facility will probably be a little too abstract for you to
4635 use comfortably. If you are interested in learning more, see an
4636 introductory textbook on data structures or algorithms for an
4637 explanation of how hash tables are implemented.
4639 @c docstring begin (texi-doc-string "guile" "hashq")
4640 @deffn primitive hashq key size
4641 Determine a hash value for @var{key} that is suitable for
4642 lookups in a hashtable of size @var{size}, where @code{eq?} is
4643 used as the equality predicate. The function returns an
4644 integer in the range 0 to @var{size} - 1. Note that
4645 @code{hashq} may use internal addresses. Thus two calls to
4646 hashq where the keys are @code{eq?} are not guaranteed to
4647 deliver the same value if the key object gets garbage collected
4648 in between. This can happen, for example with symbols:
4649 @code{(hashq 'foo n) (gc) (hashq 'foo n)} may produce two
4650 different values, since @code{foo} will be garbage collected.
4653 @c docstring begin (texi-doc-string "guile" "hashv")
4654 @deffn primitive hashv key size
4655 Determine a hash value for @var{key} that is suitable for
4656 lookups in a hashtable of size @var{size}, where @code{eqv?} is
4657 used as the equality predicate. The function returns an
4658 integer in the range 0 to @var{size} - 1. Note that
4659 @code{(hashv key)} may use internal addresses. Thus two calls
4660 to hashv where the keys are @code{eqv?} are not guaranteed to
4661 deliver the same value if the key object gets garbage collected
4662 in between. This can happen, for example with symbols:
4663 @code{(hashv 'foo n) (gc) (hashv 'foo n)} may produce two
4664 different values, since @code{foo} will be garbage collected.
4667 @c docstring begin (texi-doc-string "guile" "hash")
4668 @deffn primitive hash key size
4669 Determine a hash value for @var{key} that is suitable for
4670 lookups in a hashtable of size @var{size}, where @code{equal?}
4671 is used as the equality predicate. The function returns an
4672 integer in the range 0 to @var{size} - 1.
4675 @c ARGFIXME hash/hasher
4676 @c docstring begin (texi-doc-string "guile" "hashx-ref")
4677 @deffn primitive hashx-ref hash assoc table obj [dflt]
4678 This behaves the same way as the corresponding @code{ref}
4679 function, but uses @var{hasher} as a
4680 hash function and @var{assoc} to compare keys. @code{hasher} must
4681 be a function that takes two arguments, a key to be hashed and a
4682 table size. @code{assoc} must be an associator function, like
4683 @code{assoc}, @code{assq} or @code{assv}.
4685 By way of illustration, @code{hashq-ref table key} is equivalent
4686 to @code{hashx-ref hashq assq table key}.
4689 @c docstring begin (texi-doc-string "guile" "hashx-set!")
4690 @deffn primitive hashx-set! hash assoc table obj val
4691 This behaves the same way as the corresponding @code{set!}
4692 function, but uses @var{hasher} as a
4693 hash function and @var{assoc} to compare keys. @code{hasher} must
4694 be a function that takes two arguments, a key to be hashed and a
4695 table size. @code{assoc} must be an associator function, like
4696 @code{assoc}, @code{assq} or @code{assv}.
4698 By way of illustration, @code{hashq-set! table key} is equivalent
4699 to @code{hashx-set! hashq assq table key}.
4702 @c docstring begin (texi-doc-string "guile" "hashq-get-handle")
4703 @deffn primitive hashq-get-handle table obj
4704 This procedure is similar to its @code{-ref} cousin, but returns a
4705 @dfn{handle} from the hash table rather than the value associated with
4706 @var{key}. By convention, a handle in a hash table is the pair which
4707 associates a key with a value. Where @code{hashq-ref table key} returns
4708 only a @code{value}, @code{hashq-get-handle table key} returns the pair
4709 @code{(key . value)}.
4712 @c docstring begin (texi-doc-string "guile" "hashv-get-handle")
4713 @deffn primitive hashv-get-handle table obj
4714 This procedure is similar to its @code{-ref} cousin, but returns a
4715 @dfn{handle} from the hash table rather than the value associated with
4716 @var{key}. By convention, a handle in a hash table is the pair which
4717 associates a key with a value. Where @code{hashv-ref table key} returns
4718 only a @code{value}, @code{hashv-get-handle table key} returns the pair
4719 @code{(key . value)}.
4722 @c docstring begin (texi-doc-string "guile" "hash-get-handle")
4723 @deffn primitive hash-get-handle table obj
4724 This procedure is similar to its @code{-ref} cousin, but returns a
4725 @dfn{handle} from the hash table rather than the value associated with
4726 @var{key}. By convention, a handle in a hash table is the pair which
4727 associates a key with a value. Where @code{hash-ref table key} returns
4728 only a @code{value}, @code{hash-get-handle table key} returns the pair
4729 @code{(key . value)}.
4732 @c docstring begin (texi-doc-string "guile" "hashx-get-handle")
4733 @deffn primitive hashx-get-handle hash assoc table obj
4734 This behaves the same way as the corresponding @code{-get-handle}
4735 function, but uses @var{hasher} as a
4736 hash function and @var{assoc} to compare keys. @code{hasher} must
4737 be a function that takes two arguments, a key to be hashed and a
4738 table size. @code{assoc} must be an associator function, like
4739 @code{assoc}, @code{assq} or @code{assv}.
4742 @c docstring begin (texi-doc-string "guile" "hashq-create-handle!")
4743 @deffn primitive hashq-create-handle! table key init
4744 This function looks up @var{key} in @var{table} and returns its handle.
4745 If @var{key} is not already present, a new handle is created which
4746 associates @var{key} with @var{init}.
4749 @c docstring begin (texi-doc-string "guile" "hashv-create-handle!")
4750 @deffn primitive hashv-create-handle! table key init
4751 This function looks up @var{key} in @var{table} and returns its handle.
4752 If @var{key} is not already present, a new handle is created which
4753 associates @var{key} with @var{init}.
4756 @c docstring begin (texi-doc-string "guile" "hash-create-handle!")
4757 @deffn primitive hash-create-handle! table key init
4758 This function looks up @var{key} in @var{table} and returns its handle.
4759 If @var{key} is not already present, a new handle is created which
4760 associates @var{key} with @var{init}.
4763 @c docstring begin (texi-doc-string "guile" "hashx-create-handle!")
4764 @deffn primitive hashx-create-handle! hash assoc table obj init
4765 This behaves the same way as the corresponding @code{-create-handle}
4766 function, but uses @var{hasher} as a
4767 hash function and @var{assoc} to compare keys. @code{hasher} must
4768 be a function that takes two arguments, a key to be hashed and a
4769 table size. @code{assoc} must be an associator function, like
4770 @code{assoc}, @code{assq} or @code{assv}.
4773 @c docstring begin (texi-doc-string "guile" "hash-fold")
4774 @deffn primitive hash-fold proc init table
4775 An iterator over hash-table elements.
4776 Accumulates and returns a result by applying PROC successively.
4777 The arguments to PROC are "(key value prior-result)" where key
4778 and value are successive pairs from the hash table TABLE, and
4779 prior-result is either INIT (for the first application of PROC)
4780 or the return value of the previous application of PROC.
4781 For example, @code{(hash-fold acons () tab)} will convert a hash
4782 table into an a-list of key-value pairs.
4789 @r5index make-vector
4790 @c docstring begin (texi-doc-string "guile" "make-vector")
4791 @deffn primitive make-vector k [fill]
4792 Returns a newly allocated vector of @var{k} elements. If a second
4793 argument is given, then each element is initialized to @var{fill}.
4794 Otherwise the initial contents of each element is unspecified. (r5rs)
4798 @r5index list->vector
4799 @c docstring begin (texi-doc-string "guile" "vector")
4800 @c docstring begin (texi-doc-string "guile" "list->vector")
4801 @deffn primitive vector . l
4802 @deffnx primitive list->vector l
4803 Returns a newly allocated vector whose elements contain the
4804 given arguments. Analogous to @code{list}. (r5rs)
4807 (vector 'a 'b 'c) @result{} #(a b c)
4811 @r5index vector->list
4812 @c docstring begin (texi-doc-string "guile" "vector->list")
4813 @deffn primitive vector->list v
4814 @samp{Vector->list} returns a newly allocated list of the
4815 objects contained in the elements of @var{vector}. (r5rs)
4818 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
4819 (list->vector '(dididit dah)) @result{} #(dididit dah)
4823 @r5index vector-fill!
4824 @c FIXME::martin: Argument names
4825 @c docstring begin (texi-doc-string "guile" "vector-fill!")
4826 @deffn primitive vector-fill! v fill_x
4827 Stores @var{fill} in every element of @var{vector}.
4828 The value returned by @code{vector-fill!} is unspecified. (r5rs)
4832 @c docstring begin (texi-doc-string "guile" "vector?")
4833 @deffn primitive vector? obj
4834 Returns @code{#t} if @var{obj} is a vector, otherwise returns
4838 @r5index vector-length
4839 @deffn primitive vector-length vector
4840 Returns the number of elements in @var{vector} as an exact integer.
4844 @deffn primitive vector-ref vector k
4845 @var{k} must be a valid index of @var{vector}.
4846 @samp{Vector-ref} returns the contents of element @var{k} of
4849 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
4850 (vector-ref '#(1 1 2 3 5 8 13 21)
4851 (let ((i (round (* 2 (acos -1)))))
4858 @r5index vector-set!
4859 @deffn primitive vector-set! vector k obj
4860 @var{k} must be a valid index of @var{vector}.
4861 @code{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
4862 The value returned by @samp{vector-set!} is unspecified.
4864 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
4865 (vector-set! vec 1 '("Sue" "Sue"))
4866 vec) @result{} #(0 ("Sue" "Sue") "Anna")
4867 (vector-set! '#(0 1 2) 1 "doe") @result{} @emph{error} ; constant vector
4874 @c docstring begin (texi-doc-string "guile" "make-hook-with-name")
4875 @deffn primitive make-hook-with-name name [n_args]
4876 Create a named hook with the name @var{name} for storing
4877 procedures of arity @var{n_args}.
4880 @c docstring begin (texi-doc-string "guile" "make-hook")
4881 @deffn primitive make-hook [n_args]
4882 Create a hook for storing procedure of arity @var{n_args}.
4885 @c docstring begin (texi-doc-string "guile" "hook?")
4886 @deffn primitive hook? x
4887 Return @code{#t} if @var{x} is a hook.
4890 @c docstring begin (texi-doc-string "guile" "hook-empty?")
4891 @deffn primitive hook-empty? hook
4892 Return @code{#t} if @var{hook} is an empty hook.
4895 @c docstring begin (texi-doc-string "guile" "add-hook!")
4896 @deffn primitive add-hook! hook proc [append_p]
4897 Add the procedure @var{proc} to the hook @var{hook}. The
4898 procedure is added to the end if @var{append_p} is true,
4899 otherwise it is added to the front.
4902 @c docstring begin (texi-doc-string "guile" "remove-hook!")
4903 @deffn primitive remove-hook! hook proc
4904 Remove the procedure @var{proc} from the hook @var{hook}.
4907 @c docstring begin (texi-doc-string "guile" "reset-hook!")
4908 @deffn primitive reset-hook! hook
4909 Remove all procedures from the hook @var{hook}.
4912 @c docstring begin (texi-doc-string "guile" "run-hook")
4913 @deffn primitive run-hook hook . args
4914 Apply all procedures from the hook @var{hook} to the arguments
4918 @c docstring begin (texi-doc-string "guile" "hook->list")
4919 @deffn primitive hook->list hook
4920 Convert the procedure list of @var{hook} to a list.
4924 @node Other Data Types
4925 @section Other Core Guile Data Types
4929 @c TeX-master: "guile.texi"