* scheme-data.texi (Hash Tables): Added docs for
[bpt/guile.git] / doc / scheme-data.texi
CommitLineData
38a93523
NJ
1@page
2@node Data Types
3@chapter Data Types for Generic Use
4
5This chapter describes all the data types that Guile provides for
6``generic use''.
7
8One of the great strengths of Scheme is that there is no straightforward
9distinction between ``data'' and ``functionality''. For example,
10Guile's support for dynamic linking could be described
11
239d2912 12@itemize @bullet
38a93523
NJ
13@item
14either in a ``data-centric'' way, as the behaviour and properties of the
15``dynamically linked object'' data type, and the operations that may be
16applied to instances of this type
17
18@item
19or in a ``functionality-centric'' way, as the set of procedures that
20constitute Guile's support for dynamic linking, in the context of the
21module system.
22@end itemize
23
24The 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
27than their use in the implementation of a particular piece of
28@emph{functionality}.
29
30@ifinfo
31The following menu
32@end ifinfo
33@iftex
34The table of contents for this chapter
35@end iftex
36@ifhtml
37The following table of contents
38@end ifhtml
39shows the data types that are documented in this chapter. The final
40section of this chapter lists all the core Guile data types that are not
41documented here, and provides links to the ``functionality-centric''
42sections 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.
cee2ed4f 54* Vectors:: One-dimensional arrays of Scheme objects.
b576faf1
MG
55* Records::
56* Structures::
f4f2b29a
MG
57* Arrays:: Arrays of values.
58* Association Lists and Hash Tables:: Dictionary data types.
38a93523
NJ
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
39e30745 66@tpindex Booleans
38a93523
NJ
67
68The two boolean values are @code{#t} for true and @code{#f} for false.
69
70Boolean values are returned by predicate procedures, such as the general
71equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
72(@pxref{Equality}) and numerical and string comparison operators like
725fd980
NJ
73@code{string=?} (@pxref{String Comparison}) and @code{<=}
74(@pxref{Comparison}).
38a93523
NJ
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
725fd980
NJ
94In test condition contexts like @code{if} and @code{cond} (@pxref{if
95cond case}), where a group of subexpressions will be evaluated only if a
38a93523
NJ
96@var{condition} expression evaluates to ``true'', ``true'' means any
97value 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
113A result of this asymmetry is that typical Scheme source code more often
114uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
115represent an @code{if} or @code{cond} false value, whereas @code{#t} is
116not necessary to represent an @code{if} or @code{cond} true value.
117
118It is important to note that @code{#f} is @strong{not} equivalent to any
119other Scheme value. In particular, @code{#f} is not the same as the
120number 0 (like in C and C++), and not the same as the ``empty list''
121(like in some Lisp dialects).
122
123The @code{not} procedure returns the boolean inverse of its argument:
124
5c4b24e1 125@rnindex not
38a93523
NJ
126@deffn primitive not x
127Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
128@end deffn
129
130The @code{boolean?} procedure is a predicate that returns @code{#t} if
131its argument is one of the boolean values, otherwise @code{#f}.
132
5c4b24e1 133@rnindex boolean?
38a93523
NJ
134@deffn primitive boolean? obj
135Return @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
39e30745 141@tpindex Numbers
38a93523
NJ
142
143Guile supports a rich ``tower'' of numerical types --- integer,
144rational, real and complex --- and provides an extensive set of
145mathematical and scientific functions for operating on numerical
146data. This section of the manual documents those types and functions.
147
148You may also find it illuminating to read R5RS's presentation of numbers
149in Scheme, which is particularly clear and accessible: see
150@xref{Numbers,,,r5rs}.
151
152@menu
153* Numerical Tower:: Scheme's numerical "tower".
154* Integers:: Whole numbers.
155* Reals and Rationals:: Real and rational numbers.
156* Complex Numbers:: Complex numbers.
157* Exactness:: Exactness and inexactness.
b576faf1 158* Number Syntax:: Read syntax for numerical data.
38a93523
NJ
159* Integer Operations:: Operations on integer values.
160* Comparison:: Comparison predicates.
161* Conversion:: Converting numbers to and from strings.
162* Complex:: Complex number operations.
163* Arithmetic:: Arithmetic functions.
164* Scientific:: Scientific functions.
165* Primitive Numerics:: Primitive numeric functions.
166* Bitwise Operations:: Logical AND, OR, NOT, and so on.
167* Random:: Random number generation.
168@end menu
169
170
171@node Numerical Tower
172@subsection Scheme's Numerical ``Tower''
5c4b24e1 173@rnindex number?
38a93523
NJ
174
175Scheme's numerical ``tower'' consists of the following categories of
176numbers:
177
239d2912 178@itemize @bullet
38a93523
NJ
179@item
180integers (whole numbers)
181
182@item
183rationals (the set of numbers that can be expressed as P/Q where P and Q
184are integers)
185
186@item
187real numbers (the set of numbers that describes all possible positions
188along a one dimensional line)
189
190@item
191complex numbers (the set of numbers that describes all possible
192positions in a two dimensional space)
193@end itemize
194
195It is called a tower because each category ``sits on'' the one that
196follows it, in the sense that every integer is also a rational, every
197rational is also real, and every real number is also a complex number
198(but with zero imaginary part).
199
200Of these, Guile implements integers, reals and complex numbers as
201distinct types. Rationals are implemented as regards the read syntax
202for rational numbers that is specified by R5RS, but are immediately
203converted by Guile to the corresponding real number.
204
205The @code{number?} predicate may be applied to any Scheme value to
206discover whether the value is any of the supported numerical types.
207
38a93523
NJ
208@deffn primitive number? obj
209Return @code{#t} if @var{obj} is any kind of number, @code{#f} else.
210@end deffn
211
212For 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
229The next few subsections document each of Guile's numerical data types
230in detail.
231
38a93523
NJ
232@node Integers
233@subsection Integers
39e30745
MG
234
235@tpindex Integer numbers
236
5c4b24e1 237@rnindex integer?
38a93523
NJ
238
239Integers are whole numbers, that is numbers with no fractional part,
240such as 2, 83 and -3789.
241
242Integers in Guile can be arbitrarily big, as shown by the following
243example.
244
245@lisp
246(define (factorial n)
247 (let loop ((n n) (product 1))
248 (if (= n 0)
249 product
250 (loop (- n 1) (* product n)))))
251
252(factorial 3)
253@result{}
2546
255
256(factorial 20)
257@result{}
2582432902008176640000
259
260(- (factorial 45))
261@result{}
262-119622220865480194561963161495657715064383733760000000000
263@end lisp
264
265Readers whose background is in programming languages where integers are
266limited by the need to fit into just 4 or 8 bytes of memory may find
267this surprising, or suspect that Guile's representation of integers is
268inefficient. In fact, Guile achieves a near optimal balance of
269convenience and efficiency by using the host computer's native
270representation of integers where possible, and a more general
271representation where the required number does not fit in the native
272form. Conversion between these two representations is automatic and
273completely invisible to the Scheme level programmer.
274
275@c REFFIXME Maybe point here to discussion of handling immediates/bignums
276@c on the C level, where the conversion is not so automatic - NJ
277
780ee65e
NJ
278@deffn primitive integer? x
279Return @code{#t} if @var{x} is an integer number, @code{#f} else.
38a93523
NJ
280
281@lisp
282(integer? 487)
283@result{}
284#t
285
286(integer? -3.4)
287@result{}
288#f
289@end lisp
290@end deffn
291
292
293@node Reals and Rationals
294@subsection Real and Rational Numbers
39e30745
MG
295@tpindex Real numbers
296@tpindex Rational numbers
297
5c4b24e1
MG
298@rnindex real?
299@rnindex rational?
38a93523
NJ
300
301Mathematically, the real numbers are the set of numbers that describe
302all possible points along a continuous, infinite, one-dimensional line.
303The rational numbers are the set of all numbers that can be written as
304fractions P/Q, where P and Q are integers. All rational numbers are
305also real, but there are real numbers that are not rational, for example
306the square root of 2, and pi.
307
308Guile represents both real and rational numbers approximately using a
309floating point encoding with limited precision. Even though the actual
310encoding is in binary, it may be helpful to think of it as a decimal
311number with a limited number of significant figures and a decimal point
312somewhere, since this corresponds to the standard notation for non-whole
313numbers. For example:
314
315@lisp
3160.34
317-0.00000142857931198
318-5648394822220000000000.0
3194.0
320@end lisp
321
322The limited precision of Guile's encoding means that any ``real'' number
323in Guile can be written in a rational form, by multiplying and then dividing
324by sufficient powers of 10 (or in fact, 2). For example,
325@code{-0.00000142857931198} is the same as @code{142857931198} divided by
326@code{100000000000000000}. In Guile's current incarnation, therefore,
327the @code{rational?} and @code{real?} predicates are equivalent.
328
329Another aspect of this equivalence is that Guile currently does not
330preserve the exactness that is possible with rational arithmetic.
331If such exactness is needed, it is of course possible to implement
332exact rational arithmetic at the Scheme level using Guile's arbitrary
333size integers.
334
335A planned future revision of Guile's numerical tower will make it
336possible to implement exact representations and arithmetic for both
337rational numbers and real irrational numbers such as square roots,
338and in such a way that the new kinds of number integrate seamlessly
339with those that are already implemented.
340
38a93523
NJ
341@deffn primitive real? obj
342Return @code{#t} if @var{obj} is a real number, @code{#f} else.
343Note that the sets of integer and rational values form subsets
344of the set of real numbers, so the predicate will also be fulfilled
345if @var{obj} is an integer number or a rational number.
346@end deffn
347
780ee65e
NJ
348@deffn primitive rational? x
349Return @code{#t} if @var{x} is a rational number, @code{#f}
350else. Note that the set of integer values forms a subset of
351the set of rational numbers, i. e. the predicate will also be
352fulfilled if @var{x} is an integer number. Real numbers
353will also satisfy this predicate, because of their limited
354precision.
38a93523
NJ
355@end deffn
356
357
358@node Complex Numbers
359@subsection Complex Numbers
39e30745
MG
360@tpindex Complex numbers
361
5c4b24e1 362@rnindex complex?
38a93523
NJ
363
364Complex numbers are the set of numbers that describe all possible points
365in a two-dimensional space. The two coordinates of a particular point
366in this space are known as the @dfn{real} and @dfn{imaginary} parts of
367the complex number that describes that point.
368
369In Guile, complex numbers are written in rectangular form as the sum of
370their real and imaginary parts, using the symbol @code{i} to indicate
371the imaginary part.
372
373@lisp
3743+4i
375@result{}
3763.0+4.0i
377
378(* 3-8i 2.3+0.3i)
379@result{}
3809.3-17.5i
381@end lisp
382
383Guile represents a complex number as a pair of numbers both of which are
384real, so the real and imaginary parts of a complex number have the same
385properties of inexactness and limited precision as single real numbers.
386
780ee65e
NJ
387@deffn primitive complex? x
388Return @code{#t} if @var{x} is a complex number, @code{#f}
389else. Note that the sets of real, rational and integer
390values form subsets of the set of complex numbers, i. e. the
391predicate will also be fulfilled if @var{x} is a real,
392rational or integer number.
38a93523
NJ
393@end deffn
394
395
396@node Exactness
397@subsection Exact and Inexact Numbers
39e30745
MG
398@tpindex Exact numbers
399@tpindex Inexact numbers
400
5c4b24e1
MG
401@rnindex exact?
402@rnindex inexact?
403@rnindex exact->inexact
404@rnindex inexact->exact
38a93523
NJ
405
406R5RS requires that a calculation involving inexact numbers always
407produces an inexact result. To meet this requirement, Guile
408distinguishes between an exact integer value such as @code{5} and the
409corresponding inexact real value which, to the limited precision
410available, has no fractional part, and is printed as @code{5.0}. Guile
411will only convert the latter value to the former when forced to do so by
412an invocation of the @code{inexact->exact} procedure.
413
38a93523 414@deffn primitive exact? x
780ee65e
NJ
415Return @code{#t} if @var{x} is an exact number, @code{#f}
416otherwise.
38a93523
NJ
417@end deffn
418
38a93523 419@deffn primitive inexact? x
780ee65e
NJ
420Return @code{#t} if @var{x} is an inexact number, @code{#f}
421else.
38a93523
NJ
422@end deffn
423
38a93523 424@deffn primitive inexact->exact z
ae9f3a15 425Return an exact number that is numerically closest to @var{z}.
38a93523
NJ
426@end deffn
427
428@c begin (texi-doc-string "guile" "exact->inexact")
fcaedf99
MG
429@deffn primitive exact->inexact z
430Convert the number @var{z} to its inexact representation.
38a93523
NJ
431@end deffn
432
433
434@node Number Syntax
435@subsection Read Syntax for Numerical Data
436
437The read syntax for integers is a string of digits, optionally
438preceded by a minus or plus character, a code indicating the
439base in which the integer is encoded, and a code indicating whether
440the number is exact or inexact. The supported base codes are:
441
442@itemize @bullet
443@item
444@code{#b}, @code{#B} --- the integer is written in binary (base 2)
445
446@item
447@code{#o}, @code{#O} --- the integer is written in octal (base 8)
448
449@item
450@code{#d}, @code{#D} --- the integer is written in decimal (base 10)
451
452@item
453@code{#x}, @code{#X} --- the integer is written in hexadecimal (base 16).
454@end itemize
455
456If the base code is omitted, the integer is assumed to be decimal. The
457following examples show how these base codes are used.
458
459@lisp
460-13
461@result{}
462-13
463
464#d-13
465@result{}
466-13
467
468#x-13
469@result{}
470-19
471
472#b+1101
473@result{}
47413
475
476#o377
477@result{}
478255
479@end lisp
480
481The codes for indicating exactness (which can, incidentally, be applied
482to all numerical values) are:
483
484@itemize @bullet
485@item
486@code{#e}, @code{#E} --- the number is exact
487
488@item
489@code{#i}, @code{#I} --- the number is inexact.
490@end itemize
491
492If the exactness indicator is omitted, the integer is assumed to be exact,
493since Guile's internal representation for integers is always exact.
494Real numbers have limited precision similar to the precision of the
495@code{double} type in C. A consequence of the limited precision is that
496all real numbers in Guile are also rational, since any number R with a
497limited number of decimal places, say N, can be made into an integer by
498multiplying by 10^N.
499
500
501@node Integer Operations
502@subsection Operations on Integer Values
5c4b24e1
MG
503@rnindex odd?
504@rnindex even?
505@rnindex quotient
506@rnindex remainder
507@rnindex modulo
508@rnindex gcd
509@rnindex lcm
38a93523 510
38a93523 511@deffn primitive odd? n
780ee65e
NJ
512Return @code{#t} if @var{n} is an odd number, @code{#f}
513otherwise.
38a93523
NJ
514@end deffn
515
38a93523 516@deffn primitive even? n
780ee65e
NJ
517Return @code{#t} if @var{n} is an even number, @code{#f}
518otherwise.
38a93523
NJ
519@end deffn
520
521@c begin (texi-doc-string "guile" "quotient")
522@deffn primitive quotient
fcaedf99 523Return the quotient of the numbers @var{x} and @var{y}.
38a93523
NJ
524@end deffn
525
526@c begin (texi-doc-string "guile" "remainder")
527@deffn primitive remainder
fcaedf99
MG
528Return the remainder of the numbers @var{x} and @var{y}.
529@lisp
530(remainder 13 4) @result{} 1
531(remainder -13 4) @result{} -1
532@end lisp
38a93523
NJ
533@end deffn
534
535@c begin (texi-doc-string "guile" "modulo")
536@deffn primitive modulo
fcaedf99
MG
537Return the modulo of the numbers @var{x} and @var{y}.
538@lisp
539(modulo 13 4) @result{} 1
540(modulo -13 4) @result{} 3
541@end lisp
38a93523
NJ
542@end deffn
543
544@c begin (texi-doc-string "guile" "gcd")
545@deffn primitive gcd
fcaedf99
MG
546Return the greatest common divisor of all arguments.
547If called without arguments, 0 is returned.
38a93523
NJ
548@end deffn
549
550@c begin (texi-doc-string "guile" "lcm")
551@deffn primitive lcm
fcaedf99
MG
552Return the least common multiple of the arguments.
553If called without arguments, 1 is returned.
38a93523
NJ
554@end deffn
555
556
557@node Comparison
558@subsection Comparison Predicates
5c4b24e1
MG
559@rnindex zero?
560@rnindex positive?
561@rnindex negative?
38a93523
NJ
562
563@c begin (texi-doc-string "guile" "=")
564@deffn primitive =
fcaedf99 565Return @code{#t} if all parameters are numerically equal.
38a93523
NJ
566@end deffn
567
568@c begin (texi-doc-string "guile" "<")
569@deffn primitive <
fcaedf99
MG
570Return @code{#t} if the list of parameters is monotonically
571increasing.
38a93523
NJ
572@end deffn
573
574@c begin (texi-doc-string "guile" ">")
575@deffn primitive >
fcaedf99
MG
576Return @code{#t} if the list of parameters is monotonically
577decreasing.
38a93523
NJ
578@end deffn
579
580@c begin (texi-doc-string "guile" "<=")
581@deffn primitive <=
fcaedf99
MG
582Return @code{#t} if the list of parameters is monotonically
583non-decreasing.
38a93523
NJ
584@end deffn
585
586@c begin (texi-doc-string "guile" ">=")
587@deffn primitive >=
fcaedf99
MG
588Return @code{#t} if the list of parameters is monotonically
589non-increasing.
38a93523
NJ
590@end deffn
591
592@c begin (texi-doc-string "guile" "zero?")
593@deffn primitive zero?
fcaedf99
MG
594Return @code{#t} if @var{z} is an exact or inexact number equal to
595zero.
38a93523
NJ
596@end deffn
597
598@c begin (texi-doc-string "guile" "positive?")
599@deffn primitive positive?
fcaedf99
MG
600Return @code{#t} if @var{x} is an exact or inexact number greater than
601zero.
38a93523
NJ
602@end deffn
603
604@c begin (texi-doc-string "guile" "negative?")
605@deffn primitive negative?
fcaedf99
MG
606Return @code{#t} if @var{x} is an exact or inexact number less than
607zero.
38a93523
NJ
608@end deffn
609
610
611@node Conversion
612@subsection Converting Numbers To and From Strings
5c4b24e1
MG
613@rnindex number->string
614@rnindex string->number
38a93523 615
38a93523
NJ
616@deffn primitive number->string n [radix]
617Return a string holding the external representation of the
780ee65e
NJ
618number @var{n} in the given @var{radix}. If @var{n} is
619inexact, a radix of 10 will be used.
38a93523
NJ
620@end deffn
621
38a93523 622@deffn primitive string->number string [radix]
ae9f3a15 623Return a number of the maximally precise representation
780ee65e
NJ
624expressed by the given @var{string}. @var{radix} must be an
625exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
626is a default radix that may be overridden by an explicit radix
627prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
628supplied, then the default radix is 10. If string is not a
629syntactically valid notation for a number, then
630@code{string->number} returns @code{#f}.
38a93523
NJ
631@end deffn
632
633
634@node Complex
635@subsection Complex Number Operations
5c4b24e1
MG
636@rnindex make-rectangular
637@rnindex make-polar
638@rnindex real-part
639@rnindex imag-part
640@rnindex magnitude
641@rnindex angle
38a93523 642
38a93523 643@deffn primitive make-rectangular real imaginary
780ee65e
NJ
644Return a complex number constructed of the given @var{real} and
645@var{imaginary} parts.
38a93523
NJ
646@end deffn
647
38a93523 648@deffn primitive make-polar x y
780ee65e 649Return the complex number @var{x} * e^(i * @var{y}).
38a93523
NJ
650@end deffn
651
652@c begin (texi-doc-string "guile" "real-part")
653@deffn primitive real-part
fcaedf99 654Return the real part of the number @var{z}.
38a93523
NJ
655@end deffn
656
657@c begin (texi-doc-string "guile" "imag-part")
658@deffn primitive imag-part
fcaedf99 659Return the imaginary part of the number @var{z}.
38a93523
NJ
660@end deffn
661
662@c begin (texi-doc-string "guile" "magnitude")
663@deffn primitive magnitude
fcaedf99
MG
664Return the magnitude of the number @var{z}. This is the same as
665@code{abs} for real arguments, but also allows complex numbers.
38a93523
NJ
666@end deffn
667
668@c begin (texi-doc-string "guile" "angle")
669@deffn primitive angle
fcaedf99 670Return the angle of the complex number @var{z}.
38a93523
NJ
671@end deffn
672
673
674@node Arithmetic
675@subsection Arithmetic Functions
5c4b24e1
MG
676@rnindex max
677@rnindex min
678@rnindex +
679@rnindex *
680@rnindex -
681@rnindex /
682@rnindex abs
683@rnindex floor
684@rnindex ceiling
685@rnindex truncate
686@rnindex round
38a93523
NJ
687
688@c begin (texi-doc-string "guile" "+")
fcaedf99
MG
689@deffn primitive + z1 @dots{}
690Return the sum of all parameter values. Return 0 if called without any
691parameters.
38a93523
NJ
692@end deffn
693
694@c begin (texi-doc-string "guile" "-")
fcaedf99 695@deffn primitive - z1 z2 @dots{}
cee2ed4f
MG
696If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
697the sum of all but the first argument are subtracted from the first
698argument.
38a93523
NJ
699@end deffn
700
701@c begin (texi-doc-string "guile" "*")
fcaedf99
MG
702@deffn primitive * z1 @dots{}
703Return the product of all arguments. If called without arguments, 1 is
704returned.
38a93523
NJ
705@end deffn
706
707@c begin (texi-doc-string "guile" "/")
fcaedf99 708@deffn primitive / z1 z2 @dots{}
cee2ed4f
MG
709Divide the first argument by the product of the remaining arguments. If
710called with one argument @var{z1}, 1/@var{z1} is returned.
38a93523
NJ
711@end deffn
712
713@c begin (texi-doc-string "guile" "abs")
fcaedf99
MG
714@deffn primitive abs x
715Return the absolute value of @var{x}.
38a93523
NJ
716@end deffn
717
718@c begin (texi-doc-string "guile" "max")
fcaedf99
MG
719@deffn primitive max x1 x2 @dots{}
720Return the maximum of all parameter values.
38a93523
NJ
721@end deffn
722
723@c begin (texi-doc-string "guile" "min")
fcaedf99
MG
724@deffn primitive min x1 x2 @dots{}
725Return the minium of all parameter values.
38a93523
NJ
726@end deffn
727
728@c begin (texi-doc-string "guile" "truncate")
729@deffn primitive truncate
fcaedf99 730Round the inexact number @var{x} towards zero.
38a93523
NJ
731@end deffn
732
733@c begin (texi-doc-string "guile" "round")
fcaedf99
MG
734@deffn primitive round x
735Round the inexact number @var{x} towards zero.
38a93523
NJ
736@end deffn
737
738@c begin (texi-doc-string "guile" "floor")
fcaedf99
MG
739@deffn primitive floor x
740Round the number @var{x} towards minus infinity.
38a93523
NJ
741@end deffn
742
743@c begin (texi-doc-string "guile" "ceiling")
fcaedf99
MG
744@deffn primitive ceiling x
745Round the number @var{x} towards infinity.
38a93523
NJ
746@end deffn
747
748
749@node Scientific
750@subsection Scientific Functions
751
752The following procedures accept any kind of number as arguments,
753including complex numbers.
754
cee2ed4f 755@rnindex sqrt
38a93523
NJ
756@c begin (texi-doc-string "guile" "sqrt")
757@deffn procedure sqrt z
758Return the square root of @var{z}.
759@end deffn
760
cee2ed4f 761@rnindex expt
38a93523
NJ
762@c begin (texi-doc-string "guile" "expt")
763@deffn procedure expt z1 z2
764Return @var{z1} raised to the power of @var{z2}.
765@end deffn
766
cee2ed4f 767@rnindex sin
38a93523
NJ
768@c begin (texi-doc-string "guile" "sin")
769@deffn procedure sin z
770Return the sine of @var{z}.
771@end deffn
772
cee2ed4f 773@rnindex cos
38a93523
NJ
774@c begin (texi-doc-string "guile" "cos")
775@deffn procedure cos z
776Return the cosine of @var{z}.
777@end deffn
778
cee2ed4f 779@rnindex tan
38a93523
NJ
780@c begin (texi-doc-string "guile" "tan")
781@deffn procedure tan z
782Return the tangent of @var{z}.
783@end deffn
784
cee2ed4f 785@rnindex asin
38a93523
NJ
786@c begin (texi-doc-string "guile" "asin")
787@deffn procedure asin z
788Return the arcsine of @var{z}.
789@end deffn
790
cee2ed4f 791@rnindex acos
38a93523
NJ
792@c begin (texi-doc-string "guile" "acos")
793@deffn procedure acos z
794Return the arccosine of @var{z}.
795@end deffn
796
cee2ed4f 797@rnindex atan
38a93523
NJ
798@c begin (texi-doc-string "guile" "atan")
799@deffn procedure atan z
800Return the arctangent of @var{z}.
801@end deffn
802
cee2ed4f 803@rnindex exp
38a93523
NJ
804@c begin (texi-doc-string "guile" "exp")
805@deffn procedure exp z
806Return e to the power of @var{z}, where e is the base of natural
807logarithms (2.71828@dots{}).
808@end deffn
809
cee2ed4f 810@rnindex log
38a93523
NJ
811@c begin (texi-doc-string "guile" "log")
812@deffn procedure log z
813Return the natural logarithm of @var{z}.
814@end deffn
815
816@c begin (texi-doc-string "guile" "log10")
817@deffn procedure log10 z
818Return the base 10 logarithm of @var{z}.
819@end deffn
820
821@c begin (texi-doc-string "guile" "sinh")
822@deffn procedure sinh z
823Return the hyperbolic sine of @var{z}.
824@end deffn
825
826@c begin (texi-doc-string "guile" "cosh")
827@deffn procedure cosh z
828Return the hyperbolic cosine of @var{z}.
829@end deffn
830
831@c begin (texi-doc-string "guile" "tanh")
832@deffn procedure tanh z
833Return the hyperbolic tangent of @var{z}.
834@end deffn
835
836@c begin (texi-doc-string "guile" "asinh")
837@deffn procedure asinh z
838Return the hyperbolic arcsine of @var{z}.
839@end deffn
840
841@c begin (texi-doc-string "guile" "acosh")
842@deffn procedure acosh z
843Return the hyperbolic arccosine of @var{z}.
844@end deffn
845
846@c begin (texi-doc-string "guile" "atanh")
847@deffn procedure atanh z
848Return the hyperbolic arctangent of @var{z}.
849@end deffn
850
851
852@node Primitive Numerics
853@subsection Primitive Numeric Functions
854
855Many of Guile's numeric procedures which accept any kind of numbers as
856arguments, including complex numbers, are implemented as Scheme
857procedures that use the following real number-based primitives. These
858primitives signal an error if they are called with complex arguments.
859
860@c begin (texi-doc-string "guile" "$abs")
861@deffn primitive $abs x
862Return the absolute value of @var{x}.
863@end deffn
864
865@c begin (texi-doc-string "guile" "$sqrt")
866@deffn primitive $sqrt x
867Return the square root of @var{x}.
868@end deffn
869
38a93523
NJ
870@deffn primitive $expt x y
871Return @var{x} raised to the power of @var{y}. This
872procedure does not accept complex arguments.
873@end deffn
874
875@c begin (texi-doc-string "guile" "$sin")
876@deffn primitive $sin x
877Return the sine of @var{x}.
878@end deffn
879
880@c begin (texi-doc-string "guile" "$cos")
881@deffn primitive $cos x
882Return the cosine of @var{x}.
883@end deffn
884
885@c begin (texi-doc-string "guile" "$tan")
886@deffn primitive $tan x
887Return the tangent of @var{x}.
888@end deffn
889
890@c begin (texi-doc-string "guile" "$asin")
891@deffn primitive $asin x
892Return the arcsine of @var{x}.
893@end deffn
894
895@c begin (texi-doc-string "guile" "$acos")
896@deffn primitive $acos x
897Return the arccosine of @var{x}.
898@end deffn
899
900@c begin (texi-doc-string "guile" "$atan")
901@deffn primitive $atan x
902Return the arctangent of @var{x} in the range -PI/2 to PI/2.
903@end deffn
904
38a93523
NJ
905@deffn primitive $atan2 x y
906Return the arc tangent of the two arguments @var{x} and
907@var{y}. This is similar to calculating the arc tangent of
908@var{x} / @var{y}, except that the signs of both arguments
909are used to determine the quadrant of the result. This
910procedure does not accept complex arguments.
911@end deffn
912
913@c begin (texi-doc-string "guile" "$exp")
914@deffn primitive $exp x
915Return e to the power of @var{x}, where e is the base of natural
916logarithms (2.71828@dots{}).
917@end deffn
918
919@c begin (texi-doc-string "guile" "$log")
920@deffn primitive $log x
921Return the natural logarithm of @var{x}.
922@end deffn
923
924@c begin (texi-doc-string "guile" "$sinh")
925@deffn primitive $sinh x
926Return the hyperbolic sine of @var{x}.
927@end deffn
928
929@c begin (texi-doc-string "guile" "$cosh")
930@deffn primitive $cosh x
931Return the hyperbolic cosine of @var{x}.
932@end deffn
933
934@c begin (texi-doc-string "guile" "$tanh")
935@deffn primitive $tanh x
936Return the hyperbolic tangent of @var{x}.
937@end deffn
938
939@c begin (texi-doc-string "guile" "$asinh")
940@deffn primitive $asinh x
941Return the hyperbolic arcsine of @var{x}.
942@end deffn
943
944@c begin (texi-doc-string "guile" "$acosh")
945@deffn primitive $acosh x
946Return the hyperbolic arccosine of @var{x}.
947@end deffn
948
949@c begin (texi-doc-string "guile" "$atanh")
950@deffn primitive $atanh x
951Return the hyperbolic arctangent of @var{x}.
952@end deffn
953
954
955@node Bitwise Operations
956@subsection Bitwise Operations
957
38a93523 958@deffn primitive logand n1 n2
ae9f3a15 959Return the integer which is the bit-wise AND of the two integer
38a93523 960arguments.
7a095584 961
38a93523
NJ
962@lisp
963(number->string (logand #b1100 #b1010) 2)
964 @result{} "1000"
965@end lisp
966@end deffn
967
38a93523 968@deffn primitive logior n1 n2
ae9f3a15 969Return the integer which is the bit-wise OR of the two integer
38a93523 970arguments.
7a095584 971
38a93523
NJ
972@lisp
973(number->string (logior #b1100 #b1010) 2)
974 @result{} "1110"
975@end lisp
976@end deffn
977
38a93523 978@deffn primitive logxor n1 n2
ae9f3a15 979Return the integer which is the bit-wise XOR of the two integer
38a93523 980arguments.
7a095584 981
38a93523
NJ
982@lisp
983(number->string (logxor #b1100 #b1010) 2)
984 @result{} "110"
985@end lisp
986@end deffn
987
38a93523 988@deffn primitive lognot n
ae9f3a15
MG
989Return the integer which is the 2s-complement of the integer
990argument.
7a095584 991
38a93523
NJ
992@lisp
993(number->string (lognot #b10000000) 2)
994 @result{} "-10000001"
995(number->string (lognot #b0) 2)
996 @result{} "-1"
997@end lisp
998@end deffn
999
ae9f3a15
MG
1000@deffn primitive logtest j k
1001@lisp
38a93523
NJ
1002(logtest j k) @equiv{} (not (zero? (logand j k)))
1003
1004(logtest #b0100 #b1011) @result{} #f
1005(logtest #b0100 #b0111) @result{} #t
ae9f3a15 1006@end lisp
38a93523
NJ
1007@end deffn
1008
38a93523 1009@deffn primitive logbit? index j
ae9f3a15 1010@lisp
38a93523
NJ
1011(logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1012
1013(logbit? 0 #b1101) @result{} #t
1014(logbit? 1 #b1101) @result{} #f
1015(logbit? 2 #b1101) @result{} #t
1016(logbit? 3 #b1101) @result{} #t
1017(logbit? 4 #b1101) @result{} #f
ae9f3a15 1018@end lisp
38a93523
NJ
1019@end deffn
1020
38a93523 1021@deffn primitive ash n cnt
ae9f3a15
MG
1022The function ash performs an arithmetic shift left by @var{cnt}
1023bits (or shift right, if @var{cnt} is negative). 'Arithmetic'
1024means, that the function does not guarantee to keep the bit
1025structure of @var{n}, but rather guarantees that the result
1026will always be rounded towards minus infinity. Therefore, the
1027results of ash and a corresponding bitwise shift will differ if
1028@var{n} is negative.
7a095584 1029
38a93523 1030Formally, the function returns an integer equivalent to
780ee65e 1031@code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
7a095584 1032
38a93523 1033@lisp
ae9f3a15
MG
1034(number->string (ash #b1 3) 2) @result{} "1000"
1035(number->string (ash #b1010 -1) 2) @result{} "101"
38a93523
NJ
1036@end lisp
1037@end deffn
1038
38a93523 1039@deffn primitive logcount n
ae9f3a15
MG
1040Return the number of bits in integer @var{n}. If integer is
1041positive, the 1-bits in its binary representation are counted.
1042If negative, the 0-bits in its two's-complement binary
1043representation are counted. If 0, 0 is returned.
7a095584 1044
38a93523
NJ
1045@lisp
1046(logcount #b10101010)
1047 @result{} 4
1048(logcount 0)
1049 @result{} 0
1050(logcount -2)
1051 @result{} 1
1052@end lisp
1053@end deffn
1054
38a93523 1055@deffn primitive integer-length n
ae9f3a15 1056Return the number of bits neccessary to represent @var{n}.
7a095584 1057
38a93523
NJ
1058@lisp
1059(integer-length #b10101010)
1060 @result{} 8
1061(integer-length 0)
1062 @result{} 0
1063(integer-length #b1111)
1064 @result{} 4
1065@end lisp
1066@end deffn
1067
38a93523 1068@deffn primitive integer-expt n k
ae9f3a15
MG
1069Return @var{n} raised to the non-negative integer exponent
1070@var{k}.
7a095584 1071
38a93523
NJ
1072@lisp
1073(integer-expt 2 5)
1074 @result{} 32
1075(integer-expt -3 3)
1076 @result{} -27
1077@end lisp
1078@end deffn
1079
38a93523 1080@deffn primitive bit-extract n start end
ae9f3a15
MG
1081Return the integer composed of the @var{start} (inclusive)
1082through @var{end} (exclusive) bits of @var{n}. The
1083@var{start}th bit becomes the 0-th bit in the result.
7a095584 1084
38a93523
NJ
1085@lisp
1086(number->string (bit-extract #b1101101010 0 4) 2)
1087 @result{} "1010"
1088(number->string (bit-extract #b1101101010 4 9) 2)
1089 @result{} "10110"
1090@end lisp
1091@end deffn
1092
1093
1094@node Random
1095@subsection Random Number Generation
1096
38a93523
NJ
1097@deffn primitive copy-random-state [state]
1098Return a copy of the random state @var{state}.
1099@end deffn
1100
38a93523
NJ
1101@deffn primitive random n [state]
1102Return a number in [0,N).
7a095584 1103
38a93523
NJ
1104Accepts a positive integer or real n and returns a
1105number of the same type between zero (inclusive) and
1106N (exclusive). The values returned have a uniform
1107distribution.
7a095584 1108
38a93523
NJ
1109The optional argument @var{state} must be of the type produced
1110by @code{seed->random-state}. It defaults to the value of the
1111variable @var{*random-state*}. This object is used to maintain
1112the state of the pseudo-random-number generator and is altered
1113as a side effect of the random operation.
1114@end deffn
1115
38a93523 1116@deffn primitive random:exp [state]
ae9f3a15
MG
1117Return an inexact real in an exponential distribution with mean
11181. For an exponential distribution with mean u use (* u
1119(random:exp)).
38a93523
NJ
1120@end deffn
1121
38a93523
NJ
1122@deffn primitive random:hollow-sphere! v [state]
1123Fills vect with inexact real random numbers
1124the sum of whose squares is equal to 1.0.
1125Thinking of vect as coordinates in space of
1126dimension n = (vector-length vect), the coordinates
1127are uniformly distributed over the surface of the
1128unit n-shere.
1129@end deffn
1130
38a93523 1131@deffn primitive random:normal [state]
ae9f3a15
MG
1132Return an inexact real in a normal distribution. The
1133distribution used has mean 0 and standard deviation 1. For a
1134normal distribution with mean m and standard deviation d use
1135@code{(+ m (* d (random:normal)))}.
38a93523
NJ
1136@end deffn
1137
38a93523
NJ
1138@deffn primitive random:normal-vector! v [state]
1139Fills vect with inexact real random numbers that are
1140independent and standard normally distributed
1141(i.e., with mean 0 and variance 1).
1142@end deffn
1143
38a93523
NJ
1144@deffn primitive random:solid-sphere! v [state]
1145Fills vect with inexact real random numbers
1146the sum of whose squares is less than 1.0.
1147Thinking of vect as coordinates in space of
1148dimension n = (vector-length vect), the coordinates
1149are uniformly distributed within the unit n-shere.
1150The sum of the squares of the numbers is returned.
1151@end deffn
1152
38a93523 1153@deffn primitive random:uniform [state]
ae9f3a15
MG
1154Return a uniformly distributed inexact real random number in
1155[0,1).
38a93523
NJ
1156@end deffn
1157
38a93523
NJ
1158@deffn primitive seed->random-state seed
1159Return a new random state using @var{seed}.
1160@end deffn
1161
1162
1163@node Characters
1164@section Characters
39e30745 1165@tpindex Characters
38a93523
NJ
1166
1167Most of the characters in the ASCII character set may be referred to by
1168name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and so on.
1169The following table describes the ASCII names for each character.
1170
1171@multitable @columnfractions .25 .25 .25 .25
1172@item 0 = @code{#\nul}
1173 @tab 1 = @code{#\soh}
1174 @tab 2 = @code{#\stx}
1175 @tab 3 = @code{#\etx}
1176@item 4 = @code{#\eot}
1177 @tab 5 = @code{#\enq}
1178 @tab 6 = @code{#\ack}
1179 @tab 7 = @code{#\bel}
1180@item 8 = @code{#\bs}
1181 @tab 9 = @code{#\ht}
1182 @tab 10 = @code{#\nl}
1183 @tab 11 = @code{#\vt}
1184@item 12 = @code{#\np}
1185 @tab 13 = @code{#\cr}
1186 @tab 14 = @code{#\so}
1187 @tab 15 = @code{#\si}
1188@item 16 = @code{#\dle}
1189 @tab 17 = @code{#\dc1}
1190 @tab 18 = @code{#\dc2}
1191 @tab 19 = @code{#\dc3}
1192@item 20 = @code{#\dc4}
1193 @tab 21 = @code{#\nak}
1194 @tab 22 = @code{#\syn}
1195 @tab 23 = @code{#\etb}
1196@item 24 = @code{#\can}
1197 @tab 25 = @code{#\em}
1198 @tab 26 = @code{#\sub}
1199 @tab 27 = @code{#\esc}
1200@item 28 = @code{#\fs}
1201 @tab 29 = @code{#\gs}
1202 @tab 30 = @code{#\rs}
1203 @tab 31 = @code{#\us}
1204@item 32 = @code{#\sp}
1205@end multitable
1206
1207The @code{delete} character (octal 177) may be referred to with the name
1208@code{#\del}.
1209
1210Several characters have more than one name:
1211
1212@itemize @bullet
1213@item
cee2ed4f 1214@code{#\space}, @code{#\sp}
38a93523 1215@item
cee2ed4f 1216@code{#\newline}, @code{#\nl}
38a93523 1217@item
cee2ed4f 1218@code{#\tab}, @code{#\ht}
38a93523 1219@item
cee2ed4f 1220@code{#\backspace}, @code{#\bs}
38a93523 1221@item
cee2ed4f 1222@code{#\return}, @code{#\cr}
38a93523 1223@item
cee2ed4f 1224@code{#\page}, @code{#\np}
38a93523 1225@item
cee2ed4f 1226@code{#\null}, @code{#\nul}
38a93523
NJ
1227@end itemize
1228
f4f2b29a 1229@rnindex char?
38a93523
NJ
1230@deffn primitive char? x
1231Return @code{#t} iff @var{x} is a character, else @code{#f}.
1232@end deffn
1233
f4f2b29a 1234@rnindex char=?
38a93523
NJ
1235@deffn primitive char=? x y
1236Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1237@end deffn
1238
f4f2b29a 1239@rnindex char<?
38a93523
NJ
1240@deffn primitive char<? x y
1241Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence,
1242else @code{#f}.
1243@end deffn
1244
f4f2b29a 1245@rnindex char<=?
38a93523
NJ
1246@deffn primitive char<=? x y
1247Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1248ASCII sequence, else @code{#f}.
1249@end deffn
1250
f4f2b29a 1251@rnindex char>?
38a93523
NJ
1252@deffn primitive char>? x y
1253Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1254sequence, else @code{#f}.
1255@end deffn
1256
f4f2b29a 1257@rnindex char>=?
38a93523
NJ
1258@deffn primitive char>=? x y
1259Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1260ASCII sequence, else @code{#f}.
1261@end deffn
1262
f4f2b29a 1263@rnindex char-ci=?
38a93523
NJ
1264@deffn primitive char-ci=? x y
1265Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1266case, else @code{#f}.
1267@end deffn
1268
f4f2b29a 1269@rnindex char-ci<?
38a93523
NJ
1270@deffn primitive char-ci<? x y
1271Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence
1272ignoring case, else @code{#f}.
1273@end deffn
1274
f4f2b29a 1275@rnindex char-ci<=?
38a93523
NJ
1276@deffn primitive char-ci<=? x y
1277Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1278ASCII sequence ignoring case, else @code{#f}.
1279@end deffn
1280
f4f2b29a 1281@rnindex char-ci>?
38a93523
NJ
1282@deffn primitive char-ci>? x y
1283Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
1284sequence ignoring case, else @code{#f}.
1285@end deffn
1286
f4f2b29a 1287@rnindex char-ci>=?
38a93523
NJ
1288@deffn primitive char-ci>=? x y
1289Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1290ASCII sequence ignoring case, else @code{#f}.
1291@end deffn
1292
f4f2b29a 1293@rnindex char-alphabetic?
38a93523
NJ
1294@deffn primitive char-alphabetic? chr
1295Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1296Alphabetic means the same thing as the isalpha C library function.
1297@end deffn
1298
f4f2b29a 1299@rnindex char-numeric?
38a93523
NJ
1300@deffn primitive char-numeric? chr
1301Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1302Numeric means the same thing as the isdigit C library function.
1303@end deffn
1304
f4f2b29a 1305@rnindex char-whitespace?
38a93523
NJ
1306@deffn primitive char-whitespace? chr
1307Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1308Whitespace means the same thing as the isspace C library function.
1309@end deffn
1310
f4f2b29a 1311@rnindex char-upper-case?
38a93523
NJ
1312@deffn primitive char-upper-case? chr
1313Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1314Uppercase means the same thing as the isupper C library function.
1315@end deffn
1316
f4f2b29a 1317@rnindex char-lower-case?
38a93523
NJ
1318@deffn primitive char-lower-case? chr
1319Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1320Lowercase means the same thing as the islower C library function.
1321@end deffn
1322
38a93523
NJ
1323@deffn primitive char-is-both? chr
1324Return @code{#t} iff @var{chr} is either uppercase or lowercase, else @code{#f}.
1325Uppercase and lowercase are as defined by the isupper and islower
1326C library functions.
1327@end deffn
1328
f4f2b29a 1329@rnindex char->integer
38a93523
NJ
1330@deffn primitive char->integer chr
1331Return the number corresponding to ordinal position of @var{chr} in the
1332ASCII sequence.
1333@end deffn
1334
f4f2b29a 1335@rnindex integer->char
38a93523
NJ
1336@deffn primitive integer->char n
1337Return the character at position @var{n} in the ASCII sequence.
1338@end deffn
1339
f4f2b29a 1340@rnindex char-upcase
38a93523
NJ
1341@deffn primitive char-upcase chr
1342Return the uppercase character version of @var{chr}.
1343@end deffn
1344
f4f2b29a 1345@rnindex char-downcase
38a93523
NJ
1346@deffn primitive char-downcase chr
1347Return the lowercase character version of @var{chr}.
1348@end deffn
1349
1350
1351@node Strings
1352@section Strings
39e30745 1353@tpindex Strings
38a93523 1354
fb02eb66 1355Strings are fixed-length sequences of characters. They can be created
b576faf1
MG
1356by calling constructor procedures, but they can also literally get
1357entered at the REPL or in Scheme source files.
1358
b576faf1
MG
1359Guile provides a rich set of string processing procedures, because text
1360handling is very important when Guile is used as a scripting language.
38a93523 1361
5c4b24e1 1362Strings always carry the information about how many characters they are
fb02eb66 1363composed of with them, so there is no special end-of-string character,
5c4b24e1
MG
1364like in C. That means that Scheme strings can contain any character,
1365even the NUL character @code{'\0'}. But note: Since most operating
1366system calls dealing with strings (such as for file operations) expect
fb02eb66 1367strings to be zero-terminated, they might do unexpected things when
5c4b24e1
MG
1368called with string containing unusal characters.
1369
38a93523 1370@menu
5c4b24e1 1371* String Syntax:: Read syntax for strings.
b576faf1
MG
1372* String Predicates:: Testing strings for certain properties.
1373* String Constructors:: Creating new string objects.
1374* List/String Conversion:: Converting from/to lists of characters.
1375* String Selection:: Select portions from strings.
1376* String Modification:: Modify parts or whole strings.
1377* String Comparison:: Lexicographic ordering predicates.
1378* String Searching:: Searching in strings.
1379* Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1380* Appending Strings:: Appending strings to form a new string.
1381* String Miscellanea:: Miscellaneous string procedures.
38a93523
NJ
1382@end menu
1383
5c4b24e1
MG
1384@node String Syntax
1385@subsection String Read Syntax
1386
da54ce85
MG
1387The read syntax for strings is an arbitrarily long sequence of
1388characters enclosed in double quotes (@code{"}). @footnote{Actually, the
1389current implementation restricts strings to a length of 2^24
1390characters.} If you want to insert a double quote character into a
1391string literal, it must be prefixed with a backslash @code{\} character
1392(called an @emph{escape character}).
5c4b24e1
MG
1393
1394The following are examples of string literals:
1395
1396@lisp
1397"foo"
1398"bar plonk"
1399"Hello World"
1400"\"Hi\", he said."
1401@end lisp
1402
1403@c FIXME::martin: What about escape sequences like \r, \n etc.?
1404
b576faf1
MG
1405@node String Predicates
1406@subsection String Predicates
1407
1408The following procedures can be used to check whether a given string
1409fulfills some specified property.
1410
5c4b24e1 1411@rnindex string?
b576faf1 1412@deffn primitive string? obj
ae9f3a15 1413Return @code{#t} iff @var{obj} is a string, else returns
b576faf1
MG
1414@code{#f}.
1415@end deffn
1416
b576faf1 1417@deffn primitive string-null? str
ae9f3a15
MG
1418Return @code{#t} if @var{str}'s length is nonzero, and
1419@code{#f} otherwise.
1420@lisp
b576faf1 1421(string-null? "") @result{} #t
ae9f3a15
MG
1422y @result{} "foo"
1423(string-null? y) @result{} #f
1424@end lisp
b576faf1
MG
1425@end deffn
1426
1427@node String Constructors
1428@subsection String Constructors
1429
1430The string constructor procedures create new string objects, possibly
1431initializing them with some specified character data.
1432
1433@c FIXME::martin: list->string belongs into `List/String Conversion'
38a93523 1434
5c4b24e1
MG
1435@rnindex string
1436@rnindex list->string
38a93523
NJ
1437@deffn primitive string . chrs
1438@deffnx primitive list->string chrs
ae9f3a15 1439Return a newly allocated string composed of the arguments,
38a93523
NJ
1440@var{chrs}.
1441@end deffn
1442
5c4b24e1 1443@rnindex make-string
38a93523
NJ
1444@deffn primitive make-string k [chr]
1445Return a newly allocated string of
1446length @var{k}. If @var{chr} is given, then all elements of
1447the string are initialized to @var{chr}, otherwise the contents
1448of the @var{string} are unspecified.
1449@end deffn
1450
b576faf1
MG
1451@node List/String Conversion
1452@subsection List/String conversion
1453
1454When processing strings, it is often convenient to first convert them
1455into a list representation by using the procedure @code{string->list},
1456work with the resulting list, and then convert it back into a string.
1457These procedures are useful for similar tasks.
1458
5c4b24e1 1459@rnindex string->list
b576faf1 1460@deffn primitive string->list str
ae9f3a15
MG
1461Return a newly allocated list of the characters that make up
1462the given string @var{str}. @code{string->list} and
1463@code{list->string} are inverses as far as @samp{equal?} is
1464concerned.
38a93523
NJ
1465@end deffn
1466
76f944c3
MG
1467@deffn primitive string-split str chr
1468Split the string @var{str} into the a list of the substrings delimited
1469by appearances of the character @var{chr}. Note that an empty substring
1470between separator characters will result in an empty string in the
1471result list.
1472@lisp
1473(string-split "root:x:0:0:root:/root:/bin/bash" #\:)
1474@result{}
1475("root" "x" "0" "0" "root" "/root" "/bin/bash")
1476
1477(string-split "::" #\:)
1478@result{}
1479("" "" "")
1480
1481(string-split "" #\:)
1482@result{}
1483("")
1484@end lisp
1485@end deffn
1486
1487
b576faf1
MG
1488@node String Selection
1489@subsection String Selection
1490
1491Portions of strings can be extracted by these procedures.
1492@code{string-ref} delivers individual characters whereas
1493@code{substring} can be used to extract substrings from longer strings.
1494
5c4b24e1 1495@rnindex string-length
38a93523
NJ
1496@deffn primitive string-length string
1497Return the number of characters in @var{string}.
1498@end deffn
1499
5c4b24e1 1500@rnindex string-ref
38a93523
NJ
1501@deffn primitive string-ref str k
1502Return character @var{k} of @var{str} using zero-origin
1503indexing. @var{k} must be a valid index of @var{str}.
1504@end deffn
1505
5c4b24e1 1506@rnindex string-copy
b576faf1 1507@deffn primitive string-copy str
ae9f3a15 1508Return a newly allocated copy of the given @var{string}.
38a93523
NJ
1509@end deffn
1510
5c4b24e1 1511@rnindex substring
38a93523
NJ
1512@deffn primitive substring str start [end]
1513Return a newly allocated string formed from the characters
1514of @var{str} beginning with index @var{start} (inclusive) and
1515ending with index @var{end} (exclusive).
1516@var{str} must be a string, @var{start} and @var{end} must be
1517exact integers satisfying:
1518
15190 <= @var{start} <= @var{end} <= (string-length @var{str}).
1520@end deffn
1521
b576faf1
MG
1522@node String Modification
1523@subsection String Modification
38a93523 1524
fb02eb66 1525These procedures are for modifying strings in-place. That means, that
b576faf1
MG
1526not a new string is the result of a string operation, but that the
1527actual memory representation of a string is modified.
38a93523 1528
5c4b24e1 1529@rnindex string-set!
b576faf1
MG
1530@deffn primitive string-set! str k chr
1531Store @var{chr} in element @var{k} of @var{str} and return
1532an unspecified value. @var{k} must be a valid index of
1533@var{str}.
1534@end deffn
38a93523 1535
5c4b24e1 1536@rnindex string-fill!
b576faf1 1537@deffn primitive string-fill! str chr
ae9f3a15
MG
1538Store @var{char} in every element of the given @var{string} and
1539return an unspecified value.
38a93523
NJ
1540@end deffn
1541
b576faf1 1542@deffn primitive substring-fill! str start end fill
ae9f3a15
MG
1543Change every character in @var{str} between @var{start} and
1544@var{end} to @var{fill}.
7a095584 1545
ae9f3a15 1546@lisp
b576faf1
MG
1547(define y "abcdefg")
1548(substring-fill! y 1 3 #\r)
1549y
1550@result{} "arrdefg"
ae9f3a15 1551@end lisp
38a93523
NJ
1552@end deffn
1553
38a93523
NJ
1554@deffn primitive substring-move! str1 start1 end1 str2 start2
1555@deffnx primitive substring-move-left! str1 start1 end1 str2 start2
1556@deffnx primitive substring-move-right! str1 start1 end1 str2 start2
1557Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
1558into @var{str2} beginning at position @var{end2}.
1559@code{substring-move-right!} begins copying from the rightmost character
1560and moves left, and @code{substring-move-left!} copies from the leftmost
1561character moving right.
1562
1563It is useful to have two functions that copy in different directions so
1564that substrings can be copied back and forth within a single string. If
1565you wish to copy text from the left-hand side of a string to the
1566right-hand side of the same string, and the source and destination
1567overlap, you must be careful to copy the rightmost characters of the
1568text first, to avoid clobbering your data. Hence, when @var{str1} and
1569@var{str2} are the same string, you should use
1570@code{substring-move-right!} when moving text from left to right, and
1571@code{substring-move-left!} otherwise. If @code{str1} and @samp{str2}
1572are different strings, it does not matter which function you use.
38a93523
NJ
1573
1574@example
1575(define x (make-string 10 #\a))
1576(define y "bcd")
1577(substring-move-left! x 2 5 y 0)
1578y
1579@result{} "aaa"
1580
1581x
1582@result{} "aaaaaaaaaa"
1583
1584(define y "bcdefg")
1585(substring-move-left! x 2 5 y 0)
1586y
1587@result{} "aaaefg"
1588
1589(define y "abcdefg")
1590(substring-move-left! y 2 5 y 3)
1591y
1592@result{} "abccccg"
38a93523 1593
38a93523
NJ
1594(define y "abcdefg")
1595(substring-move-right! y 2 5 y 0)
1596y
1597@result{} "ededefg"
1598
1599(define y "abcdefg")
1600(substring-move-right! y 2 5 y 3)
1601y
1602@result{} "abccdeg"
1603@end example
cee2ed4f 1604@end deffn
38a93523 1605
38a93523 1606
b576faf1
MG
1607@node String Comparison
1608@subsection String Comparison
38a93523 1609
b576faf1 1610The procedures in this section are similar to the character ordering
92905faf
MG
1611predicates (@pxref{Characters}), but are defined on character sequences.
1612They all return @code{#t} on success and @code{#f} on failure. The
1613predicates ending in @code{-ci} ignore the character case when comparing
1614strings.
38a93523 1615
2954ad93 1616
5c4b24e1 1617@rnindex string=?
2954ad93
MG
1618@deffn primitive string=? s1 s2
1619Lexicographic equality predicate; return @code{#t} if the two
1620strings are the same length and contain the same characters in
1621the same positions, otherwise return @code{#f}.
7a095584 1622
2954ad93
MG
1623The procedure @code{string-ci=?} treats upper and lower case
1624letters as though they were the same character, but
1625@code{string=?} treats upper and lower case as distinct
1626characters.
1627@end deffn
1628
5c4b24e1 1629@rnindex string<?
2954ad93
MG
1630@deffn primitive string<? s1 s2
1631Lexicographic ordering predicate; return @code{#t} if @var{s1}
1632is lexicographically less than @var{s2}.
1633@end deffn
1634
5c4b24e1 1635@rnindex string<=?
2954ad93
MG
1636@deffn primitive string<=? s1 s2
1637Lexicographic ordering predicate; return @code{#t} if @var{s1}
1638is lexicographically less than or equal to @var{s2}.
38a93523
NJ
1639@end deffn
1640
5c4b24e1 1641@rnindex string>?
2954ad93
MG
1642@deffn primitive string>? s1 s2
1643Lexicographic ordering predicate; return @code{#t} if @var{s1}
1644is lexicographically greater than @var{s2}.
1645@end deffn
1646
5c4b24e1 1647@rnindex string>=?
2954ad93
MG
1648@deffn primitive string>=? s1 s2
1649Lexicographic ordering predicate; return @code{#t} if @var{s1}
1650is lexicographically greater than or equal to @var{s2}.
38a93523
NJ
1651@end deffn
1652
5c4b24e1 1653@rnindex string-ci=?
38a93523 1654@deffn primitive string-ci=? s1 s2
ae9f3a15
MG
1655Case-insensitive string equality predicate; return @code{#t} if
1656the two strings are the same length and their component
780ee65e 1657characters match (ignoring case) at each position; otherwise
ae9f3a15 1658return @code{#f}.
38a93523
NJ
1659@end deffn
1660
5c4b24e1 1661@rnindex string-ci<
2954ad93 1662@deffn primitive string-ci<? s1 s2
ae9f3a15 1663Case insensitive lexicographic ordering predicate; return
2954ad93
MG
1664@code{#t} if @var{s1} is lexicographically less than @var{s2}
1665regardless of case.
1666@end deffn
1667
5c4b24e1 1668@rnindex string<=?
2954ad93
MG
1669@deffn primitive string-ci<=? s1 s2
1670Case insensitive lexicographic ordering predicate; return
1671@code{#t} if @var{s1} is lexicographically less than or equal
1672to @var{s2} regardless of case.
38a93523
NJ
1673@end deffn
1674
5c4b24e1 1675@rnindex string-ci>?
38a93523 1676@deffn primitive string-ci>? s1 s2
ae9f3a15
MG
1677Case insensitive lexicographic ordering predicate; return
1678@code{#t} if @var{s1} is lexicographically greater than
1679@var{s2} regardless of case.
38a93523
NJ
1680@end deffn
1681
5c4b24e1 1682@rnindex string-ci>=?
2954ad93
MG
1683@deffn primitive string-ci>=? s1 s2
1684Case insensitive lexicographic ordering predicate; return
1685@code{#t} if @var{s1} is lexicographically greater than or
1686equal to @var{s2} regardless of case.
38a93523
NJ
1687@end deffn
1688
38a93523 1689
b576faf1
MG
1690@node String Searching
1691@subsection String Searching
1692
1693When searching the index of a character in a string, these procedures
1694can be used.
1695
b576faf1 1696@deffn primitive string-index str chr [frm [to]]
ae9f3a15
MG
1697Return the index of the first occurrence of @var{chr} in
1698@var{str}. The optional integer arguments @var{frm} and
1699@var{to} limit the search to a portion of the string. This
1700procedure essentially implements the @code{index} or
1701@code{strchr} functions from the C library.
7a095584 1702
ae9f3a15 1703@lisp
b576faf1
MG
1704(string-index "weiner" #\e)
1705@result{} 1
1706
1707(string-index "weiner" #\e 2)
1708@result{} 4
1709
1710(string-index "weiner" #\e 2 4)
1711@result{} #f
ae9f3a15 1712@end lisp
38a93523
NJ
1713@end deffn
1714
b576faf1 1715@deffn primitive string-rindex str chr [frm [to]]
ae9f3a15
MG
1716Like @code{string-index}, but search from the right of the
1717string rather than from the left. This procedure essentially
1718implements the @code{rindex} or @code{strrchr} functions from
1719the C library.
7a095584 1720
ae9f3a15 1721@lisp
b576faf1
MG
1722(string-rindex "weiner" #\e)
1723@result{} 4
1724
1725(string-rindex "weiner" #\e 2 4)
1726@result{} #f
1727
1728(string-rindex "weiner" #\e 2 5)
1729@result{} 4
ae9f3a15 1730@end lisp
38a93523
NJ
1731@end deffn
1732
b576faf1
MG
1733@node Alphabetic Case Mapping
1734@subsection Alphabetic Case Mapping
1735
fb02eb66 1736These are procedures for mapping strings to their upper- or lower-case
b576faf1
MG
1737equivalents, respectively, or for capitalizing strings.
1738
2954ad93
MG
1739@deffn primitive string-upcase str
1740Return a freshly allocated string containing the characters of
1741@var{str} in upper case.
1742@end deffn
1743
b576faf1 1744@deffn primitive string-upcase! str
ae9f3a15
MG
1745Destructively upcase every character in @var{str} and return
1746@var{str}.
1747@lisp
1748y @result{} "arrdefg"
1749(string-upcase! y) @result{} "ARRDEFG"
1750y @result{} "ARRDEFG"
1751@end lisp
38a93523
NJ
1752@end deffn
1753
2954ad93
MG
1754@deffn primitive string-downcase str
1755Return a freshly allocation string containing the characters in
1756@var{str} in lower case.
b576faf1
MG
1757@end deffn
1758
b576faf1 1759@deffn primitive string-downcase! str
ae9f3a15
MG
1760Destructively downcase every character in @var{str} and return
1761@var{str}.
1762@lisp
1763y @result{} "ARRDEFG"
1764(string-downcase! y) @result{} "arrdefg"
1765y @result{} "arrdefg"
1766@end lisp
b576faf1
MG
1767@end deffn
1768
2954ad93
MG
1769@deffn primitive string-capitalize str
1770Return a freshly allocated string with the characters in
1771@var{str}, where the first character of every word is
1772capitalized.
b576faf1
MG
1773@end deffn
1774
b576faf1 1775@deffn primitive string-capitalize! str
ae9f3a15
MG
1776Upcase the first character of every word in @var{str}
1777destructively and return @var{str}.
7a095584 1778
ae9f3a15
MG
1779@lisp
1780y @result{} "hello world"
1781(string-capitalize! y) @result{} "Hello World"
1782y @result{} "Hello World"
1783@end lisp
b576faf1
MG
1784@end deffn
1785
b576faf1
MG
1786
1787@node Appending Strings
1788@subsection Appending Strings
1789
1790The procedure @code{string-append} appends several strings together to
1791form a longer result string.
1792
5c4b24e1 1793@rnindex string-append
cee2ed4f 1794@deffn primitive string-append string1 @dots{}
b576faf1 1795Return a newly allocated string whose characters form the
cee2ed4f 1796concatenation of the given strings.
b576faf1
MG
1797@end deffn
1798
1799
1800@node String Miscellanea
1801@subsection String Miscellanea
1802
cee2ed4f 1803This section contains all remaining string procedures.
b576faf1 1804
b576faf1 1805@deffn primitive string-ci->symbol str
ae9f3a15
MG
1806Return the symbol whose name is @var{str}. @var{str} is
1807converted to lowercase before the conversion is done, if Guile
fb02eb66 1808is currently reading symbols case-insensitively.
38a93523
NJ
1809@end deffn
1810
1811
38a93523
NJ
1812@node Regular Expressions
1813@section Regular Expressions
39e30745 1814@tpindex Regular expressions
38a93523
NJ
1815
1816@cindex regular expressions
1817@cindex regex
1818@cindex emacs regexp
1819
1820A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
1821describes a whole class of strings. A full description of regular
1822expressions and their syntax is beyond the scope of this manual;
1823an introduction can be found in the Emacs manual (@pxref{Regexps,
1824, Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, or
1825in many general Unix reference books.
1826
1827If your system does not include a POSIX regular expression library, and
1828you have not linked Guile with a third-party regexp library such as Rx,
1829these functions will not be available. You can tell whether your Guile
1830installation includes regular expression support by checking whether the
1831@code{*features*} list includes the @code{regex} symbol.
1832
1833@menu
1834* Regexp Functions:: Functions that create and match regexps.
1835* Match Structures:: Finding what was matched by a regexp.
1836* Backslash Escapes:: Removing the special meaning of regexp metacharacters.
1837* Rx Interface:: Tom Lord's Rx library does things differently.
1838@end menu
1839
1840[FIXME: it may be useful to include an Examples section. Parts of this
1841interface are bewildering on first glance.]
1842
1843@node Regexp Functions
1844@subsection Regexp Functions
1845
1846By default, Guile supports POSIX extended regular expressions.
1847That means that the characters @samp{(}, @samp{)}, @samp{+} and
1848@samp{?} are special, and must be escaped if you wish to match the
1849literal characters.
1850
1851This regular expression interface was modeled after that
1852implemented by SCSH, the Scheme Shell. It is intended to be
1853upwardly compatible with SCSH regular expressions.
1854
1855@c begin (scm-doc-string "regex.scm" "string-match")
1856@deffn procedure string-match pattern str [start]
1857Compile the string @var{pattern} into a regular expression and compare
1858it with @var{str}. The optional numeric argument @var{start} specifies
1859the position of @var{str} at which to begin matching.
1860
1861@code{string-match} returns a @dfn{match structure} which
1862describes what, if anything, was matched by the regular
1863expression. @xref{Match Structures}. If @var{str} does not match
1864@var{pattern} at all, @code{string-match} returns @code{#f}.
1865@end deffn
1866
1867Each time @code{string-match} is called, it must compile its
1868@var{pattern} argument into a regular expression structure. This
1869operation is expensive, which makes @code{string-match} inefficient if
1870the same regular expression is used several times (for example, in a
1871loop). For better performance, you can compile a regular expression in
1872advance and then match strings against the compiled regexp.
1873
38a93523 1874@deffn primitive make-regexp pat . flags
ae9f3a15
MG
1875Compile the regular expression described by @var{pat}, and
1876return the compiled regexp structure. If @var{pat} does not
1877describe a legal regular expression, @code{make-regexp} throws
1878a @code{regular-expression-syntax} error.
7a095584 1879
ae9f3a15
MG
1880The @var{flags} arguments change the behavior of the compiled
1881regular expression. The following flags may be supplied:
7a095584 1882
38a93523
NJ
1883@table @code
1884@item regexp/icase
ae9f3a15
MG
1885Consider uppercase and lowercase letters to be the same when
1886matching.
38a93523 1887@item regexp/newline
ae9f3a15
MG
1888If a newline appears in the target string, then permit the
1889@samp{^} and @samp{$} operators to match immediately after or
1890immediately before the newline, respectively. Also, the
1891@samp{.} and @samp{[^...]} operators will never match a newline
1892character. The intent of this flag is to treat the target
1893string as a buffer containing many lines of text, and the
1894regular expression as a pattern that may match a single one of
1895those lines.
38a93523
NJ
1896@item regexp/basic
1897Compile a basic (``obsolete'') regexp instead of the extended
ae9f3a15
MG
1898(``modern'') regexps that are the default. Basic regexps do
1899not consider @samp{|}, @samp{+} or @samp{?} to be special
1900characters, and require the @samp{@{...@}} and @samp{(...)}
1901metacharacters to be backslash-escaped (@pxref{Backslash
1902Escapes}). There are several other differences between basic
1903and extended regular expressions, but these are the most
1904significant.
38a93523 1905@item regexp/extended
ae9f3a15
MG
1906Compile an extended regular expression rather than a basic
1907regexp. This is the default behavior; this flag will not
1908usually be needed. If a call to @code{make-regexp} includes
1909both @code{regexp/basic} and @code{regexp/extended} flags, the
1910one which comes last will override the earlier one.
38a93523
NJ
1911@end table
1912@end deffn
1913
38a93523 1914@deffn primitive regexp-exec rx str [start [flags]]
ae9f3a15
MG
1915Match the compiled regular expression @var{rx} against
1916@code{str}. If the optional integer @var{start} argument is
1917provided, begin matching from that position in the string.
1918Return a match structure describing the results of the match,
1919or @code{#f} if no match could be found.
38a93523
NJ
1920@end deffn
1921
ae9f3a15
MG
1922@deffn primitive regexp? obj
1923Return @code{#t} if @var{obj} is a compiled regular expression,
1924or @code{#f} otherwise.
38a93523
NJ
1925@end deffn
1926
1927Regular expressions are commonly used to find patterns in one string and
1928replace them with the contents of another string.
1929
1930@c begin (scm-doc-string "regex.scm" "regexp-substitute")
1931@deffn procedure regexp-substitute port match [item@dots{}]
1932Write to the output port @var{port} selected contents of the match
1933structure @var{match}. Each @var{item} specifies what should be
1934written, and may be one of the following arguments:
1935
1936@itemize @bullet
1937@item
1938A string. String arguments are written out verbatim.
1939
1940@item
1941An integer. The submatch with that number is written.
1942
1943@item
1944The symbol @samp{pre}. The portion of the matched string preceding
1945the regexp match is written.
1946
1947@item
1948The symbol @samp{post}. The portion of the matched string following
1949the regexp match is written.
1950@end itemize
1951
1952@var{port} may be @code{#f}, in which case nothing is written; instead,
1953@code{regexp-substitute} constructs a string from the specified
1954@var{item}s and returns that.
1955@end deffn
1956
1957@c begin (scm-doc-string "regex.scm" "regexp-substitute")
1958@deffn procedure regexp-substitute/global port regexp target [item@dots{}]
1959Similar to @code{regexp-substitute}, but can be used to perform global
1960substitutions on @var{str}. Instead of taking a match structure as an
1961argument, @code{regexp-substitute/global} takes two string arguments: a
1962@var{regexp} string describing a regular expression, and a @var{target}
1963string which should be matched against this regular expression.
1964
1965Each @var{item} behaves as in @var{regexp-substitute}, with the
1966following exceptions:
1967
1968@itemize @bullet
1969@item
1970A function may be supplied. When this function is called, it will be
1971passed one argument: a match structure for a given regular expression
1972match. It should return a string to be written out to @var{port}.
1973
1974@item
1975The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
1976on the unmatched portion of @var{str}. This @emph{must} be supplied in
1977order to perform global search-and-replace on @var{str}; if it is not
1978present among the @var{item}s, then @code{regexp-substitute/global} will
1979return after processing a single match.
1980@end itemize
1981@end deffn
1982
1983@node Match Structures
1984@subsection Match Structures
1985
1986@cindex match structures
1987
1988A @dfn{match structure} is the object returned by @code{string-match} and
1989@code{regexp-exec}. It describes which portion of a string, if any,
1990matched the given regular expression. Match structures include: a
1991reference to the string that was checked for matches; the starting and
1992ending positions of the regexp match; and, if the regexp included any
1993parenthesized subexpressions, the starting and ending positions of each
1994submatch.
1995
1996In each of the regexp match functions described below, the @code{match}
1997argument must be a match structure returned by a previous call to
1998@code{string-match} or @code{regexp-exec}. Most of these functions
1999return some information about the original target string that was
2000matched against a regular expression; we will call that string
2001@var{target} for easy reference.
2002
2003@c begin (scm-doc-string "regex.scm" "regexp-match?")
2004@deffn procedure regexp-match? obj
2005Return @code{#t} if @var{obj} is a match structure returned by a
2006previous call to @code{regexp-exec}, or @code{#f} otherwise.
2007@end deffn
2008
2009@c begin (scm-doc-string "regex.scm" "match:substring")
2010@deffn procedure match:substring match [n]
2011Return the portion of @var{target} matched by subexpression number
2012@var{n}. Submatch 0 (the default) represents the entire regexp match.
2013If the regular expression as a whole matched, but the subexpression
2014number @var{n} did not match, return @code{#f}.
2015@end deffn
2016
2017@c begin (scm-doc-string "regex.scm" "match:start")
2018@deffn procedure match:start match [n]
2019Return the starting position of submatch number @var{n}.
2020@end deffn
2021
2022@c begin (scm-doc-string "regex.scm" "match:end")
2023@deffn procedure match:end match [n]
2024Return the ending position of submatch number @var{n}.
2025@end deffn
2026
2027@c begin (scm-doc-string "regex.scm" "match:prefix")
2028@deffn procedure match:prefix match
2029Return the unmatched portion of @var{target} preceding the regexp match.
2030@end deffn
2031
2032@c begin (scm-doc-string "regex.scm" "match:suffix")
2033@deffn procedure match:suffix match
2034Return the unmatched portion of @var{target} following the regexp match.
2035@end deffn
2036
2037@c begin (scm-doc-string "regex.scm" "match:count")
2038@deffn procedure match:count match
2039Return the number of parenthesized subexpressions from @var{match}.
2040Note that the entire regular expression match itself counts as a
2041subexpression, and failed submatches are included in the count.
2042@end deffn
2043
2044@c begin (scm-doc-string "regex.scm" "match:string")
2045@deffn procedure match:string match
2046Return the original @var{target} string.
2047@end deffn
2048
2049@node Backslash Escapes
2050@subsection Backslash Escapes
2051
2052Sometimes you will want a regexp to match characters like @samp{*} or
2053@samp{$} exactly. For example, to check whether a particular string
2054represents a menu entry from an Info node, it would be useful to match
2055it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2056because the asterisk is a metacharacter, it won't match the @samp{*} at
2057the beginning of the string. In this case, we want to make the first
2058asterisk un-magic.
2059
2060You can do this by preceding the metacharacter with a backslash
2061character @samp{\}. (This is also called @dfn{quoting} the
2062metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2063sees a backslash in a regular expression, it considers the following
2064glyph to be an ordinary character, no matter what special meaning it
2065would ordinarily have. Therefore, we can make the above example work by
2066changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2067the regular expression engine to match only a single asterisk in the
2068target string.
2069
2070Since the backslash is itself a metacharacter, you may force a regexp to
2071match a backslash in the target string by preceding the backslash with
2072itself. For example, to find variable references in a @TeX{} program,
2073you might want to find occurrences of the string @samp{\let\} followed
2074by any number of alphabetic characters. The regular expression
2075@samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2076regexp each match a single backslash in the target string.
2077
2078@c begin (scm-doc-string "regex.scm" "regexp-quote")
2079@deffn procedure regexp-quote str
2080Quote each special character found in @var{str} with a backslash, and
2081return the resulting string.
2082@end deffn
2083
2084@strong{Very important:} Using backslash escapes in Guile source code
2085(as in Emacs Lisp or C) can be tricky, because the backslash character
2086has special meaning for the Guile reader. For example, if Guile
2087encounters the character sequence @samp{\n} in the middle of a string
2088while processing Scheme code, it replaces those characters with a
2089newline character. Similarly, the character sequence @samp{\t} is
2090replaced by a horizontal tab. Several of these @dfn{escape sequences}
2091are processed by the Guile reader before your code is executed.
2092Unrecognized escape sequences are ignored: if the characters @samp{\*}
2093appear in a string, they will be translated to the single character
2094@samp{*}.
2095
2096This translation is obviously undesirable for regular expressions, since
2097we want to be able to include backslashes in a string in order to
2098escape regexp metacharacters. Therefore, to make sure that a backslash
2099is preserved in a string in your Guile program, you must use @emph{two}
2100consecutive backslashes:
2101
2102@lisp
2103(define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2104@end lisp
2105
2106The string in this example is preprocessed by the Guile reader before
2107any code is executed. The resulting argument to @code{make-regexp} is
2108the string @samp{^\* [^:]*}, which is what we really want.
2109
2110This also means that in order to write a regular expression that matches
2111a single backslash character, the regular expression string in the
2112source code must include @emph{four} backslashes. Each consecutive pair
2113of backslashes gets translated by the Guile reader to a single
2114backslash, and the resulting double-backslash is interpreted by the
2115regexp engine as matching a single backslash character. Hence:
2116
2117@lisp
2118(define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2119@end lisp
2120
2121The reason for the unwieldiness of this syntax is historical. Both
2122regular expression pattern matchers and Unix string processing systems
2123have traditionally used backslashes with the special meanings
2124described above. The POSIX regular expression specification and ANSI C
2125standard both require these semantics. Attempting to abandon either
2126convention would cause other kinds of compatibility problems, possibly
2127more severe ones. Therefore, without extending the Scheme reader to
2128support strings with different quoting conventions (an ungainly and
2129confusing extension when implemented in other languages), we must adhere
2130to this cumbersome escape syntax.
2131
2132@node Rx Interface
2133@subsection Rx Interface
2134
f4f2b29a
MG
2135@c FIXME::martin: Shouldn't this be removed or moved to the
2136@c ``Guile Modules'' chapter? The functions are not available in
2137@c plain Guile...
2138
38a93523
NJ
2139[FIXME: this is taken from Gary and Mark's quick summaries and should be
2140reviewed and expanded. Rx is pretty stable, so could already be done!]
2141
2142@cindex rx
2143@cindex finite automaton
2144
2145Guile includes an interface to Tom Lord's Rx library (currently only to
2146POSIX regular expressions). Use of the library requires a two step
2147process: compile a regular expression into an efficient structure, then
2148use the structure in any number of string comparisons.
2149
2150For example, given the
2151regular expression @samp{abc.} (which matches any string containing
2152@samp{abc} followed by any single character):
2153
2154@smalllisp
2155guile> @kbd{(define r (regcomp "abc."))}
2156guile> @kbd{r}
2157#<rgx abc.>
2158guile> @kbd{(regexec r "abc")}
2159#f
2160guile> @kbd{(regexec r "abcd")}
2161#((0 . 4))
2162guile>
2163@end smalllisp
2164
2165The definitions of @code{regcomp} and @code{regexec} are as follows:
2166
2167@c NJFIXME not in libguile!
2168@deffn primitive regcomp pattern [flags]
2169Compile the regular expression pattern using POSIX rules. Flags is
2170optional and should be specified using symbolic names:
2171@defvar REG_EXTENDED
2172use extended POSIX syntax
2173@end defvar
2174@defvar REG_ICASE
2175use case-insensitive matching
2176@end defvar
2177@defvar REG_NEWLINE
2178allow anchors to match after newline characters in the
2179string and prevents @code{.} or @code{[^...]} from matching newlines.
2180@end defvar
2181
2182The @code{logior} procedure can be used to combine multiple flags.
2183The default is to use
2184POSIX basic syntax, which makes @code{+} and @code{?} literals and @code{\+}
2185and @code{\?}
2186operators. Backslashes in @var{pattern} must be escaped if specified in a
2187literal string e.g., @code{"\\(a\\)\\?"}.
2188@end deffn
2189
2190@c NJFIXME not in libguile!
2191@deffn primitive regexec regex string [match-pick] [flags]
2192
2193Match @var{string} against the compiled POSIX regular expression
2194@var{regex}.
2195@var{match-pick} and @var{flags} are optional. Possible flags (which can be
2196combined using the logior procedure) are:
2197
2198@defvar REG_NOTBOL
2199The beginning of line operator won't match the beginning of
2200@var{string} (presumably because it's not the beginning of a line)
2201@end defvar
2202
2203@defvar REG_NOTEOL
2204Similar to REG_NOTBOL, but prevents the end of line operator
2205from matching the end of @var{string}.
2206@end defvar
2207
2208If no match is possible, regexec returns #f. Otherwise @var{match-pick}
2209determines the return value:
2210
2211@code{#t} or unspecified: a newly-allocated vector is returned,
2212containing pairs with the indices of the matched part of @var{string} and any
2213substrings.
2214
2215@code{""}: a list is returned: the first element contains a nested list
2216with the matched part of @var{string} surrounded by the the unmatched parts.
2217Remaining elements are matched substrings (if any). All returned
2218substrings share memory with @var{string}.
2219
2220@code{#f}: regexec returns #t if a match is made, otherwise #f.
2221
2222vector: the supplied vector is returned, with the first element replaced
2223by a pair containing the indices of the matched portion of @var{string} and
2224further elements replaced by pairs containing the indices of matched
2225substrings (if any).
2226
2227list: a list will be returned, with each member of the list
2228specified by a code in the corresponding position of the supplied list:
2229
2230a number: the numbered matching substring (0 for the entire match).
2231
2232@code{#\<}: the beginning of @var{string} to the beginning of the part matched
2233by regex.
2234
2235@code{#\>}: the end of the matched part of @var{string} to the end of
2236@var{string}.
2237
2238@code{#\c}: the "final tag", which seems to be associated with the "cut
2239operator", which doesn't seem to be available through the posix
2240interface.
2241
2242e.g., @code{(list #\< 0 1 #\>)}. The returned substrings share memory with
2243@var{string}.
2244@end deffn
2245
2246Here are some other procedures that might be used when using regular
2247expressions:
2248
2249@c NJFIXME not in libguile!
2250@deffn primitive compiled-regexp? obj
2251Test whether obj is a compiled regular expression.
2252@end deffn
2253
2254@c NJFIXME not in libguile!
2255@deffn primitive regexp->dfa regex [flags]
2256@end deffn
2257
2258@c NJFIXME not in libguile!
2259@deffn primitive dfa-fork dfa
2260@end deffn
2261
2262@c NJFIXME not in libguile!
2263@deffn primitive reset-dfa! dfa
2264@end deffn
2265
2266@c NJFIXME not in libguile!
2267@deffn primitive dfa-final-tag dfa
2268@end deffn
2269
2270@c NJFIXME not in libguile!
2271@deffn primitive dfa-continuable? dfa
2272@end deffn
2273
2274@c NJFIXME not in libguile!
2275@deffn primitive advance-dfa! dfa string
2276@end deffn
2277
2278
2279@node Symbols and Variables
2280@section Symbols and Variables
fcaedf99 2281
f4f2b29a 2282@c FIXME::martin: Review me!
38a93523 2283
f4f2b29a
MG
2284Symbols are a data type with a special property. On the one hand,
2285symbols are used for denoting variables in a Scheme program, on the
2286other they can be used as literal data as well.
38a93523 2287
f4f2b29a
MG
2288The association between symbols and values is maintained in special data
2289structures, the symbol tables.
38a93523 2290
fb02eb66 2291In addition, Guile offers variables as first-class objects. They can
f4f2b29a 2292be used for interacting with the module system.
38a93523 2293
f4f2b29a
MG
2294@menu
2295* Symbols:: All about symbols as a data type.
2296* Symbol Tables:: Tables for mapping symbols to values.
fb02eb66 2297* Variables:: First-class variables.
f4f2b29a 2298@end menu
38a93523 2299
f4f2b29a
MG
2300@node Symbols
2301@subsection Symbols
39e30745 2302@tpindex Symbols
38a93523 2303
f4f2b29a
MG
2304@c FIXME::martin: Review me!
2305
2306Symbols are especially useful because two symbols which are spelled the
2307same way are equivalent in the sense of @code{eq?}. That means that
2308they are actually the same Scheme object. The advantage is that symbols
2309can be compared extremely efficiently, although they carry more
2310information for the human reader than, say, numbers.
2311
2312It is very common in Scheme programs to use symbols as keys in
725fd980
NJ
2313association lists (@pxref{Association Lists}) or hash tables
2314(@pxref{Hash Tables}), because this usage improves the readability a
2315lot, and does not cause any performance loss.
38a93523 2316
f4f2b29a
MG
2317The read syntax for symbols is a sequence of letters, digits, and
2318@emph{extended alphabetic characters} that begins with a character that
2319cannot begin a number is an identifier. In addition, @code{+},
2320@code{-}, and @code{...} are identifiers.
38a93523 2321
f4f2b29a
MG
2322Extended alphabetic characters may be used within identifiers as if
2323they were letters. The following are extended alphabetic characters:
2324
2325@example
2326! $ % & * + - . / : < = > ? @@ ^ _ ~
2327@end example
2328
2329In addition to the read syntax defined above (which is taken from R5RS
725fd980
NJ
2330(@pxref{Formal syntax,,,r5rs,The Revised^5 Report on Scheme})), Guile
2331provides a method for writing symbols with unusual characters, such as
2332space characters. If you (for whatever reason) need to write a symbol
2333containing characters not mentioned above, you write symbols as follows:
f4f2b29a
MG
2334
2335@itemize @bullet
239d2912
MG
2336@item
2337Begin the symbol with the two character @code{#@{},
2338
2339@item
2340write the characters of the symbol and
2341
2342@item
2343finish the symbol with the characters @code{@}#}.
f4f2b29a
MG
2344@end itemize
2345
2346Here are a few examples of this form of read syntax; the first
2347containing a space character, the second containing a line break and the
2348last one looks like a number.
2349
2350@lisp
2351#@{foo bar@}#
2352#@{what
2353ever@}#
2354#@{4242@}#
2355@end lisp
2356
2357Usage of this form of read syntax is discouraged, because it is not
2358portable at all, and is not very readable.
2359
2360@rnindex symbol?
2361@deffn primitive symbol? obj
2362Return @code{#t} if @var{obj} is a symbol, otherwise return
2363@code{#f}.
38a93523
NJ
2364@end deffn
2365
5c4b24e1 2366@rnindex string->symbol
38a93523 2367@deffn primitive string->symbol string
ae9f3a15
MG
2368Return the symbol whose name is @var{string}. This procedure
2369can create symbols with names containing special characters or
2370letters in the non-standard case, but it is usually a bad idea
2371to create such symbols because in some implementations of
2372Scheme they cannot be read as themselves. See
2373@code{symbol->string}.
7a095584 2374
780ee65e
NJ
2375The following examples assume that the implementation's
2376standard case is lower case:
7a095584 2377
780ee65e
NJ
2378@lisp
2379(eq? 'mISSISSIppi 'mississippi) @result{} #t
2380(string->symbol "mISSISSIppi") @result{} @r{the symbol with name "mISSISSIppi"}
2381(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
38a93523 2382(eq? 'JollyWog
780ee65e 2383 (string->symbol (symbol->string 'JollyWog))) @result{} #t
38a93523 2384(string=? "K. Harper, M.D."
780ee65e
NJ
2385 (symbol->string
2386 (string->symbol "K. Harper, M.D."))) @result{}#t
2387@end lisp
38a93523
NJ
2388@end deffn
2389
5c4b24e1 2390@rnindex symbol->string
780ee65e 2391@deffn primitive symbol->string s
ae9f3a15
MG
2392Return the name of @var{symbol} as a string. If the symbol was
2393part of an object returned as the value of a literal expression
8c34cf5b 2394(section @pxref{Literal expressions,,,r5rs, The Revised^5
ae9f3a15
MG
2395Report on Scheme}) or by a call to the @code{read} procedure,
2396and its name contains alphabetic characters, then the string
2397returned will contain characters in the implementation's
fb02eb66 2398preferred standard case--some implementations will prefer
ae9f3a15
MG
2399upper case, others lower case. If the symbol was returned by
2400@code{string->symbol}, the case of characters in the string
2401returned will be the same as the case in the string that was
2402passed to @code{string->symbol}. It is an error to apply
2403mutation procedures like @code{string-set!} to strings returned
2404by this procedure.
7a095584 2405
780ee65e
NJ
2406The following examples assume that the implementation's
2407standard case is lower case:
7a095584 2408
780ee65e 2409@lisp
ae9f3a15
MG
2410(symbol->string 'flying-fish) @result{} "flying-fish"
2411(symbol->string 'Martin) @result{} "martin"
38a93523 2412(symbol->string
780ee65e
NJ
2413 (string->symbol "Malvina")) @result{} "Malvina"
2414@end lisp
38a93523
NJ
2415@end deffn
2416
f4f2b29a
MG
2417@node Symbol Tables
2418@subsection Symbol Tables
2419
2420@c FIXME::martin: Review me!
2421
2422@c FIXME::martin: Are all these procedures still relevant?
2423
2424Guile symbol tables are hash tables. Each hash table, also called an
2425@dfn{obarray} (for `object array'), is a vector of association lists.
2426Each entry in the alists is a pair (@var{SYMBOL} . @var{VALUE}). To
2427@dfn{intern} a symbol in a symbol table means to return its
2428(@var{SYMBOL} . @var{VALUE}) pair, adding a new entry to the symbol
2429table (with an undefined value) if none is yet present.
2430
2431@c FIXME::martin: According to NEWS, removed. Remove here too, or
2432@c leave for compatibility?
2433@c @c docstring begin (texi-doc-string "guile" "builtin-bindings")
2434@c @deffn primitive builtin-bindings
2435@c Create and return a copy of the global symbol table, removing all
2436@c unbound symbols.
2437@c @end deffn
2438
2439@deffn primitive gensym [prefix]
2440Create a new symbol with a name constructed from a prefix and
2441a counter value. The string @var{prefix} can be specified as
2442an optional argument. Default prefix is @code{g}. The counter
2443is increased by 1 at each call. There is no provision for
2444resetting the counter.
2445@end deffn
2446
2447@deffn primitive gentemp [prefix [obarray]]
2448Create a new symbol with a name unique in an obarray.
2449The name is constructed from an optional string @var{prefix}
2450and a counter value. The default prefix is @code{t}. The
2451@var{obarray} is specified as a second optional argument.
2452Default is the system obarray where all normal symbols are
2453interned. The counter is increased by 1 at each
2454call. There is no provision for resetting the counter.
2455@end deffn
2456
2457@deffn primitive intern-symbol obarray string
2458Add a new symbol to @var{obarray} with name @var{string}, bound to an
2459unspecified initial value. The symbol table is not modified if a symbol
2460with this name is already present.
2461@end deffn
2462
2463@deffn primitive string->obarray-symbol obarray string [soft?]
2464Intern a new symbol in @var{obarray}, a symbol table, with name
2465@var{string}.
2466@end deffn
2467
38a93523
NJ
2468@deffn primitive symbol-binding obarray string
2469Look up in @var{obarray} the symbol whose name is @var{string}, and
2470return the value to which it is bound. If @var{obarray} is @code{#f},
2471use the global symbol table. If @var{string} is not interned in
2472@var{obarray}, an error is signalled.
2473@end deffn
2474
38a93523 2475@deffn primitive symbol-bound? obarray string
780ee65e 2476Return @code{#t} if @var{obarray} contains a symbol with name
38a93523 2477@var{string} bound to a defined value. This differs from
780ee65e
NJ
2478@var{symbol-interned?} in that the mere mention of a symbol
2479usually causes it to be interned; @code{symbol-bound?}
2480determines whether a symbol has been given any meaningful
2481value.
38a93523
NJ
2482@end deffn
2483
38a93523
NJ
2484@deffn primitive symbol-fref symbol
2485Return the contents of @var{symbol}'s @dfn{function slot}.
2486@end deffn
2487
38a93523
NJ
2488@deffn primitive symbol-fset! symbol value
2489Change the binding of @var{symbol}'s function slot.
2490@end deffn
2491
38a93523
NJ
2492@deffn primitive symbol-hash symbol
2493Return a hash value for @var{symbol}.
2494@end deffn
2495
38a93523 2496@deffn primitive symbol-interned? obarray string
780ee65e
NJ
2497Return @code{#t} if @var{obarray} contains a symbol with name
2498@var{string}, and @code{#f} otherwise.
38a93523
NJ
2499@end deffn
2500
38a93523
NJ
2501@deffn primitive symbol-pref symbol
2502Return the @dfn{property list} currently associated with @var{symbol}.
2503@end deffn
2504
38a93523
NJ
2505@deffn primitive symbol-pset! symbol value
2506Change the binding of @var{symbol}'s property slot.
2507@end deffn
2508
38a93523
NJ
2509@deffn primitive symbol-set! obarray string value
2510Find the symbol in @var{obarray} whose name is @var{string}, and rebind
2511it to @var{value}. An error is signalled if @var{string} is not present
2512in @var{obarray}.
2513@end deffn
2514
38a93523
NJ
2515@deffn primitive unintern-symbol obarray string
2516Remove the symbol with name @var{string} from @var{obarray}. This
2517function returns @code{#t} if the symbol was present and @code{#f}
2518otherwise.
2519@end deffn
2520
f4f2b29a
MG
2521@node Variables
2522@subsection Variables
39e30745 2523@tpindex Variables
f4f2b29a
MG
2524
2525@c FIXME::martin: Review me!
2526
2527Variables are objects with two fields. They contain a value and they
2528can contain a symbol, which is the name of the variable. A variable is
2529said to be bound if it does not contain the object denoting unbound
2530variables in the value slot.
2531
2532Variables do not have a read syntax, they have to be created by calling
2533one of the constructor procedures @code{make-variable} or
2534@code{make-undefined-variable} or retrieved by @code{builtin-variable}.
2535
fb02eb66 2536First-class variables are especially useful for interacting with the
92905faf 2537current module system (@pxref{The Guile module system}).
f4f2b29a 2538
38a93523
NJ
2539@deffn primitive builtin-variable name
2540Return the built-in variable with the name @var{name}.
2541@var{name} must be a symbol (not a string).
2542Then use @code{variable-ref} to access its value.
2543@end deffn
2544
38a93523
NJ
2545@deffn primitive make-undefined-variable [name-hint]
2546Return a variable object initialized to an undefined value.
2547If given, uses @var{name-hint} as its internal (debugging)
2548name, otherwise just treat it as an anonymous variable.
2549Remember, of course, that multiple bindings to the same
2550variable may exist, so @var{name-hint} is just that---a hint.
2551@end deffn
2552
38a93523
NJ
2553@deffn primitive make-variable init [name-hint]
2554Return a variable object initialized to value @var{init}.
2555If given, uses @var{name-hint} as its internal (debugging)
2556name, otherwise just treat it as an anonymous variable.
2557Remember, of course, that multiple bindings to the same
2558variable may exist, so @var{name-hint} is just that---a hint.
2559@end deffn
2560
38a93523
NJ
2561@deffn primitive variable-bound? var
2562Return @code{#t} iff @var{var} is bound to a value.
2563Throws an error if @var{var} is not a variable object.
2564@end deffn
2565
38a93523
NJ
2566@deffn primitive variable-ref var
2567Dereference @var{var} and return its value.
2568@var{var} must be a variable object; see @code{make-variable}
2569and @code{make-undefined-variable}.
2570@end deffn
2571
38a93523
NJ
2572@deffn primitive variable-set! var val
2573Set the value of the variable @var{var} to @var{val}.
2574@var{var} must be a variable object, @var{val} can be any
2575value. Return an unspecified value.
2576@end deffn
2577
38a93523
NJ
2578@deffn primitive variable? obj
2579Return @code{#t} iff @var{obj} is a variable object, else
2580return @code{#f}
2581@end deffn
2582
2583
2584@node Keywords
2585@section Keywords
39e30745 2586@tpindex Keywords
38a93523
NJ
2587
2588Keywords are self-evaluating objects with a convenient read syntax that
2589makes them easy to type.
2590
8c34cf5b 2591Guile's keyword support conforms to R5RS, and adds a (switchable) read
38a93523
NJ
2592syntax extension to permit keywords to begin with @code{:} as well as
2593@code{#:}.
2594
2595@menu
5c4b24e1
MG
2596* Why Use Keywords?:: Motivation for keyword usage.
2597* Coding With Keywords:: How to use keywords.
2598* Keyword Read Syntax:: Read syntax for keywords.
cee2ed4f
MG
2599* Keyword Procedures:: Procedures for dealing with keywords.
2600* Keyword Primitives:: The underlying primitive procedures.
38a93523
NJ
2601@end menu
2602
2603@node Why Use Keywords?
2604@subsection Why Use Keywords?
2605
2606Keywords are useful in contexts where a program or procedure wants to be
2607able to accept a large number of optional arguments without making its
2608interface unmanageable.
2609
2610To illustrate this, consider a hypothetical @code{make-window}
2611procedure, which creates a new window on the screen for drawing into
2612using some graphical toolkit. There are many parameters that the caller
2613might like to specify, but which could also be sensibly defaulted, for
2614example:
2615
2616@itemize @bullet
2617@item
2618colour depth -- Default: the colour depth for the screen
2619
2620@item
2621background colour -- Default: white
2622
2623@item
2624width -- Default: 600
2625
2626@item
2627height -- Default: 400
2628@end itemize
2629
2630If @code{make-window} did not use keywords, the caller would have to
2631pass in a value for each possible argument, remembering the correct
2632argument order and using a special value to indicate the default value
2633for that argument:
2634
2635@lisp
2636(make-window 'default ;; Colour depth
2637 'default ;; Background colour
2638 800 ;; Width
2639 100 ;; Height
2640 @dots{}) ;; More make-window arguments
2641@end lisp
2642
2643With keywords, on the other hand, defaulted arguments are omitted, and
2644non-default arguments are clearly tagged by the appropriate keyword. As
2645a result, the invocation becomes much clearer:
2646
2647@lisp
2648(make-window #:width 800 #:height 100)
2649@end lisp
2650
2651On the other hand, for a simpler procedure with few arguments, the use
2652of keywords would be a hindrance rather than a help. The primitive
2653procedure @code{cons}, for example, would not be improved if it had to
2654be invoked as
2655
2656@lisp
2657(cons #:car x #:cdr y)
2658@end lisp
2659
2660So the decision whether to use keywords or not is purely pragmatic: use
2661them if they will clarify the procedure invocation at point of call.
2662
2663@node Coding With Keywords
2664@subsection Coding With Keywords
2665
2666If a procedure wants to support keywords, it should take a rest argument
2667and then use whatever means is convenient to extract keywords and their
2668corresponding arguments from the contents of that rest argument.
2669
2670The following example illustrates the principle: the code for
2671@code{make-window} uses a helper procedure called
2672@code{get-keyword-value} to extract individual keyword arguments from
2673the rest argument.
2674
2675@lisp
2676(define (get-keyword-value args keyword default)
2677 (let ((kv (memq keyword args)))
2678 (if (and kv (>= (length kv) 2))
2679 (cadr kv)
2680 default)))
2681
2682(define (make-window . args)
2683 (let ((depth (get-keyword-value args #:depth screen-depth))
2684 (bg (get-keyword-value args #:bg "white"))
2685 (width (get-keyword-value args #:width 800))
2686 (height (get-keyword-value args #:height 100))
2687 @dots{})
2688 @dots{}))
2689@end lisp
2690
2691But you don't need to write @code{get-keyword-value}. The @code{(ice-9
2692optargs)} module provides a set of powerful macros that you can use to
2693implement keyword-supporting procedures like this:
2694
2695@lisp
2696(use-modules (ice-9 optargs))
2697
2698(define (make-window . args)
2699 (let-keywords args #f ((depth screen-depth)
2700 (bg "white")
2701 (width 800)
2702 (height 100))
2703 ...))
2704@end lisp
2705
2706@noindent
2707Or, even more economically, like this:
2708
2709@lisp
2710(use-modules (ice-9 optargs))
2711
2712(define* (make-window #:key (depth screen-depth)
2713 (bg "white")
2714 (width 800)
2715 (height 100))
2716 ...)
2717@end lisp
2718
2719For further details on @code{let-keywords}, @code{define*} and other
2720facilities provided by the @code{(ice-9 optargs)} module, @ref{Optional
2721Arguments}.
2722
2723
2724@node Keyword Read Syntax
2725@subsection Keyword Read Syntax
2726
2727Guile, by default, only recognizes the keyword syntax specified by R5RS.
2728A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
2729as a Scheme symbol, is the external representation of the keyword named
2730@code{NAME}. Keyword objects print using this syntax as well, so values
2731containing keyword objects can be read back into Guile. When used in an
2732expression, keywords are self-quoting objects.
2733
2734If the @code{keyword} read option is set to @code{'prefix}, Guile also
2735recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
8c34cf5b 2736of the form @code{:NAME} are read as symbols, as required by R5RS.
38a93523 2737
8c34cf5b 2738To enable and disable the alternative non-R5RS keyword syntax, you use
38a93523
NJ
2739the @code{read-options} procedure documented in @ref{General option
2740interface} and @ref{Reader options}.
2741
2742@smalllisp
2743(read-set! keywords 'prefix)
2744
2745#:type
2746@result{}
2747#:type
2748
2749:type
2750@result{}
2751#:type
2752
2753(read-set! keywords #f)
2754
2755#:type
2756@result{}
2757#:type
2758
2759:type
2760@result{}
2761ERROR: In expression :type:
2762ERROR: Unbound variable: :type
2763ABORT: (unbound-variable)
2764@end smalllisp
2765
cee2ed4f
MG
2766@node Keyword Procedures
2767@subsection Keyword Procedures
2768
2769@c FIXME::martin: Review me!
2770
2771The following procedures can be used for converting symbols to keywords
2772and back.
2773
2774@deffn procedure symbol->keyword sym
2775Return a keyword with the same characters as in @var{sym}.
2776@end deffn
2777
2778@deffn procedure keyword->symbol kw
2779Return a symbol with the same characters as in @var{kw}.
2780@end deffn
2781
2782
38a93523
NJ
2783@node Keyword Primitives
2784@subsection Keyword Primitives
2785
2786Internally, a keyword is implemented as something like a tagged symbol,
2787where the tag identifies the keyword as being self-evaluating, and the
2788symbol, known as the keyword's @dfn{dash symbol} has the same name as
2789the keyword name but prefixed by a single dash. For example, the
2790keyword @code{#:name} has the corresponding dash symbol @code{-name}.
2791
2792Most keyword objects are constructed automatically by the reader when it
2793reads a token beginning with @code{#:}. However, if you need to
2794construct a keyword object programmatically, you can do so by calling
2795@code{make-keyword-from-dash-symbol} with the corresponding dash symbol
2796(as the reader does). The dash symbol for a keyword object can be
2797retrieved using the @code{keyword-dash-symbol} procedure.
2798
38a93523
NJ
2799@deffn primitive make-keyword-from-dash-symbol symbol
2800Make a keyword object from a @var{symbol} that starts with a dash.
2801@end deffn
2802
38a93523 2803@deffn primitive keyword? obj
ae9f3a15
MG
2804Return @code{#t} if the argument @var{obj} is a keyword, else
2805@code{#f}.
38a93523
NJ
2806@end deffn
2807
38a93523
NJ
2808@deffn primitive keyword-dash-symbol keyword
2809Return the dash symbol for @var{keyword}.
2810This is the inverse of @code{make-keyword-from-dash-symbol}.
2811@end deffn
2812
38a93523
NJ
2813@node Pairs
2814@section Pairs
39e30745 2815@tpindex Pairs
5c4b24e1
MG
2816
2817@c FIXME::martin: Review me!
2818
2819Pairs are used to combine two Scheme objects into one compound object.
2820Hence the name: A pair stores a pair of objects.
2821
2822The data type @emph{pair} is extremely important in Scheme, just like in
2823any other Lisp dialect. The reason is that pairs are not only used to
2824make two values available as one object, but that pairs are used for
2825constructing lists of values. Because lists are so important in Scheme,
2826they are described in a section of their own (@pxref{Lists}).
2827
2828Pairs can literally get entered in source code or at the REPL, in the
2829so-called @dfn{dotted list} syntax. This syntax consists of an opening
2830parentheses, the first element of the pair, a dot, the second element
2831and a closing parentheses. The following example shows how a pair
2832consisting of the two numbers 1 and 2, and a pair containing the symbols
2833@code{foo} and @code{bar} can be entered. It is very important to write
2834the whitespace before and after the dot, because otherwise the Scheme
2835parser whould not be able to figure out where to split the tokens.
2836
2837@lisp
2838(1 . 2)
2839(foo . bar)
2840@end lisp
2841
2842But beware, if you want to try out these examples, you have to
2843@dfn{quote} the expressions. More information about quotation is
2844available in the section (REFFIXME). The correct way to try these
2845examples is as follows.
2846
2847@lisp
2848'(1 . 2)
2849@result{}
2850(1 . 2)
2851'(foo . bar)
2852@result{}
2853(foo . bar)
2854@end lisp
2855
2856A new pair is made by calling the procedure @code{cons} with two
2857arguments. Then the argument values are stored into a newly allocated
2858pair, and the pair is returned. The name @code{cons} stands for
2859@emph{construct}. Use the procedure @code{pair?} to test whether a
2860given Scheme object is a pair or not.
2861
2862@rnindex cons
38a93523 2863@deffn primitive cons x y
ae9f3a15
MG
2864Return a newly allocated pair whose car is @var{x} and whose
2865cdr is @var{y}. The pair is guaranteed to be different (in the
2866sense of @code{eq?}) from every previously existing object.
38a93523
NJ
2867@end deffn
2868
5c4b24e1 2869@rnindex pair?
38a93523 2870@deffn primitive pair? x
ae9f3a15
MG
2871Return @code{#t} if @var{x} is a pair; otherwise return
2872@code{#f}.
38a93523
NJ
2873@end deffn
2874
5c4b24e1
MG
2875The two parts of a pair are traditionally called @emph{car} and
2876@emph{cdr}. They can be retrieved with procedures of the same name
2877(@code{car} and @code{cdr}), and can be modified with the procedures
2878@code{set-car!} and @code{set-cdr!}. Since a very common operation in
2879Scheme programs is to access the car of a pair, or the car of the cdr of
2880a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
2881are also predefined.
2882
2883@rnindex car
2884@rnindex cdr
fcaedf99
MG
2885@deffn primitive car pair
2886@deffnx primitive cdr pair
2887Return the car or the cdr of @var{pair}, respectively.
2888@end deffn
2889
2890@deffn primitive caar pair
2891@deffnx primitive cadr pair @dots{}
2892@deffnx primitive cdddar pair
2893@deffnx primitive cddddr pair
2894These procedures are compositions of @code{car} and @code{cdr}, where
2895for example @code{caddr} could be defined by
2896
2897@lisp
2898(define caddr (lambda (x) (car (cdr (cdr x)))))
2899@end lisp
2900@end deffn
2901
5c4b24e1 2902@rnindex set-car!
38a93523
NJ
2903@deffn primitive set-car! pair value
2904Stores @var{value} in the car field of @var{pair}. The value returned
2905by @code{set-car!} is unspecified.
2906@end deffn
2907
5c4b24e1 2908@rnindex set-cdr!
38a93523
NJ
2909@deffn primitive set-cdr! pair value
2910Stores @var{value} in the cdr field of @var{pair}. The value returned
2911by @code{set-cdr!} is unspecified.
2912@end deffn
2913
2914
2915@node Lists
2916@section Lists
39e30745 2917@tpindex Lists
fcaedf99 2918
f4f2b29a
MG
2919@c FIXME::martin: Review me!
2920
2921A very important data type in Scheme---as well as in all other Lisp
5c4b24e1
MG
2922dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
2923Scheme does not have a real datatype @emph{list}. Lists are made up of
f4f2b29a 2924chained @emph{pairs}, and only exist by definition---a list is a chain
5c4b24e1
MG
2925of pairs which looks like a list.}
2926
2927This is the short definition of what a list is:
2928
2929@itemize @bullet
239d2912
MG
2930@item
2931Either the empty list @code{()},
2932
2933@item
2934or a pair which has a list in its cdr.
5c4b24e1
MG
2935@end itemize
2936
2937@c FIXME::martin: Describe the pair chaining in more detail.
2938
2939@c FIXME::martin: What is a proper, what an improper list?
2940@c What is a circular list?
2941
2942@c FIXME::martin: Maybe steal some graphics from the Elisp reference
2943@c manual?
2944
2945@menu
2946* List Syntax:: Writing literal lists.
2947* List Predicates:: Testing lists.
2948* List Constructors:: Creating new lists.
2949* List Selection:: Selecting from lists, getting their length.
2950* Append/Reverse:: Appending and reversing lists.
2951* List Modifification:: Modifying list structure.
2952* List Searching:: Searching for list elements
2953* List Mapping:: Applying procedures to lists.
2954@end menu
2955
2956@node List Syntax
2957@subsection List Read Syntax
2958
f4f2b29a
MG
2959@c FIXME::martin: Review me!
2960
5c4b24e1
MG
2961The syntax for lists is an opening parentheses, then all the elements of
2962the list (separated by whitespace) and finally a closing
2963parentheses.@footnote{Note that there is no separation character between
2964the list elements, like a comma or a semicolon.}.
2965
2966@lisp
2967(1 2 3) ; @r{a list of the numbers 1, 2 and 3}
2968("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
2969() ; @r{the empty list}
2970@end lisp
2971
2972The last example needs a bit more explanation. A list with no elements,
2973called the @dfn{empty list}, is special in some ways. It is used for
2974terminating lists by storing it into the cdr of the last pair that makes
2975up a list. An example will clear that up:
38a93523 2976
5c4b24e1
MG
2977@lisp
2978(car '(1))
2979@result{}
29801
2981(cdr '(1))
2982@result{}
2983()
2984@end lisp
2985
2986This example also shows that lists have to be quoted (REFFIXME) when
2987written, because they would otherwise be mistakingly taken as procedure
92905faf 2988applications (@pxref{Simple Invocation}).
5c4b24e1
MG
2989
2990
2991@node List Predicates
2992@subsection List Predicates
2993
f4f2b29a
MG
2994@c FIXME::martin: Review me!
2995
5c4b24e1 2996Often it is useful to test whether a given Scheme object is a list or
fb02eb66 2997not. List-processing procedures could use this information to test
5c4b24e1
MG
2998whether their input is valid, or they could do different things
2999depending on the datatype of their arguments.
3000
3001@rnindex list?
5c4b24e1
MG
3002@deffn primitive list? x
3003Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
3004@end deffn
3005
fb02eb66 3006The predicate @code{null?} is often used in list-processing code to
5c4b24e1
MG
3007tell whether a given list has run out of elements. That is, a loop
3008somehow deals with the elements of a list until the list satisfies
3009@code{null?}. Then, teh algorithm terminates.
3010
3011@rnindex null?
5c4b24e1
MG
3012@deffn primitive null? x
3013Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
3014@end deffn
3015
3016@node List Constructors
3017@subsection List Constructors
3018
3019This section describes the procedures for constructing new lists.
3020@code{list} simply returns a list where the elements are the arguments,
3021@code{cons*} is similar, but the last argument is stored in the cdr of
3022the last pair of the list.
3023
3024@rnindex list
5c4b24e1 3025@deffn primitive list arg1 @dots{}
780ee65e
NJ
3026Return a list containing @var{objs}, the arguments to
3027@code{list}.
38a93523
NJ
3028@end deffn
3029
5c4b24e1 3030@deffn primitive cons* arg1 arg2 @dots{}
780ee65e
NJ
3031Like @code{list}, but the last arg provides the tail of the
3032constructed list, returning @code{(cons @var{arg1} (cons
8d009ee4 3033@var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
780ee65e
NJ
3034argument. If given one argument, that argument is returned as
3035result. This function is called @code{list*} in some other
3036Schemes and in Common LISP.
38a93523
NJ
3037@end deffn
3038
5c4b24e1
MG
3039@deffn primitive list-copy lst
3040Return a (newly-created) copy of @var{lst}.
38a93523
NJ
3041@end deffn
3042
39e30745
MG
3043@deffn procedure make-list n [init]
3044Create a list containing of @var{n} elements, where each element is
3045initialized to @var{init}. @var{init} defaults to the empty list
3046@code{()} if not given.
3047@end deffn
3048
5c4b24e1
MG
3049Note that @code{list-copy} only makes a copy of the pairs which make up
3050the spine of the lists. The list elements are not copied, which means
3051that modifying the elements of the new list also modyfies the elements
3052of the old list. On the other hand, applying procedures like
3053@code{set-cdr!} or @code{delv!} to the new list will not alter the old
3054list. If you also need to copy the list elements (making a deep copy),
92905faf 3055use the procedure @code{copy-tree} (@pxref{Copying}).
38a93523 3056
5c4b24e1
MG
3057@node List Selection
3058@subsection List Selection
3059
f4f2b29a
MG
3060@c FIXME::martin: Review me!
3061
5c4b24e1
MG
3062These procedures are used to get some information about a list, or to
3063retrieve one or more elements of a list.
3064
3065@rnindex length
38a93523 3066@deffn primitive length lst
780ee65e 3067Return the number of elements in list @var{lst}.
38a93523
NJ
3068@end deffn
3069
5c4b24e1
MG
3070@deffn primitive last-pair lst
3071Return a pointer to the last pair in @var{lst}, signalling an error if
3072@var{lst} is circular.
3073@end deffn
3074
3075@rnindex list-ref
5c4b24e1
MG
3076@deffn primitive list-ref list k
3077Return the @var{k}th element from @var{list}.
3078@end deffn
3079
3080@rnindex list-tail
5c4b24e1
MG
3081@deffn primitive list-tail lst k
3082@deffnx primitive list-cdr-ref lst k
3083Return the "tail" of @var{lst} beginning with its @var{k}th element.
3084The first element of the list is considered to be element 0.
3085
3086@code{list-tail} and @code{list-cdr-ref} are identical. It may help to
3087think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
3088or returning the results of cdring @var{k} times down @var{lst}.
3089@end deffn
3090
5c4b24e1
MG
3091@deffn primitive list-head lst k
3092Copy the first @var{k} elements from @var{lst} into a new list, and
3093return it.
3094@end deffn
3095
3096@node Append/Reverse
3097@subsection Append and Reverse
3098
f4f2b29a
MG
3099@c FIXME::martin: Review me!
3100
5c4b24e1
MG
3101@code{append} and @code{append!} are used to concatenate two or more
3102lists in order to form a new list. @code{reverse} and @code{reverse!}
3103return lists with the same elements as their arguments, but in reverse
3104order. The procedure variants with an @code{!} directly modify the
3105pairs which form the list, whereas the other procedures create new
fb02eb66 3106pairs. This is why you should be careful when using the side-effecting
5c4b24e1
MG
3107variants.
3108
3109@rnindex append
38a93523 3110@deffn primitive append . args
780ee65e
NJ
3111Return a list consisting of the elements the lists passed as
3112arguments.
ae9f3a15 3113@lisp
780ee65e
NJ
3114(append '(x) '(y)) @result{} (x y)
3115(append '(a) '(b c d)) @result{} (a b c d)
3116(append '(a (b)) '((c))) @result{} (a (b) (c))
ae9f3a15 3117@end lisp
780ee65e
NJ
3118The resulting list is always newly allocated, except that it
3119shares structure with the last list argument. The last
3120argument may actually be any object; an improper list results
3121if the last argument is not a proper list.
ae9f3a15 3122@lisp
780ee65e
NJ
3123(append '(a b) '(c . d)) @result{} (a b c . d)
3124(append '() 'a) @result{} a
ae9f3a15 3125@end lisp
38a93523
NJ
3126@end deffn
3127
ae9f3a15
MG
3128@deffn primitive append! . lists
3129A destructive version of @code{append} (@pxref{Pairs and
8c34cf5b 3130lists,,,r5rs, The Revised^5 Report on Scheme}). The cdr field
ae9f3a15
MG
3131of each list's final pair is changed to point to the head of
3132the next list, so no consing is performed. Return a pointer to
3133the mutated list.
38a93523
NJ
3134@end deffn
3135
5c4b24e1 3136@rnindex reverse
38a93523 3137@deffn primitive reverse lst
780ee65e
NJ
3138Return a new list that contains the elements of @var{lst} but
3139in reverse order.
38a93523
NJ
3140@end deffn
3141
3142@c NJFIXME explain new_tail
38a93523 3143@deffn primitive reverse! lst [new_tail]
8c34cf5b
NJ
3144A destructive version of @code{reverse} (@pxref{Pairs and lists,,,r5rs,
3145The Revised^5 Report on Scheme}). The cdr of each cell in @var{lst} is
38a93523
NJ
3146modified to point to the previous list element. Return a pointer to the
3147head of the reversed list.
3148
3149Caveat: because the list is modified in place, the tail of the original
3150list now becomes its head, and the head of the original list now becomes
3151the tail. Therefore, the @var{lst} symbol to which the head of the
3152original list was bound now points to the tail. To ensure that the head
3153of the modified list is not lost, it is wise to save the return value of
3154@code{reverse!}
3155@end deffn
3156
5c4b24e1
MG
3157@node List Modifification
3158@subsection List Modification
3159
f4f2b29a
MG
3160@c FIXME::martin: Review me!
3161
5c4b24e1
MG
3162The following procedures modify existing list. @code{list-set!} and
3163@code{list-cdr-set!} change which elements a list contains, the various
3164deletion procedures @code{delq}, @code{delv} etc.
38a93523 3165
38a93523
NJ
3166@deffn primitive list-set! list k val
3167Set the @var{k}th element of @var{list} to @var{val}.
3168@end deffn
3169
38a93523
NJ
3170@deffn primitive list-cdr-set! list k val
3171Set the @var{k}th cdr of @var{list} to @var{val}.
3172@end deffn
3173
38a93523 3174@deffn primitive delq item lst
780ee65e
NJ
3175Return a newly-created copy of @var{lst} with elements
3176@code{eq?} to @var{item} removed. This procedure mirrors
3177@code{memq}: @code{delq} compares elements of @var{lst} against
3178@var{item} with @code{eq?}.
38a93523
NJ
3179@end deffn
3180
38a93523 3181@deffn primitive delv item lst
780ee65e
NJ
3182Return a newly-created copy of @var{lst} with elements
3183@code{eqv?} to @var{item} removed. This procedure mirrors
3184@code{memv}: @code{delv} compares elements of @var{lst} against
3185@var{item} with @code{eqv?}.
38a93523
NJ
3186@end deffn
3187
38a93523 3188@deffn primitive delete item lst
780ee65e
NJ
3189Return a newly-created copy of @var{lst} with elements
3190@code{equal?} to @var{item} removed. This procedure mirrors
3191@code{member}: @code{delete} compares elements of @var{lst}
3192against @var{item} with @code{equal?}.
38a93523
NJ
3193@end deffn
3194
38a93523
NJ
3195@deffn primitive delq! item lst
3196@deffnx primitive delv! item lst
3197@deffnx primitive delete! item lst
3198These procedures are destructive versions of @code{delq}, @code{delv}
3199and @code{delete}: they modify the pointers in the existing @var{lst}
3200rather than creating a new list. Caveat evaluator: Like other
3201destructive list functions, these functions cannot modify the binding of
3202@var{lst}, and so cannot be used to delete the first element of
3203@var{lst} destructively.
3204@end deffn
3205
38a93523 3206@deffn primitive delq1! item lst
780ee65e
NJ
3207Like @code{delq!}, but only deletes the first occurrence of
3208@var{item} from @var{lst}. Tests for equality using
3209@code{eq?}. See also @code{delv1!} and @code{delete1!}.
38a93523
NJ
3210@end deffn
3211
38a93523 3212@deffn primitive delv1! item lst
780ee65e
NJ
3213Like @code{delv!}, but only deletes the first occurrence of
3214@var{item} from @var{lst}. Tests for equality using
3215@code{eqv?}. See also @code{delq1!} and @code{delete1!}.
38a93523
NJ
3216@end deffn
3217
38a93523 3218@deffn primitive delete1! item lst
780ee65e
NJ
3219Like @code{delete!}, but only deletes the first occurrence of
3220@var{item} from @var{lst}. Tests for equality using
3221@code{equal?}. See also @code{delq1!} and @code{delv1!}.
38a93523
NJ
3222@end deffn
3223
5c4b24e1
MG
3224@node List Searching
3225@subsection List Searching
3226
f4f2b29a
MG
3227@c FIXME::martin: Review me!
3228
5c4b24e1
MG
3229The following procedures search lists for particular elements. They use
3230different comparison predicates for comparing list elements with the
3231object to be seached. When they fail, they return @code{#f}, otherwise
3232they return the sublist whose car is equal to the search object, where
3233equality depends on the equality predicate used.
3234
3235@rnindex memq
5c4b24e1
MG
3236@deffn primitive memq x lst
3237Return the first sublist of @var{lst} whose car is @code{eq?}
3238to @var{x} where the sublists of @var{lst} are the non-empty
3239lists returned by @code{(list-tail @var{lst} @var{k})} for
3240@var{k} less than the length of @var{lst}. If @var{x} does not
3241occur in @var{lst}, then @code{#f} (not the empty list) is
3242returned.
3243@end deffn
3244
3245@rnindex memv
5c4b24e1
MG
3246@deffn primitive memv x lst
3247Return the first sublist of @var{lst} whose car is @code{eqv?}
3248to @var{x} where the sublists of @var{lst} are the non-empty
3249lists returned by @code{(list-tail @var{lst} @var{k})} for
3250@var{k} less than the length of @var{lst}. If @var{x} does not
3251occur in @var{lst}, then @code{#f} (not the empty list) is
3252returned.
3253@end deffn
3254
3255@rnindex member
5c4b24e1
MG
3256@deffn primitive member x lst
3257Return the first sublist of @var{lst} whose car is
3258@code{equal?} to @var{x} where the sublists of @var{lst} are
3259the non-empty lists returned by @code{(list-tail @var{lst}
3260@var{k})} for @var{k} less than the length of @var{lst}. If
3261@var{x} does not occur in @var{lst}, then @code{#f} (not the
3262empty list) is returned.
3263@end deffn
3264
38a93523
NJ
3265[FIXME: is there any reason to have the `sloppy' functions available at
3266high level at all? Maybe these docs should be relegated to a "Guile
3267Internals" node or something. -twp]
3268
38a93523
NJ
3269@deffn primitive sloppy-memq x lst
3270This procedure behaves like @code{memq}, but does no type or error checking.
3271Its use is recommended only in writing Guile internals,
3272not for high-level Scheme programs.
3273@end deffn
3274
38a93523
NJ
3275@deffn primitive sloppy-memv x lst
3276This procedure behaves like @code{memv}, but does no type or error checking.
3277Its use is recommended only in writing Guile internals,
3278not for high-level Scheme programs.
3279@end deffn
3280
38a93523
NJ
3281@deffn primitive sloppy-member x lst
3282This procedure behaves like @code{member}, but does no type or error checking.
3283Its use is recommended only in writing Guile internals,
3284not for high-level Scheme programs.
3285@end deffn
3286
5c4b24e1
MG
3287@node List Mapping
3288@subsection List Mapping
3289
f4f2b29a
MG
3290@c FIXME::martin: Review me!
3291
5c4b24e1
MG
3292List processing is very convenient in Scheme because the process of
3293iterating over the elements of a list can be highly abstracted. The
3294procedures in this section are the most basic iterating procedures for
3295lists. They take a procedure and one or more lists as arguments, and
3296apply the procedure to each element of the list. They differ in what
3297the result of the invocation is.
3298
3299@rnindex map
38a93523 3300@c begin (texi-doc-string "guile" "map")
5c4b24e1
MG
3301@deffn primitive map proc arg1 arg2 @dots{}
3302@deffnx primitive map-in-order proc arg1 arg2 @dots{}
3303Apply @var{proc} to each element of the list @var{arg1} (if only two
3304arguments are given), or to the corresponding elements of the argument
3305lists (if more than two arguments are given). The result(s) of the
3306procedure applications are saved and returned in a list. For
3307@code{map}, the order of procedure applications is not specified,
3308@code{map-in-order} applies the procedure from left to right to the list
3309elements.
3310@end deffn
3311
3312@rnindex for-each
38a93523 3313@c begin (texi-doc-string "guile" "for-each")
5c4b24e1
MG
3314@deffn primitive for-each proc arg1 arg2 @dots{}
3315Like @code{map}, but the procedure is always applied from left to right,
3316and the result(s) of the procedure applications are thrown away. The
3317return value is not specified.
38a93523
NJ
3318@end deffn
3319
3320
cee2ed4f
MG
3321@node Vectors
3322@section Vectors
39e30745 3323@tpindex Vectors
cee2ed4f
MG
3324
3325@c FIXME::martin: Review me!
3326
3327@c FIXME::martin: Should the subsections of this section be nodes
3328@c of their own, or are the resulting nodes too short, then?
3329
3330Vectors are sequences of Scheme objects. Unlike lists, the length of a
3331vector, once the vector is created, cannot be changed. The advantage of
3332vectors over lists is that the time required to access one element of a
3333vector is constant, whereas lists have an access time linear to the
3334index of the accessed element in the list.
3335
3336Note that the vectors documented in this section can contain any kind of
3337Scheme object, it is even possible to have different types of objects in
3338the same vector.
3339
3340@subsection Vector Read Syntax
3341
3342Vectors can literally be entered in source code, just like strings,
3343characters or some of the other data types. The read syntax for vectors
3344is as follows: A sharp sign (@code{#}), followed by an opening
3345parentheses, all elements of the vector in their respective read syntax,
3346and finally a closing parentheses. The following are examples of the
3347read syntax for vectors; where the first vector only contains numbers
3348and the second three different object types: a string, a symbol and a
3349number in hexidecimal notation.
3350
3351@lisp
3352#(1 2 3)
3353#("Hello" foo #xdeadbeef)
3354@end lisp
3355
3356@subsection Vector Predicates
3357
3358@rnindex vector?
3359@deffn primitive vector? obj
3360Return @code{#t} if @var{obj} is a vector, otherwise return
3361@code{#f}.
3362@end deffn
3363
3364@subsection Vector Constructors
3365
3366@rnindex make-vector
3367@deffn primitive make-vector k [fill]
3368Return a newly allocated vector of @var{k} elements. If a
3369second argument is given, then each element is initialized to
3370@var{fill}. Otherwise the initial contents of each element is
3371unspecified.
3372@end deffn
3373
3374@rnindex vector
3375@rnindex list->vector
3376@deffn primitive vector . l
3377@deffnx primitive list->vector l
3378Return a newly allocated vector whose elements contain the
3379given arguments. Analogous to @code{list}.
3380
3381@lisp
3382(vector 'a 'b 'c) @result{} #(a b c)
3383@end lisp
3384@end deffn
3385
3386@rnindex vector->list
3387@deffn primitive vector->list v
3388Return a newly allocated list of the objects contained in the
3389elements of @var{vector}.
3390
3391@lisp
3392(vector->list '#(dah dah didah)) @result{} (dah dah didah)
3393(list->vector '(dididit dah)) @result{} #(dididit dah)
3394@end lisp
3395@end deffn
3396
3397@subsection Vector Modification
3398
3399A vector created by any of the vector constructor procedures
3400(@pxref{Vectors}) documented above can be modified using the
3401following procedures.
3402
3403According to R5RS, using any of these procedures on literally entered
3404vectors is an error, because these vectors are considered to be
3405constant, although Guile currently does not detect this error.
3406
3407@rnindex vector-set!
3408@deffn primitive vector-set! vector k obj
3409@var{k} must be a valid index of @var{vector}.
3410@code{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
3411The value returned by @samp{vector-set!} is unspecified.
3412@lisp
3413(let ((vec (vector 0 '(2 2 2 2) "Anna")))
3414 (vector-set! vec 1 '("Sue" "Sue"))
3415 vec) @result{} #(0 ("Sue" "Sue") "Anna")
3416(vector-set! '#(0 1 2) 1 "doe") @result{} @emph{error} ; constant vector
3417@end lisp
3418@end deffn
3419
3420@rnindex vector-fill!
3421@deffn primitive vector-fill! v fill
3422Store @var{fill} in every element of @var{vector}. The value
3423returned by @code{vector-fill!} is unspecified.
3424@end deffn
3425
3426@deffn primitive vector-move-left! vec1 start1 end1 vec2 start2
3427Vector version of @code{substring-move-left!}.
3428@end deffn
3429
3430@deffn primitive vector-move-right! vec1 start1 end1 vec2 start2
3431Vector version of @code{substring-move-right!}.
3432@end deffn
3433
3434@subsection Vector Selection
3435
3436These procedures return information about a given vector, such as the
3437size or what elements are contained in the vector.
3438
3439@rnindex vector-length
3440@deffn primitive vector-length vector
3441Returns the number of elements in @var{vector} as an exact integer.
3442@end deffn
3443
3444@rnindex vector-ref
3445@deffn primitive vector-ref vector k
3446@var{k} must be a valid index of @var{vector}.
3447@samp{Vector-ref} returns the contents of element @var{k} of
3448@var{vector}.
3449@lisp
3450(vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
3451(vector-ref '#(1 1 2 3 5 8 13 21)
3452 (let ((i (round (* 2 (acos -1)))))
3453 (if (inexact? i)
3454 (inexact->exact i)
3455 i))) @result{} 13
3456@end lisp
3457@end deffn
3458
3459
38a93523
NJ
3460@node Records
3461@section Records
3462
3463[FIXME: this is pasted in from Tom Lord's original guile.texi and should
3464be reviewed]
3465
3466A @dfn{record type} is a first class object representing a user-defined
3467data type. A @dfn{record} is an instance of a record type.
3468
3469@deffn procedure record? obj
3470Returns @code{#t} if @var{obj} is a record of any type and @code{#f}
3471otherwise.
3472
3473Note that @code{record?} may be true of any Scheme value; there is no
3474promise that records are disjoint with other Scheme types.
3475@end deffn
3476
3477@deffn procedure make-record-type type-name field-names
3478Returns a @dfn{record-type descriptor}, a value representing a new data
3479type disjoint from all others. The @var{type-name} argument must be a
3480string, but is only used for debugging purposes (such as the printed
3481representation of a record of the new type). The @var{field-names}
3482argument is a list of symbols naming the @dfn{fields} of a record of the
3483new type. It is an error if the list contains any duplicates. It is
3484unspecified how record-type descriptors are represented.@refill
3485@end deffn
3486
3487@deffn procedure record-constructor rtd [field-names]
3488Returns a procedure for constructing new members of the type represented
3489by @var{rtd}. The returned procedure accepts exactly as many arguments
3490as there are symbols in the given list, @var{field-names}; these are
3491used, in order, as the initial values of those fields in a new record,
3492which is returned by the constructor procedure. The values of any
3493fields not named in that list are unspecified. The @var{field-names}
3494argument defaults to the list of field names in the call to
3495@code{make-record-type} that created the type represented by @var{rtd};
3496if the @var{field-names} argument is provided, it is an error if it
3497contains any duplicates or any symbols not in the default list.@refill
3498@end deffn
3499
3500@deffn procedure record-predicate rtd
3501Returns a procedure for testing membership in the type represented by
3502@var{rtd}. The returned procedure accepts exactly one argument and
3503returns a true value if the argument is a member of the indicated record
3504type; it returns a false value otherwise.@refill
3505@end deffn
3506
3507@deffn procedure record-accessor rtd field-name
3508Returns a procedure for reading the value of a particular field of a
3509member of the type represented by @var{rtd}. The returned procedure
3510accepts exactly one argument which must be a record of the appropriate
3511type; it returns the current value of the field named by the symbol
3512@var{field-name} in that record. The symbol @var{field-name} must be a
3513member of the list of field-names in the call to @code{make-record-type}
3514that created the type represented by @var{rtd}.@refill
3515@end deffn
3516
3517@deffn procedure record-modifier rtd field-name
3518Returns a procedure for writing the value of a particular field of a
3519member of the type represented by @var{rtd}. The returned procedure
3520accepts exactly two arguments: first, a record of the appropriate type,
3521and second, an arbitrary Scheme value; it modifies the field named by
3522the symbol @var{field-name} in that record to contain the given value.
3523The returned value of the modifier procedure is unspecified. The symbol
3524@var{field-name} must be a member of the list of field-names in the call
3525to @code{make-record-type} that created the type represented by
3526@var{rtd}.@refill
3527@end deffn
3528
3529@deffn procedure record-type-descriptor record
3530Returns a record-type descriptor representing the type of the given
3531record. That is, for example, if the returned descriptor were passed to
3532@code{record-predicate}, the resulting predicate would return a true
3533value when passed the given record. Note that it is not necessarily the
3534case that the returned descriptor is the one that was passed to
3535@code{record-constructor} in the call that created the constructor
3536procedure that created the given record.@refill
3537@end deffn
3538
3539@deffn procedure record-type-name rtd
3540Returns the type-name associated with the type represented by rtd. The
3541returned value is @code{eqv?} to the @var{type-name} argument given in
3542the call to @code{make-record-type} that created the type represented by
3543@var{rtd}.@refill
3544@end deffn
3545
3546@deffn procedure record-type-fields rtd
3547Returns a list of the symbols naming the fields in members of the type
3548represented by @var{rtd}. The returned value is @code{equal?} to the
3549field-names argument given in the call to @code{make-record-type} that
3550created the type represented by @var{rtd}.@refill
3551@end deffn
3552
3553
3554@node Structures
3555@section Structures
39e30745 3556@tpindex Structures
38a93523
NJ
3557
3558[FIXME: this is pasted in from Tom Lord's original guile.texi and should
3559be reviewed]
3560
3561A @dfn{structure type} is a first class user-defined data type. A
3562@dfn{structure} is an instance of a structure type. A structure type is
3563itself a structure.
3564
3565Structures are less abstract and more general than traditional records.
3566In fact, in Guile Scheme, records are implemented using structures.
3567
3568@menu
3569* Structure Concepts:: The structure of Structures
3570* Structure Layout:: Defining the layout of structure types
3571* Structure Basics:: make-, -ref and -set! procedures for structs
3572* Vtables:: Accessing type-specific data
3573@end menu
3574
3575@node Structure Concepts
3576@subsection Structure Concepts
3577
3578A structure object consists of a handle, structure data, and a vtable.
3579The handle is a Scheme value which points to both the vtable and the
3580structure's data. Structure data is a dynamically allocated region of
3581memory, private to the structure, divided up into typed fields. A
3582vtable is another structure used to hold type-specific data. Multiple
3583structures can share a common vtable.
3584
3585Three concepts are key to understanding structures.
3586
3587@itemize @bullet{}
3588@item @dfn{layout specifications}
3589
3590Layout specifications determine how memory allocated to structures is
3591divided up into fields. Programmers must write a layout specification
3592whenever a new type of structure is defined.
3593
3594@item @dfn{structural accessors}
3595
3596Structure access is by field number. There is only one set of
3597accessors common to all structure objects.
3598
3599@item @dfn{vtables}
3600
3601Vtables, themselves structures, are first class representations of
3602disjoint sub-types of structures in general. In most cases, when a
3603new structure is created, programmers must specifiy a vtable for the
3604new structure. Each vtable has a field describing the layout of its
3605instances. Vtables can have additional, user-defined fields as well.
3606@end itemize
3607
3608
3609
3610@node Structure Layout
3611@subsection Structure Layout
3612
3613When a structure is created, a region of memory is allocated to hold its
3614state. The @dfn{layout} of the structure's type determines how that
3615memory is divided into fields.
3616
3617Each field has a specified type. There are only three types allowed, each
3618corresponding to a one letter code. The allowed types are:
3619
3620@itemize @bullet{}
3621@item 'u' -- unprotected
3622
3623The field holds binary data that is not GC protected.
3624
3625@item 'p' -- protected
3626
3627The field holds a Scheme value and is GC protected.
3628
3629@item 's' -- self
3630
3631The field holds a Scheme value and is GC protected. When a structure is
3632created with this type of field, the field is initialized to refer to
3633the structure's own handle. This kind of field is mainly useful when
3634mixing Scheme and C code in which the C code may need to compute a
3635structure's handle given only the address of its malloced data.
3636@end itemize
3637
3638
3639Each field also has an associated access protection. There are only
3640three kinds of protection, each corresponding to a one letter code.
3641The allowed protections are:
3642
3643@itemize @bullet{}
3644@item 'w' -- writable
3645
3646The field can be read and written.
3647
3648@item 'r' -- readable
3649
3650The field can be read, but not written.
3651
3652@item 'o' -- opaque
3653
3654The field can be neither read nor written. This kind
3655of protection is for fields useful only to built-in routines.
3656@end itemize
3657
3658A layout specification is described by stringing together pairs
3659of letters: one to specify a field type and one to specify a field
3660protection. For example, a traditional cons pair type object could
3661be described as:
3662
3663@example
3664; cons pairs have two writable fields of Scheme data
3665"pwpw"
3666@end example
3667
3668A pair object in which the first field is held constant could be:
3669
3670@example
3671"prpw"
3672@end example
3673
3674Binary fields, (fields of type "u"), hold one @emph{word} each. The
3675size of a word is a machine dependent value defined to be equal to the
3676value of the C expression: @code{sizeof (long)}.
3677
3678The last field of a structure layout may specify a tail array.
3679A tail array is indicated by capitalizing the field's protection
3680code ('W', 'R' or 'O'). A tail-array field is replaced by
3681a read-only binary data field containing an array size. The array
3682size is determined at the time the structure is created. It is followed
3683by a corresponding number of fields of the type specified for the
3684tail array. For example, a conventional Scheme vector can be
3685described as:
3686
3687@example
3688; A vector is an arbitrary number of writable fields holding Scheme
3689; values:
3690"pW"
3691@end example
3692
3693In the above example, field 0 contains the size of the vector and
3694fields beginning at 1 contain the vector elements.
3695
3696A kind of tagged vector (a constant tag followed by conventioal
3697vector elements) might be:
3698
3699@example
3700"prpW"
3701@end example
3702
3703
3704Structure layouts are represented by specially interned symbols whose
3705name is a string of type and protection codes. To create a new
3706structure layout, use this procedure:
3707
38a93523
NJ
3708@deffn primitive make-struct-layout fields
3709Return a new structure layout object.
3710
3711@var{fields} must be a string made up of pairs of characters
3712strung together. The first character of each pair describes a field
3713type, the second a field protection. Allowed types are 'p' for
3714GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
3715a field that points to the structure itself. Allowed protections
3716are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
3717fields. The last field protection specification may be capitalized to
3718indicate that the field is a tail-array.
3719@end deffn
3720
3721
3722
3723@node Structure Basics
3724@subsection Structure Basics
3725
3726This section describes the basic procedures for creating and accessing
3727structures.
3728
38a93523
NJ
3729@deffn primitive make-struct vtable tail_array_size . init
3730Create a new structure.
3731
3732@var{type} must be a vtable structure (@pxref{Vtables}).
3733
3734@var{tail-elts} must be a non-negative integer. If the layout
3735specification indicated by @var{type} includes a tail-array,
3736this is the number of elements allocated to that array.
3737
3738The @var{init1}, @dots{} are optional arguments describing how
3739successive fields of the structure should be initialized. Only fields
3740with protection 'r' or 'w' can be initialized, except for fields of
3741type 's', which are automatically initialized to point to the new
3742structure itself; fields with protection 'o' can not be initialized by
3743Scheme programs.
3744
3745If fewer optional arguments than initializable fields are supplied,
3746fields of type 'p' get default value #f while fields of type 'u' are
3747initialized to 0.
3748
3749Structs are currently the basic representation for record-like data
3750structures in Guile. The plan is to eventually replace them with a
3751new representation which will at the same time be easier to use and
3752more powerful.
3753
3754For more information, see the documentation for @code{make-vtable-vtable}.
3755@end deffn
3756
38a93523 3757@deffn primitive struct? x
780ee65e
NJ
3758Return @code{#t} iff @var{obj} is a structure object, else
3759@code{#f}.
38a93523
NJ
3760@end deffn
3761
3762
38a93523
NJ
3763@deffn primitive struct-ref handle pos
3764@deffnx primitive struct-set! struct n value
3765Access (or modify) the @var{n}th field of @var{struct}.
3766
3767If the field is of type 'p', then it can be set to an arbitrary value.
3768
3769If the field is of type 'u', then it can only be set to a non-negative
3770integer value small enough to fit in one machine word.
3771@end deffn
3772
3773
3774
3775@node Vtables
3776@subsection Vtables
3777
3778Vtables are structures that are used to represent structure types. Each
3779vtable contains a layout specification in field
3780@code{vtable-index-layout} -- instances of the type are laid out
3781according to that specification. Vtables contain additional fields
3782which are used only internally to libguile. The variable
3783@code{vtable-offset-user} is bound to a field number. Vtable fields
3784at that position or greater are user definable.
3785
38a93523
NJ
3786@deffn primitive struct-vtable handle
3787Return the vtable structure that describes the type of @var{struct}.
3788@end deffn
3789
38a93523 3790@deffn primitive struct-vtable? x
780ee65e 3791Return @code{#t} iff obj is a vtable structure.
38a93523
NJ
3792@end deffn
3793
3794If you have a vtable structure, @code{V}, you can create an instance of
3795the type it describes by using @code{(make-struct V ...)}. But where
3796does @code{V} itself come from? One possibility is that @code{V} is an
3797instance of a user-defined vtable type, @code{V'}, so that @code{V} is
3798created by using @code{(make-struct V' ...)}. Another possibility is
3799that @code{V} is an instance of the type it itself describes. Vtable
3800structures of the second sort are created by this procedure:
3801
38a93523
NJ
3802@deffn primitive make-vtable-vtable user_fields tail_array_size . init
3803Return a new, self-describing vtable structure.
3804
3805@var{user-fields} is a string describing user defined fields of the
3806vtable beginning at index @code{vtable-offset-user}
3807(see @code{make-struct-layout}).
3808
3809@var{tail-size} specifies the size of the tail-array (if any) of
3810this vtable.
3811
3812@var{init1}, @dots{} are the optional initializers for the fields of
3813the vtable.
3814
3815Vtables have one initializable system field---the struct printer.
3816This field comes before the user fields in the initializers passed
3817to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
3818a third optional argument to @code{make-vtable-vtable} and a fourth to
3819@code{make-struct} when creating vtables:
3820
3821If the value is a procedure, it will be called instead of the standard
3822printer whenever a struct described by this vtable is printed.
3823The procedure will be called with arguments STRUCT and PORT.
3824
3825The structure of a struct is described by a vtable, so the vtable is
3826in essence the type of the struct. The vtable is itself a struct with
3827a vtable. This could go on forever if it weren't for the
3828vtable-vtables which are self-describing vtables, and thus terminate
3829the chain.
3830
3831There are several potential ways of using structs, but the standard
3832one is to use three kinds of structs, together building up a type
3833sub-system: one vtable-vtable working as the root and one or several
3834"types", each with a set of "instances". (The vtable-vtable should be
3835compared to the class <class> which is the class of itself.)
3836
ae9f3a15 3837@lisp
38a93523
NJ
3838(define ball-root (make-vtable-vtable "pr" 0))
3839
3840(define (make-ball-type ball-color)
3841 (make-struct ball-root 0
3842 (make-struct-layout "pw")
3843 (lambda (ball port)
3844 (format port "#<a ~A ball owned by ~A>"
3845 (color ball)
3846 (owner ball)))
3847 ball-color))
3848(define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
3849(define (owner ball) (struct-ref ball 0))
3850
3851(define red (make-ball-type 'red))
3852(define green (make-ball-type 'green))
3853
3854(define (make-ball type owner) (make-struct type 0 owner))
3855
3856(define ball (make-ball green 'Nisse))
3857ball @result{} #<a green ball owned by Nisse>
ae9f3a15 3858@end lisp
38a93523
NJ
3859@end deffn
3860
38a93523
NJ
3861@deffn primitive struct-vtable-name vtable
3862Return the name of the vtable @var{vtable}.
3863@end deffn
3864
38a93523
NJ
3865@deffn primitive set-struct-vtable-name! vtable name
3866Set the name of the vtable @var{vtable} to @var{name}.
3867@end deffn
3868
38a93523
NJ
3869@deffn primitive struct-vtable-tag handle
3870Return the vtable tag of the structure @var{handle}.
3871@end deffn
3872
3873
3874@node Arrays
3875@section Arrays
39e30745 3876@tpindex Arrays
38a93523
NJ
3877
3878@menu
b576faf1
MG
3879* Conventional Arrays:: Arrays with arbitrary data.
3880* Array Mapping:: Applying a procedure to the contents of an array.
3881* Uniform Arrays:: Arrays with data of a single type.
3882* Bit Vectors:: Vectors of bits.
38a93523
NJ
3883@end menu
3884
3885@node Conventional Arrays
3886@subsection Conventional Arrays
3887
3888@dfn{Conventional arrays} are a collection of cells organised into an
3889arbitrary number of dimensions. Each cell can hold any kind of Scheme
3890value and can be accessed in constant time by supplying an index for
3891each dimension. This contrasts with uniform arrays, which use memory
3892more efficiently but can hold data of only a single type, and lists
3893where inserting and deleting cells is more efficient, but more time
3894is usually required to access a particular cell.
3895
3896A conventional array is displayed as @code{#} followed by the @dfn{rank}
3897(number of dimensions) followed by the cells, organised into dimensions
3898using parentheses. The nesting depth of the parentheses is equal to
3899the rank.
3900
3901When an array is created, the number of dimensions and range of each
3902dimension must be specified, e.g., to create a 2x3 array with a
3903zero-based index:
3904
3905@example
3906(make-array 'ho 2 3) @result{}
3907#2((ho ho ho) (ho ho ho))
3908@end example
3909
3910The range of each dimension can also be given explicitly, e.g., another
3911way to create the same array:
3912
3913@example
3914(make-array 'ho '(0 1) '(0 2)) @result{}
3915#2((ho ho ho) (ho ho ho))
3916@end example
3917
3918A conventional array with one dimension based at zero is identical to
3919a vector:
3920
3921@example
3922(make-array 'ho 3) @result{}
3923#(ho ho ho)
3924@end example
3925
3926The following procedures can be used with conventional arrays (or vectors).
3927
38a93523 3928@deffn primitive array? v [prot]
ae9f3a15
MG
3929Return @code{#t} if the @var{obj} is an array, and @code{#f} if
3930not. The @var{prototype} argument is used with uniform arrays
3931and is described elsewhere.
38a93523
NJ
3932@end deffn
3933
3934@deffn procedure make-array initial-value bound1 bound2 @dots{}
3935Creates and returns an array that has as many dimensions as there are
3936@var{bound}s and fills it with @var{initial-value}.
3937@end deffn
3938
3939@c array-ref's type is `compiled-closure'. There's some weird stuff
3940@c going on in array.c, too. Let's call it a primitive. -twp
3941
38a93523
NJ
3942@deffn primitive uniform-vector-ref v args
3943@deffnx primitive array-ref v . args
ae9f3a15
MG
3944Return the element at the @code{(index1, index2)} element in
3945@var{array}.
38a93523
NJ
3946@end deffn
3947
38a93523 3948@deffn primitive array-in-bounds? v . args
ae9f3a15
MG
3949Return @code{#t} if its arguments would be acceptable to
3950@code{array-ref}.
38a93523
NJ
3951@end deffn
3952
38a93523
NJ
3953@deffn primitive array-set! v obj . args
3954@deffnx primitive uniform-array-set1! v obj args
3955Sets the element at the @code{(index1, index2)} element in @var{array} to
3956@var{new-value}. The value returned by array-set! is unspecified.
3957@end deffn
3958
38a93523
NJ
3959@deffn primitive make-shared-array oldra mapfunc . dims
3960@code{make-shared-array} can be used to create shared subarrays of other
3961arrays. The @var{mapper} is a function that translates coordinates in
3962the new array into coordinates in the old array. A @var{mapper} must be
3963linear, and its range must stay within the bounds of the old array, but
3964it can be otherwise arbitrary. A simple example:
ae9f3a15 3965@lisp
38a93523
NJ
3966(define fred (make-array #f 8 8))
3967(define freds-diagonal
3968 (make-shared-array fred (lambda (i) (list i i)) 8))
3969(array-set! freds-diagonal 'foo 3)
3970(array-ref fred 3 3) @result{} foo
3971(define freds-center
3972 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
3973(array-ref freds-center 0 0) @result{} foo
ae9f3a15 3974@end lisp
38a93523
NJ
3975@end deffn
3976
38a93523
NJ
3977@deffn primitive shared-array-increments ra
3978For each dimension, return the distance between elements in the root vector.
3979@end deffn
3980
38a93523
NJ
3981@deffn primitive shared-array-offset ra
3982Return the root vector index of the first element in the array.
3983@end deffn
3984
38a93523
NJ
3985@deffn primitive shared-array-root ra
3986Return the root vector of a shared array.
3987@end deffn
3988
38a93523 3989@deffn primitive transpose-array ra . args
ae9f3a15
MG
3990Return an array sharing contents with @var{array}, but with
3991dimensions arranged in a different order. There must be one
3992@var{dim} argument for each dimension of @var{array}.
3993@var{dim0}, @var{dim1}, @dots{} should be integers between 0
3994and the rank of the array to be returned. Each integer in that
3995range must appear at least once in the argument list.
7a095584 3996
ae9f3a15
MG
3997The values of @var{dim0}, @var{dim1}, @dots{} correspond to
3998dimensions in the array to be returned, their positions in the
3999argument list to dimensions of @var{array}. Several @var{dim}s
4000may have the same value, in which case the returned array will
4001have smaller rank than @var{array}.
7a095584 4002
ae9f3a15 4003@lisp
38a93523
NJ
4004(transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
4005(transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
4006(transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
4007 #2((a 4) (b 5) (c 6))
ae9f3a15 4008@end lisp
38a93523
NJ
4009@end deffn
4010
38a93523
NJ
4011@deffn primitive enclose-array ra . axes
4012@var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
4013the rank of @var{array}. @var{enclose-array} returns an array
4014resembling an array of shared arrays. The dimensions of each shared
4015array are the same as the @var{dim}th dimensions of the original array,
4016the dimensions of the outer array are the same as those of the original
4017array that did not match a @var{dim}.
4018
4019An enclosed array is not a general Scheme array. Its elements may not
4020be set using @code{array-set!}. Two references to the same element of
4021an enclosed array will be @code{equal?} but will not in general be
4022@code{eq?}. The value returned by @var{array-prototype} when given an
4023enclosed array is unspecified.
4024
4025examples:
ae9f3a15 4026@lisp
38a93523
NJ
4027(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
4028 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
4029
4030(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
4031 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
ae9f3a15 4032@end lisp
38a93523
NJ
4033@end deffn
4034
4035@deffn procedure array-shape array
4036Returns a list of inclusive bounds of integers.
4037@example
4038(array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
4039@end example
4040@end deffn
4041
38a93523
NJ
4042@deffn primitive array-dimensions ra
4043@code{Array-dimensions} is similar to @code{array-shape} but replaces
4044elements with a @code{0} minimum with one greater than the maximum. So:
ae9f3a15 4045@lisp
38a93523 4046(array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
ae9f3a15 4047@end lisp
38a93523
NJ
4048@end deffn
4049
38a93523 4050@deffn primitive array-rank ra
ae9f3a15
MG
4051Return the number of dimensions of @var{obj}. If @var{obj} is
4052not an array, @code{0} is returned.
38a93523
NJ
4053@end deffn
4054
38a93523 4055@deffn primitive array->list v
ae9f3a15
MG
4056Return a list consisting of all the elements, in order, of
4057@var{array}.
38a93523
NJ
4058@end deffn
4059
38a93523
NJ
4060@deffn primitive array-copy! src dst
4061@deffnx primitive array-copy-in-order! src dst
4062Copies every element from vector or array @var{source} to the
4063corresponding element of @var{destination}. @var{destination} must have
4064the same rank as @var{source}, and be at least as large in each
4065dimension. The order is unspecified.
4066@end deffn
4067
38a93523
NJ
4068@deffn primitive array-fill! ra fill
4069Stores @var{fill} in every element of @var{array}. The value returned
4070is unspecified.
4071@end deffn
4072
4073@c begin (texi-doc-string "guile" "array-equal?")
4074@deffn primitive array-equal? ra0 ra1
4075Returns @code{#t} iff all arguments are arrays with the same shape, the
4076same type, and have corresponding elements which are either
4077@code{equal?} or @code{array-equal?}. This function differs from
4078@code{equal?} in that a one dimensional shared array may be
4079@var{array-equal?} but not @var{equal?} to a vector or uniform vector.
4080@end deffn
4081
38a93523
NJ
4082@deffn primitive array-contents ra [strict]
4083@deffnx primitive array-contents array strict
4084If @var{array} may be @dfn{unrolled} into a one dimensional shared array
4085without changing their order (last subscript changing fastest), then
4086@code{array-contents} returns that shared array, otherwise it returns
4087@code{#f}. All arrays made by @var{make-array} and
4088@var{make-uniform-array} may be unrolled, some arrays made by
4089@var{make-shared-array} may not be.
4090
4091If the optional argument @var{strict} is provided, a shared array will
4092be returned only if its elements are stored internally contiguous in
4093memory.
4094@end deffn
4095
4096@node Array Mapping
4097@subsection Array Mapping
4098
38a93523
NJ
4099@deffn primitive array-map! ra0 proc . lra
4100@deffnx primitive array-map-in-order! ra0 proc . lra
4101@var{array1}, @dots{} must have the same number of dimensions as
4102@var{array0} and have a range for each index which includes the range
4103for the corresponding index in @var{array0}. @var{proc} is applied to
4104each tuple of elements of @var{array1} @dots{} and the result is stored
4105as the corresponding element in @var{array0}. The value returned is
4106unspecified. The order of application is unspecified.
4107@end deffn
4108
38a93523
NJ
4109@deffn primitive array-for-each proc ra0 . lra
4110@var{proc} is applied to each tuple of elements of @var{array0} @dots{}
4111in row-major order. The value returned is unspecified.
4112@end deffn
4113
38a93523
NJ
4114@deffn primitive array-index-map! ra proc
4115applies @var{proc} to the indices of each element of @var{array} in
4116turn, storing the result in the corresponding element. The value
4117returned and the order of application are unspecified.
4118
4119One can implement @var{array-indexes} as
ae9f3a15 4120@lisp
38a93523
NJ
4121(define (array-indexes array)
4122 (let ((ra (apply make-array #f (array-shape array))))
4123 (array-index-map! ra (lambda x x))
4124 ra))
ae9f3a15 4125@end lisp
38a93523 4126Another example:
ae9f3a15 4127@lisp
38a93523
NJ
4128(define (apl:index-generator n)
4129 (let ((v (make-uniform-vector n 1)))
4130 (array-index-map! v (lambda (i) i))
4131 v))
ae9f3a15 4132@end lisp
38a93523
NJ
4133@end deffn
4134
4135@node Uniform Arrays
4136@subsection Uniform Arrays
39e30745 4137@tpindex Uniform Arrays
38a93523
NJ
4138
4139@noindent
4140@dfn{Uniform arrays} have elements all of the
4141same type and occupy less storage than conventional
4142arrays. Uniform arrays with a single zero-based dimension
4143are also known as @dfn{uniform vectors}. The procedures in
4144this section can also be used on conventional arrays, vectors,
4145bit-vectors and strings.
4146
4147@noindent
4148When creating a uniform array, the type of data to be stored
4149is indicated with a @var{prototype} argument. The following table
4150lists the types available and example prototypes:
4151
4152@example
4153prototype type printing character
4154
4155#t boolean (bit-vector) b
4156#\a char (string) a
4157#\nul byte (integer) y
4158's short (integer) h
41591 unsigned long (integer) u
4160-1 signed long (integer) e
4161'l signed long long (integer) l
41621.0 float (single precision) s
41631/3 double (double precision float) i
41640+i complex (double precision) c
4165() conventional vector
4166@end example
4167
4168@noindent
4169Unshared uniform arrays of characters with a single zero-based dimension
4170are identical to strings:
4171
4172@example
4173(make-uniform-array #\a 3) @result{}
4174"aaa"
4175@end example
4176
4177@noindent
4178Unshared uniform arrays of booleans with a single zero-based dimension
4179are identical to @ref{Bit Vectors, bit-vectors}.
4180
4181@example
4182(make-uniform-array #t 3) @result{}
4183#*111
4184@end example
4185
4186@noindent
4187Other uniform vectors are written in a form similar to that of vectors,
4188except that a single character from the above table is put between
4189@code{#} and @code{(}. For example, a uniform vector of signed
4190long integers is displayed in the form @code{'#e(3 5 9)}.
4191
38a93523
NJ
4192@deffn primitive array? v [prot]
4193Returns @code{#t} if the @var{obj} is an array, and @code{#f} if not.
4194
4195The @var{prototype} argument is used with uniform arrays and is described
4196elsewhere.
4197@end deffn
4198
4199@deffn procedure make-uniform-array prototype bound1 bound2 @dots{}
4200Creates and returns a uniform array of type corresponding to
4201@var{prototype} that has as many dimensions as there are @var{bound}s
4202and fills it with @var{prototype}.
4203@end deffn
4204
38a93523 4205@deffn primitive array-prototype ra
ae9f3a15
MG
4206Return an object that would produce an array of the same type
4207as @var{array}, if used as the @var{prototype} for
38a93523
NJ
4208@code{make-uniform-array}.
4209@end deffn
4210
38a93523
NJ
4211@deffn primitive list->uniform-array ndim prot lst
4212@deffnx procedure list->uniform-vector prot lst
ae9f3a15
MG
4213Return a uniform array of the type indicated by prototype
4214@var{prot} with elements the same as those of @var{lst}.
4215Elements must be of the appropriate type, no coercions are
4216done.
38a93523
NJ
4217@end deffn
4218
4219@deffn primitive uniform-vector-fill! uve fill
4220Stores @var{fill} in every element of @var{uve}. The value returned is
4221unspecified.
4222@end deffn
4223
38a93523 4224@deffn primitive uniform-vector-length v
ae9f3a15 4225Return the number of elements in @var{uve}.
38a93523
NJ
4226@end deffn
4227
38a93523
NJ
4228@deffn primitive dimensions->uniform-array dims prot [fill]
4229@deffnx primitive make-uniform-vector length prototype [fill]
ae9f3a15
MG
4230Create and return a uniform array or vector of type
4231corresponding to @var{prototype} with dimensions @var{dims} or
4232length @var{length}. If @var{fill} is supplied, it's used to
4233fill the array, otherwise @var{prototype} is used.
38a93523
NJ
4234@end deffn
4235
4236@c Another compiled-closure. -twp
4237
38a93523
NJ
4238@deffn primitive uniform-array-read! ra [port_or_fd [start [end]]]
4239@deffnx primitive uniform-vector-read! uve [port-or-fdes] [start] [end]
4240Attempts to read all elements of @var{ura}, in lexicographic order, as
4241binary objects from @var{port-or-fdes}.
4242If an end of file is encountered during
4243uniform-array-read! the objects up to that point only are put into @var{ura}
4244(starting at the beginning) and the remainder of the array is
4245unchanged.
4246
4247The optional arguments @var{start} and @var{end} allow
4248a specified region of a vector (or linearized array) to be read,
4249leaving the remainder of the vector unchanged.
4250
4251@code{uniform-array-read!} returns the number of objects read.
4252@var{port-or-fdes} may be omitted, in which case it defaults to the value
4253returned by @code{(current-input-port)}.
4254@end deffn
4255
38a93523
NJ
4256@deffn primitive uniform-array-write v [port_or_fd [start [end]]]
4257@deffnx primitive uniform-vector-write uve [port-or-fdes] [start] [end]
4258Writes all elements of @var{ura} as binary objects to
4259@var{port-or-fdes}.
4260
4261The optional arguments @var{start}
4262and @var{end} allow
4263a specified region of a vector (or linearized array) to be written.
4264
4265The number of objects actually written is returned.
4266@var{port-or-fdes} may be
4267omitted, in which case it defaults to the value returned by
4268@code{(current-output-port)}.
4269@end deffn
4270
4271@node Bit Vectors
4272@subsection Bit Vectors
4273
4274@noindent
4275Bit vectors are a specific type of uniform array: an array of booleans
4276with a single zero-based index.
4277
4278@noindent
4279They are displayed as a sequence of @code{0}s and
4280@code{1}s prefixed by @code{#*}, e.g.,
4281
4282@example
4283(make-uniform-vector 8 #t #f) @result{}
4284#*00000000
4285
4286#b(#t #f #t) @result{}
4287#*101
4288@end example
4289
38a93523 4290@deffn primitive bit-count b bitvector
ae9f3a15 4291Return the number of occurrences of the boolean @var{b} in
38a93523
NJ
4292@var{bitvector}.
4293@end deffn
4294
38a93523 4295@deffn primitive bit-position item v k
ae9f3a15
MG
4296Return the minimum index of an occurrence of @var{bool} in
4297@var{bv} which is at least @var{k}. If no @var{bool} occurs
4298within the specified range @code{#f} is returned.
38a93523
NJ
4299@end deffn
4300
38a93523
NJ
4301@deffn primitive bit-invert! v
4302Modifies @var{bv} by replacing each element with its negation.
4303@end deffn
4304
38a93523
NJ
4305@deffn primitive bit-set*! v kv obj
4306If uve is a bit-vector @var{bv} and uve must be of the same
4307length. If @var{bool} is @code{#t}, uve is OR'ed into
4308@var{bv}; If @var{bool} is @code{#f}, the inversion of uve is
4309AND'ed into @var{bv}.
4310
1be6b49c 4311If uve is a unsigned long integer vector all the elements of uve
38a93523
NJ
4312must be between 0 and the @code{length} of @var{bv}. The bits
4313of @var{bv} corresponding to the indexes in uve are set to
4314@var{bool}. The return value is unspecified.
4315@end deffn
4316
38a93523 4317@deffn primitive bit-count* v kv obj
ae9f3a15
MG
4318Return
4319@lisp
38a93523 4320(bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
ae9f3a15 4321@end lisp
38a93523
NJ
4322@var{bv} is not modified.
4323@end deffn
4324
4325
4326@node Association Lists and Hash Tables
4327@section Association Lists and Hash Tables
4328
4329This chapter discusses dictionary objects: data structures that are
4330useful for organizing and indexing large bodies of information.
4331
4332@menu
4333* Dictionary Types:: About dictionary types; what they're good for.
78c51768
MG
4334* Association Lists:: List-based dictionaries.
4335* Hash Tables:: Table-based dictionaries.
38a93523
NJ
4336@end menu
4337
4338@node Dictionary Types
4339@subsection Dictionary Types
4340
4341A @dfn{dictionary} object is a data structure used to index
4342information in a user-defined way. In standard Scheme, the main
4343aggregate data types are lists and vectors. Lists are not really
4344indexed at all, and vectors are indexed only by number
4345(e.g. @code{(vector-ref foo 5)}). Often you will find it useful
4346to index your data on some other type; for example, in a library
4347catalog you might want to look up a book by the name of its
4348author. Dictionaries are used to help you organize information in
4349such a way.
4350
4351An @dfn{association list} (or @dfn{alist} for short) is a list of
4352key-value pairs. Each pair represents a single quantity or
4353object; the @code{car} of the pair is a key which is used to
4354identify the object, and the @code{cdr} is the object's value.
4355
4356A @dfn{hash table} also permits you to index objects with
4357arbitrary keys, but in a way that makes looking up any one object
4358extremely fast. A well-designed hash system makes hash table
4359lookups almost as fast as conventional array or vector references.
4360
4361Alists are popular among Lisp programmers because they use only
4362the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
4363and the equality primitives). No changes to the language core are
4364necessary. Therefore, with Scheme's built-in list manipulation
4365facilities, it is very convenient to handle data stored in an
4366association list. Also, alists are highly portable and can be
4367easily implemented on even the most minimal Lisp systems.
4368
4369However, alists are inefficient, especially for storing large
4370quantities of data. Because we want Guile to be useful for large
4371software systems as well as small ones, Guile provides a rich set
4372of tools for using either association lists or hash tables.
4373
4374@node Association Lists
4375@subsection Association Lists
39e30745
MG
4376@tpindex Association Lists
4377@tpindex Alist
4378
38a93523
NJ
4379@cindex Association List
4380@cindex Alist
4381@cindex Database
4382
4383An association list is a conventional data structure that is often used
4384to implement simple key-value databases. It consists of a list of
4385entries in which each entry is a pair. The @dfn{key} of each entry is
4386the @code{car} of the pair and the @dfn{value} of each entry is the
4387@code{cdr}.
4388
4389@example
4390ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
4391 (KEY2 . VALUE2)
4392 (KEY3 . VALUE3)
4393 @dots{}
4394 )
4395@end example
4396
4397@noindent
4398Association lists are also known, for short, as @dfn{alists}.
4399
4400The structure of an association list is just one example of the infinite
4401number of possible structures that can be built using pairs and lists.
4402As such, the keys and values in an association list can be manipulated
4403using the general list structure procedures @code{cons}, @code{car},
4404@code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
4405because association lists are so useful, Guile also provides specific
4406procedures for manipulating them.
4407
4408@menu
b576faf1
MG
4409* Alist Key Equality::
4410* Adding or Setting Alist Entries::
4411* Retrieving Alist Entries::
4412* Removing Alist Entries::
4413* Sloppy Alist Functions::
4414* Alist Example::
38a93523
NJ
4415@end menu
4416
4417@node Alist Key Equality
4418@subsubsection Alist Key Equality
4419
4420All of Guile's dedicated association list procedures, apart from
4421@code{acons}, come in three flavours, depending on the level of equality
4422that is required to decide whether an existing key in the association
4423list is the same as the key that the procedure call uses to identify the
4424required entry.
4425
4426@itemize @bullet
4427@item
4428Procedures with @dfn{assq} in their name use @code{eq?} to determine key
4429equality.
4430
4431@item
4432Procedures with @dfn{assv} in their name use @code{eqv?} to determine
4433key equality.
4434
4435@item
4436Procedures with @dfn{assoc} in their name use @code{equal?} to
4437determine key equality.
4438@end itemize
4439
4440@code{acons} is an exception because it is used to build association
4441lists which do not require their entries' keys to be unique.
4442
4443@node Adding or Setting Alist Entries
4444@subsubsection Adding or Setting Alist Entries
38a93523
NJ
4445
4446@code{acons} adds a new entry to an association list and returns the
4447combined association list. The combined alist is formed by consing the
4448new entry onto the head of the alist specified in the @code{acons}
4449procedure call. So the specified alist is not modified, but its
4450contents become shared with the tail of the combined alist that
4451@code{acons} returns.
4452
4453In the most common usage of @code{acons}, a variable holding the
4454original association list is updated with the combined alist:
4455
4456@example
4457(set! address-list (acons name address address-list))
4458@end example
4459
4460In such cases, it doesn't matter that the old and new values of
4461@code{address-list} share some of their contents, since the old value is
4462usually no longer independently accessible.
4463
4464Note that @code{acons} adds the specified new entry regardless of
4465whether the alist may already contain entries with keys that are, in
4466some sense, the same as that of the new entry. Thus @code{acons} is
4467ideal for building alists where there is no concept of key uniqueness.
4468
4469@example
4470(set! task-list (acons 3 "pay gas bill" '()))
4471task-list
4472@result{}
4473((3 . "pay gas bill"))
4474
4475(set! task-list (acons 3 "tidy bedroom" task-list))
4476task-list
4477@result{}
4478((3 . "tidy bedroom") (3 . "pay gas bill"))
4479@end example
4480
4481@code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
4482or replace an entry in an association list where there @emph{is} a
4483concept of key uniqueness. If the specified association list already
4484contains an entry whose key is the same as that specified in the
4485procedure call, the existing entry is replaced by the new one.
4486Otherwise, the new entry is consed onto the head of the old association
4487list to create the combined alist. In all cases, these procedures
4488return the combined alist.
4489
4490@code{assq-set!} and friends @emph{may} destructively modify the
4491structure of the old association list in such a way that an existing
4492variable is correctly updated without having to @code{set!} it to the
4493value returned:
4494
4495@example
4496address-list
4497@result{}
4498(("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
4499
4500(assoc-set! address-list "james" "1a London Road")
4501@result{}
4502(("mary" . "34 Elm Road") ("james" . "1a London Road"))
4503
4504address-list
4505@result{}
4506(("mary" . "34 Elm Road") ("james" . "1a London Road"))
4507@end example
4508
4509Or they may not:
4510
4511@example
4512(assoc-set! address-list "bob" "11 Newington Avenue")
4513@result{}
4514(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4515 ("james" . "1a London Road"))
4516
4517address-list
4518@result{}
4519(("mary" . "34 Elm Road") ("james" . "1a London Road"))
4520@end example
4521
4522The only safe way to update an association list variable when adding or
4523replacing an entry like this is to @code{set!} the variable to the
4524returned value:
4525
4526@example
4527(set! address-list
4528 (assoc-set! address-list "bob" "11 Newington Avenue"))
4529address-list
4530@result{}
4531(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4532 ("james" . "1a London Road"))
4533@end example
4534
4535Because of this slight inconvenience, you may find it more convenient to
4536use hash tables to store dictionary data. If your application will not
4537be modifying the contents of an alist very often, this may not make much
4538difference to you.
4539
4540If you need to keep the old value of an association list in a form
4541independent from the list that results from modification by
4542@code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
4543use @code{list-copy} to copy the old association list before modifying
4544it.
4545
38a93523
NJ
4546@deffn primitive acons key value alist
4547Adds a new key-value pair to @var{alist}. A new pair is
4548created whose car is @var{key} and whose cdr is @var{value}, and the
4549pair is consed onto @var{alist}, and the new list is returned. This
4550function is @emph{not} destructive; @var{alist} is not modified.
4551@end deffn
4552
38a93523
NJ
4553@deffn primitive assq-set! alist key val
4554@deffnx primitive assv-set! alist key value
4555@deffnx primitive assoc-set! alist key value
4556Reassociate @var{key} in @var{alist} with @var{value}: find any existing
4557@var{alist} entry for @var{key} and associate it with the new
4558@var{value}. If @var{alist} does not contain an entry for @var{key},
4559add a new one. Return the (possibly new) alist.
4560
4561These functions do not attempt to verify the structure of @var{alist},
4562and so may cause unusual results if passed an object that is not an
4563association list.
4564@end deffn
4565
4566@node Retrieving Alist Entries
4567@subsubsection Retrieving Alist Entries
5c4b24e1
MG
4568@rnindex assq
4569@rnindex assv
4570@rnindex assoc
38a93523
NJ
4571
4572@code{assq}, @code{assv} and @code{assoc} take an alist and a key as
4573arguments and return the entry for that key if an entry exists, or
4574@code{#f} if there is no entry for that key. Note that, in the cases
4575where an entry exists, these procedures return the complete entry, that
4576is @code{(KEY . VALUE)}, not just the value.
4577
38a93523
NJ
4578@deffn primitive assq key alist
4579@deffnx primitive assv key alist
4580@deffnx primitive assoc key alist
4581Fetches the entry in @var{alist} that is associated with @var{key}. To
4582decide whether the argument @var{key} matches a particular entry in
4583@var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
4584uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
4585cannot be found in @var{alist} (according to whichever equality
4586predicate is in use), then @code{#f} is returned. These functions
4587return the entire alist entry found (i.e. both the key and the value).
4588@end deffn
4589
4590@code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
4591hand, take an alist and a key and return @emph{just the value} for that
4592key, if an entry exists. If there is no entry for the specified key,
4593these procedures return @code{#f}.
4594
4595This creates an ambiguity: if the return value is @code{#f}, it means
4596either that there is no entry with the specified key, or that there
4597@emph{is} an entry for the specified key, with value @code{#f}.
4598Consequently, @code{assq-ref} and friends should only be used where it
4599is known that an entry exists, or where the ambiguity doesn't matter
4600for some other reason.
4601
38a93523
NJ
4602@deffn primitive assq-ref alist key
4603@deffnx primitive assv-ref alist key
4604@deffnx primitive assoc-ref alist key
4605Like @code{assq}, @code{assv} and @code{assoc}, except that only the
4606value associated with @var{key} in @var{alist} is returned. These
4607functions are equivalent to
4608
4609@lisp
4610(let ((ent (@var{associator} @var{key} @var{alist})))
4611 (and ent (cdr ent)))
4612@end lisp
4613
4614where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
4615@end deffn
4616
4617@node Removing Alist Entries
4618@subsubsection Removing Alist Entries
38a93523
NJ
4619
4620To remove the element from an association list whose key matches a
4621specified key, use @code{assq-remove!}, @code{assv-remove!} or
4622@code{assoc-remove!} (depending, as usual, on the level of equality
4623required between the key that you specify and the keys in the
4624association list).
4625
4626As with @code{assq-set!} and friends, the specified alist may or may not
4627be modified destructively, and the only safe way to update a variable
4628containing the alist is to @code{set!} it to the value that
4629@code{assq-remove!} and friends return.
4630
4631@example
4632address-list
4633@result{}
4634(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
4635 ("james" . "1a London Road"))
4636
4637(set! address-list (assoc-remove! address-list "mary"))
4638address-list
4639@result{}
4640(("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
4641@end example
4642
4643Note that, when @code{assq/v/oc-remove!} is used to modify an
4644association list that has been constructed only using the corresponding
4645@code{assq/v/oc-set!}, there can be at most one matching entry in the
4646alist, so the question of multiple entries being removed in one go does
4647not arise. If @code{assq/v/oc-remove!} is applied to an association
4648list that has been constructed using @code{acons}, or an
4649@code{assq/v/oc-set!} with a different level of equality, or any mixture
4650of these, it removes only the first matching entry from the alist, even
4651if the alist might contain further matching entries. For example:
4652
4653@example
4654(define address-list '())
4655(set! address-list (assq-set! address-list "mary" "11 Elm Street"))
4656(set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
4657address-list
4658@result{}
4659(("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
4660
4661(set! address-list (assoc-remove! address-list "mary"))
4662address-list
4663@result{}
4664(("mary" . "11 Elm Street"))
4665@end example
4666
4667In this example, the two instances of the string "mary" are not the same
4668when compared using @code{eq?}, so the two @code{assq-set!} calls add
4669two distinct entries to @code{address-list}. When compared using
4670@code{equal?}, both "mary"s in @code{address-list} are the same as the
4671"mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
4672after removing the first matching entry that it finds, and so one of the
4673"mary" entries is left in place.
4674
38a93523
NJ
4675@deffn primitive assq-remove! alist key
4676@deffnx primitive assv-remove! alist key
4677@deffnx primitive assoc-remove! alist key
4678Delete the first entry in @var{alist} associated with @var{key}, and return
4679the resulting alist.
4680@end deffn
4681
4682@node Sloppy Alist Functions
4683@subsubsection Sloppy Alist Functions
38a93523
NJ
4684
4685@code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
4686like the corresponding non-@code{sloppy-} procedures, except that they
4687return @code{#f} when the specified association list is not well-formed,
4688where the non-@code{sloppy-} versions would signal an error.
4689
4690Specifically, there are two conditions for which the non-@code{sloppy-}
4691procedures signal an error, which the @code{sloppy-} procedures handle
4692instead by returning @code{#f}. Firstly, if the specified alist as a
4693whole is not a proper list:
4694
4695@example
4696(assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4697@result{}
4698ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
4699ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
4700ABORT: (wrong-type-arg)
4701
4702(sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
4703@result{}
4704#f
4705@end example
4706
4707@noindent
4708Secondly, if one of the entries in the specified alist is not a pair:
4709
4710@example
4711(assoc 2 '((1 . 1) 2 (3 . 9)))
4712@result{}
4713ERROR: In procedure assoc in expression (assoc 2 (quote #)):
4714ERROR: Wrong type argument in position 2 (expecting CONSP): 2
4715ABORT: (wrong-type-arg)
4716
4717(sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
4718@result{}
4719#f
4720@end example
4721
4722Unless you are explicitly working with badly formed association lists,
4723it is much safer to use the non-@code{sloppy-} procedures, because they
4724help to highlight coding and data errors that the @code{sloppy-}
4725versions would silently cover up.
4726
38a93523
NJ
4727@deffn primitive sloppy-assq key alist
4728Behaves like @code{assq} but does not do any error checking.
4729Recommended only for use in Guile internals.
4730@end deffn
4731
38a93523
NJ
4732@deffn primitive sloppy-assv key alist
4733Behaves like @code{assv} but does not do any error checking.
4734Recommended only for use in Guile internals.
4735@end deffn
4736
38a93523
NJ
4737@deffn primitive sloppy-assoc key alist
4738Behaves like @code{assoc} but does not do any error checking.
4739Recommended only for use in Guile internals.
4740@end deffn
4741
4742@node Alist Example
4743@subsubsection Alist Example
4744
4745Here is a longer example of how alists may be used in practice.
4746
4747@lisp
4748(define capitals '(("New York" . "Albany")
4749 ("Oregon" . "Salem")
4750 ("Florida" . "Miami")))
4751
4752;; What's the capital of Oregon?
4753(assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
4754(assoc-ref capitals "Oregon") @result{} "Salem"
4755
4756;; We left out South Dakota.
4757(set! capitals
4758 (assoc-set! capitals "South Dakota" "Bismarck"))
4759capitals
4760@result{} (("South Dakota" . "Bismarck")
4761 ("New York" . "Albany")
4762 ("Oregon" . "Salem")
4763 ("Florida" . "Miami"))
4764
4765;; And we got Florida wrong.
4766(set! capitals
4767 (assoc-set! capitals "Florida" "Tallahassee"))
4768capitals
4769@result{} (("South Dakota" . "Bismarck")
4770 ("New York" . "Albany")
4771 ("Oregon" . "Salem")
4772 ("Florida" . "Tallahassee"))
4773
4774;; After Oregon secedes, we can remove it.
4775(set! capitals
4776 (assoc-remove! capitals "Oregon"))
4777capitals
4778@result{} (("South Dakota" . "Bismarck")
4779 ("New York" . "Albany")
4780 ("Florida" . "Tallahassee"))
4781@end lisp
4782
4783@node Hash Tables
4784@subsection Hash Tables
39e30745 4785@tpindex Hash Tables
38a93523
NJ
4786
4787Like the association list functions, the hash table functions come
4788in several varieties: @code{hashq}, @code{hashv}, and @code{hash}.
4789The @code{hashq} functions use @code{eq?} to determine whether two
4790keys match. The @code{hashv} functions use @code{eqv?}, and the
4791@code{hash} functions use @code{equal?}.
4792
4793In each of the functions that follow, the @var{table} argument
4794must be a vector. The @var{key} and @var{value} arguments may be
4795any Scheme object.
4796
78c51768
MG
4797@deffn procedure make-hash-table size
4798Create a new hash table of @var{size} slots. Note that the number of
4799slots does not limit the size of the table, it just tells how large
4800the underlying vector will be. The @var{size} should be similar to
4801the expected number of elements which will be added to the table, but
4802they need not match. For good performance, it might be a good idea to
4803use a prime number as the @var{size}.
4804@end deffn
4805
ae9f3a15 4806@deffn primitive hashq-ref table key [dflt]
38a93523
NJ
4807Look up @var{key} in the hash table @var{table}, and return the
4808value (if any) associated with it. If @var{key} is not found,
780ee65e
NJ
4809return @var{default} (or @code{#f} if no @var{default} argument
4810is supplied). Uses @code{eq?} for equality testing.
38a93523
NJ
4811@end deffn
4812
ae9f3a15 4813@deffn primitive hashv-ref table key [dflt]
38a93523
NJ
4814Look up @var{key} in the hash table @var{table}, and return the
4815value (if any) associated with it. If @var{key} is not found,
780ee65e
NJ
4816return @var{default} (or @code{#f} if no @var{default} argument
4817is supplied). Uses @code{eqv?} for equality testing.
38a93523
NJ
4818@end deffn
4819
ae9f3a15 4820@deffn primitive hash-ref table key [dflt]
38a93523
NJ
4821Look up @var{key} in the hash table @var{table}, and return the
4822value (if any) associated with it. If @var{key} is not found,
780ee65e
NJ
4823return @var{default} (or @code{#f} if no @var{default} argument
4824is supplied). Uses @code{equal?} for equality testing.
38a93523
NJ
4825@end deffn
4826
ae9f3a15 4827@deffn primitive hashq-set! table key val
780ee65e
NJ
4828Find the entry in @var{table} associated with @var{key}, and
4829store @var{value} there. Uses @code{eq?} for equality testing.
38a93523
NJ
4830@end deffn
4831
ae9f3a15 4832@deffn primitive hashv-set! table key val
780ee65e
NJ
4833Find the entry in @var{table} associated with @var{key}, and
4834store @var{value} there. Uses @code{eqv?} for equality testing.
38a93523
NJ
4835@end deffn
4836
ae9f3a15 4837@deffn primitive hash-set! table key val
780ee65e
NJ
4838Find the entry in @var{table} associated with @var{key}, and
4839store @var{value} there. Uses @code{equal?} for equality
4840testing.
38a93523
NJ
4841@end deffn
4842
ae9f3a15 4843@deffn primitive hashq-remove! table key
780ee65e
NJ
4844Remove @var{key} (and any value associated with it) from
4845@var{table}. Uses @code{eq?} for equality tests.
38a93523
NJ
4846@end deffn
4847
ae9f3a15 4848@deffn primitive hashv-remove! table key
780ee65e
NJ
4849Remove @var{key} (and any value associated with it) from
4850@var{table}. Uses @code{eqv?} for equality tests.
38a93523
NJ
4851@end deffn
4852
ae9f3a15 4853@deffn primitive hash-remove! table key
780ee65e
NJ
4854Remove @var{key} (and any value associated with it) from
4855@var{table}. Uses @code{equal?} for equality tests.
38a93523
NJ
4856@end deffn
4857
4858The standard hash table functions may be too limited for some
4859applications. For example, you may want a hash table to store
4860strings in a case-insensitive manner, so that references to keys
4861named ``foobar'', ``FOOBAR'' and ``FooBaR'' will all yield the
4862same item. Guile provides you with @dfn{extended} hash tables
4863that permit you to specify a hash function and associator function
4864of your choosing. The functions described in the rest of this section
4865can be used to implement such custom hash table structures.
4866
4867If you are unfamiliar with the inner workings of hash tables, then
4868this facility will probably be a little too abstract for you to
4869use comfortably. If you are interested in learning more, see an
4870introductory textbook on data structures or algorithms for an
4871explanation of how hash tables are implemented.
4872
38a93523 4873@deffn primitive hashq key size
780ee65e
NJ
4874Determine a hash value for @var{key} that is suitable for
4875lookups in a hashtable of size @var{size}, where @code{eq?} is
4876used as the equality predicate. The function returns an
4877integer in the range 0 to @var{size} - 1. Note that
4878@code{hashq} may use internal addresses. Thus two calls to
4879hashq where the keys are @code{eq?} are not guaranteed to
4880deliver the same value if the key object gets garbage collected
4881in between. This can happen, for example with symbols:
4882@code{(hashq 'foo n) (gc) (hashq 'foo n)} may produce two
4883different values, since @code{foo} will be garbage collected.
38a93523
NJ
4884@end deffn
4885
38a93523 4886@deffn primitive hashv key size
780ee65e
NJ
4887Determine a hash value for @var{key} that is suitable for
4888lookups in a hashtable of size @var{size}, where @code{eqv?} is
4889used as the equality predicate. The function returns an
4890integer in the range 0 to @var{size} - 1. Note that
4891@code{(hashv key)} may use internal addresses. Thus two calls
4892to hashv where the keys are @code{eqv?} are not guaranteed to
4893deliver the same value if the key object gets garbage collected
4894in between. This can happen, for example with symbols:
4895@code{(hashv 'foo n) (gc) (hashv 'foo n)} may produce two
4896different values, since @code{foo} will be garbage collected.
38a93523
NJ
4897@end deffn
4898
38a93523 4899@deffn primitive hash key size
780ee65e
NJ
4900Determine a hash value for @var{key} that is suitable for
4901lookups in a hashtable of size @var{size}, where @code{equal?}
4902is used as the equality predicate. The function returns an
4903integer in the range 0 to @var{size} - 1.
38a93523
NJ
4904@end deffn
4905
ae9f3a15 4906@deffn primitive hashx-ref hash assoc table key [dflt]
38a93523 4907This behaves the same way as the corresponding @code{ref}
ae9f3a15
MG
4908function, but uses @var{hash} as a hash function and
4909@var{assoc} to compare keys. @code{hash} must be a function
4910that takes two arguments, a key to be hashed and a table size.
4911@code{assoc} must be an associator function, like @code{assoc},
4912@code{assq} or @code{assv}.
7a095584 4913
ae9f3a15
MG
4914By way of illustration, @code{hashq-ref table key} is
4915equivalent to @code{hashx-ref hashq assq table key}.
38a93523
NJ
4916@end deffn
4917
ae9f3a15 4918@deffn primitive hashx-set! hash assoc table key val
38a93523 4919This behaves the same way as the corresponding @code{set!}
ae9f3a15
MG
4920function, but uses @var{hash} as a hash function and
4921@var{assoc} to compare keys. @code{hash} must be a function
4922that takes two arguments, a key to be hashed and a table size.
4923@code{assoc} must be an associator function, like @code{assoc},
4924@code{assq} or @code{assv}.
7a095584 4925
ae9f3a15
MG
4926 By way of illustration, @code{hashq-set! table key} is
4927equivalent to @code{hashx-set! hashq assq table key}.
38a93523
NJ
4928@end deffn
4929
ae9f3a15
MG
4930@deffn primitive hashq-get-handle table key
4931This procedure returns the @code{(key . value)} pair from the
4932hash table @var{table}. If @var{table} does not hold an
4933associated value for @var{key}, @code{#f} is returned.
4934Uses @code{eq?} for equality testing.
38a93523
NJ
4935@end deffn
4936
ae9f3a15
MG
4937@deffn primitive hashv-get-handle table key
4938This procedure returns the @code{(key . value)} pair from the
4939hash table @var{table}. If @var{table} does not hold an
4940associated value for @var{key}, @code{#f} is returned.
4941Uses @code{eqv?} for equality testing.
38a93523
NJ
4942@end deffn
4943
ae9f3a15
MG
4944@deffn primitive hash-get-handle table key
4945This procedure returns the @code{(key . value)} pair from the
4946hash table @var{table}. If @var{table} does not hold an
4947associated value for @var{key}, @code{#f} is returned.
4948Uses @code{equal?} for equality testing.
38a93523
NJ
4949@end deffn
4950
ae9f3a15
MG
4951@deffn primitive hashx-get-handle hash assoc table key
4952This behaves the same way as the corresponding
4953@code{-get-handle} function, but uses @var{hash} as a hash
4954function and @var{assoc} to compare keys. @code{hash} must be
4955a function that takes two arguments, a key to be hashed and a
38a93523
NJ
4956table size. @code{assoc} must be an associator function, like
4957@code{assoc}, @code{assq} or @code{assv}.
4958@end deffn
4959
38a93523
NJ
4960@deffn primitive hashq-create-handle! table key init
4961This function looks up @var{key} in @var{table} and returns its handle.
4962If @var{key} is not already present, a new handle is created which
4963associates @var{key} with @var{init}.
4964@end deffn
4965
38a93523
NJ
4966@deffn primitive hashv-create-handle! table key init
4967This function looks up @var{key} in @var{table} and returns its handle.
4968If @var{key} is not already present, a new handle is created which
4969associates @var{key} with @var{init}.
4970@end deffn
4971
38a93523
NJ
4972@deffn primitive hash-create-handle! table key init
4973This function looks up @var{key} in @var{table} and returns its handle.
4974If @var{key} is not already present, a new handle is created which
4975associates @var{key} with @var{init}.
4976@end deffn
4977
ae9f3a15
MG
4978@deffn primitive hashx-create-handle! hash assoc table key init
4979This behaves the same way as the corresponding
4980@code{-create-handle} function, but uses @var{hash} as a hash
4981function and @var{assoc} to compare keys. @code{hash} must be
4982a function that takes two arguments, a key to be hashed and a
38a93523
NJ
4983table size. @code{assoc} must be an associator function, like
4984@code{assoc}, @code{assq} or @code{assv}.
4985@end deffn
4986
38a93523
NJ
4987@deffn primitive hash-fold proc init table
4988An iterator over hash-table elements.
4989Accumulates and returns a result by applying PROC successively.
4990The arguments to PROC are "(key value prior-result)" where key
4991and value are successive pairs from the hash table TABLE, and
4992prior-result is either INIT (for the first application of PROC)
4993or the return value of the previous application of PROC.
4994For example, @code{(hash-fold acons () tab)} will convert a hash
4995table into an a-list of key-value pairs.
4996@end deffn
4997
4998
38a93523
NJ
4999@node Hooks
5000@section Hooks
39e30745 5001@tpindex Hooks
38a93523 5002
5c4b24e1
MG
5003@c FIXME::martin: Review me!
5004
5005A hook is basically a list of procedures to be called at well defined
5006points in time. Hooks are used internally for several debugging
5007facilities, but they can be used in user code, too.
5008
5009Hooks are created with @code{make-hook}, then procedures can be added to
5010a hook with @code{add-hook!} or removed with @code{remove-hook!} or
5011@code{reset-hook!}. The procedures stored in a hook can be invoked with
5012@code{run-hook}.
5013
5014@menu
5015* Hook Examples:: Hook usage by example.
5016* Hook Reference:: Reference of all hook procedures.
5017@end menu
5018
5019@node Hook Examples
5020@subsection Hook Examples
5021
5022Hook usage is shown by some examples in this section. First, we will
fb02eb66 5023define a hook of arity 2 --- that is, the procedures stored in the hook
5c4b24e1
MG
5024will have to accept two arguments.
5025
5026@lisp
5027(define hook (make-hook 2))
5028hook
5029@result{} #<hook 2 40286c90>
5030@end lisp
5031
5032Now we are ready to add some procedures to the newly created hook with
5033@code{add-hook!}. In the following example, two procedures are added,
5034which print different messages and do different things with their
5035arguments. When the procedures have been added, we can invoke them
5036using @code{run-hook}.
5037
5038@lisp
5039(add-hook! hook (lambda (x y)
5040 (display "Foo: ")
5041 (display (+ x y))
5042 (newline)))
5043(add-hook! hook (lambda (x y)
5044 (display "Bar: ")
5045 (display (* x y))
5046 (newline)))
5047(run-hook hook 3 4)
f4f2b29a
MG
5048@print{} Bar: 12
5049@print{} Foo: 7
5c4b24e1
MG
5050@end lisp
5051
5052Note that the procedures are called in reverse order than they were
5053added. This can be changed by providing the optional third argument
5054on the second call to @code{add-hook!}.
5055
5056@lisp
5057(add-hook! hook (lambda (x y)
5058 (display "Foo: ")
5059 (display (+ x y))
5060 (newline)))
5061(add-hook! hook (lambda (x y)
5062 (display "Bar: ")
5063 (display (* x y))
5064 (newline))
f4f2b29a 5065 #t) ; @r{<- Change here!}
5c4b24e1 5066(run-hook hook 3 4)
f4f2b29a
MG
5067@print{} Foo: 7
5068@print{} Bar: 12
5c4b24e1
MG
5069@end lisp
5070
5071@node Hook Reference
5072@subsection Hook Reference
5073
5074When a hook is created with @code{make-hook}, you can supply the arity
5075of the procedures which can be added to the hook. The arity defaults to
5076zero. All procedures of a hook must have the same arity, and when the
5077procedures are invoked using @code{run-hook}, the number of arguments
5078must match the arity of the procedures.
5079
5080The order in which procedures are added to a hook matters. If the third
5081parameter to @var{add-hook!} is omitted or is equal to @code{#f}, the
5082procedure is added in front of the procedures which might already be on
5083that hook, otherwise the procedure is added at the end. The procedures
5084are always called from first to last when they are invoked via
5085@code{run-hook}.
5086
5087When calling @code{hook->list}, the procedures in the resulting list are
5088in the same order as they would have been called by @code{run-hook}.
5089
38a93523
NJ
5090@deffn primitive make-hook-with-name name [n_args]
5091Create a named hook with the name @var{name} for storing
5c4b24e1
MG
5092procedures of arity @var{n_args}. @var{n_args} defaults to
5093zero.
38a93523
NJ
5094@end deffn
5095
38a93523 5096@deffn primitive make-hook [n_args]
5c4b24e1
MG
5097Create a hook for storing procedure of arity
5098@var{n_args}. @var{n_args} defaults to zero.
38a93523
NJ
5099@end deffn
5100
38a93523 5101@deffn primitive hook? x
5c4b24e1 5102Return @code{#t} if @var{x} is a hook, @code{#f} otherwise.
38a93523
NJ
5103@end deffn
5104
38a93523 5105@deffn primitive hook-empty? hook
5c4b24e1
MG
5106Return @code{#t} if @var{hook} is an empty hook, @code{#f}
5107otherwise.
38a93523
NJ
5108@end deffn
5109
38a93523
NJ
5110@deffn primitive add-hook! hook proc [append_p]
5111Add the procedure @var{proc} to the hook @var{hook}. The
5112procedure is added to the end if @var{append_p} is true,
5113otherwise it is added to the front.
5114@end deffn
5115
38a93523
NJ
5116@deffn primitive remove-hook! hook proc
5117Remove the procedure @var{proc} from the hook @var{hook}.
5118@end deffn
5119
38a93523
NJ
5120@deffn primitive reset-hook! hook
5121Remove all procedures from the hook @var{hook}.
5122@end deffn
5123
38a93523
NJ
5124@deffn primitive run-hook hook . args
5125Apply all procedures from the hook @var{hook} to the arguments
5c4b24e1
MG
5126@var{args}. The order of the procedure application is first to
5127last.
38a93523
NJ
5128@end deffn
5129
38a93523
NJ
5130@deffn primitive hook->list hook
5131Convert the procedure list of @var{hook} to a list.
5132@end deffn
5133
5134
5135@node Other Data Types
5136@section Other Core Guile Data Types
5137
38a93523
NJ
5138@c Local Variables:
5139@c TeX-master: "guile.texi"
5140@c End: