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