* Automatic docstring updates.
[bpt/guile.git] / doc / scheme-data.texi
1 @page
2 @node Data Types
3 @chapter Data Types for Generic Use
4
5 This chapter describes all the data types that Guile provides for
6 ``generic use''.
7
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
11
12 @itemize
13 @item
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
17
18 @item
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
21 module system.
22 @end itemize
23
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
28 @emph{functionality}.
29
30 @ifinfo
31 The following menu
32 @end ifinfo
33 @iftex
34 The table of contents for this chapter
35 @end iftex
36 @ifhtml
37 The following table of contents
38 @end ifhtml
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.
43
44 @menu
45 * Booleans:: True/false values.
46 * Numbers:: Numerical data types.
47 * Characters:: New character names.
48 * Strings:: Special things about strings.
49 * Regular Expressions:: Pattern matching and substitution.
50 * Symbols and Variables:: Manipulating the Scheme symbol table.
51 * Keywords:: Self-quoting, customizable display keywords.
52 * Pairs:: Scheme's basic building block.
53 * Lists:: Special list functions supported by Guile.
54 * Records::
55 * Structures::
56 * Arrays::
57 * Association Lists and Hash Tables::
58 * Vectors::
59 * Hooks:: User-customizable event lists.
60 * Other Data Types:: Data types that are documented elsewhere.
61 @end menu
62
63
64 @node Booleans
65 @section Booleans
66 @r5index not
67 @r5index boolean?
68
69 The two boolean values are @code{#t} for true and @code{#f} for false.
70
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).
75
76 @lisp
77 (<= 3 8)
78 @result{}
79 #t
80
81 (<= 3 -3)
82 @result{}
83 #f
84
85 (equal? "house" "houses")
86 @result{}
87 #f
88
89 (eq? #f #f)
90 @result{}
91 #t
92 @end lisp
93
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}.
98
99 @lisp
100 (if #t "yes" "no")
101 @result{}
102 "yes"
103
104 (if 0 "yes" "no")
105 @result{}
106 "yes"
107
108 (if #f "yes" "no")
109 @result{}
110 "no"
111 @end lisp
112
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.
117
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).
122
123 The @code{not} procedure returns the boolean inverse of its argument:
124
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}.
128 @end deffn
129
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}.
132
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}.
136 @end deffn
137
138
139 @node Numbers
140 @section Numerical data types
141
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.
146
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}.
150
151 @menu
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.
167 @end menu
168
169
170 @node Numerical Tower
171 @subsection Scheme's Numerical ``Tower''
172 @r5index number?
173
174 Scheme's numerical ``tower'' consists of the following categories of
175 numbers:
176
177 @itemize
178 @item
179 integers (whole numbers)
180
181 @item
182 rationals (the set of numbers that can be expressed as P/Q where P and Q
183 are integers)
184
185 @item
186 real numbers (the set of numbers that describes all possible positions
187 along a one dimensional line)
188
189 @item
190 complex numbers (the set of numbers that describes all possible
191 positions in a two dimensional space)
192 @end itemize
193
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).
198
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.
203
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.
206
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.
210 @end deffn
211
212 For example:
213
214 @lisp
215 (number? 3)
216 @result{}
217 #t
218
219 (number? "hello there!")
220 @result{}
221 #f
222
223 (define pi 3.141592654)
224 (number? pi)
225 @result{}
226 #t
227 @end lisp
228
229 The next few subsections document each of Guile's numerical data types
230 in detail.
231
232
233 @node Integers
234 @subsection Integers
235 @r5index integer?
236
237 Integers are whole numbers, that is numbers with no fractional part,
238 such as 2, 83 and -3789.
239
240 Integers in Guile can be arbitrarily big, as shown by the following
241 example.
242
243 @lisp
244 (define (factorial n)
245 (let loop ((n n) (product 1))
246 (if (= n 0)
247 product
248 (loop (- n 1) (* product n)))))
249
250 (factorial 3)
251 @result{}
252 6
253
254 (factorial 20)
255 @result{}
256 2432902008176640000
257
258 (- (factorial 45))
259 @result{}
260 -119622220865480194561963161495657715064383733760000000000
261 @end lisp
262
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.
272
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
275
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.
279
280 @lisp
281 (integer? 487)
282 @result{}
283 #t
284
285 (integer? -3.4)
286 @result{}
287 #f
288 @end lisp
289 @end deffn
290
291
292 @node Reals and Rationals
293 @subsection Real and Rational Numbers
294 @r5index real?
295 @r5index rational?
296
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.
303
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:
310
311 @lisp
312 0.34
313 -0.00000142857931198
314 -5648394822220000000000.0
315 4.0
316 @end lisp
317
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.
324
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
329 size integers.
330
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.
336
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.
343 @end deffn
344
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
352 precision.
353 @end deffn
354
355
356 @node Complex Numbers
357 @subsection Complex Numbers
358 @r5index complex?
359
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.
364
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
367 the imaginary part.
368
369 @lisp
370 3+4i
371 @result{}
372 3.0+4.0i
373
374 (* 3-8i 2.3+0.3i)
375 @result{}
376 9.3-17.5i
377 @end lisp
378
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.
382
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.
390 @end deffn
391
392
393 @node Exactness
394 @subsection Exact and Inexact Numbers
395 @r5index exact?
396 @r5index inexact?
397 @r5index exact->inexact
398 @r5index inexact->exact
399
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.
407
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}
411 otherwise.
412 @end deffn
413
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}
417 else.
418 @end deffn
419
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}.
423 @end deffn
424
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.
428 @end deffn
429
430
431 @node Number Syntax
432 @subsection Read Syntax for Numerical Data
433
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:
438
439 @itemize @bullet
440 @item
441 @code{#b}, @code{#B} --- the integer is written in binary (base 2)
442
443 @item
444 @code{#o}, @code{#O} --- the integer is written in octal (base 8)
445
446 @item
447 @code{#d}, @code{#D} --- the integer is written in decimal (base 10)
448
449 @item
450 @code{#x}, @code{#X} --- the integer is written in hexadecimal (base 16).
451 @end itemize
452
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.
455
456 @lisp
457 -13
458 @result{}
459 -13
460
461 #d-13
462 @result{}
463 -13
464
465 #x-13
466 @result{}
467 -19
468
469 #b+1101
470 @result{}
471 13
472
473 #o377
474 @result{}
475 255
476 @end lisp
477
478 The codes for indicating exactness (which can, incidentally, be applied
479 to all numerical values) are:
480
481 @itemize @bullet
482 @item
483 @code{#e}, @code{#E} --- the number is exact
484
485 @item
486 @code{#i}, @code{#I} --- the number is inexact.
487 @end itemize
488
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
495 multiplying by 10^N.
496
497
498 @node Integer Operations
499 @subsection Operations on Integer Values
500 @r5index odd?
501 @r5index even?
502 @r5index quotient
503 @r5index remainder
504 @r5index modulo
505 @r5index gcd
506 @r5index lcm
507
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}
511 otherwise.
512 @end deffn
513
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}
517 otherwise.
518 @end deffn
519
520 @c begin (texi-doc-string "guile" "quotient")
521 @deffn primitive quotient
522 Return the quotient of the numbers @var{x} and @var{y}.
523 @end deffn
524
525 @c begin (texi-doc-string "guile" "remainder")
526 @deffn primitive remainder
527 Return the remainder of the numbers @var{x} and @var{y}.
528 @lisp
529 (remainder 13 4) @result{} 1
530 (remainder -13 4) @result{} -1
531 @end lisp
532 @end deffn
533
534 @c begin (texi-doc-string "guile" "modulo")
535 @deffn primitive modulo
536 Return the modulo of the numbers @var{x} and @var{y}.
537 @lisp
538 (modulo 13 4) @result{} 1
539 (modulo -13 4) @result{} 3
540 @end lisp
541 @end deffn
542
543 @c begin (texi-doc-string "guile" "gcd")
544 @deffn primitive gcd
545 Return the greatest common divisor of all arguments.
546 If called without arguments, 0 is returned.
547 @end deffn
548
549 @c begin (texi-doc-string "guile" "lcm")
550 @deffn primitive lcm
551 Return the least common multiple of the arguments.
552 If called without arguments, 1 is returned.
553 @end deffn
554
555
556 @node Comparison
557 @subsection Comparison Predicates
558 @r5index zero?
559 @r5index positive?
560 @r5index negative?
561
562 @c begin (texi-doc-string "guile" "=")
563 @deffn primitive =
564 Return @code{#t} if all parameters are numerically equal.
565 @end deffn
566
567 @c begin (texi-doc-string "guile" "<")
568 @deffn primitive <
569 Return @code{#t} if the list of parameters is monotonically
570 increasing.
571 @end deffn
572
573 @c begin (texi-doc-string "guile" ">")
574 @deffn primitive >
575 Return @code{#t} if the list of parameters is monotonically
576 decreasing.
577 @end deffn
578
579 @c begin (texi-doc-string "guile" "<=")
580 @deffn primitive <=
581 Return @code{#t} if the list of parameters is monotonically
582 non-decreasing.
583 @end deffn
584
585 @c begin (texi-doc-string "guile" ">=")
586 @deffn primitive >=
587 Return @code{#t} if the list of parameters is monotonically
588 non-increasing.
589 @end deffn
590
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
594 zero.
595 @end deffn
596
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
600 zero.
601 @end deffn
602
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
606 zero.
607 @end deffn
608
609
610 @node Conversion
611 @subsection Converting Numbers To and From Strings
612 @r5index number->string
613 @r5index string->number
614
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.
620 @end deffn
621
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}.
632 @end deffn
633
634
635 @node Complex
636 @subsection Complex Number Operations
637 @r5index make-rectangular
638 @r5index make-polar
639 @r5index real-part
640 @r5index imag-part
641 @r5index magnitude
642 @r5index angle
643
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.
648 @end deffn
649
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}).
653 @end deffn
654
655 @c begin (texi-doc-string "guile" "real-part")
656 @deffn primitive real-part
657 Return the real part of the number @var{z}.
658 @end deffn
659
660 @c begin (texi-doc-string "guile" "imag-part")
661 @deffn primitive imag-part
662 Return the imaginary part of the number @var{z}.
663 @end deffn
664
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.
669 @end deffn
670
671 @c begin (texi-doc-string "guile" "angle")
672 @deffn primitive angle
673 Return the angle of the complex number @var{z}.
674 @end deffn
675
676
677 @node Arithmetic
678 @subsection Arithmetic Functions
679 @r5index max
680 @r5index min
681 @r5index +
682 @r5index *
683 @r5index -
684 @r5index /
685 @r5index abs
686 @r5index floor
687 @r5index ceiling
688 @r5index truncate
689 @r5index round
690
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
694 parameters.
695 @end deffn
696
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.
701 @end deffn
702
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
706 returned.
707 @end deffn
708
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.
712 @end deffn
713
714 @c begin (texi-doc-string "guile" "abs")
715 @deffn primitive abs x
716 Return the absolute value of @var{x}.
717 @end deffn
718
719 @c begin (texi-doc-string "guile" "max")
720 @deffn primitive max x1 x2 @dots{}
721 Return the maximum of all parameter values.
722 @end deffn
723
724 @c begin (texi-doc-string "guile" "min")
725 @deffn primitive min x1 x2 @dots{}
726 Return the minium of all parameter values.
727 @end deffn
728
729 @c begin (texi-doc-string "guile" "truncate")
730 @deffn primitive truncate
731 Round the inexact number @var{x} towards zero.
732 @end deffn
733
734 @c begin (texi-doc-string "guile" "round")
735 @deffn primitive round x
736 Round the inexact number @var{x} towards zero.
737 @end deffn
738
739 @c begin (texi-doc-string "guile" "floor")
740 @deffn primitive floor x
741 Round the number @var{x} towards minus infinity.
742 @end deffn
743
744 @c begin (texi-doc-string "guile" "ceiling")
745 @deffn primitive ceiling x
746 Round the number @var{x} towards infinity.
747 @end deffn
748
749
750 @node Scientific
751 @subsection Scientific Functions
752 @r5index exp
753 @r5index log
754 @r5index sin
755 @r5index cos
756 @r5index tan
757 @r5index asin
758 @r5index acos
759 @r5index atan
760 @r5index sqrt
761 @r5index expt
762
763 The following procedures accept any kind of number as arguments,
764 including complex numbers.
765
766 @c begin (texi-doc-string "guile" "sqrt")
767 @deffn procedure sqrt z
768 Return the square root of @var{z}.
769 @end deffn
770
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}.
774 @end deffn
775
776 @c begin (texi-doc-string "guile" "sin")
777 @deffn procedure sin z
778 Return the sine of @var{z}.
779 @end deffn
780
781 @c begin (texi-doc-string "guile" "cos")
782 @deffn procedure cos z
783 Return the cosine of @var{z}.
784 @end deffn
785
786 @c begin (texi-doc-string "guile" "tan")
787 @deffn procedure tan z
788 Return the tangent of @var{z}.
789 @end deffn
790
791 @c begin (texi-doc-string "guile" "asin")
792 @deffn procedure asin z
793 Return the arcsine of @var{z}.
794 @end deffn
795
796 @c begin (texi-doc-string "guile" "acos")
797 @deffn procedure acos z
798 Return the arccosine of @var{z}.
799 @end deffn
800
801 @c begin (texi-doc-string "guile" "atan")
802 @deffn procedure atan z
803 Return the arctangent of @var{z}.
804 @end deffn
805
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{}).
810 @end deffn
811
812 @c begin (texi-doc-string "guile" "log")
813 @deffn procedure log z
814 Return the natural logarithm of @var{z}.
815 @end deffn
816
817 @c begin (texi-doc-string "guile" "log10")
818 @deffn procedure log10 z
819 Return the base 10 logarithm of @var{z}.
820 @end deffn
821
822 @c begin (texi-doc-string "guile" "sinh")
823 @deffn procedure sinh z
824 Return the hyperbolic sine of @var{z}.
825 @end deffn
826
827 @c begin (texi-doc-string "guile" "cosh")
828 @deffn procedure cosh z
829 Return the hyperbolic cosine of @var{z}.
830 @end deffn
831
832 @c begin (texi-doc-string "guile" "tanh")
833 @deffn procedure tanh z
834 Return the hyperbolic tangent of @var{z}.
835 @end deffn
836
837 @c begin (texi-doc-string "guile" "asinh")
838 @deffn procedure asinh z
839 Return the hyperbolic arcsine of @var{z}.
840 @end deffn
841
842 @c begin (texi-doc-string "guile" "acosh")
843 @deffn procedure acosh z
844 Return the hyperbolic arccosine of @var{z}.
845 @end deffn
846
847 @c begin (texi-doc-string "guile" "atanh")
848 @deffn procedure atanh z
849 Return the hyperbolic arctangent of @var{z}.
850 @end deffn
851
852
853 @node Primitive Numerics
854 @subsection Primitive Numeric Functions
855
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.
860
861 @c begin (texi-doc-string "guile" "$abs")
862 @deffn primitive $abs x
863 Return the absolute value of @var{x}.
864 @end deffn
865
866 @c begin (texi-doc-string "guile" "$sqrt")
867 @deffn primitive $sqrt x
868 Return the square root of @var{x}.
869 @end deffn
870
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.
875 @end deffn
876
877 @c begin (texi-doc-string "guile" "$sin")
878 @deffn primitive $sin x
879 Return the sine of @var{x}.
880 @end deffn
881
882 @c begin (texi-doc-string "guile" "$cos")
883 @deffn primitive $cos x
884 Return the cosine of @var{x}.
885 @end deffn
886
887 @c begin (texi-doc-string "guile" "$tan")
888 @deffn primitive $tan x
889 Return the tangent of @var{x}.
890 @end deffn
891
892 @c begin (texi-doc-string "guile" "$asin")
893 @deffn primitive $asin x
894 Return the arcsine of @var{x}.
895 @end deffn
896
897 @c begin (texi-doc-string "guile" "$acos")
898 @deffn primitive $acos x
899 Return the arccosine of @var{x}.
900 @end deffn
901
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.
905 @end deffn
906
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.
914 @end deffn
915
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{}).
920 @end deffn
921
922 @c begin (texi-doc-string "guile" "$log")
923 @deffn primitive $log x
924 Return the natural logarithm of @var{x}.
925 @end deffn
926
927 @c begin (texi-doc-string "guile" "$sinh")
928 @deffn primitive $sinh x
929 Return the hyperbolic sine of @var{x}.
930 @end deffn
931
932 @c begin (texi-doc-string "guile" "$cosh")
933 @deffn primitive $cosh x
934 Return the hyperbolic cosine of @var{x}.
935 @end deffn
936
937 @c begin (texi-doc-string "guile" "$tanh")
938 @deffn primitive $tanh x
939 Return the hyperbolic tangent of @var{x}.
940 @end deffn
941
942 @c begin (texi-doc-string "guile" "$asinh")
943 @deffn primitive $asinh x
944 Return the hyperbolic arcsine of @var{x}.
945 @end deffn
946
947 @c begin (texi-doc-string "guile" "$acosh")
948 @deffn primitive $acosh x
949 Return the hyperbolic arccosine of @var{x}.
950 @end deffn
951
952 @c begin (texi-doc-string "guile" "$atanh")
953 @deffn primitive $atanh x
954 Return the hyperbolic arctangent of @var{x}.
955 @end deffn
956
957
958 @node Bitwise Operations
959 @subsection Bitwise Operations
960
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
964 arguments.
965
966 Example:
967 @lisp
968 (number->string (logand #b1100 #b1010) 2)
969 @result{} "1000"
970 @end lisp
971 @end deffn
972
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
976 arguments.
977
978 Example:
979 @lisp
980 (number->string (logior #b1100 #b1010) 2)
981 @result{} "1110"
982 @end lisp
983 @end deffn
984
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
988 arguments.
989
990 Example:
991 @lisp
992 (number->string (logxor #b1100 #b1010) 2)
993 @result{} "110"
994 @end lisp
995 @end deffn
996
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.
1000
1001 Example:
1002 @lisp
1003 (number->string (lognot #b10000000) 2)
1004 @result{} "-10000001"
1005 (number->string (lognot #b0) 2)
1006 @result{} "-1"
1007 @end lisp
1008 @end deffn
1009
1010 @c ARGFIXME j/n1 k/n2
1011 @c docstring begin (texi-doc-string "guile" "logtest")
1012 @deffn primitive logtest n1 n2
1013 @example
1014 (logtest j k) @equiv{} (not (zero? (logand j k)))
1015
1016 (logtest #b0100 #b1011) @result{} #f
1017 (logtest #b0100 #b0111) @result{} #t
1018 @end example
1019 @end deffn
1020
1021 @c docstring begin (texi-doc-string "guile" "logbit?")
1022 @deffn primitive logbit? index j
1023 @example
1024 (logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1025
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
1031 @end example
1032 @end deffn
1033
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.
1044
1045 Formally, the function returns an integer equivalent to
1046 @code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
1047
1048 Example:
1049 @lisp
1050 (number->string (ash #b1 3) 2)
1051 @result{} "1000"
1052 (number->string (ash #b1010 -1) 2)
1053 @result{} "101"
1054 @end lisp
1055 @end deffn
1056
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,
1062 0 is returned.
1063
1064 Example:
1065 @lisp
1066 (logcount #b10101010)
1067 @result{} 4
1068 (logcount 0)
1069 @result{} 0
1070 (logcount -2)
1071 @result{} 1
1072 @end lisp
1073 @end deffn
1074
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}.
1078
1079 Example:
1080 @lisp
1081 (integer-length #b10101010)
1082 @result{} 8
1083 (integer-length 0)
1084 @result{} 0
1085 (integer-length #b1111)
1086 @result{} 4
1087 @end lisp
1088 @end deffn
1089
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}.
1093
1094 Example:
1095 @lisp
1096 (integer-expt 2 5)
1097 @result{} 32
1098 (integer-expt -3 3)
1099 @result{} -27
1100 @end lisp
1101 @end deffn
1102
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
1108
1109 Example:
1110 @lisp
1111 (number->string (bit-extract #b1101101010 0 4) 2)
1112 @result{} "1010"
1113 (number->string (bit-extract #b1101101010 4 9) 2)
1114 @result{} "10110"
1115 @end lisp
1116 @end deffn
1117
1118
1119 @node Random
1120 @subsection Random Number Generation
1121
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}.
1125 @end deffn
1126
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
1133 distribution.
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.
1139 @end deffn
1140
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)).
1145 @end deffn
1146
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
1154 unit n-shere.
1155 @end deffn
1156
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)))}.
1163 @end deffn
1164
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).
1170 @end deffn
1171
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.
1180 @end deffn
1181
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).
1185 @end deffn
1186
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}.
1190 @end deffn
1191
1192
1193 @node Characters
1194 @section Characters
1195 @r5index char?
1196 @r5index char=?
1197 @r5index char<?
1198 @r5index char>?
1199 @r5index char<=?
1200 @r5index char>=?
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
1210
1211
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.
1215
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}
1250 @end multitable
1251
1252 The @code{delete} character (octal 177) may be referred to with the name
1253 @code{#\del}.
1254
1255 Several characters have more than one name:
1256
1257 @itemize @bullet
1258 @item
1259 #\space, #\sp
1260 @item
1261 #\newline, #\nl
1262 @item
1263 #\tab, #\ht
1264 @item
1265 #\backspace, #\bs
1266 @item
1267 #\return, #\cr
1268 @item
1269 #\page, #\np
1270 @item
1271 #\null, #\nul
1272 @end itemize
1273
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}.
1277 @end deffn
1278
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}.
1282 @end deffn
1283
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,
1287 else @code{#f}.
1288 @end deffn
1289
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}.
1294 @end deffn
1295
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}.
1300 @end deffn
1301
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}.
1306 @end deffn
1307
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}.
1312 @end deffn
1313
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}.
1318 @end deffn
1319
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}.
1324 @end deffn
1325
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}.
1330 @end deffn
1331
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}.
1336 @end deffn
1337
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.
1342 @end deffn
1343
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.
1348 @end deffn
1349
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.
1354 @end deffn
1355
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.
1360 @end deffn
1361
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.
1366 @end deffn
1367
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.
1373 @end deffn
1374
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
1378 ASCII sequence.
1379 @end deffn
1380
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.
1384 @end deffn
1385
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}.
1389 @end deffn
1390
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}.
1394 @end deffn
1395
1396
1397 @node Strings
1398 @section Strings
1399
1400 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
1401 be reviewed]
1402
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.
1408
1409 @menu
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.
1413 @end menu
1414
1415 @node String Fun
1416 @subsection String Fun
1417
1418 @r5index string
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,
1425 @var{chrs}.
1426 @end deffn
1427
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.
1435 @end deffn
1436
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}.
1442 @end deffn
1443
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}.
1448 @end deffn
1449
1450 @r5index string-ref
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}.
1455 @end deffn
1456
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
1462 @var{str}.
1463 @end deffn
1464
1465 @r5index string?
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
1469 @code{#f}.
1470 @end deffn
1471
1472 @r5index substring
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:
1480
1481 0 <= @var{start} <= @var{end} <= (string-length @var{str}).
1482 @end deffn
1483
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.
1490
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).
1495
1496 @example
1497 (string-index "weiner" #\e)
1498 @result{} 1
1499
1500 (string-index "weiner" #\e 2)
1501 @result{} 4
1502
1503 (string-index "weiner" #\e 2 4)
1504 @result{} #f
1505 @end example
1506 @end deffn
1507
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.
1513
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
1516 the entire string.
1517
1518 @example
1519 (string-rindex "weiner" #\e)
1520 @result{} 4
1521
1522 (string-rindex "weiner" #\e 2 4)
1523 @result{} #f
1524
1525 (string-rindex "weiner" #\e 2 5)
1526 @result{} 4
1527 @end example
1528 @end deffn
1529
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.
1541
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.
1552 @end deffn
1553
1554 @deffn primitive substring-move-left! str1 start1 end1 str2 start2
1555 @end deffn
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].
1558
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.
1562
1563 @example
1564 (define x (make-string 10 #\a))
1565 (define y "bcd")
1566 (substring-move-left! x 2 5 y 0)
1567 y
1568 @result{} "aaa"
1569
1570 x
1571 @result{} "aaaaaaaaaa"
1572
1573 (define y "bcdefg")
1574 (substring-move-left! x 2 5 y 0)
1575 y
1576 @result{} "aaaefg"
1577
1578 (define y "abcdefg")
1579 (substring-move-left! y 2 5 y 3)
1580 y
1581 @result{} "abccccg"
1582 @end example
1583 @end deftypefn
1584
1585 @deffn substring-move-right! str1 start1 end1 str2 start2
1586 @end deffn
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].
1590
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.
1593 @example
1594 (define y "abcdefg")
1595 (substring-move-right! y 2 5 y 0)
1596 y
1597 @result{} "ededefg"
1598
1599 (define y "abcdefg")
1600 (substring-move-right! y 2 5 y 3)
1601 y
1602 @result{} "abccdeg"
1603 @end example
1604 @end deftypefn
1605
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!}.
1609 @end deffn
1610
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!}.
1614 @end deffn
1615
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
1620 @var{fill-char}.
1621
1622 (qdocs:) Destructively fills @var{str}, from @var{start} to @var{end}, with @var{fill}.
1623
1624 @example
1625 (define y "abcdefg")
1626 (substring-fill! y 1 3 #\r)
1627 y
1628 @result{} "arrdefg"
1629 @end example
1630 @end deffn
1631
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}
1635 otherwise.
1636
1637 (qdocs:) Returns @code{#t} if @var{str} is empty, else returns @code{#f}.
1638
1639 @example
1640 (string-null? "")
1641 @result{} #t
1642
1643 (string-null? y)
1644 @result{} #f
1645 @end example
1646 @end deffn
1647
1648 @c ARGFIXME v/str
1649 @c docstring begin (texi-doc-string "guile" "string-upcase!")
1650 @deffn primitive string-upcase! str
1651 Destructively upcase every character in @code{str}.
1652
1653 (qdocs:) Converts each element in @var{str} to upper case.
1654
1655 @example
1656 (string-upcase! y)
1657 @result{} "ARRDEFG"
1658
1659 y
1660 @result{} "ARRDEFG"
1661 @end example
1662 @end deffn
1663
1664 @c docstring begin (texi-doc-string "guile" "string-upcase")
1665 @deffn primitive string-upcase str
1666 Upcase every character in @code{str}.
1667 @end deffn
1668
1669 @c ARGFIXME v/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}.
1673
1674 (qdocs:) Converts each element in @var{str} to lower case.
1675
1676 @example
1677 y
1678 @result{} "ARRDEFG"
1679
1680 (string-downcase! y)
1681 @result{} "arrdefg"
1682
1683 y
1684 @result{} "arrdefg"
1685 @end example
1686 @end deffn
1687
1688 @c docstring begin (texi-doc-string "guile" "string-downcase")
1689 @deffn primitive string-downcase str
1690 Downcase every character in @code{str}.
1691 @end deffn
1692
1693 @c docstring begin (texi-doc-string "guile" "string-capitalize!")
1694 @deffn primitive string-capitalize! str
1695 Destructively capitalize every character in @code{str}.
1696 @end deffn
1697
1698 @c docstring begin (texi-doc-string "guile" "string-capitalize")
1699 @deffn primitive string-capitalize str
1700 Capitalize every character in @code{str}.
1701 @end deffn
1702
1703 @r5index string<=?
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)
1709 @end deffn
1710
1711 @r5index string-ci<
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)
1717 @end deffn
1718
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)
1726 @end deffn
1727
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)
1734 @end deffn
1735
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)
1742 @end deffn
1743
1744 @r5index string<=?
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}.
1749 (r5rs)
1750 @end deffn
1751
1752 @r5index string<?
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)
1757 @end deffn
1758
1759 @r5index string=?
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)
1766
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
1770 characters.
1771 @end deffn
1772
1773 @r5index string>=?
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
1778 @var{s2}. (r5rs)
1779 @end deffn
1780
1781 @r5index string>?
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)
1786 @end deffn
1787
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)
1797 @end deffn
1798
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(???).
1802 @end deffn
1803
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)
1808 @end deffn
1809
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)
1815 @end deffn
1816
1817
1818 @node Shared Substrings
1819 @subsection Shared Substrings
1820
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.
1825
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
1830 string.
1831
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
1841 @var{str}.
1842 @end deffn
1843
1844 Example:
1845
1846 @example
1847 (define foo "the quick brown fox")
1848 (define bar (make-shared-substring some-string 4 9))
1849
1850 foo => "t h e q u i c k b r o w n f o x"
1851 bar =========> |---------|
1852 @end example
1853
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.
1861
1862 @example
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!
1867 @end example
1868
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
1873 substrings.
1874
1875 @example
1876 (string-set! foo 7 #\r)
1877 bar @result{} "quirk"
1878 @end example
1879
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.)
1886
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.
1890
1891 @node Read Only Strings
1892 @subsection Read Only Strings
1893
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:
1898
1899 @c ARGFIXME x/obj
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,
1903
1904 This illustrates the difference between @code{string?} and
1905 @code{read-only-string?}:
1906
1907 @example
1908 (string? "a string") @result{} #t
1909 (string? 'a-symbol) @result{} #f
1910
1911 (read-only-string? "a string") @result{} #t
1912 (read-only-string? 'a-symbol) @result{} #t
1913 @end example
1914 @end deffn
1915
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.
1920
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.
1925
1926 Shared substrings, discussed in the previous chapter, also happen to be
1927 read-only strings.
1928
1929
1930 @node Regular Expressions
1931 @section Regular Expressions
1932
1933 @cindex regular expressions
1934 @cindex regex
1935 @cindex emacs regexp
1936
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.
1943
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.
1949
1950 @menu
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.
1955 @end menu
1956
1957 [FIXME: it may be useful to include an Examples section. Parts of this
1958 interface are bewildering on first glance.]
1959
1960 @node Regexp Functions
1961 @subsection Regexp Functions
1962
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
1966 literal characters.
1967
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.
1971
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.
1977
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}.
1982 @end deffn
1983
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.
1990
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.
1998
1999 The @var{flag} arguments change the behavior of the compiled regexp.
2000 The following flags may be supplied:
2001
2002 @table @code
2003 @item regexp/icase
2004 Consider uppercase and lowercase letters to be the same when matching.
2005
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
2013 lines.
2014
2015 @item regexp/basic
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.
2023
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
2029 the earlier one.
2030 @end table
2031 @end deffn
2032
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.
2040 @end deffn
2041
2042 @c ARGFIXME x/obj
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.
2047 @end deffn
2048
2049 Regular expressions are commonly used to find patterns in one string and
2050 replace them with the contents of another string.
2051
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:
2057
2058 @itemize @bullet
2059 @item
2060 A string. String arguments are written out verbatim.
2061
2062 @item
2063 An integer. The submatch with that number is written.
2064
2065 @item
2066 The symbol @samp{pre}. The portion of the matched string preceding
2067 the regexp match is written.
2068
2069 @item
2070 The symbol @samp{post}. The portion of the matched string following
2071 the regexp match is written.
2072 @end itemize
2073
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.
2077 @end deffn
2078
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.
2086
2087 Each @var{item} behaves as in @var{regexp-substitute}, with the
2088 following exceptions:
2089
2090 @itemize @bullet
2091 @item
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}.
2095
2096 @item
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.
2102 @end itemize
2103 @end deffn
2104
2105 @node Match Structures
2106 @subsection Match Structures
2107
2108 @cindex match structures
2109
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
2116 submatch.
2117
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.
2124
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.
2129 @end deffn
2130
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}.
2137 @end deffn
2138
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}.
2142 @end deffn
2143
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}.
2147 @end deffn
2148
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.
2152 @end deffn
2153
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.
2157 @end deffn
2158
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.
2164 @end deffn
2165
2166 @c begin (scm-doc-string "regex.scm" "match:string")
2167 @deffn procedure match:string match
2168 Return the original @var{target} string.
2169 @end deffn
2170
2171 @node Backslash Escapes
2172 @subsection Backslash Escapes
2173
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
2180 asterisk un-magic.
2181
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
2190 target string.
2191
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.
2199
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.
2204 @end deffn
2205
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
2216 @samp{*}.
2217
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:
2223
2224 @lisp
2225 (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2226 @end lisp
2227
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.
2231
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:
2238
2239 @lisp
2240 (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2241 @end lisp
2242
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.
2253
2254 @node Rx Interface
2255 @subsection Rx Interface
2256
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!]
2259
2260 @cindex rx
2261 @cindex finite automaton
2262
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.
2267
2268 For example, given the
2269 regular expression @samp{abc.} (which matches any string containing
2270 @samp{abc} followed by any single character):
2271
2272 @smalllisp
2273 guile> @kbd{(define r (regcomp "abc."))}
2274 guile> @kbd{r}
2275 #<rgx abc.>
2276 guile> @kbd{(regexec r "abc")}
2277 #f
2278 guile> @kbd{(regexec r "abcd")}
2279 #((0 . 4))
2280 guile>
2281 @end smalllisp
2282
2283 The definitions of @code{regcomp} and @code{regexec} are as follows:
2284
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
2291 @end defvar
2292 @defvar REG_ICASE
2293 use case-insensitive matching
2294 @end defvar
2295 @defvar REG_NEWLINE
2296 allow anchors to match after newline characters in the
2297 string and prevents @code{.} or @code{[^...]} from matching newlines.
2298 @end defvar
2299
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{\+}
2303 and @code{\?}
2304 operators. Backslashes in @var{pattern} must be escaped if specified in a
2305 literal string e.g., @code{"\\(a\\)\\?"}.
2306 @end deffn
2307
2308 @c NJFIXME not in libguile!
2309 @deffn primitive regexec regex string [match-pick] [flags]
2310
2311 Match @var{string} against the compiled POSIX regular expression
2312 @var{regex}.
2313 @var{match-pick} and @var{flags} are optional. Possible flags (which can be
2314 combined using the logior procedure) are:
2315
2316 @defvar REG_NOTBOL
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)
2319 @end defvar
2320
2321 @defvar REG_NOTEOL
2322 Similar to REG_NOTBOL, but prevents the end of line operator
2323 from matching the end of @var{string}.
2324 @end defvar
2325
2326 If no match is possible, regexec returns #f. Otherwise @var{match-pick}
2327 determines the return value:
2328
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
2331 substrings.
2332
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}.
2337
2338 @code{#f}: regexec returns #t if a match is made, otherwise #f.
2339
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).
2344
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:
2347
2348 a number: the numbered matching substring (0 for the entire match).
2349
2350 @code{#\<}: the beginning of @var{string} to the beginning of the part matched
2351 by regex.
2352
2353 @code{#\>}: the end of the matched part of @var{string} to the end of
2354 @var{string}.
2355
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
2358 interface.
2359
2360 e.g., @code{(list #\< 0 1 #\>)}. The returned substrings share memory with
2361 @var{string}.
2362 @end deffn
2363
2364 Here are some other procedures that might be used when using regular
2365 expressions:
2366
2367 @c NJFIXME not in libguile!
2368 @deffn primitive compiled-regexp? obj
2369 Test whether obj is a compiled regular expression.
2370 @end deffn
2371
2372 @c NJFIXME not in libguile!
2373 @deffn primitive regexp->dfa regex [flags]
2374 @end deffn
2375
2376 @c NJFIXME not in libguile!
2377 @deffn primitive dfa-fork dfa
2378 @end deffn
2379
2380 @c NJFIXME not in libguile!
2381 @deffn primitive reset-dfa! dfa
2382 @end deffn
2383
2384 @c NJFIXME not in libguile!
2385 @deffn primitive dfa-final-tag dfa
2386 @end deffn
2387
2388 @c NJFIXME not in libguile!
2389 @deffn primitive dfa-continuable? dfa
2390 @end deffn
2391
2392 @c NJFIXME not in libguile!
2393 @deffn primitive advance-dfa! dfa string
2394 @end deffn
2395
2396
2397 @node Symbols and Variables
2398 @section Symbols and Variables
2399 @r5index symbol?
2400 @r5index symbol->string
2401 @r5index string->symbol
2402
2403
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.
2410
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
2416 @c unbound symbols.
2417 @c @end deffn
2418
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.
2426 @end deffn
2427
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.
2437 @end deffn
2438
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.
2444 @end deffn
2445
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
2449 @var{string}.
2450
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>}).
2455
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}.
2461 @end deffn
2462
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}.
2470
2471 The following examples assume that the implementation's
2472 standard case is lower case:
2473
2474 @lisp
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
2478 (eq? 'JollyWog
2479 (string->symbol (symbol->string 'JollyWog))) @result{} #t
2480 (string=? "K. Harper, M.D."
2481 (symbol->string
2482 (string->symbol "K. Harper, M.D."))) @result{}#t
2483 @end lisp
2484 @end deffn
2485
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)
2501
2502 The following examples assume that the implementation's
2503 standard case is lower case:
2504
2505 @lisp
2506 (symbol->string 'flying-fish) @result{} "flying-fish"
2507 (symbol->string 'Martin) @result{} "martin"
2508 (symbol->string
2509 (string->symbol "Malvina")) @result{} "Malvina"
2510 @end lisp
2511 @end deffn
2512
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.
2519 @end deffn
2520
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
2528 value.
2529 @end deffn
2530
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}.
2534 @end deffn
2535
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.
2539 @end deffn
2540
2541 @c docstring begin (texi-doc-string "guile" "symbol-hash")
2542 @deffn primitive symbol-hash symbol
2543 Return a hash value for @var{symbol}.
2544 @end deffn
2545
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.
2550 @end deffn
2551
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}.
2555 @end deffn
2556
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.
2560 @end deffn
2561
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
2566 in @var{obarray}.
2567 @end deffn
2568
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
2572 @code{#f}. (r5rs)
2573 @end deffn
2574
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}
2579 otherwise.
2580 @end deffn
2581
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.
2587 @end deffn
2588
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.
2596 @end deffn
2597
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.
2605 @end deffn
2606
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.
2611 @end deffn
2612
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}.
2618 @end deffn
2619
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.
2625 @end deffn
2626
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
2630 return @code{#f}
2631 @end deffn
2632
2633
2634 @node Keywords
2635 @section Keywords
2636
2637 Keywords are self-evaluating objects with a convenient read syntax that
2638 makes them easy to type.
2639
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
2642 @code{#:}.
2643
2644 @menu
2645 * Why Use Keywords?::
2646 * Coding With Keywords::
2647 * Keyword Read Syntax::
2648 * Keyword Primitives::
2649 @end menu
2650
2651 @node Why Use Keywords?
2652 @subsection Why Use Keywords?
2653
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.
2657
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
2662 example:
2663
2664 @itemize @bullet
2665 @item
2666 colour depth -- Default: the colour depth for the screen
2667
2668 @item
2669 background colour -- Default: white
2670
2671 @item
2672 width -- Default: 600
2673
2674 @item
2675 height -- Default: 400
2676 @end itemize
2677
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
2681 for that argument:
2682
2683 @lisp
2684 (make-window 'default ;; Colour depth
2685 'default ;; Background colour
2686 800 ;; Width
2687 100 ;; Height
2688 @dots{}) ;; More make-window arguments
2689 @end lisp
2690
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:
2694
2695 @lisp
2696 (make-window #:width 800 #:height 100)
2697 @end lisp
2698
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
2702 be invoked as
2703
2704 @lisp
2705 (cons #:car x #:cdr y)
2706 @end lisp
2707
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.
2710
2711 @node Coding With Keywords
2712 @subsection Coding With Keywords
2713
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.
2717
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
2721 the rest argument.
2722
2723 @lisp
2724 (define (get-keyword-value args keyword default)
2725 (let ((kv (memq keyword args)))
2726 (if (and kv (>= (length kv) 2))
2727 (cadr kv)
2728 default)))
2729
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))
2735 @dots{})
2736 @dots{}))
2737 @end lisp
2738
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:
2742
2743 @lisp
2744 (use-modules (ice-9 optargs))
2745
2746 (define (make-window . args)
2747 (let-keywords args #f ((depth screen-depth)
2748 (bg "white")
2749 (width 800)
2750 (height 100))
2751 ...))
2752 @end lisp
2753
2754 @noindent
2755 Or, even more economically, like this:
2756
2757 @lisp
2758 (use-modules (ice-9 optargs))
2759
2760 (define* (make-window #:key (depth screen-depth)
2761 (bg "white")
2762 (width 800)
2763 (height 100))
2764 ...)
2765 @end lisp
2766
2767 For further details on @code{let-keywords}, @code{define*} and other
2768 facilities provided by the @code{(ice-9 optargs)} module, @ref{Optional
2769 Arguments}.
2770
2771
2772 @node Keyword Read Syntax
2773 @subsection Keyword Read Syntax
2774
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.
2781
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.
2785
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}.
2789
2790 @smalllisp
2791 (read-set! keywords 'prefix)
2792
2793 #:type
2794 @result{}
2795 #:type
2796
2797 :type
2798 @result{}
2799 #:type
2800
2801 (read-set! keywords #f)
2802
2803 #:type
2804 @result{}
2805 #:type
2806
2807 :type
2808 @result{}
2809 ERROR: In expression :type:
2810 ERROR: Unbound variable: :type
2811 ABORT: (unbound-variable)
2812 @end smalllisp
2813
2814 @node Keyword Primitives
2815 @subsection Keyword Primitives
2816
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}.
2822
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.
2829
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.
2833 @end deffn
2834
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}.
2838 @end deffn
2839
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}.
2844 @end deffn
2845
2846
2847 @node Pairs
2848 @section Pairs
2849 @r5index pair?
2850 @r5index cons
2851 @r5index set-car!
2852 @r5index set-cdr!
2853
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.
2859 @end deffn
2860
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}.
2864 @end deffn
2865
2866 @r5index car
2867 @r5index cdr
2868 @deffn primitive car pair
2869 @deffnx primitive cdr pair
2870 Return the car or the cdr of @var{pair}, respectively.
2871 @end deffn
2872
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
2879
2880 @lisp
2881 (define caddr (lambda (x) (car (cdr (cdr x)))))
2882 @end lisp
2883 @end deffn
2884
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.
2889 @end deffn
2890
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.
2895 @end deffn
2896
2897
2898 @node Lists
2899 @section Lists
2900 @r5index null?
2901 @r5index list?
2902 @r5index list
2903 @r5index length
2904 @r5index append
2905 @r5index reverse
2906 @r5index list-tail
2907 @r5index list-ref
2908 @r5index memq
2909 @r5index memv
2910 @r5index member
2911
2912
2913 @c docstring begin (texi-doc-string "guile" "list")
2914 @deffn primitive list . objs
2915 Return a list containing @var{objs}, the arguments to
2916 @code{list}.
2917 @end deffn
2918
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.
2927 @end deffn
2928
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}.
2932 @end deffn
2933
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}.
2937 @end deffn
2938
2939 @c docstring begin (texi-doc-string "guile" "length")
2940 @deffn primitive length lst
2941 Return the number of elements in list @var{lst}.
2942 @end deffn
2943
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
2947 arguments.
2948 @example
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))
2952 @end example
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.
2957 @example
2958 (append '(a b) '(c . d)) @result{} (a b c . d)
2959 (append '() 'a) @result{} a
2960 @end example
2961 @end deffn
2962
2963 @c ARGFIXME args ?
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.
2970 @end deffn
2971
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.
2976 @end deffn
2977
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
2981 in reverse order.
2982 @end deffn
2983
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.
2991
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
2997 @code{reverse!}
2998 @end deffn
2999
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}.
3003 @end deffn
3004
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}.
3008 @end deffn
3009
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.
3016
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}.
3020 @end deffn
3021
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}.
3025 @end deffn
3026
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
3030 return it.
3031 @end deffn
3032
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}.
3036 @end deffn
3037
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
3045 returned.
3046 @end deffn
3047
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
3055 returned.
3056 @end deffn
3057
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.
3066 @end deffn
3067
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?}.
3074 @end deffn
3075
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?}.
3082 @end deffn
3083
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?}.
3090 @end deffn
3091
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.
3104 @end deffn
3105
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!}.
3111 @end deffn
3112
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!}.
3118 @end deffn
3119
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!}.
3125 @end deffn
3126
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]
3130
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.
3136 @end deffn
3137
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.
3143 @end deffn
3144
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.
3150 @end deffn
3151
3152 @r5index map
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
3157 @end deffn
3158
3159 @r5index for-each
3160 @c begin (texi-doc-string "guile" "for-each")
3161 @deffn primitive for-each proc arg1 . args
3162 @end deffn
3163
3164
3165 @node Records
3166 @section Records
3167
3168 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3169 be reviewed]
3170
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.
3173
3174 @deffn procedure record? obj
3175 Returns @code{#t} if @var{obj} is a record of any type and @code{#f}
3176 otherwise.
3177
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.
3180 @end deffn
3181
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
3190 @end deffn
3191
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
3203 @end deffn
3204
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
3210 @end deffn
3211
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
3220 @end deffn
3221
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
3231 @var{rtd}.@refill
3232 @end deffn
3233
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
3242 @end deffn
3243
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
3248 @var{rtd}.@refill
3249 @end deffn
3250
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
3256 @end deffn
3257
3258
3259 @node Structures
3260 @section Structures
3261
3262 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
3263 be reviewed]
3264
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
3267 itself a structure.
3268
3269 Structures are less abstract and more general than traditional records.
3270 In fact, in Guile Scheme, records are implemented using structures.
3271
3272 @menu
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
3277 @end menu
3278
3279 @node Structure Concepts
3280 @subsection Structure Concepts
3281
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.
3288
3289 Three concepts are key to understanding structures.
3290
3291 @itemize @bullet{}
3292 @item @dfn{layout specifications}
3293
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.
3297
3298 @item @dfn{structural accessors}
3299
3300 Structure access is by field number. There is only one set of
3301 accessors common to all structure objects.
3302
3303 @item @dfn{vtables}
3304
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.
3310 @end itemize
3311
3312
3313
3314 @node Structure Layout
3315 @subsection Structure Layout
3316
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.
3320
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:
3323
3324 @itemize @bullet{}
3325 @item 'u' -- unprotected
3326
3327 The field holds binary data that is not GC protected.
3328
3329 @item 'p' -- protected
3330
3331 The field holds a Scheme value and is GC protected.
3332
3333 @item 's' -- self
3334
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.
3340 @end itemize
3341
3342
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:
3346
3347 @itemize @bullet{}
3348 @item 'w' -- writable
3349
3350 The field can be read and written.
3351
3352 @item 'r' -- readable
3353
3354 The field can be read, but not written.
3355
3356 @item 'o' -- opaque
3357
3358 The field can be neither read nor written. This kind
3359 of protection is for fields useful only to built-in routines.
3360 @end itemize
3361
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
3365 be described as:
3366
3367 @example
3368 ; cons pairs have two writable fields of Scheme data
3369 "pwpw"
3370 @end example
3371
3372 A pair object in which the first field is held constant could be:
3373
3374 @example
3375 "prpw"
3376 @end example
3377
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)}.
3381
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
3389 described as:
3390
3391 @example
3392 ; A vector is an arbitrary number of writable fields holding Scheme
3393 ; values:
3394 "pW"
3395 @end example
3396
3397 In the above example, field 0 contains the size of the vector and
3398 fields beginning at 1 contain the vector elements.
3399
3400 A kind of tagged vector (a constant tag followed by conventioal
3401 vector elements) might be:
3402
3403 @example
3404 "prpW"
3405 @end example
3406
3407
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:
3411
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.
3415
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.
3424 @end deffn
3425
3426
3427
3428 @node Structure Basics
3429 @subsection Structure Basics
3430
3431 This section describes the basic procedures for creating and accessing
3432 structures.
3433
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.
3437
3438 @var{type} must be a vtable structure (@pxref{Vtables}).
3439
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.
3443
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
3449 Scheme programs.
3450
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
3453 initialized to 0.
3454
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
3458 more powerful.
3459
3460 For more information, see the documentation for @code{make-vtable-vtable}.
3461 @end deffn
3462
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
3466 @code{#f}.
3467 @end deffn
3468
3469
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}.
3475
3476 If the field is of type 'p', then it can be set to an arbitrary value.
3477
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.
3480 @end deffn
3481
3482
3483
3484 @node Vtables
3485 @subsection Vtables
3486
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.
3494
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}.
3498 @end deffn
3499
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.
3503 @end deffn
3504
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:
3512
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.
3516
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}).
3520
3521 @var{tail-size} specifies the size of the tail-array (if any) of
3522 this vtable.
3523
3524 @var{init1}, @dots{} are the optional initializers for the fields of
3525 the vtable.
3526
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:
3532
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.
3536
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
3541 the chain.
3542
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.)
3548
3549 @example
3550 (define ball-root (make-vtable-vtable "pr" 0))
3551
3552 (define (make-ball-type ball-color)
3553 (make-struct ball-root 0
3554 (make-struct-layout "pw")
3555 (lambda (ball port)
3556 (format port "#<a ~A ball owned by ~A>"
3557 (color ball)
3558 (owner ball)))
3559 ball-color))
3560 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
3561 (define (owner ball) (struct-ref ball 0))
3562
3563 (define red (make-ball-type 'red))
3564 (define green (make-ball-type 'green))
3565
3566 (define (make-ball type owner) (make-struct type 0 owner))
3567
3568 (define ball (make-ball green 'Nisse))
3569 ball @result{} #<a green ball owned by Nisse>
3570 @end example
3571 @end deffn
3572
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}.
3576 @end deffn
3577
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}.
3581 @end deffn
3582
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}.
3586 @end deffn
3587
3588
3589 @node Arrays
3590 @section Arrays
3591
3592 @menu
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.
3597 @end menu
3598
3599 @node Conventional Arrays
3600 @subsection Conventional Arrays
3601
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.
3609
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
3613 the rank.
3614
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
3617 zero-based index:
3618
3619 @example
3620 (make-array 'ho 2 3) @result{}
3621 #2((ho ho ho) (ho ho ho))
3622 @end example
3623
3624 The range of each dimension can also be given explicitly, e.g., another
3625 way to create the same array:
3626
3627 @example
3628 (make-array 'ho '(0 1) '(0 2)) @result{}
3629 #2((ho ho ho) (ho ho ho))
3630 @end example
3631
3632 A conventional array with one dimension based at zero is identical to
3633 a vector:
3634
3635 @example
3636 (make-array 'ho 3) @result{}
3637 #(ho ho ho)
3638 @end example
3639
3640 The following procedures can be used with conventional arrays (or vectors).
3641
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.
3645
3646 The @var{prototype} argument is used with uniform arrays and is described
3647 elsewhere.
3648 @end deffn
3649
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}.
3653 @end deffn
3654
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
3657
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}.
3663 @end deffn
3664
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.
3668 @end deffn
3669
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.
3676 @end deffn
3677
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:
3685 @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
3694 @end example
3695 @end deffn
3696
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.
3700 @end deffn
3701
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.
3705 @end deffn
3706
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.
3710 @end deffn
3711
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.
3719
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
3724 @var{array}.
3725
3726 examples:
3727 @example
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))
3732 @end example
3733 @end deffn
3734
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}.
3743
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.
3749
3750 examples:
3751 @example
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))>
3754
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))>
3757 @end example
3758 @end deffn
3759
3760 @deffn procedure array-shape array
3761 Returns a list of inclusive bounds of integers.
3762 @example
3763 (array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
3764 @end example
3765 @end deffn
3766
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:
3771 @example
3772 (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
3773 @end example
3774 @end deffn
3775
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.
3780 @end deffn
3781
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}.
3785 @end deffn
3786
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.
3795 @end deffn
3796
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
3800 is unspecified.
3801 @end deffn
3802
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.
3810 @end deffn
3811
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.
3821
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
3824 memory.
3825 @end deffn
3826
3827 @node Array Mapping
3828 @subsection Array Mapping
3829
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.
3840 @end deffn
3841
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.
3846 @end deffn
3847
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.
3853
3854 One can implement @var{array-indexes} as
3855 @example
3856 (define (array-indexes array)
3857 (let ((ra (apply make-array #f (array-shape array))))
3858 (array-index-map! ra (lambda x x))
3859 ra))
3860 @end example
3861 Another example:
3862 @example
3863 (define (apl:index-generator n)
3864 (let ((v (make-uniform-vector n 1)))
3865 (array-index-map! v (lambda (i) i))
3866 v))
3867 @end example
3868 @end deffn
3869
3870 @node Uniform Arrays
3871 @subsection Uniform Arrays
3872
3873 @noindent
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.
3880
3881 @noindent
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:
3885
3886 @example
3887 prototype type printing character
3888
3889 #t boolean (bit-vector) b
3890 #\a char (string) a
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
3900 @end example
3901
3902 @noindent
3903 Unshared uniform arrays of characters with a single zero-based dimension
3904 are identical to strings:
3905
3906 @example
3907 (make-uniform-array #\a 3) @result{}
3908 "aaa"
3909 @end example
3910
3911 @noindent
3912 Unshared uniform arrays of booleans with a single zero-based dimension
3913 are identical to @ref{Bit Vectors, bit-vectors}.
3914
3915 @example
3916 (make-uniform-array #t 3) @result{}
3917 #*111
3918 @end example
3919
3920 @noindent
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)}.
3925
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.
3929
3930 The @var{prototype} argument is used with uniform arrays and is described
3931 elsewhere.
3932 @end deffn
3933
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}.
3938 @end deffn
3939
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}.
3945 @end deffn
3946
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.
3953 @end deffn
3954
3955 @deffn primitive uniform-vector-fill! uve fill
3956 Stores @var{fill} in every element of @var{uve}. The value returned is
3957 unspecified.
3958 @end deffn
3959
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}.
3963 @end deffn
3964
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.
3972 @end deffn
3973
3974 @c Another compiled-closure. -twp
3975
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
3984 unchanged.
3985
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.
3989
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)}.
3993 @end deffn
3994
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
3999 @var{port-or-fdes}.
4000
4001 The optional arguments @var{start}
4002 and @var{end} allow
4003 a specified region of a vector (or linearized array) to be written.
4004
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)}.
4009 @end deffn
4010
4011 @node Bit Vectors
4012 @subsection Bit Vectors
4013
4014 @noindent
4015 Bit vectors are a specific type of uniform array: an array of booleans
4016 with a single zero-based index.
4017
4018 @noindent
4019 They are displayed as a sequence of @code{0}s and
4020 @code{1}s prefixed by @code{#*}, e.g.,
4021
4022 @example
4023 (make-uniform-vector 8 #t #f) @result{}
4024 #*00000000
4025
4026 #b(#t #f #t) @result{}
4027 #*101
4028 @end example
4029
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
4033 @var{bitvector}.
4034 @end deffn
4035
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.
4041 @end deffn
4042
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.
4046 @end deffn
4047
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}.
4054
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.
4059 @end deffn
4060
4061 @c docstring begin (texi-doc-string "guile" "bit-count*")
4062 @deffn primitive bit-count* v kv obj
4063 Returns
4064 @example
4065 (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
4066 @end example
4067 @var{bv} is not modified.
4068 @end deffn
4069
4070
4071 @node Association Lists and Hash Tables
4072 @section Association Lists and Hash Tables
4073
4074 This chapter discusses dictionary objects: data structures that are
4075 useful for organizing and indexing large bodies of information.
4076
4077 @menu
4078 * Dictionary Types:: About dictionary types; what they're good for.
4079 * Association Lists::
4080 * Hash Tables::
4081 @end menu
4082
4083 @node Dictionary Types
4084 @subsection Dictionary Types
4085
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
4094 such a way.
4095
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.
4100
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.
4105
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.
4113
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.
4118
4119 @node Association Lists
4120 @subsection Association Lists
4121 @cindex Association List
4122 @cindex Alist
4123 @cindex Database
4124
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
4129 @code{cdr}.
4130
4131 @example
4132 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
4133 (KEY2 . VALUE2)
4134 (KEY3 . VALUE3)
4135 @dots{}
4136 )
4137 @end example
4138
4139 @noindent
4140 Association lists are also known, for short, as @dfn{alists}.
4141
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.
4149
4150 @menu
4151 * Alist Key Equality::
4152 * Adding or Setting Alist Entries::
4153 * Retrieving Alist Entries::
4154 * Removing Alist Entries::
4155 * Sloppy Alist Functions::
4156 * Alist Example::
4157 @end menu
4158
4159 @node Alist Key Equality
4160 @subsubsection Alist Key Equality
4161
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
4166 required entry.
4167
4168 @itemize @bullet
4169 @item
4170 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
4171 equality.
4172
4173 @item
4174 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
4175 key equality.
4176
4177 @item
4178 Procedures with @dfn{assoc} in their name use @code{equal?} to
4179 determine key equality.
4180 @end itemize
4181
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.
4184
4185 @node Adding or Setting Alist Entries
4186 @subsubsection Adding or Setting Alist Entries
4187
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.
4194
4195 In the most common usage of @code{acons}, a variable holding the
4196 original association list is updated with the combined alist:
4197
4198 @example
4199 (set! address-list (acons name address address-list))
4200 @end example
4201
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.
4205
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.
4210
4211 @example
4212 (set! task-list (acons 3 "pay gas bill" '()))
4213 task-list
4214 @result{}
4215 ((3 . "pay gas bill"))
4216
4217 (set! task-list (acons 3 "tidy bedroom" task-list))
4218 task-list
4219 @result{}
4220 ((3 . "tidy bedroom") (3 . "pay gas bill"))
4221 @end example
4222
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.
4231
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
4235 value returned:
4236
4237 @example
4238 address-list
4239 @result{}
4240 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
4241
4242 (assoc-set! address-list "james" "1a London Road")
4243 @result{}
4244 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4245
4246 address-list
4247 @result{}
4248 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4249 @end example
4250
4251 Or they may not:
4252
4253 @example
4254 (assoc-set! address-list "bob" "11 Newington Avenue")
4255 @result{}
4256 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4257 ("james" . "1a London Road"))
4258
4259 address-list
4260 @result{}
4261 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
4262 @end example
4263
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
4266 returned value:
4267
4268 @example
4269 (set! address-list
4270 (assoc-set! address-list "bob" "11 Newington Avenue"))
4271 address-list
4272 @result{}
4273 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4274 ("james" . "1a London Road"))
4275 @end example
4276
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
4280 difference to you.
4281
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
4286 it.
4287
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.
4294 @end deffn
4295
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.
4306
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
4309 association list.
4310 @end deffn
4311
4312 @node Retrieving Alist Entries
4313 @subsubsection Retrieving Alist Entries
4314 @r5index assq
4315 @r5index assv
4316 @r5index assoc
4317
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.
4323
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).
4337 @end deffn
4338
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}.
4343
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.
4350
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
4360
4361 @lisp
4362 (let ((ent (@var{associator} @var{key} @var{alist})))
4363 (and ent (cdr ent)))
4364 @end lisp
4365
4366 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
4367 @end deffn
4368
4369 @node Removing Alist Entries
4370 @subsubsection Removing Alist Entries
4371
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
4376 association list).
4377
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.
4382
4383 @example
4384 address-list
4385 @result{}
4386 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4387 ("james" . "1a London Road"))
4388
4389 (set! address-list (assoc-remove! address-list "mary"))
4390 address-list
4391 @result{}
4392 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
4393 @end example
4394
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:
4404
4405 @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"))
4409 address-list
4410 @result{}
4411 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
4412
4413 (set! address-list (assoc-remove! address-list "mary"))
4414 address-list
4415 @result{}
4416 (("mary" . "11 Elm Street"))
4417 @end example
4418
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.
4426
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.
4435 @end deffn
4436
4437 @node Sloppy Alist Functions
4438 @subsubsection Sloppy Alist Functions
4439
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.
4444
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:
4449
4450 @example
4451 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4452 @result{}
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)
4456
4457 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4458 @result{}
4459 #f
4460 @end example
4461
4462 @noindent
4463 Secondly, if one of the entries in the specified alist is not a pair:
4464
4465 @example
4466 (assoc 2 '((1 . 1) 2 (3 . 9)))
4467 @result{}
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)
4471
4472 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
4473 @result{}
4474 #f
4475 @end example
4476
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.
4481
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.
4486 @end deffn
4487
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.
4492 @end deffn
4493
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.
4498 @end deffn
4499
4500 @node Alist Example
4501 @subsubsection Alist Example
4502
4503 Here is a longer example of how alists may be used in practice.
4504
4505 @lisp
4506 (define capitals '(("New York" . "Albany")
4507 ("Oregon" . "Salem")
4508 ("Florida" . "Miami")))
4509
4510 ;; What's the capital of Oregon?
4511 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
4512 (assoc-ref capitals "Oregon") @result{} "Salem"
4513
4514 ;; We left out South Dakota.
4515 (set! capitals
4516 (assoc-set! capitals "South Dakota" "Bismarck"))
4517 capitals
4518 @result{} (("South Dakota" . "Bismarck")
4519 ("New York" . "Albany")
4520 ("Oregon" . "Salem")
4521 ("Florida" . "Miami"))
4522
4523 ;; And we got Florida wrong.
4524 (set! capitals
4525 (assoc-set! capitals "Florida" "Tallahassee"))
4526 capitals
4527 @result{} (("South Dakota" . "Bismarck")
4528 ("New York" . "Albany")
4529 ("Oregon" . "Salem")
4530 ("Florida" . "Tallahassee"))
4531
4532 ;; After Oregon secedes, we can remove it.
4533 (set! capitals
4534 (assoc-remove! capitals "Oregon"))
4535 capitals
4536 @result{} (("South Dakota" . "Bismarck")
4537 ("New York" . "Albany")
4538 ("Florida" . "Tallahassee"))
4539 @end lisp
4540
4541 @node Hash Tables
4542 @subsection Hash Tables
4543
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?}.
4549
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
4552 any Scheme object.
4553
4554 @c ARGFIXME obj/key
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.
4561 @end deffn
4562
4563 @c ARGFIXME obj/key
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.
4570 @end deffn
4571
4572 @c ARGFIXME obj/key
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.
4579 @end deffn
4580
4581 @c ARGFIXME obj/key
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.
4586 @end deffn
4587
4588 @c ARGFIXME obj/key
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.
4593 @end deffn
4594
4595 @c ARGFIXME obj/key
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
4600 testing.
4601 @end deffn
4602
4603 @c ARGFIXME obj/key
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.
4608 @end deffn
4609
4610 @c ARGFIXME obj/key
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.
4615 @end deffn
4616
4617 @c ARGFIXME obj/key
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.
4622 @end deffn
4623
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.
4632
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.
4638
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.
4651 @end deffn
4652
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.
4665 @end deffn
4666
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.
4673 @end deffn
4674
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}.
4684
4685 By way of illustration, @code{hashq-ref table key} is equivalent
4686 to @code{hashx-ref hashq assq table key}.
4687 @end deffn
4688
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}.
4697
4698 By way of illustration, @code{hashq-set! table key} is equivalent
4699 to @code{hashx-set! hashq assq table key}.
4700 @end deffn
4701
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)}.
4710 @end deffn
4711
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)}.
4720 @end deffn
4721
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)}.
4730 @end deffn
4731
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}.
4740 @end deffn
4741
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}.
4747 @end deffn
4748
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}.
4754 @end deffn
4755
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}.
4761 @end deffn
4762
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}.
4771 @end deffn
4772
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.
4783 @end deffn
4784
4785
4786 @node Vectors
4787 @section Vectors
4788
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)
4795 @end deffn
4796
4797 @r5index vector
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)
4805
4806 @lisp
4807 (vector 'a 'b 'c) @result{} #(a b c)
4808 @end lisp
4809 @end deffn
4810
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)
4816
4817 @lisp
4818 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
4819 (list->vector '(dididit dah)) @result{} #(dididit dah)
4820 @end lisp
4821 @end deffn
4822
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)
4829 @end deffn
4830
4831 @r5index vector?
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
4835 @code{#f}. (r5rs)
4836 @end deffn
4837
4838 @r5index vector-length
4839 @deffn primitive vector-length vector
4840 Returns the number of elements in @var{vector} as an exact integer.
4841 @end deffn
4842
4843 @r5index vector-ref
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
4847 @var{vector}.
4848 @lisp
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)))))
4852 (if (inexact? i)
4853 (inexact->exact i)
4854 i))) @result{} 13
4855 @end lisp
4856 @end deffn
4857
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.
4863 @lisp
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
4868 @end lisp
4869 @end deffn
4870
4871 @node Hooks
4872 @section Hooks
4873
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}.
4878 @end deffn
4879
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}.
4883 @end deffn
4884
4885 @c docstring begin (texi-doc-string "guile" "hook?")
4886 @deffn primitive hook? x
4887 Return @code{#t} if @var{x} is a hook.
4888 @end deffn
4889
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.
4893 @end deffn
4894
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.
4900 @end deffn
4901
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}.
4905 @end deffn
4906
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}.
4910 @end deffn
4911
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
4915 @var{args}.
4916 @end deffn
4917
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.
4921 @end deffn
4922
4923
4924 @node Other Data Types
4925 @section Other Core Guile Data Types
4926
4927
4928 @c Local Variables:
4929 @c TeX-master: "guile.texi"
4930 @c End: