Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / doc / ref / api-compound.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 @c 2007, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node Compound Data Types
8 @section Compound Data Types
9
10 This chapter describes Guile's compound data types. By @dfn{compound}
11 we mean that the primary purpose of these data types is to act as
12 containers for other kinds of data (including other compound objects).
13 For instance, a (non-uniform) vector with length 5 is a container that
14 can hold five arbitrary Scheme objects.
15
16 The various kinds of container object differ from each other in how
17 their memory is allocated, how they are indexed, and how particular
18 values can be looked up within them.
19
20 @menu
21 * Pairs:: Scheme's basic building block.
22 * Lists:: Special list functions supported by Guile.
23 * Vectors:: One-dimensional arrays of Scheme objects.
24 * Bit Vectors:: Vectors of bits.
25 * Generalized Vectors:: Treating all vector-like things uniformly.
26 * Arrays:: Matrices, etc.
27 * VLists:: Vector-like lists.
28 * Record Overview:: Walking through the maze of record APIs.
29 * SRFI-9 Records:: The standard, recommended record API.
30 * Records:: Guile's historical record API.
31 * Structures:: Low-level record representation.
32 * Dictionary Types:: About dictionary types in general.
33 * Association Lists:: List-based dictionaries.
34 * VHashes:: VList-based dictionaries.
35 * Hash Tables:: Table-based dictionaries.
36 @end menu
37
38
39 @node Pairs
40 @subsection Pairs
41 @tpindex Pairs
42
43 Pairs are used to combine two Scheme objects into one compound object.
44 Hence the name: A pair stores a pair of objects.
45
46 The data type @dfn{pair} is extremely important in Scheme, just like in
47 any other Lisp dialect. The reason is that pairs are not only used to
48 make two values available as one object, but that pairs are used for
49 constructing lists of values. Because lists are so important in Scheme,
50 they are described in a section of their own (@pxref{Lists}).
51
52 Pairs can literally get entered in source code or at the REPL, in the
53 so-called @dfn{dotted list} syntax. This syntax consists of an opening
54 parentheses, the first element of the pair, a dot, the second element
55 and a closing parentheses. The following example shows how a pair
56 consisting of the two numbers 1 and 2, and a pair containing the symbols
57 @code{foo} and @code{bar} can be entered. It is very important to write
58 the whitespace before and after the dot, because otherwise the Scheme
59 parser would not be able to figure out where to split the tokens.
60
61 @lisp
62 (1 . 2)
63 (foo . bar)
64 @end lisp
65
66 But beware, if you want to try out these examples, you have to
67 @dfn{quote} the expressions. More information about quotation is
68 available in the section @ref{Expression Syntax}. The correct way
69 to try these examples is as follows.
70
71 @lisp
72 '(1 . 2)
73 @result{}
74 (1 . 2)
75 '(foo . bar)
76 @result{}
77 (foo . bar)
78 @end lisp
79
80 A new pair is made by calling the procedure @code{cons} with two
81 arguments. Then the argument values are stored into a newly allocated
82 pair, and the pair is returned. The name @code{cons} stands for
83 "construct". Use the procedure @code{pair?} to test whether a
84 given Scheme object is a pair or not.
85
86 @rnindex cons
87 @deffn {Scheme Procedure} cons x y
88 @deffnx {C Function} scm_cons (x, y)
89 Return a newly allocated pair whose car is @var{x} and whose
90 cdr is @var{y}. The pair is guaranteed to be different (in the
91 sense of @code{eq?}) from every previously existing object.
92 @end deffn
93
94 @rnindex pair?
95 @deffn {Scheme Procedure} pair? x
96 @deffnx {C Function} scm_pair_p (x)
97 Return @code{#t} if @var{x} is a pair; otherwise return
98 @code{#f}.
99 @end deffn
100
101 @deftypefn {C Function} int scm_is_pair (SCM x)
102 Return 1 when @var{x} is a pair; otherwise return 0.
103 @end deftypefn
104
105 The two parts of a pair are traditionally called @dfn{car} and
106 @dfn{cdr}. They can be retrieved with procedures of the same name
107 (@code{car} and @code{cdr}), and can be modified with the procedures
108 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
109 Scheme programs is to access the car of a car of a pair, or the car of
110 the cdr of a pair, etc., the procedures called @code{caar},
111 @code{cadr} and so on are also predefined.
112
113 @rnindex car
114 @rnindex cdr
115 @deffn {Scheme Procedure} car pair
116 @deffnx {Scheme Procedure} cdr pair
117 @deffnx {C Function} scm_car (pair)
118 @deffnx {C Function} scm_cdr (pair)
119 Return the car or the cdr of @var{pair}, respectively.
120 @end deffn
121
122 @deftypefn {C Macro} SCM SCM_CAR (SCM pair)
123 @deftypefnx {C Macro} SCM SCM_CDR (SCM pair)
124 These two macros are the fastest way to access the car or cdr of a
125 pair; they can be thought of as compiling into a single memory
126 reference.
127
128 These macros do no checking at all. The argument @var{pair} must be a
129 valid pair.
130 @end deftypefn
131
132 @deffn {Scheme Procedure} cddr pair
133 @deffnx {Scheme Procedure} cdar pair
134 @deffnx {Scheme Procedure} cadr pair
135 @deffnx {Scheme Procedure} caar pair
136 @deffnx {Scheme Procedure} cdddr pair
137 @deffnx {Scheme Procedure} cddar pair
138 @deffnx {Scheme Procedure} cdadr pair
139 @deffnx {Scheme Procedure} cdaar pair
140 @deffnx {Scheme Procedure} caddr pair
141 @deffnx {Scheme Procedure} cadar pair
142 @deffnx {Scheme Procedure} caadr pair
143 @deffnx {Scheme Procedure} caaar pair
144 @deffnx {Scheme Procedure} cddddr pair
145 @deffnx {Scheme Procedure} cdddar pair
146 @deffnx {Scheme Procedure} cddadr pair
147 @deffnx {Scheme Procedure} cddaar pair
148 @deffnx {Scheme Procedure} cdaddr pair
149 @deffnx {Scheme Procedure} cdadar pair
150 @deffnx {Scheme Procedure} cdaadr pair
151 @deffnx {Scheme Procedure} cdaaar pair
152 @deffnx {Scheme Procedure} cadddr pair
153 @deffnx {Scheme Procedure} caddar pair
154 @deffnx {Scheme Procedure} cadadr pair
155 @deffnx {Scheme Procedure} cadaar pair
156 @deffnx {Scheme Procedure} caaddr pair
157 @deffnx {Scheme Procedure} caadar pair
158 @deffnx {Scheme Procedure} caaadr pair
159 @deffnx {Scheme Procedure} caaaar pair
160 @deffnx {C Function} scm_cddr (pair)
161 @deffnx {C Function} scm_cdar (pair)
162 @deffnx {C Function} scm_cadr (pair)
163 @deffnx {C Function} scm_caar (pair)
164 @deffnx {C Function} scm_cdddr (pair)
165 @deffnx {C Function} scm_cddar (pair)
166 @deffnx {C Function} scm_cdadr (pair)
167 @deffnx {C Function} scm_cdaar (pair)
168 @deffnx {C Function} scm_caddr (pair)
169 @deffnx {C Function} scm_cadar (pair)
170 @deffnx {C Function} scm_caadr (pair)
171 @deffnx {C Function} scm_caaar (pair)
172 @deffnx {C Function} scm_cddddr (pair)
173 @deffnx {C Function} scm_cdddar (pair)
174 @deffnx {C Function} scm_cddadr (pair)
175 @deffnx {C Function} scm_cddaar (pair)
176 @deffnx {C Function} scm_cdaddr (pair)
177 @deffnx {C Function} scm_cdadar (pair)
178 @deffnx {C Function} scm_cdaadr (pair)
179 @deffnx {C Function} scm_cdaaar (pair)
180 @deffnx {C Function} scm_cadddr (pair)
181 @deffnx {C Function} scm_caddar (pair)
182 @deffnx {C Function} scm_cadadr (pair)
183 @deffnx {C Function} scm_cadaar (pair)
184 @deffnx {C Function} scm_caaddr (pair)
185 @deffnx {C Function} scm_caadar (pair)
186 @deffnx {C Function} scm_caaadr (pair)
187 @deffnx {C Function} scm_caaaar (pair)
188 These procedures are compositions of @code{car} and @code{cdr}, where
189 for example @code{caddr} could be defined by
190
191 @lisp
192 (define caddr (lambda (x) (car (cdr (cdr x)))))
193 @end lisp
194
195 @code{cadr}, @code{caddr} and @code{cadddr} pick out the second, third
196 or fourth elements of a list, respectively. SRFI-1 provides the same
197 under the names @code{second}, @code{third} and @code{fourth}
198 (@pxref{SRFI-1 Selectors}).
199 @end deffn
200
201 @rnindex set-car!
202 @deffn {Scheme Procedure} set-car! pair value
203 @deffnx {C Function} scm_set_car_x (pair, value)
204 Stores @var{value} in the car field of @var{pair}. The value returned
205 by @code{set-car!} is unspecified.
206 @end deffn
207
208 @rnindex set-cdr!
209 @deffn {Scheme Procedure} set-cdr! pair value
210 @deffnx {C Function} scm_set_cdr_x (pair, value)
211 Stores @var{value} in the cdr field of @var{pair}. The value returned
212 by @code{set-cdr!} is unspecified.
213 @end deffn
214
215
216 @node Lists
217 @subsection Lists
218 @tpindex Lists
219
220 A very important data type in Scheme---as well as in all other Lisp
221 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
222 Scheme does not have a real datatype @dfn{list}. Lists are made up of
223 @dfn{chained pairs}, and only exist by definition---a list is a chain
224 of pairs which looks like a list.}
225
226 This is the short definition of what a list is:
227
228 @itemize @bullet
229 @item
230 Either the empty list @code{()},
231
232 @item
233 or a pair which has a list in its cdr.
234 @end itemize
235
236 @c FIXME::martin: Describe the pair chaining in more detail.
237
238 @c FIXME::martin: What is a proper, what an improper list?
239 @c What is a circular list?
240
241 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
242 @c manual?
243
244 @menu
245 * List Syntax:: Writing literal lists.
246 * List Predicates:: Testing lists.
247 * List Constructors:: Creating new lists.
248 * List Selection:: Selecting from lists, getting their length.
249 * Append/Reverse:: Appending and reversing lists.
250 * List Modification:: Modifying existing lists.
251 * List Searching:: Searching for list elements
252 * List Mapping:: Applying procedures to lists.
253 @end menu
254
255 @node List Syntax
256 @subsubsection List Read Syntax
257
258 The syntax for lists is an opening parentheses, then all the elements of
259 the list (separated by whitespace) and finally a closing
260 parentheses.@footnote{Note that there is no separation character between
261 the list elements, like a comma or a semicolon.}.
262
263 @lisp
264 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
265 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
266 () ; @r{the empty list}
267 @end lisp
268
269 The last example needs a bit more explanation. A list with no elements,
270 called the @dfn{empty list}, is special in some ways. It is used for
271 terminating lists by storing it into the cdr of the last pair that makes
272 up a list. An example will clear that up:
273
274 @lisp
275 (car '(1))
276 @result{}
277 1
278 (cdr '(1))
279 @result{}
280 ()
281 @end lisp
282
283 This example also shows that lists have to be quoted when written
284 (@pxref{Expression Syntax}), because they would otherwise be
285 mistakingly taken as procedure applications (@pxref{Simple
286 Invocation}).
287
288
289 @node List Predicates
290 @subsubsection List Predicates
291
292 Often it is useful to test whether a given Scheme object is a list or
293 not. List-processing procedures could use this information to test
294 whether their input is valid, or they could do different things
295 depending on the datatype of their arguments.
296
297 @rnindex list?
298 @deffn {Scheme Procedure} list? x
299 @deffnx {C Function} scm_list_p (x)
300 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
301 @end deffn
302
303 The predicate @code{null?} is often used in list-processing code to
304 tell whether a given list has run out of elements. That is, a loop
305 somehow deals with the elements of a list until the list satisfies
306 @code{null?}. Then, the algorithm terminates.
307
308 @rnindex null?
309 @deffn {Scheme Procedure} null? x
310 @deffnx {C Function} scm_null_p (x)
311 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
312 @end deffn
313
314 @deftypefn {C Function} int scm_is_null (SCM x)
315 Return 1 when @var{x} is the empty list; otherwise return 0.
316 @end deftypefn
317
318
319 @node List Constructors
320 @subsubsection List Constructors
321
322 This section describes the procedures for constructing new lists.
323 @code{list} simply returns a list where the elements are the arguments,
324 @code{cons*} is similar, but the last argument is stored in the cdr of
325 the last pair of the list.
326
327 @c C Function scm_list(rest) used to be documented here, but it's a
328 @c no-op since it does nothing but return the list the caller must
329 @c have already created.
330 @c
331 @deffn {Scheme Procedure} list elem @dots{}
332 @deffnx {C Function} scm_list_1 (elem1)
333 @deffnx {C Function} scm_list_2 (elem1, elem2)
334 @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
335 @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
336 @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
337 @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
338 @rnindex list
339 Return a new list containing elements @var{elem} @enddots{}.
340
341 @code{scm_list_n} takes a variable number of arguments, terminated by
342 the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
343 not included in the list. None of @var{elem} @dots{} can
344 themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
345 terminate at that point.
346 @end deffn
347
348 @c C Function scm_cons_star(arg1,rest) used to be documented here,
349 @c but it's not really a useful interface, since it expects the
350 @c caller to have already consed up all but the first argument
351 @c already.
352 @c
353 @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
354 Like @code{list}, but the last arg provides the tail of the
355 constructed list, returning @code{(cons @var{arg1} (cons
356 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
357 argument. If given one argument, that argument is returned as
358 result. This function is called @code{list*} in some other
359 Schemes and in Common LISP.
360 @end deffn
361
362 @deffn {Scheme Procedure} list-copy lst
363 @deffnx {C Function} scm_list_copy (lst)
364 Return a (newly-created) copy of @var{lst}.
365 @end deffn
366
367 @deffn {Scheme Procedure} make-list n [init]
368 Create a list containing of @var{n} elements, where each element is
369 initialized to @var{init}. @var{init} defaults to the empty list
370 @code{()} if not given.
371 @end deffn
372
373 Note that @code{list-copy} only makes a copy of the pairs which make up
374 the spine of the lists. The list elements are not copied, which means
375 that modifying the elements of the new list also modifies the elements
376 of the old list. On the other hand, applying procedures like
377 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
378 list. If you also need to copy the list elements (making a deep copy),
379 use the procedure @code{copy-tree} (@pxref{Copying}).
380
381 @node List Selection
382 @subsubsection List Selection
383
384 These procedures are used to get some information about a list, or to
385 retrieve one or more elements of a list.
386
387 @rnindex length
388 @deffn {Scheme Procedure} length lst
389 @deffnx {C Function} scm_length (lst)
390 Return the number of elements in list @var{lst}.
391 @end deffn
392
393 @deffn {Scheme Procedure} last-pair lst
394 @deffnx {C Function} scm_last_pair (lst)
395 Return the last pair in @var{lst}, signalling an error if
396 @var{lst} is circular.
397 @end deffn
398
399 @rnindex list-ref
400 @deffn {Scheme Procedure} list-ref list k
401 @deffnx {C Function} scm_list_ref (list, k)
402 Return the @var{k}th element from @var{list}.
403 @end deffn
404
405 @rnindex list-tail
406 @deffn {Scheme Procedure} list-tail lst k
407 @deffnx {Scheme Procedure} list-cdr-ref lst k
408 @deffnx {C Function} scm_list_tail (lst, k)
409 Return the "tail" of @var{lst} beginning with its @var{k}th element.
410 The first element of the list is considered to be element 0.
411
412 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
413 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
414 or returning the results of cdring @var{k} times down @var{lst}.
415 @end deffn
416
417 @deffn {Scheme Procedure} list-head lst k
418 @deffnx {C Function} scm_list_head (lst, k)
419 Copy the first @var{k} elements from @var{lst} into a new list, and
420 return it.
421 @end deffn
422
423 @node Append/Reverse
424 @subsubsection Append and Reverse
425
426 @code{append} and @code{append!} are used to concatenate two or more
427 lists in order to form a new list. @code{reverse} and @code{reverse!}
428 return lists with the same elements as their arguments, but in reverse
429 order. The procedure variants with an @code{!} directly modify the
430 pairs which form the list, whereas the other procedures create new
431 pairs. This is why you should be careful when using the side-effecting
432 variants.
433
434 @rnindex append
435 @deffn {Scheme Procedure} append lst @dots{} obj
436 @deffnx {Scheme Procedure} append
437 @deffnx {Scheme Procedure} append! lst @dots{} obj
438 @deffnx {Scheme Procedure} append!
439 @deffnx {C Function} scm_append (lstlst)
440 @deffnx {C Function} scm_append_x (lstlst)
441 Return a list comprising all the elements of lists @var{lst} @dots{}
442 @var{obj}. If called with no arguments, return the empty list.
443
444 @lisp
445 (append '(x) '(y)) @result{} (x y)
446 (append '(a) '(b c d)) @result{} (a b c d)
447 (append '(a (b)) '((c))) @result{} (a (b) (c))
448 @end lisp
449
450 The last argument @var{obj} may actually be any object; an improper
451 list results if the last argument is not a proper list.
452
453 @lisp
454 (append '(a b) '(c . d)) @result{} (a b c . d)
455 (append '() 'a) @result{} a
456 @end lisp
457
458 @code{append} doesn't modify the given lists, but the return may share
459 structure with the final @var{obj}. @code{append!} modifies the
460 given lists to form its return.
461
462 For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
463 of the list operands @var{lst} @dots{} @var{obj}. That @var{lstlst}
464 itself is not modified or used in the return.
465 @end deffn
466
467 @rnindex reverse
468 @deffn {Scheme Procedure} reverse lst
469 @deffnx {Scheme Procedure} reverse! lst [newtail]
470 @deffnx {C Function} scm_reverse (lst)
471 @deffnx {C Function} scm_reverse_x (lst, newtail)
472 Return a list comprising the elements of @var{lst}, in reverse order.
473
474 @code{reverse} constructs a new list, @code{reverse!} modifies
475 @var{lst} in constructing its return.
476
477 For @code{reverse!}, the optional @var{newtail} is appended to the
478 result. @var{newtail} isn't reversed, it simply becomes the list
479 tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
480 mandatory, but can be @code{SCM_EOL} if no further tail is required.
481 @end deffn
482
483 @node List Modification
484 @subsubsection List Modification
485
486 The following procedures modify an existing list, either by changing
487 elements of the list, or by changing the list structure itself.
488
489 @deffn {Scheme Procedure} list-set! list k val
490 @deffnx {C Function} scm_list_set_x (list, k, val)
491 Set the @var{k}th element of @var{list} to @var{val}.
492 @end deffn
493
494 @deffn {Scheme Procedure} list-cdr-set! list k val
495 @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
496 Set the @var{k}th cdr of @var{list} to @var{val}.
497 @end deffn
498
499 @deffn {Scheme Procedure} delq item lst
500 @deffnx {C Function} scm_delq (item, lst)
501 Return a newly-created copy of @var{lst} with elements
502 @code{eq?} to @var{item} removed. This procedure mirrors
503 @code{memq}: @code{delq} compares elements of @var{lst} against
504 @var{item} with @code{eq?}.
505 @end deffn
506
507 @deffn {Scheme Procedure} delv item lst
508 @deffnx {C Function} scm_delv (item, lst)
509 Return a newly-created copy of @var{lst} with elements
510 @code{eqv?} to @var{item} removed. This procedure mirrors
511 @code{memv}: @code{delv} compares elements of @var{lst} against
512 @var{item} with @code{eqv?}.
513 @end deffn
514
515 @deffn {Scheme Procedure} delete item lst
516 @deffnx {C Function} scm_delete (item, lst)
517 Return a newly-created copy of @var{lst} with elements
518 @code{equal?} to @var{item} removed. This procedure mirrors
519 @code{member}: @code{delete} compares elements of @var{lst}
520 against @var{item} with @code{equal?}.
521
522 See also SRFI-1 which has an extended @code{delete} (@ref{SRFI-1
523 Deleting}), and also an @code{lset-difference} which can delete
524 multiple @var{item}s in one call (@ref{SRFI-1 Set Operations}).
525 @end deffn
526
527 @deffn {Scheme Procedure} delq! item lst
528 @deffnx {Scheme Procedure} delv! item lst
529 @deffnx {Scheme Procedure} delete! item lst
530 @deffnx {C Function} scm_delq_x (item, lst)
531 @deffnx {C Function} scm_delv_x (item, lst)
532 @deffnx {C Function} scm_delete_x (item, lst)
533 These procedures are destructive versions of @code{delq}, @code{delv}
534 and @code{delete}: they modify the pointers in the existing @var{lst}
535 rather than creating a new list. Caveat evaluator: Like other
536 destructive list functions, these functions cannot modify the binding of
537 @var{lst}, and so cannot be used to delete the first element of
538 @var{lst} destructively.
539 @end deffn
540
541 @deffn {Scheme Procedure} delq1! item lst
542 @deffnx {C Function} scm_delq1_x (item, lst)
543 Like @code{delq!}, but only deletes the first occurrence of
544 @var{item} from @var{lst}. Tests for equality using
545 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
546 @end deffn
547
548 @deffn {Scheme Procedure} delv1! item lst
549 @deffnx {C Function} scm_delv1_x (item, lst)
550 Like @code{delv!}, but only deletes the first occurrence of
551 @var{item} from @var{lst}. Tests for equality using
552 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
553 @end deffn
554
555 @deffn {Scheme Procedure} delete1! item lst
556 @deffnx {C Function} scm_delete1_x (item, lst)
557 Like @code{delete!}, but only deletes the first occurrence of
558 @var{item} from @var{lst}. Tests for equality using
559 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
560 @end deffn
561
562 @deffn {Scheme Procedure} filter pred lst
563 @deffnx {Scheme Procedure} filter! pred lst
564 Return a list containing all elements from @var{lst} which satisfy the
565 predicate @var{pred}. The elements in the result list have the same
566 order as in @var{lst}. The order in which @var{pred} is applied to
567 the list elements is not specified.
568
569 @code{filter} does not change @var{lst}, but the result may share a
570 tail with it. @code{filter!} may modify @var{lst} to construct its
571 return.
572 @end deffn
573
574 @node List Searching
575 @subsubsection List Searching
576
577 The following procedures search lists for particular elements. They use
578 different comparison predicates for comparing list elements with the
579 object to be searched. When they fail, they return @code{#f}, otherwise
580 they return the sublist whose car is equal to the search object, where
581 equality depends on the equality predicate used.
582
583 @rnindex memq
584 @deffn {Scheme Procedure} memq x lst
585 @deffnx {C Function} scm_memq (x, lst)
586 Return the first sublist of @var{lst} whose car is @code{eq?}
587 to @var{x} where the sublists of @var{lst} are the non-empty
588 lists returned by @code{(list-tail @var{lst} @var{k})} for
589 @var{k} less than the length of @var{lst}. If @var{x} does not
590 occur in @var{lst}, then @code{#f} (not the empty list) is
591 returned.
592 @end deffn
593
594 @rnindex memv
595 @deffn {Scheme Procedure} memv x lst
596 @deffnx {C Function} scm_memv (x, lst)
597 Return the first sublist of @var{lst} whose car is @code{eqv?}
598 to @var{x} where the sublists of @var{lst} are the non-empty
599 lists returned by @code{(list-tail @var{lst} @var{k})} for
600 @var{k} less than the length of @var{lst}. If @var{x} does not
601 occur in @var{lst}, then @code{#f} (not the empty list) is
602 returned.
603 @end deffn
604
605 @rnindex member
606 @deffn {Scheme Procedure} member x lst
607 @deffnx {C Function} scm_member (x, lst)
608 Return the first sublist of @var{lst} whose car is
609 @code{equal?} to @var{x} where the sublists of @var{lst} are
610 the non-empty lists returned by @code{(list-tail @var{lst}
611 @var{k})} for @var{k} less than the length of @var{lst}. If
612 @var{x} does not occur in @var{lst}, then @code{#f} (not the
613 empty list) is returned.
614
615 See also SRFI-1 which has an extended @code{member} function
616 (@ref{SRFI-1 Searching}).
617 @end deffn
618
619
620 @node List Mapping
621 @subsubsection List Mapping
622
623 List processing is very convenient in Scheme because the process of
624 iterating over the elements of a list can be highly abstracted. The
625 procedures in this section are the most basic iterating procedures for
626 lists. They take a procedure and one or more lists as arguments, and
627 apply the procedure to each element of the list. They differ in their
628 return value.
629
630 @rnindex map
631 @c begin (texi-doc-string "guile" "map")
632 @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
633 @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
634 @deffnx {C Function} scm_map (proc, arg1, args)
635 Apply @var{proc} to each element of the list @var{arg1} (if only two
636 arguments are given), or to the corresponding elements of the argument
637 lists (if more than two arguments are given). The result(s) of the
638 procedure applications are saved and returned in a list. For
639 @code{map}, the order of procedure applications is not specified,
640 @code{map-in-order} applies the procedure from left to right to the list
641 elements.
642 @end deffn
643
644 @rnindex for-each
645 @c begin (texi-doc-string "guile" "for-each")
646 @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
647 Like @code{map}, but the procedure is always applied from left to right,
648 and the result(s) of the procedure applications are thrown away. The
649 return value is not specified.
650 @end deffn
651
652 See also SRFI-1 which extends these functions to take lists of unequal
653 lengths (@ref{SRFI-1 Fold and Map}).
654
655 @node Vectors
656 @subsection Vectors
657 @tpindex Vectors
658
659 Vectors are sequences of Scheme objects. Unlike lists, the length of a
660 vector, once the vector is created, cannot be changed. The advantage of
661 vectors over lists is that the time required to access one element of a vector
662 given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
663 is constant, whereas lists have an access time linear to the position of the
664 accessed element in the list.
665
666 Vectors can contain any kind of Scheme object; it is even possible to
667 have different types of objects in the same vector. For vectors
668 containing vectors, you may wish to use arrays, instead. Note, too,
669 that vectors are the special case of one dimensional non-uniform arrays
670 and that most array procedures operate happily on vectors
671 (@pxref{Arrays}).
672
673 @menu
674 * Vector Syntax:: Read syntax for vectors.
675 * Vector Creation:: Dynamic vector creation and validation.
676 * Vector Accessors:: Accessing and modifying vector contents.
677 * Vector Accessing from C:: Ways to work with vectors from C.
678 * Uniform Numeric Vectors:: Vectors of unboxed numeric values.
679 @end menu
680
681
682 @node Vector Syntax
683 @subsubsection Read Syntax for Vectors
684
685 Vectors can literally be entered in source code, just like strings,
686 characters or some of the other data types. The read syntax for vectors
687 is as follows: A sharp sign (@code{#}), followed by an opening
688 parentheses, all elements of the vector in their respective read syntax,
689 and finally a closing parentheses. The following are examples of the
690 read syntax for vectors; where the first vector only contains numbers
691 and the second three different object types: a string, a symbol and a
692 number in hexadecimal notation.
693
694 @lisp
695 #(1 2 3)
696 #("Hello" foo #xdeadbeef)
697 @end lisp
698
699 Like lists, vectors have to be quoted:
700
701 @lisp
702 '#(a b c) @result{} #(a b c)
703 @end lisp
704
705 @node Vector Creation
706 @subsubsection Dynamic Vector Creation and Validation
707
708 Instead of creating a vector implicitly by using the read syntax just
709 described, you can create a vector dynamically by calling one of the
710 @code{vector} and @code{list->vector} primitives with the list of Scheme
711 values that you want to place into a vector. The size of the vector
712 thus created is determined implicitly by the number of arguments given.
713
714 @rnindex vector
715 @rnindex list->vector
716 @deffn {Scheme Procedure} vector arg @dots{}
717 @deffnx {Scheme Procedure} list->vector l
718 @deffnx {C Function} scm_vector (l)
719 Return a newly allocated vector composed of the
720 given arguments. Analogous to @code{list}.
721
722 @lisp
723 (vector 'a 'b 'c) @result{} #(a b c)
724 @end lisp
725 @end deffn
726
727 The inverse operation is @code{vector->list}:
728
729 @rnindex vector->list
730 @deffn {Scheme Procedure} vector->list v
731 @deffnx {C Function} scm_vector_to_list (v)
732 Return a newly allocated list composed of the elements of @var{v}.
733
734 @lisp
735 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
736 (list->vector '(dididit dah)) @result{} #(dididit dah)
737 @end lisp
738 @end deffn
739
740 To allocate a vector with an explicitly specified size, use
741 @code{make-vector}. With this primitive you can also specify an initial
742 value for the vector elements (the same value for all elements, that
743 is):
744
745 @rnindex make-vector
746 @deffn {Scheme Procedure} make-vector len [fill]
747 @deffnx {C Function} scm_make_vector (len, fill)
748 Return a newly allocated vector of @var{len} elements. If a
749 second argument is given, then each position is initialized to
750 @var{fill}. Otherwise the initial contents of each position is
751 unspecified.
752 @end deffn
753
754 @deftypefn {C Function} SCM scm_c_make_vector (size_t k, SCM fill)
755 Like @code{scm_make_vector}, but the length is given as a @code{size_t}.
756 @end deftypefn
757
758 To check whether an arbitrary Scheme value @emph{is} a vector, use the
759 @code{vector?} primitive:
760
761 @rnindex vector?
762 @deffn {Scheme Procedure} vector? obj
763 @deffnx {C Function} scm_vector_p (obj)
764 Return @code{#t} if @var{obj} is a vector, otherwise return
765 @code{#f}.
766 @end deffn
767
768 @deftypefn {C Function} int scm_is_vector (SCM obj)
769 Return non-zero when @var{obj} is a vector, otherwise return
770 @code{zero}.
771 @end deftypefn
772
773 @node Vector Accessors
774 @subsubsection Accessing and Modifying Vector Contents
775
776 @code{vector-length} and @code{vector-ref} return information about a
777 given vector, respectively its size and the elements that are contained
778 in the vector.
779
780 @rnindex vector-length
781 @deffn {Scheme Procedure} vector-length vector
782 @deffnx {C Function} scm_vector_length (vector)
783 Return the number of elements in @var{vector} as an exact integer.
784 @end deffn
785
786 @deftypefn {C Function} size_t scm_c_vector_length (SCM vec)
787 Return the number of elements in @var{vec} as a @code{size_t}.
788 @end deftypefn
789
790 @rnindex vector-ref
791 @deffn {Scheme Procedure} vector-ref vec k
792 @deffnx {C Function} scm_vector_ref (vec, k)
793 Return the contents of position @var{k} of @var{vec}.
794 @var{k} must be a valid index of @var{vec}.
795 @lisp
796 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
797 (vector-ref '#(1 1 2 3 5 8 13 21)
798 (let ((i (round (* 2 (acos -1)))))
799 (if (inexact? i)
800 (inexact->exact i)
801 i))) @result{} 13
802 @end lisp
803 @end deffn
804
805 @deftypefn {C Function} SCM scm_c_vector_ref (SCM vec, size_t k)
806 Return the contents of position @var{k} (a @code{size_t}) of
807 @var{vec}.
808 @end deftypefn
809
810 A vector created by one of the dynamic vector constructor procedures
811 (@pxref{Vector Creation}) can be modified using the following
812 procedures.
813
814 @emph{NOTE:} According to R5RS, it is an error to use any of these
815 procedures on a literally read vector, because such vectors should be
816 considered as constants. Currently, however, Guile does not detect this
817 error.
818
819 @rnindex vector-set!
820 @deffn {Scheme Procedure} vector-set! vec k obj
821 @deffnx {C Function} scm_vector_set_x (vec, k, obj)
822 Store @var{obj} in position @var{k} of @var{vec}.
823 @var{k} must be a valid index of @var{vec}.
824 The value returned by @samp{vector-set!} is unspecified.
825 @lisp
826 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
827 (vector-set! vec 1 '("Sue" "Sue"))
828 vec) @result{} #(0 ("Sue" "Sue") "Anna")
829 @end lisp
830 @end deffn
831
832 @deftypefn {C Function} void scm_c_vector_set_x (SCM vec, size_t k, SCM obj)
833 Store @var{obj} in position @var{k} (a @code{size_t}) of @var{vec}.
834 @end deftypefn
835
836 @rnindex vector-fill!
837 @deffn {Scheme Procedure} vector-fill! vec fill
838 @deffnx {C Function} scm_vector_fill_x (vec, fill)
839 Store @var{fill} in every position of @var{vec}. The value
840 returned by @code{vector-fill!} is unspecified.
841 @end deffn
842
843 @deffn {Scheme Procedure} vector-copy vec
844 @deffnx {C Function} scm_vector_copy (vec)
845 Return a copy of @var{vec}.
846 @end deffn
847
848 @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
849 @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
850 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
851 to @var{vec2} starting at position @var{start2}. @var{start1} and
852 @var{start2} are inclusive indices; @var{end1} is exclusive.
853
854 @code{vector-move-left!} copies elements in leftmost order.
855 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
856 same vector, @code{vector-move-left!} is usually appropriate when
857 @var{start1} is greater than @var{start2}.
858 @end deffn
859
860 @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
861 @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
862 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
863 to @var{vec2} starting at position @var{start2}. @var{start1} and
864 @var{start2} are inclusive indices; @var{end1} is exclusive.
865
866 @code{vector-move-right!} copies elements in rightmost order.
867 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
868 same vector, @code{vector-move-right!} is usually appropriate when
869 @var{start1} is less than @var{start2}.
870 @end deffn
871
872 @node Vector Accessing from C
873 @subsubsection Vector Accessing from C
874
875 A vector can be read and modified from C with the functions
876 @code{scm_c_vector_ref} and @code{scm_c_vector_set_x}, for example. In
877 addition to these functions, there are two more ways to access vectors
878 from C that might be more efficient in certain situations: you can
879 restrict yourself to @dfn{simple vectors} and then use the very fast
880 @emph{simple vector macros}; or you can use the very general framework
881 for accessing all kinds of arrays (@pxref{Accessing Arrays from C}),
882 which is more verbose, but can deal efficiently with all kinds of
883 vectors (and arrays). For vectors, you can use the
884 @code{scm_vector_elements} and @code{scm_vector_writable_elements}
885 functions as shortcuts.
886
887 @deftypefn {C Function} int scm_is_simple_vector (SCM obj)
888 Return non-zero if @var{obj} is a simple vector, else return zero. A
889 simple vector is a vector that can be used with the @code{SCM_SIMPLE_*}
890 macros below.
891
892 The following functions are guaranteed to return simple vectors:
893 @code{scm_make_vector}, @code{scm_c_make_vector}, @code{scm_vector},
894 @code{scm_list_to_vector}.
895 @end deftypefn
896
897 @deftypefn {C Macro} size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)
898 Evaluates to the length of the simple vector @var{vec}. No type
899 checking is done.
900 @end deftypefn
901
902 @deftypefn {C Macro} SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)
903 Evaluates to the element at position @var{idx} in the simple vector
904 @var{vec}. No type or range checking is done.
905 @end deftypefn
906
907 @deftypefn {C Macro} void SCM_SIMPLE_VECTOR_SET (SCM vec, size_t idx, SCM val)
908 Sets the element at position @var{idx} in the simple vector
909 @var{vec} to @var{val}. No type or range checking is done.
910 @end deftypefn
911
912 @deftypefn {C Function} {const SCM *} scm_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
913 Acquire a handle for the vector @var{vec} and return a pointer to the
914 elements of it. This pointer can only be used to read the elements of
915 @var{vec}. When @var{vec} is not a vector, an error is signaled. The
916 handle must eventually be released with
917 @code{scm_array_handle_release}.
918
919 The variables pointed to by @var{lenp} and @var{incp} are filled with
920 the number of elements of the vector and the increment (number of
921 elements) between successive elements, respectively. Successive
922 elements of @var{vec} need not be contiguous in their underlying
923 ``root vector'' returned here; hence the increment is not necessarily
924 equal to 1 and may well be negative too (@pxref{Shared Arrays}).
925
926 The following example shows the typical way to use this function. It
927 creates a list of all elements of @var{vec} (in reverse order).
928
929 @example
930 scm_t_array_handle handle;
931 size_t i, len;
932 ssize_t inc;
933 const SCM *elt;
934 SCM list;
935
936 elt = scm_vector_elements (vec, &handle, &len, &inc);
937 list = SCM_EOL;
938 for (i = 0; i < len; i++, elt += inc)
939 list = scm_cons (*elt, list);
940 scm_array_handle_release (&handle);
941 @end example
942
943 @end deftypefn
944
945 @deftypefn {C Function} {SCM *} scm_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
946 Like @code{scm_vector_elements} but the pointer can be used to modify
947 the vector.
948
949 The following example shows the typical way to use this function. It
950 fills a vector with @code{#t}.
951
952 @example
953 scm_t_array_handle handle;
954 size_t i, len;
955 ssize_t inc;
956 SCM *elt;
957
958 elt = scm_vector_writable_elements (vec, &handle, &len, &inc);
959 for (i = 0; i < len; i++, elt += inc)
960 *elt = SCM_BOOL_T;
961 scm_array_handle_release (&handle);
962 @end example
963
964 @end deftypefn
965
966 @node Uniform Numeric Vectors
967 @subsubsection Uniform Numeric Vectors
968
969 A uniform numeric vector is a vector whose elements are all of a single
970 numeric type. Guile offers uniform numeric vectors for signed and
971 unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
972 floating point values, and complex floating-point numbers of these two
973 sizes. @xref{SRFI-4}, for more information.
974
975 For many purposes, bytevectors work just as well as uniform vectors, and have
976 the advantage that they integrate well with binary input and output.
977 @xref{Bytevectors}, for more information on bytevectors.
978
979 @node Bit Vectors
980 @subsection Bit Vectors
981
982 @noindent
983 Bit vectors are zero-origin, one-dimensional arrays of booleans. They
984 are displayed as a sequence of @code{0}s and @code{1}s prefixed by
985 @code{#*}, e.g.,
986
987 @example
988 (make-bitvector 8 #f) @result{}
989 #*00000000
990 @end example
991
992 Bit vectors are also generalized vectors, @xref{Generalized
993 Vectors}, and can thus be used with the array procedures, @xref{Arrays}.
994 Bit vectors are the special case of one dimensional bit arrays.
995
996 @deffn {Scheme Procedure} bitvector? obj
997 @deffnx {C Function} scm_bitvector_p (obj)
998 Return @code{#t} when @var{obj} is a bitvector, else
999 return @code{#f}.
1000 @end deffn
1001
1002 @deftypefn {C Function} int scm_is_bitvector (SCM obj)
1003 Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
1004 @end deftypefn
1005
1006 @deffn {Scheme Procedure} make-bitvector len [fill]
1007 @deffnx {C Function} scm_make_bitvector (len, fill)
1008 Create a new bitvector of length @var{len} and
1009 optionally initialize all elements to @var{fill}.
1010 @end deffn
1011
1012 @deftypefn {C Function} SCM scm_c_make_bitvector (size_t len, SCM fill)
1013 Like @code{scm_make_bitvector}, but the length is given as a
1014 @code{size_t}.
1015 @end deftypefn
1016
1017 @deffn {Scheme Procedure} bitvector bit @dots{}
1018 @deffnx {C Function} scm_bitvector (bits)
1019 Create a new bitvector with the arguments as elements.
1020 @end deffn
1021
1022 @deffn {Scheme Procedure} bitvector-length vec
1023 @deffnx {C Function} scm_bitvector_length (vec)
1024 Return the length of the bitvector @var{vec}.
1025 @end deffn
1026
1027 @deftypefn {C Function} size_t scm_c_bitvector_length (SCM vec)
1028 Like @code{scm_bitvector_length}, but the length is returned as a
1029 @code{size_t}.
1030 @end deftypefn
1031
1032 @deffn {Scheme Procedure} bitvector-ref vec idx
1033 @deffnx {C Function} scm_bitvector_ref (vec, idx)
1034 Return the element at index @var{idx} of the bitvector
1035 @var{vec}.
1036 @end deffn
1037
1038 @deftypefn {C Function} SCM scm_c_bitvector_ref (SCM vec, size_t idx)
1039 Return the element at index @var{idx} of the bitvector
1040 @var{vec}.
1041 @end deftypefn
1042
1043 @deffn {Scheme Procedure} bitvector-set! vec idx val
1044 @deffnx {C Function} scm_bitvector_set_x (vec, idx, val)
1045 Set the element at index @var{idx} of the bitvector
1046 @var{vec} when @var{val} is true, else clear it.
1047 @end deffn
1048
1049 @deftypefn {C Function} SCM scm_c_bitvector_set_x (SCM vec, size_t idx, SCM val)
1050 Set the element at index @var{idx} of the bitvector
1051 @var{vec} when @var{val} is true, else clear it.
1052 @end deftypefn
1053
1054 @deffn {Scheme Procedure} bitvector-fill! vec val
1055 @deffnx {C Function} scm_bitvector_fill_x (vec, val)
1056 Set all elements of the bitvector
1057 @var{vec} when @var{val} is true, else clear them.
1058 @end deffn
1059
1060 @deffn {Scheme Procedure} list->bitvector list
1061 @deffnx {C Function} scm_list_to_bitvector (list)
1062 Return a new bitvector initialized with the elements
1063 of @var{list}.
1064 @end deffn
1065
1066 @deffn {Scheme Procedure} bitvector->list vec
1067 @deffnx {C Function} scm_bitvector_to_list (vec)
1068 Return a new list initialized with the elements
1069 of the bitvector @var{vec}.
1070 @end deffn
1071
1072 @deffn {Scheme Procedure} bit-count bool bitvector
1073 @deffnx {C Function} scm_bit_count (bool, bitvector)
1074 Return a count of how many entries in @var{bitvector} are equal to
1075 @var{bool}. For example,
1076
1077 @example
1078 (bit-count #f #*000111000) @result{} 6
1079 @end example
1080 @end deffn
1081
1082 @deffn {Scheme Procedure} bit-position bool bitvector start
1083 @deffnx {C Function} scm_bit_position (bool, bitvector, start)
1084 Return the index of the first occurrence of @var{bool} in
1085 @var{bitvector}, starting from @var{start}. If there is no @var{bool}
1086 entry between @var{start} and the end of @var{bitvector}, then return
1087 @code{#f}. For example,
1088
1089 @example
1090 (bit-position #t #*000101 0) @result{} 3
1091 (bit-position #f #*0001111 3) @result{} #f
1092 @end example
1093 @end deffn
1094
1095 @deffn {Scheme Procedure} bit-invert! bitvector
1096 @deffnx {C Function} scm_bit_invert_x (bitvector)
1097 Modify @var{bitvector} by replacing each element with its negation.
1098 @end deffn
1099
1100 @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1101 @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1102 Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1103 selecting the entries to change. The return value is unspecified.
1104
1105 If @var{uvec} is a bit vector, then those entries where it has
1106 @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1107 @var{uvec} and @var{bitvector} must be the same length. When
1108 @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1109 @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1110 ANDNOT.
1111
1112 @example
1113 (define bv #*01000010)
1114 (bit-set*! bv #*10010001 #t)
1115 bv
1116 @result{} #*11010011
1117 @end example
1118
1119 If @var{uvec} is a uniform vector of unsigned long integers, then
1120 they're indexes into @var{bitvector} which are set to @var{bool}.
1121
1122 @example
1123 (define bv #*01000010)
1124 (bit-set*! bv #u(5 2 7) #t)
1125 bv
1126 @result{} #*01100111
1127 @end example
1128 @end deffn
1129
1130 @deffn {Scheme Procedure} bit-count* bitvector uvec bool
1131 @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1132 Return a count of how many entries in @var{bitvector} are equal to
1133 @var{bool}, with @var{uvec} selecting the entries to consider.
1134
1135 @var{uvec} is interpreted in the same way as for @code{bit-set*!}
1136 above. Namely, if @var{uvec} is a bit vector then entries which have
1137 @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1138 is a uniform vector of unsigned long integers then it's the indexes in
1139 @var{bitvector} to consider.
1140
1141 For example,
1142
1143 @example
1144 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1145 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1146 @end example
1147 @end deffn
1148
1149 @deftypefn {C Function} {const scm_t_uint32 *} scm_bitvector_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
1150 Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
1151 for bitvectors. The variable pointed to by @var{offp} is set to the
1152 value returned by @code{scm_array_handle_bit_elements_offset}. See
1153 @code{scm_array_handle_bit_elements} for how to use the returned
1154 pointer and the offset.
1155 @end deftypefn
1156
1157 @deftypefn {C Function} {scm_t_uint32 *} scm_bitvector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
1158 Like @code{scm_bitvector_elements}, but the pointer is good for reading
1159 and writing.
1160 @end deftypefn
1161
1162 @node Generalized Vectors
1163 @subsection Generalized Vectors
1164
1165 Guile has a number of data types that are generally vector-like:
1166 strings, uniform numeric vectors, bytevectors, bitvectors, and of course
1167 ordinary vectors of arbitrary Scheme values. These types are disjoint:
1168 a Scheme value belongs to at most one of the five types listed above.
1169
1170 If you want to gloss over this distinction and want to treat all four
1171 types with common code, you can use the procedures in this section.
1172 They work with the @emph{generalized vector} type, which is the union
1173 of the five vector-like types.
1174
1175 @deffn {Scheme Procedure} generalized-vector? obj
1176 @deffnx {C Function} scm_generalized_vector_p (obj)
1177 Return @code{#t} if @var{obj} is a vector, bytevector, string,
1178 bitvector, or uniform numeric vector.
1179 @end deffn
1180
1181 @deffn {Scheme Procedure} generalized-vector-length v
1182 @deffnx {C Function} scm_generalized_vector_length (v)
1183 Return the length of the generalized vector @var{v}.
1184 @end deffn
1185
1186 @deffn {Scheme Procedure} generalized-vector-ref v idx
1187 @deffnx {C Function} scm_generalized_vector_ref (v, idx)
1188 Return the element at index @var{idx} of the
1189 generalized vector @var{v}.
1190 @end deffn
1191
1192 @deffn {Scheme Procedure} generalized-vector-set! v idx val
1193 @deffnx {C Function} scm_generalized_vector_set_x (v, idx, val)
1194 Set the element at index @var{idx} of the
1195 generalized vector @var{v} to @var{val}.
1196 @end deffn
1197
1198 @deffn {Scheme Procedure} generalized-vector->list v
1199 @deffnx {C Function} scm_generalized_vector_to_list (v)
1200 Return a new list whose elements are the elements of the
1201 generalized vector @var{v}.
1202 @end deffn
1203
1204 @deftypefn {C Function} int scm_is_generalized_vector (SCM obj)
1205 Return @code{1} if @var{obj} is a vector, string,
1206 bitvector, or uniform numeric vector; else return @code{0}.
1207 @end deftypefn
1208
1209 @deftypefn {C Function} size_t scm_c_generalized_vector_length (SCM v)
1210 Return the length of the generalized vector @var{v}.
1211 @end deftypefn
1212
1213 @deftypefn {C Function} SCM scm_c_generalized_vector_ref (SCM v, size_t idx)
1214 Return the element at index @var{idx} of the generalized vector @var{v}.
1215 @end deftypefn
1216
1217 @deftypefn {C Function} void scm_c_generalized_vector_set_x (SCM v, size_t idx, SCM val)
1218 Set the element at index @var{idx} of the generalized vector @var{v}
1219 to @var{val}.
1220 @end deftypefn
1221
1222 @deftypefn {C Function} void scm_generalized_vector_get_handle (SCM v, scm_t_array_handle *handle)
1223 Like @code{scm_array_get_handle} but an error is signalled when @var{v}
1224 is not of rank one. You can use @code{scm_array_handle_ref} and
1225 @code{scm_array_handle_set} to read and write the elements of @var{v},
1226 or you can use functions like @code{scm_array_handle_<foo>_elements} to
1227 deal with specific types of vectors.
1228 @end deftypefn
1229
1230 @node Arrays
1231 @subsection Arrays
1232 @tpindex Arrays
1233
1234 @dfn{Arrays} are a collection of cells organized into an arbitrary
1235 number of dimensions. Each cell can be accessed in constant time by
1236 supplying an index for each dimension.
1237
1238 In the current implementation, an array uses a generalized vector for
1239 the actual storage of its elements. Any kind of generalized vector
1240 will do, so you can have arrays of uniform numeric values, arrays of
1241 characters, arrays of bits, and of course, arrays of arbitrary Scheme
1242 values. For example, arrays with an underlying @code{c64vector} might
1243 be nice for digital signal processing, while arrays made from a
1244 @code{u8vector} might be used to hold gray-scale images.
1245
1246 The number of dimensions of an array is called its @dfn{rank}. Thus,
1247 a matrix is an array of rank 2, while a vector has rank 1. When
1248 accessing an array element, you have to specify one exact integer for
1249 each dimension. These integers are called the @dfn{indices} of the
1250 element. An array specifies the allowed range of indices for each
1251 dimension via an inclusive lower and upper bound. These bounds can
1252 well be negative, but the upper bound must be greater than or equal to
1253 the lower bound minus one. When all lower bounds of an array are
1254 zero, it is called a @dfn{zero-origin} array.
1255
1256 Arrays can be of rank 0, which could be interpreted as a scalar.
1257 Thus, a zero-rank array can store exactly one object and the list of
1258 indices of this element is the empty list.
1259
1260 Arrays contain zero elements when one of their dimensions has a zero
1261 length. These empty arrays maintain information about their shape: a
1262 matrix with zero columns and 3 rows is different from a matrix with 3
1263 columns and zero rows, which again is different from a vector of
1264 length zero.
1265
1266 Generalized vectors, such as strings, uniform numeric vectors,
1267 bytevectors, bit vectors and ordinary vectors, are the special case of
1268 one dimensional arrays.
1269
1270 @menu
1271 * Array Syntax::
1272 * Array Procedures::
1273 * Shared Arrays::
1274 * Accessing Arrays from C::
1275 @end menu
1276
1277 @node Array Syntax
1278 @subsubsection Array Syntax
1279
1280 An array is displayed as @code{#} followed by its rank, followed by a
1281 tag that describes the underlying vector, optionally followed by
1282 information about its shape, and finally followed by the cells,
1283 organized into dimensions using parentheses.
1284
1285 In more words, the array tag is of the form
1286
1287 @example
1288 #<rank><vectag><@@lower><:len><@@lower><:len>...
1289 @end example
1290
1291 where @code{<rank>} is a positive integer in decimal giving the rank of
1292 the array. It is omitted when the rank is 1 and the array is non-shared
1293 and has zero-origin (see below). For shared arrays and for a non-zero
1294 origin, the rank is always printed even when it is 1 to distinguish
1295 them from ordinary vectors.
1296
1297 The @code{<vectag>} part is the tag for a uniform numeric vector, like
1298 @code{u8}, @code{s16}, etc, @code{b} for bitvectors, or @code{a} for
1299 strings. It is empty for ordinary vectors.
1300
1301 The @code{<@@lower>} part is a @samp{@@} character followed by a signed
1302 integer in decimal giving the lower bound of a dimension. There is one
1303 @code{<@@lower>} for each dimension. When all lower bounds are zero,
1304 all @code{<@@lower>} parts are omitted.
1305
1306 The @code{<:len>} part is a @samp{:} character followed by an unsigned
1307 integer in decimal giving the length of a dimension. Like for the lower
1308 bounds, there is one @code{<:len>} for each dimension, and the
1309 @code{<:len>} part always follows the @code{<@@lower>} part for a
1310 dimension. Lengths are only then printed when they can't be deduced
1311 from the nested lists of elements of the array literal, which can happen
1312 when at least one length is zero.
1313
1314 As a special case, an array of rank 0 is printed as
1315 @code{#0<vectag>(<scalar>)}, where @code{<scalar>} is the result of
1316 printing the single element of the array.
1317
1318 Thus,
1319
1320 @table @code
1321 @item #(1 2 3)
1322 is an ordinary array of rank 1 with lower bound 0 in dimension 0.
1323 (I.e., a regular vector.)
1324
1325 @item #@@2(1 2 3)
1326 is an ordinary array of rank 1 with lower bound 2 in dimension 0.
1327
1328 @item #2((1 2 3) (4 5 6))
1329 is a non-uniform array of rank 2; a 3@cross{}3 matrix with index ranges 0..2
1330 and 0..2.
1331
1332 @item #u32(0 1 2)
1333 is a uniform u8 array of rank 1.
1334
1335 @item #2u32@@2@@3((1 2) (2 3))
1336 is a uniform u8 array of rank 2 with index ranges 2..3 and 3..4.
1337
1338 @item #2()
1339 is a two-dimensional array with index ranges 0..-1 and 0..-1, i.e.@:
1340 both dimensions have length zero.
1341
1342 @item #2:0:2()
1343 is a two-dimensional array with index ranges 0..-1 and 0..1, i.e.@: the
1344 first dimension has length zero, but the second has length 2.
1345
1346 @item #0(12)
1347 is a rank-zero array with contents 12.
1348
1349 @end table
1350
1351 In addition, bytevectors are also arrays, but use a different syntax
1352 (@pxref{Bytevectors}):
1353
1354 @table @code
1355
1356 @item #vu8(1 2 3)
1357 is a 3-byte long bytevector, with contents 1, 2, 3.
1358
1359 @end table
1360
1361 @node Array Procedures
1362 @subsubsection Array Procedures
1363
1364 When an array is created, the range of each dimension must be
1365 specified, e.g., to create a 2@cross{}3 array with a zero-based index:
1366
1367 @example
1368 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1369 @end example
1370
1371 The range of each dimension can also be given explicitly, e.g., another
1372 way to create the same array:
1373
1374 @example
1375 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1376 @end example
1377
1378 The following procedures can be used with arrays (or vectors). An
1379 argument shown as @var{idx}@dots{} means one parameter for each
1380 dimension in the array. A @var{idxlist} argument means a list of such
1381 values, one for each dimension.
1382
1383
1384 @deffn {Scheme Procedure} array? obj
1385 @deffnx {C Function} scm_array_p (obj, unused)
1386 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1387 not.
1388
1389 The second argument to scm_array_p is there for historical reasons,
1390 but it is not used. You should always pass @code{SCM_UNDEFINED} as
1391 its value.
1392 @end deffn
1393
1394 @deffn {Scheme Procedure} typed-array? obj type
1395 @deffnx {C Function} scm_typed_array_p (obj, type)
1396 Return @code{#t} if the @var{obj} is an array of type @var{type}, and
1397 @code{#f} if not.
1398 @end deffn
1399
1400 @deftypefn {C Function} int scm_is_array (SCM obj)
1401 Return @code{1} if the @var{obj} is an array and @code{0} if not.
1402 @end deftypefn
1403
1404 @deftypefn {C Function} int scm_is_typed_array (SCM obj, SCM type)
1405 Return @code{0} if the @var{obj} is an array of type @var{type}, and
1406 @code{1} if not.
1407 @end deftypefn
1408
1409 @deffn {Scheme Procedure} make-array fill bound @dots{}
1410 @deffnx {C Function} scm_make_array (fill, bounds)
1411 Equivalent to @code{(make-typed-array #t @var{fill} @var{bound} ...)}.
1412 @end deffn
1413
1414 @deffn {Scheme Procedure} make-typed-array type fill bound @dots{}
1415 @deffnx {C Function} scm_make_typed_array (type, fill, bounds)
1416 Create and return an array that has as many dimensions as there are
1417 @var{bound}s and (maybe) fill it with @var{fill}.
1418
1419 The underlying storage vector is created according to @var{type},
1420 which must be a symbol whose name is the `vectag' of the array as
1421 explained above, or @code{#t} for ordinary, non-specialized arrays.
1422
1423 For example, using the symbol @code{f64} for @var{type} will create an
1424 array that uses a @code{f64vector} for storing its elements, and
1425 @code{a} will use a string.
1426
1427 When @var{fill} is not the special @emph{unspecified} value, the new
1428 array is filled with @var{fill}. Otherwise, the initial contents of
1429 the array is unspecified. The special @emph{unspecified} value is
1430 stored in the variable @code{*unspecified*} so that for example
1431 @code{(make-typed-array 'u32 *unspecified* 4)} creates a uninitialized
1432 @code{u32} vector of length 4.
1433
1434 Each @var{bound} may be a positive non-zero integer @var{n}, in which
1435 case the index for that dimension can range from 0 through @var{n}-1; or
1436 an explicit index range specifier in the form @code{(LOWER UPPER)},
1437 where both @var{lower} and @var{upper} are integers, possibly less than
1438 zero, and possibly the same number (however, @var{lower} cannot be
1439 greater than @var{upper}).
1440 @end deffn
1441
1442 @deffn {Scheme Procedure} list->array dimspec list
1443 Equivalent to @code{(list->typed-array #t @var{dimspec}
1444 @var{list})}.
1445 @end deffn
1446
1447 @deffn {Scheme Procedure} list->typed-array type dimspec list
1448 @deffnx {C Function} scm_list_to_typed_array (type, dimspec, list)
1449 Return an array of the type indicated by @var{type} with elements the
1450 same as those of @var{list}.
1451
1452 The argument @var{dimspec} determines the number of dimensions of the
1453 array and their lower bounds. When @var{dimspec} is an exact integer,
1454 it gives the number of dimensions directly and all lower bounds are
1455 zero. When it is a list of exact integers, then each element is the
1456 lower index bound of a dimension, and there will be as many dimensions
1457 as elements in the list.
1458 @end deffn
1459
1460 @deffn {Scheme Procedure} array-type array
1461 Return the type of @var{array}. This is the `vectag' used for
1462 printing @var{array} (or @code{#t} for ordinary arrays) and can be
1463 used with @code{make-typed-array} to create an array of the same kind
1464 as @var{array}.
1465 @end deffn
1466
1467 @deffn {Scheme Procedure} array-ref array idx @dots{}
1468 Return the element at @code{(idx @dots{})} in @var{array}.
1469
1470 @example
1471 (define a (make-array 999 '(1 2) '(3 4)))
1472 (array-ref a 2 4) @result{} 999
1473 @end example
1474 @end deffn
1475
1476 @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
1477 @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
1478 Return @code{#t} if the given index would be acceptable to
1479 @code{array-ref}.
1480
1481 @example
1482 (define a (make-array #f '(1 2) '(3 4)))
1483 (array-in-bounds? a 2 3) @result{} #t
1484 (array-in-bounds? a 0 0) @result{} #f
1485 @end example
1486 @end deffn
1487
1488 @deffn {Scheme Procedure} array-set! array obj idx @dots{}
1489 @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
1490 Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
1491 The return value is unspecified.
1492
1493 @example
1494 (define a (make-array #f '(0 1) '(0 1)))
1495 (array-set! a #t 1 1)
1496 a @result{} #2((#f #f) (#f #t))
1497 @end example
1498 @end deffn
1499
1500 @deffn {Scheme Procedure} array-shape array
1501 @deffnx {Scheme Procedure} array-dimensions array
1502 @deffnx {C Function} scm_array_dimensions (array)
1503 Return a list of the bounds for each dimension of @var{array}.
1504
1505 @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
1506 dimension. @code{array-dimensions} instead returns just
1507 @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
1508 suitable as input to @code{make-array}.
1509
1510 For example,
1511
1512 @example
1513 (define a (make-array 'foo '(-1 3) 5))
1514 (array-shape a) @result{} ((-1 3) (0 4))
1515 (array-dimensions a) @result{} ((-1 3) 5)
1516 @end example
1517 @end deffn
1518
1519 @deffn {Scheme Procedure} array-rank array
1520 @deffnx {C Function} scm_array_rank (array)
1521 Return the rank of @var{array}.
1522 @end deffn
1523
1524 @deftypefn {C Function} size_t scm_c_array_rank (SCM array)
1525 Return the rank of @var{array} as a @code{size_t}.
1526 @end deftypefn
1527
1528 @deffn {Scheme Procedure} array->list array
1529 @deffnx {C Function} scm_array_to_list (array)
1530 Return a list consisting of all the elements, in order, of
1531 @var{array}.
1532 @end deffn
1533
1534 @c FIXME: Describe how the order affects the copying (it matters for
1535 @c shared arrays with the same underlying root vector, presumably).
1536 @c
1537 @deffn {Scheme Procedure} array-copy! src dst
1538 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1539 @deffnx {C Function} scm_array_copy_x (src, dst)
1540 Copy every element from vector or array @var{src} to the corresponding
1541 element of @var{dst}. @var{dst} must have the same rank as @var{src},
1542 and be at least as large in each dimension. The return value is
1543 unspecified.
1544 @end deffn
1545
1546 @deffn {Scheme Procedure} array-fill! array fill
1547 @deffnx {C Function} scm_array_fill_x (array, fill)
1548 Store @var{fill} in every element of @var{array}. The value returned
1549 is unspecified.
1550 @end deffn
1551
1552 @c begin (texi-doc-string "guile" "array-equal?")
1553 @deffn {Scheme Procedure} array-equal? array @dots{}
1554 Return @code{#t} if all arguments are arrays with the same shape, the
1555 same type, and have corresponding elements which are either
1556 @code{equal?} or @code{array-equal?}. This function differs from
1557 @code{equal?} (@pxref{Equality}) in that all arguments must be arrays.
1558 @end deffn
1559
1560 @c FIXME: array-map! accepts no source arrays at all, and in that
1561 @c case makes calls "(proc)". Is that meant to be a documented
1562 @c feature?
1563 @c
1564 @c FIXME: array-for-each doesn't say what happens if the sources have
1565 @c different index ranges. The code currently iterates over the
1566 @c indices of the first and expects the others to cover those. That
1567 @c at least vaguely matches array-map!, but is it meant to be a
1568 @c documented feature?
1569
1570 @deffn {Scheme Procedure} array-map! dst proc src @dots{}
1571 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1572 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1573 Set each element of the @var{dst} array to values obtained from calls
1574 to @var{proc}. The value returned is unspecified.
1575
1576 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1577 where each @var{elem} is from the corresponding @var{src} array, at
1578 the @var{dst} index. @code{array-map-in-order!} makes the calls in
1579 row-major order, @code{array-map!} makes them in an unspecified order.
1580
1581 The @var{src} arrays must have the same number of dimensions as
1582 @var{dst}, and must have a range for each dimension which covers the
1583 range in @var{dst}. This ensures all @var{dst} indices are valid in
1584 each @var{src}.
1585 @end deffn
1586
1587 @deffn {Scheme Procedure} array-for-each proc src1 src2 @dots{}
1588 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1589 Apply @var{proc} to each tuple of elements of @var{src1} @var{src2}
1590 @dots{}, in row-major order. The value returned is unspecified.
1591 @end deffn
1592
1593 @deffn {Scheme Procedure} array-index-map! dst proc
1594 @deffnx {C Function} scm_array_index_map_x (dst, proc)
1595 Set each element of the @var{dst} array to values returned by calls to
1596 @var{proc}. The value returned is unspecified.
1597
1598 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1599 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
1600 each dimension. The order in which the calls are made is unspecified.
1601
1602 For example, to create a @m{4\times4, 4x4} matrix representing a
1603 cyclic group,
1604
1605 @tex
1606 \advance\leftskip by 2\lispnarrowing {
1607 $\left(\matrix{%
1608 0 & 1 & 2 & 3 \cr
1609 1 & 2 & 3 & 0 \cr
1610 2 & 3 & 0 & 1 \cr
1611 3 & 0 & 1 & 2 \cr
1612 }\right)$} \par
1613 @end tex
1614 @ifnottex
1615 @example
1616 / 0 1 2 3 \
1617 | 1 2 3 0 |
1618 | 2 3 0 1 |
1619 \ 3 0 1 2 /
1620 @end example
1621 @end ifnottex
1622
1623 @example
1624 (define a (make-array #f 4 4))
1625 (array-index-map! a (lambda (i j)
1626 (modulo (+ i j) 4)))
1627 @end example
1628 @end deffn
1629
1630 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
1631 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
1632 Attempt to read all elements of array @var{ra}, in lexicographic order, as
1633 binary objects from @var{port_or_fd}.
1634 If an end of file is encountered,
1635 the objects up to that point are put into @var{ra}
1636 (starting at the beginning) and the remainder of the array is
1637 unchanged.
1638
1639 The optional arguments @var{start} and @var{end} allow
1640 a specified region of a vector (or linearized array) to be read,
1641 leaving the remainder of the vector unchanged.
1642
1643 @code{uniform-array-read!} returns the number of objects read.
1644 @var{port_or_fd} may be omitted, in which case it defaults to the value
1645 returned by @code{(current-input-port)}.
1646 @end deffn
1647
1648 @deffn {Scheme Procedure} uniform-array-write ra [port_or_fd [start [end]]]
1649 @deffnx {C Function} scm_uniform_array_write (ra, port_or_fd, start, end)
1650 Writes all elements of @var{ra} as binary objects to
1651 @var{port_or_fd}.
1652
1653 The optional arguments @var{start}
1654 and @var{end} allow
1655 a specified region of a vector (or linearized array) to be written.
1656
1657 The number of objects actually written is returned.
1658 @var{port_or_fd} may be
1659 omitted, in which case it defaults to the value returned by
1660 @code{(current-output-port)}.
1661 @end deffn
1662
1663 @node Shared Arrays
1664 @subsubsection Shared Arrays
1665
1666 @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
1667 @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
1668 Return a new array which shares the storage of @var{oldarray}.
1669 Changes made through either affect the same underlying storage. The
1670 @var{bound} @dots{} arguments are the shape of the new array, the same
1671 as @code{make-array} (@pxref{Array Procedures}).
1672
1673 @var{mapfunc} translates coordinates from the new array to the
1674 @var{oldarray}. It's called as @code{(@var{mapfunc} newidx1 @dots{})}
1675 with one parameter for each dimension of the new array, and should
1676 return a list of indices for @var{oldarray}, one for each dimension of
1677 @var{oldarray}.
1678
1679 @var{mapfunc} must be affine linear, meaning that each @var{oldarray}
1680 index must be formed by adding integer multiples (possibly negative)
1681 of some or all of @var{newidx1} etc, plus a possible integer offset.
1682 The multiples and offset must be the same in each call.
1683
1684 @sp 1
1685 One good use for a shared array is to restrict the range of some
1686 dimensions, so as to apply say @code{array-for-each} or
1687 @code{array-fill!} to only part of an array. The plain @code{list}
1688 function can be used for @var{mapfunc} in this case, making no changes
1689 to the index values. For example,
1690
1691 @example
1692 (make-shared-array #2((a b c) (d e f) (g h i)) list 3 2)
1693 @result{} #2((a b) (d e) (g h))
1694 @end example
1695
1696 The new array can have fewer dimensions than @var{oldarray}, for
1697 example to take a column from an array.
1698
1699 @example
1700 (make-shared-array #2((a b c) (d e f) (g h i))
1701 (lambda (i) (list i 2))
1702 '(0 2))
1703 @result{} #1(c f i)
1704 @end example
1705
1706 A diagonal can be taken by using the single new array index for both
1707 row and column in the old array. For example,
1708
1709 @example
1710 (make-shared-array #2((a b c) (d e f) (g h i))
1711 (lambda (i) (list i i))
1712 '(0 2))
1713 @result{} #1(a e i)
1714 @end example
1715
1716 Dimensions can be increased by for instance considering portions of a
1717 one dimensional array as rows in a two dimensional array.
1718 (@code{array-contents} below can do the opposite, flattening an
1719 array.)
1720
1721 @example
1722 (make-shared-array #1(a b c d e f g h i j k l)
1723 (lambda (i j) (list (+ (* i 3) j)))
1724 4 3)
1725 @result{} #2((a b c) (d e f) (g h i) (j k l))
1726 @end example
1727
1728 By negating an index the order that elements appear can be reversed.
1729 The following just reverses the column order,
1730
1731 @example
1732 (make-shared-array #2((a b c) (d e f) (g h i))
1733 (lambda (i j) (list i (- 2 j)))
1734 3 3)
1735 @result{} #2((c b a) (f e d) (i h g))
1736 @end example
1737
1738 A fixed offset on indexes allows for instance a change from a 0 based
1739 to a 1 based array,
1740
1741 @example
1742 (define x #2((a b c) (d e f) (g h i)))
1743 (define y (make-shared-array x
1744 (lambda (i j) (list (1- i) (1- j)))
1745 '(1 3) '(1 3)))
1746 (array-ref x 0 0) @result{} a
1747 (array-ref y 1 1) @result{} a
1748 @end example
1749
1750 A multiple on an index allows every Nth element of an array to be
1751 taken. The following is every third element,
1752
1753 @example
1754 (make-shared-array #1(a b c d e f g h i j k l)
1755 (lambda (i) (list (* i 3)))
1756 4)
1757 @result{} #1(a d g j)
1758 @end example
1759
1760 The above examples can be combined to make weird and wonderful
1761 selections from an array, but it's important to note that because
1762 @var{mapfunc} must be affine linear, arbitrary permutations are not
1763 possible.
1764
1765 In the current implementation, @var{mapfunc} is not called for every
1766 access to the new array but only on some sample points to establish a
1767 base and stride for new array indices in @var{oldarray} data. A few
1768 sample points are enough because @var{mapfunc} is linear.
1769 @end deffn
1770
1771 @deffn {Scheme Procedure} shared-array-increments array
1772 @deffnx {C Function} scm_shared_array_increments (array)
1773 For each dimension, return the distance between elements in the root vector.
1774 @end deffn
1775
1776 @deffn {Scheme Procedure} shared-array-offset array
1777 @deffnx {C Function} scm_shared_array_offset (array)
1778 Return the root vector index of the first element in the array.
1779 @end deffn
1780
1781 @deffn {Scheme Procedure} shared-array-root array
1782 @deffnx {C Function} scm_shared_array_root (array)
1783 Return the root vector of a shared array.
1784 @end deffn
1785
1786 @deffn {Scheme Procedure} array-contents array [strict]
1787 @deffnx {C Function} scm_array_contents (array, strict)
1788 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1789 without changing their order (last subscript changing fastest), then
1790 @code{array-contents} returns that shared array, otherwise it returns
1791 @code{#f}. All arrays made by @code{make-array} and
1792 @code{make-typed-array} may be unrolled, some arrays made by
1793 @code{make-shared-array} may not be.
1794
1795 If the optional argument @var{strict} is provided, a shared array will
1796 be returned only if its elements are stored internally contiguous in
1797 memory.
1798 @end deffn
1799
1800 @deffn {Scheme Procedure} transpose-array array dim1 dim2 @dots{}
1801 @deffnx {C Function} scm_transpose_array (array, dimlist)
1802 Return an array sharing contents with @var{array}, but with
1803 dimensions arranged in a different order. There must be one
1804 @var{dim} argument for each dimension of @var{array}.
1805 @var{dim1}, @var{dim2}, @dots{} should be integers between 0
1806 and the rank of the array to be returned. Each integer in that
1807 range must appear at least once in the argument list.
1808
1809 The values of @var{dim1}, @var{dim2}, @dots{} correspond to
1810 dimensions in the array to be returned, and their positions in the
1811 argument list to dimensions of @var{array}. Several @var{dim}s
1812 may have the same value, in which case the returned array will
1813 have smaller rank than @var{array}.
1814
1815 @lisp
1816 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1817 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1818 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1819 #2((a 4) (b 5) (c 6))
1820 @end lisp
1821 @end deffn
1822
1823 @node Accessing Arrays from C
1824 @subsubsection Accessing Arrays from C
1825
1826 For interworking with external C code, Guile provides an API to allow C
1827 code to access the elements of a Scheme array. In particular, for
1828 uniform numeric arrays, the API exposes the underlying uniform data as a
1829 C array of numbers of the relevant type.
1830
1831 While pointers to the elements of an array are in use, the array itself
1832 must be protected so that the pointer remains valid. Such a protected
1833 array is said to be @dfn{reserved}. A reserved array can be read but
1834 modifications to it that would cause the pointer to its elements to
1835 become invalid are prevented. When you attempt such a modification, an
1836 error is signalled.
1837
1838 (This is similar to locking the array while it is in use, but without
1839 the danger of a deadlock. In a multi-threaded program, you will need
1840 additional synchronization to avoid modifying reserved arrays.)
1841
1842 You must take care to always unreserve an array after reserving it,
1843 even in the presence of non-local exits. If a non-local exit can
1844 happen between these two calls, you should install a dynwind context
1845 that releases the array when it is left (@pxref{Dynamic Wind}).
1846
1847 In addition, array reserving and unreserving must be properly
1848 paired. For instance, when reserving two or more arrays in a certain
1849 order, you need to unreserve them in the opposite order.
1850
1851 Once you have reserved an array and have retrieved the pointer to its
1852 elements, you must figure out the layout of the elements in memory.
1853 Guile allows slices to be taken out of arrays without actually making a
1854 copy, such as making an alias for the diagonal of a matrix that can be
1855 treated as a vector. Arrays that result from such an operation are not
1856 stored contiguously in memory and when working with their elements
1857 directly, you need to take this into account.
1858
1859 The layout of array elements in memory can be defined via a
1860 @emph{mapping function} that computes a scalar position from a vector of
1861 indices. The scalar position then is the offset of the element with the
1862 given indices from the start of the storage block of the array.
1863
1864 In Guile, this mapping function is restricted to be @dfn{affine}: all
1865 mapping functions of Guile arrays can be written as @code{p = b +
1866 c[0]*i[0] + c[1]*i[1] + ... + c[n-1]*i[n-1]} where @code{i[k]} is the
1867 @nicode{k}th index and @code{n} is the rank of the array. For
1868 example, a matrix of size 3x3 would have @code{b == 0}, @code{c[0] ==
1869 3} and @code{c[1] == 1}. When you transpose this matrix (with
1870 @code{transpose-array}, say), you will get an array whose mapping
1871 function has @code{b == 0}, @code{c[0] == 1} and @code{c[1] == 3}.
1872
1873 The function @code{scm_array_handle_dims} gives you (indirect) access to
1874 the coefficients @code{c[k]}.
1875
1876 @c XXX
1877 Note that there are no functions for accessing the elements of a
1878 character array yet. Once the string implementation of Guile has been
1879 changed to use Unicode, we will provide them.
1880
1881 @deftp {C Type} scm_t_array_handle
1882 This is a structure type that holds all information necessary to manage
1883 the reservation of arrays as explained above. Structures of this type
1884 must be allocated on the stack and must only be accessed by the
1885 functions listed below.
1886 @end deftp
1887
1888 @deftypefn {C Function} void scm_array_get_handle (SCM array, scm_t_array_handle *handle)
1889 Reserve @var{array}, which must be an array, and prepare @var{handle} to
1890 be used with the functions below. You must eventually call
1891 @code{scm_array_handle_release} on @var{handle}, and do this in a
1892 properly nested fashion, as explained above. The structure pointed to
1893 by @var{handle} does not need to be initialized before calling this
1894 function.
1895 @end deftypefn
1896
1897 @deftypefn {C Function} void scm_array_handle_release (scm_t_array_handle *handle)
1898 End the array reservation represented by @var{handle}. After a call to
1899 this function, @var{handle} might be used for another reservation.
1900 @end deftypefn
1901
1902 @deftypefn {C Function} size_t scm_array_handle_rank (scm_t_array_handle *handle)
1903 Return the rank of the array represented by @var{handle}.
1904 @end deftypefn
1905
1906 @deftp {C Type} scm_t_array_dim
1907 This structure type holds information about the layout of one dimension
1908 of an array. It includes the following fields:
1909
1910 @table @code
1911 @item ssize_t lbnd
1912 @itemx ssize_t ubnd
1913 The lower and upper bounds (both inclusive) of the permissible index
1914 range for the given dimension. Both values can be negative, but
1915 @var{lbnd} is always less than or equal to @var{ubnd}.
1916
1917 @item ssize_t inc
1918 The distance from one element of this dimension to the next. Note, too,
1919 that this can be negative.
1920 @end table
1921 @end deftp
1922
1923 @deftypefn {C Function} {const scm_t_array_dim *} scm_array_handle_dims (scm_t_array_handle *handle)
1924 Return a pointer to a C vector of information about the dimensions of
1925 the array represented by @var{handle}. This pointer is valid as long as
1926 the array remains reserved. As explained above, the
1927 @code{scm_t_array_dim} structures returned by this function can be used
1928 calculate the position of an element in the storage block of the array
1929 from its indices.
1930
1931 This position can then be used as an index into the C array pointer
1932 returned by the various @code{scm_array_handle_<foo>_elements}
1933 functions, or with @code{scm_array_handle_ref} and
1934 @code{scm_array_handle_set}.
1935
1936 Here is how one can compute the position @var{pos} of an element given
1937 its indices in the vector @var{indices}:
1938
1939 @example
1940 ssize_t indices[RANK];
1941 scm_t_array_dim *dims;
1942 ssize_t pos;
1943 size_t i;
1944
1945 pos = 0;
1946 for (i = 0; i < RANK; i++)
1947 @{
1948 if (indices[i] < dims[i].lbnd || indices[i] > dims[i].ubnd)
1949 out_of_range ();
1950 pos += (indices[i] - dims[i].lbnd) * dims[i].inc;
1951 @}
1952 @end example
1953 @end deftypefn
1954
1955 @deftypefn {C Function} ssize_t scm_array_handle_pos (scm_t_array_handle *handle, SCM indices)
1956 Compute the position corresponding to @var{indices}, a list of
1957 indices. The position is computed as described above for
1958 @code{scm_array_handle_dims}. The number of the indices and their
1959 range is checked and an appropriate error is signalled for invalid
1960 indices.
1961 @end deftypefn
1962
1963 @deftypefn {C Function} SCM scm_array_handle_ref (scm_t_array_handle *handle, ssize_t pos)
1964 Return the element at position @var{pos} in the storage block of the
1965 array represented by @var{handle}. Any kind of array is acceptable. No
1966 range checking is done on @var{pos}.
1967 @end deftypefn
1968
1969 @deftypefn {C Function} void scm_array_handle_set (scm_t_array_handle *handle, ssize_t pos, SCM val)
1970 Set the element at position @var{pos} in the storage block of the array
1971 represented by @var{handle} to @var{val}. Any kind of array is
1972 acceptable. No range checking is done on @var{pos}. An error is
1973 signalled when the array can not store @var{val}.
1974 @end deftypefn
1975
1976 @deftypefn {C Function} {const SCM *} scm_array_handle_elements (scm_t_array_handle *handle)
1977 Return a pointer to the elements of a ordinary array of general Scheme
1978 values (i.e., a non-uniform array) for reading. This pointer is valid
1979 as long as the array remains reserved.
1980 @end deftypefn
1981
1982 @deftypefn {C Function} {SCM *} scm_array_handle_writable_elements (scm_t_array_handle *handle)
1983 Like @code{scm_array_handle_elements}, but the pointer is good for
1984 reading and writing.
1985 @end deftypefn
1986
1987 @deftypefn {C Function} {const void *} scm_array_handle_uniform_elements (scm_t_array_handle *handle)
1988 Return a pointer to the elements of a uniform numeric array for reading.
1989 This pointer is valid as long as the array remains reserved. The size
1990 of each element is given by @code{scm_array_handle_uniform_element_size}.
1991 @end deftypefn
1992
1993 @deftypefn {C Function} {void *} scm_array_handle_uniform_writable_elements (scm_t_array_handle *handle)
1994 Like @code{scm_array_handle_uniform_elements}, but the pointer is good
1995 reading and writing.
1996 @end deftypefn
1997
1998 @deftypefn {C Function} size_t scm_array_handle_uniform_element_size (scm_t_array_handle *handle)
1999 Return the size of one element of the uniform numeric array represented
2000 by @var{handle}.
2001 @end deftypefn
2002
2003 @deftypefn {C Function} {const scm_t_uint8 *} scm_array_handle_u8_elements (scm_t_array_handle *handle)
2004 @deftypefnx {C Function} {const scm_t_int8 *} scm_array_handle_s8_elements (scm_t_array_handle *handle)
2005 @deftypefnx {C Function} {const scm_t_uint16 *} scm_array_handle_u16_elements (scm_t_array_handle *handle)
2006 @deftypefnx {C Function} {const scm_t_int16 *} scm_array_handle_s16_elements (scm_t_array_handle *handle)
2007 @deftypefnx {C Function} {const scm_t_uint32 *} scm_array_handle_u32_elements (scm_t_array_handle *handle)
2008 @deftypefnx {C Function} {const scm_t_int32 *} scm_array_handle_s32_elements (scm_t_array_handle *handle)
2009 @deftypefnx {C Function} {const scm_t_uint64 *} scm_array_handle_u64_elements (scm_t_array_handle *handle)
2010 @deftypefnx {C Function} {const scm_t_int64 *} scm_array_handle_s64_elements (scm_t_array_handle *handle)
2011 @deftypefnx {C Function} {const float *} scm_array_handle_f32_elements (scm_t_array_handle *handle)
2012 @deftypefnx {C Function} {const double *} scm_array_handle_f64_elements (scm_t_array_handle *handle)
2013 @deftypefnx {C Function} {const float *} scm_array_handle_c32_elements (scm_t_array_handle *handle)
2014 @deftypefnx {C Function} {const double *} scm_array_handle_c64_elements (scm_t_array_handle *handle)
2015 Return a pointer to the elements of a uniform numeric array of the
2016 indicated kind for reading. This pointer is valid as long as the array
2017 remains reserved.
2018
2019 The pointers for @code{c32} and @code{c64} uniform numeric arrays point
2020 to pairs of floating point numbers. The even index holds the real part,
2021 the odd index the imaginary part of the complex number.
2022 @end deftypefn
2023
2024 @deftypefn {C Function} {scm_t_uint8 *} scm_array_handle_u8_writable_elements (scm_t_array_handle *handle)
2025 @deftypefnx {C Function} {scm_t_int8 *} scm_array_handle_s8_writable_elements (scm_t_array_handle *handle)
2026 @deftypefnx {C Function} {scm_t_uint16 *} scm_array_handle_u16_writable_elements (scm_t_array_handle *handle)
2027 @deftypefnx {C Function} {scm_t_int16 *} scm_array_handle_s16_writable_elements (scm_t_array_handle *handle)
2028 @deftypefnx {C Function} {scm_t_uint32 *} scm_array_handle_u32_writable_elements (scm_t_array_handle *handle)
2029 @deftypefnx {C Function} {scm_t_int32 *} scm_array_handle_s32_writable_elements (scm_t_array_handle *handle)
2030 @deftypefnx {C Function} {scm_t_uint64 *} scm_array_handle_u64_writable_elements (scm_t_array_handle *handle)
2031 @deftypefnx {C Function} {scm_t_int64 *} scm_array_handle_s64_writable_elements (scm_t_array_handle *handle)
2032 @deftypefnx {C Function} {float *} scm_array_handle_f32_writable_elements (scm_t_array_handle *handle)
2033 @deftypefnx {C Function} {double *} scm_array_handle_f64_writable_elements (scm_t_array_handle *handle)
2034 @deftypefnx {C Function} {float *} scm_array_handle_c32_writable_elements (scm_t_array_handle *handle)
2035 @deftypefnx {C Function} {double *} scm_array_handle_c64_writable_elements (scm_t_array_handle *handle)
2036 Like @code{scm_array_handle_<kind>_elements}, but the pointer is good
2037 for reading and writing.
2038 @end deftypefn
2039
2040 @deftypefn {C Function} {const scm_t_uint32 *} scm_array_handle_bit_elements (scm_t_array_handle *handle)
2041 Return a pointer to the words that store the bits of the represented
2042 array, which must be a bit array.
2043
2044 Unlike other arrays, bit arrays have an additional offset that must be
2045 figured into index calculations. That offset is returned by
2046 @code{scm_array_handle_bit_elements_offset}.
2047
2048 To find a certain bit you first need to calculate its position as
2049 explained above for @code{scm_array_handle_dims} and then add the
2050 offset. This gives the absolute position of the bit, which is always a
2051 non-negative integer.
2052
2053 Each word of the bit array storage block contains exactly 32 bits, with
2054 the least significant bit in that word having the lowest absolute
2055 position number. The next word contains the next 32 bits.
2056
2057 Thus, the following code can be used to access a bit whose position
2058 according to @code{scm_array_handle_dims} is given in @var{pos}:
2059
2060 @example
2061 SCM bit_array;
2062 scm_t_array_handle handle;
2063 scm_t_uint32 *bits;
2064 ssize_t pos;
2065 size_t abs_pos;
2066 size_t word_pos, mask;
2067
2068 scm_array_get_handle (&bit_array, &handle);
2069 bits = scm_array_handle_bit_elements (&handle);
2070
2071 pos = ...
2072 abs_pos = pos + scm_array_handle_bit_elements_offset (&handle);
2073 word_pos = abs_pos / 32;
2074 mask = 1L << (abs_pos % 32);
2075
2076 if (bits[word_pos] & mask)
2077 /* bit is set. */
2078
2079 scm_array_handle_release (&handle);
2080 @end example
2081
2082 @end deftypefn
2083
2084 @deftypefn {C Function} {scm_t_uint32 *} scm_array_handle_bit_writable_elements (scm_t_array_handle *handle)
2085 Like @code{scm_array_handle_bit_elements} but the pointer is good for
2086 reading and writing. You must take care not to modify bits outside of
2087 the allowed index range of the array, even for contiguous arrays.
2088 @end deftypefn
2089
2090 @node VLists
2091 @subsection VLists
2092
2093 @cindex vlist
2094
2095 The @code{(ice-9 vlist)} module provides an implementation of the @dfn{VList}
2096 data structure designed by Phil Bagwell in 2002. VLists are immutable lists,
2097 which can contain any Scheme object. They improve on standard Scheme linked
2098 lists in several areas:
2099
2100 @itemize
2101 @item
2102 Random access has typically constant-time complexity.
2103
2104 @item
2105 Computing the length of a VList has time complexity logarithmic in the number of
2106 elements.
2107
2108 @item
2109 VLists use less storage space than standard lists.
2110
2111 @item
2112 VList elements are stored in contiguous regions, which improves memory locality
2113 and leads to more efficient use of hardware caches.
2114 @end itemize
2115
2116 The idea behind VLists is to store vlist elements in increasingly large
2117 contiguous blocks (implemented as vectors here). These blocks are linked to one
2118 another using a pointer to the next block and an offset within that block. The
2119 size of these blocks form a geometric series with ratio
2120 @code{block-growth-factor} (2 by default).
2121
2122 The VList structure also serves as the basis for the @dfn{VList-based hash
2123 lists} or ``vhashes'', an immutable dictionary type (@pxref{VHashes}).
2124
2125 However, the current implementation in @code{(ice-9 vlist)} has several
2126 noteworthy shortcomings:
2127
2128 @itemize
2129
2130 @item
2131 It is @emph{not} thread-safe. Although operations on vlists are all
2132 @dfn{referentially transparent} (i.e., purely functional), adding elements to a
2133 vlist with @code{vlist-cons} mutates part of its internal structure, which makes
2134 it non-thread-safe. This could be fixed, but it would slow down
2135 @code{vlist-cons}.
2136
2137 @item
2138 @code{vlist-cons} always allocates at least as much memory as @code{cons}.
2139 Again, Phil Bagwell describes how to fix it, but that would require tuning the
2140 garbage collector in a way that may not be generally beneficial.
2141
2142 @item
2143 @code{vlist-cons} is a Scheme procedure compiled to bytecode, and it does not
2144 compete with the straightforward C implementation of @code{cons}, and with the
2145 fact that the VM has a special @code{cons} instruction.
2146
2147 @end itemize
2148
2149 We hope to address these in the future.
2150
2151 The programming interface exported by @code{(ice-9 vlist)} is defined below.
2152 Most of it is the same as SRFI-1 with an added @code{vlist-} prefix to function
2153 names.
2154
2155 @deffn {Scheme Procedure} vlist? obj
2156 Return true if @var{obj} is a VList.
2157 @end deffn
2158
2159 @defvr {Scheme Variable} vlist-null
2160 The empty VList. Note that it's possible to create an empty VList not
2161 @code{eq?} to @code{vlist-null}; thus, callers should always use
2162 @code{vlist-null?} when testing whether a VList is empty.
2163 @end defvr
2164
2165 @deffn {Scheme Procedure} vlist-null? vlist
2166 Return true if @var{vlist} is empty.
2167 @end deffn
2168
2169 @deffn {Scheme Procedure} vlist-cons item vlist
2170 Return a new vlist with @var{item} as its head and @var{vlist} as its tail.
2171 @end deffn
2172
2173 @deffn {Scheme Procedure} vlist-head vlist
2174 Return the head of @var{vlist}.
2175 @end deffn
2176
2177 @deffn {Scheme Procedure} vlist-tail vlist
2178 Return the tail of @var{vlist}.
2179 @end deffn
2180
2181 @defvr {Scheme Variable} block-growth-factor
2182 A fluid that defines the growth factor of VList blocks, 2 by default.
2183 @end defvr
2184
2185 The functions below provide the usual set of higher-level list operations.
2186
2187 @deffn {Scheme Procedure} vlist-fold proc init vlist
2188 @deffnx {Scheme Procedure} vlist-fold-right proc init vlist
2189 Fold over @var{vlist}, calling @var{proc} for each element, as for SRFI-1
2190 @code{fold} and @code{fold-right} (@pxref{SRFI-1, @code{fold}}).
2191 @end deffn
2192
2193 @deffn {Scheme Procedure} vlist-ref vlist index
2194 Return the element at index @var{index} in @var{vlist}. This is typically a
2195 constant-time operation.
2196 @end deffn
2197
2198 @deffn {Scheme Procedure} vlist-length vlist
2199 Return the length of @var{vlist}. This is typically logarithmic in the number
2200 of elements in @var{vlist}.
2201 @end deffn
2202
2203 @deffn {Scheme Procedure} vlist-reverse vlist
2204 Return a new @var{vlist} whose content are those of @var{vlist} in reverse
2205 order.
2206 @end deffn
2207
2208 @deffn {Scheme Procedure} vlist-map proc vlist
2209 Map @var{proc} over the elements of @var{vlist} and return a new vlist.
2210 @end deffn
2211
2212 @deffn {Scheme Procedure} vlist-for-each proc vlist
2213 Call @var{proc} on each element of @var{vlist}. The result is unspecified.
2214 @end deffn
2215
2216 @deffn {Scheme Procedure} vlist-drop vlist count
2217 Return a new vlist that does not contain the @var{count} first elements of
2218 @var{vlist}. This is typically a constant-time operation.
2219 @end deffn
2220
2221 @deffn {Scheme Procedure} vlist-take vlist count
2222 Return a new vlist that contains only the @var{count} first elements of
2223 @var{vlist}.
2224 @end deffn
2225
2226 @deffn {Scheme Procedure} vlist-filter pred vlist
2227 Return a new vlist containing all the elements from @var{vlist} that satisfy
2228 @var{pred}.
2229 @end deffn
2230
2231 @deffn {Scheme Procedure} vlist-delete x vlist [equal?]
2232 Return a new vlist corresponding to @var{vlist} without the elements
2233 @var{equal?} to @var{x}.
2234 @end deffn
2235
2236 @deffn {Scheme Procedure} vlist-unfold p f g seed [tail-gen]
2237 @deffnx {Scheme Procedure} vlist-unfold-right p f g seed [tail]
2238 Return a new vlist, as for SRFI-1 @code{unfold} and @code{unfold-right}
2239 (@pxref{SRFI-1, @code{unfold}}).
2240 @end deffn
2241
2242 @deffn {Scheme Procedure} vlist-append vlist @dots{}
2243 Append the given vlists and return the resulting vlist.
2244 @end deffn
2245
2246 @deffn {Scheme Procedure} list->vlist lst
2247 Return a new vlist whose contents correspond to @var{lst}.
2248 @end deffn
2249
2250 @deffn {Scheme Procedure} vlist->list vlist
2251 Return a new list whose contents match those of @var{vlist}.
2252 @end deffn
2253
2254 @node Record Overview
2255 @subsection Record Overview
2256
2257 @cindex record
2258 @cindex structure
2259
2260 @dfn{Records}, also called @dfn{structures}, are Scheme's primary
2261 mechanism to define new disjoint types. A @dfn{record type} defines a
2262 list of @dfn{fields} that instances of the type consist of. This is like
2263 C's @code{struct}.
2264
2265 Historically, Guile has offered several different ways to define record
2266 types and to create records, offering different features, and making
2267 different trade-offs. Over the years, each ``standard'' has also come
2268 with its own new record interface, leading to a maze of record APIs.
2269
2270 At the highest level is SRFI-9, a high-level record interface
2271 implemented by most Scheme implementations (@pxref{SRFI-9}). It defines
2272 a simple and efficient syntactic abstraction of record types and their
2273 associated type predicate, fields, and field accessors. SRFI-9 is
2274 suitable for most uses, and this is the recommended way to create record
2275 types in Guile. Similar high-level record APIs include SRFI-35
2276 (@pxref{SRFI-35}) and R6RS records (@pxref{rnrs records syntactic}).
2277
2278 Then comes Guile's historical ``records'' API (@pxref{Records}). Record
2279 types defined this way are first-class objects. Introspection
2280 facilities are available, allowing users to query the list of fields or
2281 the value of a specific field at run-time, without prior knowledge of
2282 the type.
2283
2284 Finally, the common denominator of these interfaces is Guile's
2285 @dfn{structure} API (@pxref{Structures}). Guile's structures are the
2286 low-level building block for all other record APIs. Application writers
2287 will normally not need to use it.
2288
2289 Records created with these APIs may all be pattern-matched using Guile's
2290 standard pattern matcher (@pxref{Pattern Matching}).
2291
2292
2293 @node SRFI-9 Records
2294 @subsection SRFI-9 Records
2295
2296 @cindex SRFI-9
2297 @cindex record
2298
2299 SRFI-9 standardizes a syntax for defining new record types and creating
2300 predicate, constructor, and field getter and setter functions. In Guile
2301 this is the recommended option to create new record types (@pxref{Record
2302 Overview}). It can be used with:
2303
2304 @example
2305 (use-modules (srfi srfi-9))
2306 @end example
2307
2308 @deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
2309 @sp 1
2310 Create a new record type, and make various @code{define}s for using
2311 it. This syntax can only occur at the top-level, not nested within
2312 some other form.
2313
2314 @var{type} is bound to the record type, which is as per the return
2315 from the core @code{make-record-type}. @var{type} also provides the
2316 name for the record, as per @code{record-type-name}.
2317
2318 @var{constructor} is bound to a function to be called as
2319 @code{(@var{constructor} fieldval @dots{})} to create a new record of
2320 this type. The arguments are initial values for the fields, one
2321 argument for each field, in the order they appear in the
2322 @code{define-record-type} form.
2323
2324 The @var{fieldname}s provide the names for the record fields, as per
2325 the core @code{record-type-fields} etc, and are referred to in the
2326 subsequent accessor/modifier forms.
2327
2328 @var{predicate} is bound to a function to be called as
2329 @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
2330 according to whether @var{obj} is a record of this type.
2331
2332 Each @var{accessor} is bound to a function to be called
2333 @code{(@var{accessor} record)} to retrieve the respective field from a
2334 @var{record}. Similarly each @var{modifier} is bound to a function to
2335 be called @code{(@var{modifier} record val)} to set the respective
2336 field in a @var{record}.
2337 @end deffn
2338
2339 @noindent
2340 An example will illustrate typical usage,
2341
2342 @example
2343 (define-record-type employee-type
2344 (make-employee name age salary)
2345 employee?
2346 (name get-employee-name)
2347 (age get-employee-age set-employee-age)
2348 (salary get-employee-salary set-employee-salary))
2349 @end example
2350
2351 This creates a new employee data type, with name, age and salary
2352 fields. Accessor functions are created for each field, but no
2353 modifier function for the name (the intention in this example being
2354 that it's established only when an employee object is created). These
2355 can all then be used as for example,
2356
2357 @example
2358 employee-type @result{} #<record-type employee-type>
2359
2360 (define fred (make-employee "Fred" 45 20000.00))
2361
2362 (employee? fred) @result{} #t
2363 (get-employee-age fred) @result{} 45
2364 (set-employee-salary fred 25000.00) ;; pay rise
2365 @end example
2366
2367 The functions created by @code{define-record-type} are ordinary
2368 top-level @code{define}s. They can be redefined or @code{set!} as
2369 desired, exported from a module, etc.
2370
2371 @unnumberedsubsubsec Non-toplevel Record Definitions
2372
2373 The SRFI-9 specification explicitly disallows record definitions in a
2374 non-toplevel context, such as inside @code{lambda} body or inside a
2375 @var{let} block. However, Guile's implementation does not enforce that
2376 restriction.
2377
2378 @unnumberedsubsubsec Custom Printers
2379
2380 You may use @code{set-record-type-printer!} to customize the default printing
2381 behavior of records. This is a Guile extension and is not part of SRFI-9. It
2382 is located in the @nicode{(srfi srfi-9 gnu)} module.
2383
2384 @deffn {Scheme Syntax} set-record-type-printer! name thunk
2385 Where @var{type} corresponds to the first argument of @code{define-record-type},
2386 and @var{thunk} is a procedure accepting two arguments, the record to print, and
2387 an output port.
2388 @end deffn
2389
2390 @noindent
2391 This example prints the employee's name in brackets, for instance @code{[Fred]}.
2392
2393 @example
2394 (set-record-type-printer! employee-type
2395 (lambda (record port)
2396 (write-char #\[ port)
2397 (display (get-employee-name record) port)
2398 (write-char #\] port)))
2399 @end example
2400
2401 @unnumberedsubsubsec Functional ``Setters''
2402
2403 @cindex functional setters
2404
2405 When writing code in a functional style, it is desirable to never alter
2406 the contents of records. For such code, a simple way to return new
2407 record instances based on existing ones is highly desirable.
2408
2409 The @code{(srfi srfi-9 gnu)} module extends SRFI-9 with facilities to
2410 return new record instances based on existing ones, only with one or
2411 more field values changed---@dfn{functional setters}. First, the
2412 @code{define-immutable-record-type} works like
2413 @code{define-record-type}, except that fields are immutable and setters
2414 are defined as functional setters.
2415
2416 @deffn {Scheme Syntax} define-immutable-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
2417 Define @var{type} as a new record type, like @code{define-record-type}.
2418 However, the record type is made @emph{immutable} (records may not be
2419 mutated, even with @code{struct-set!}), and any @var{modifier} is
2420 defined to be a functional setter---a procedure that returns a new
2421 record instance with the specified field changed, and leaves the
2422 original unchanged (see example below.)
2423 @end deffn
2424
2425 @noindent
2426 In addition, the generic @code{set-field} and @code{set-fields} macros
2427 may be applied to any SRFI-9 record.
2428
2429 @deffn {Scheme Syntax} set-field record (field sub-fields ...) value
2430 Return a new record of @var{record}'s type whose fields are equal to
2431 the corresponding fields of @var{record} except for the one specified by
2432 @var{field}.
2433
2434 @var{field} must be the name of the getter corresponding to the field of
2435 @var{record} being ``set''. Subsequent @var{sub-fields} must be record
2436 getters designating sub-fields within that field value to be set (see
2437 example below.)
2438 @end deffn
2439
2440 @deffn {Scheme Syntax} set-fields record ((field sub-fields ...) value) ...
2441 Like @code{set-field}, but can be used to set more than one field at a
2442 time. This expands to code that is more efficient than a series of
2443 single @code{set-field} calls.
2444 @end deffn
2445
2446 To illustrate the use of functional setters, let's assume these two
2447 record type definitions:
2448
2449 @example
2450 (define-record-type <address>
2451 (address street city country)
2452 address?
2453 (street address-street)
2454 (city address-city)
2455 (country address-country))
2456
2457 (define-immutable-record-type <person>
2458 (person age email address)
2459 person?
2460 (age person-age set-person-age)
2461 (email person-email set-person-email)
2462 (address person-address set-person-address))
2463 @end example
2464
2465 @noindent
2466 First, note that the @code{<person>} record type definition introduces
2467 named functional setters. These may be used like this:
2468
2469 @example
2470 (define fsf-address
2471 (address "Franklin Street" "Boston" "USA"))
2472
2473 (define rms
2474 (person 30 "rms@@gnu.org" fsf-address))
2475
2476 (and (equal? (set-person-age rms 60)
2477 (person 60 "rms@@gnu.org" fsf-address))
2478 (= (person-age rms) 30))
2479 @result{} #t
2480 @end example
2481
2482 @noindent
2483 Here, the original @code{<person>} record, to which @var{rms} is bound,
2484 is left unchanged.
2485
2486 Now, suppose we want to change both the street and age of @var{rms}.
2487 This can be achieved using @code{set-fields}:
2488
2489 @example
2490 (set-fields rms
2491 ((person-age) 60)
2492 ((person-address address-street) "Temple Place"))
2493 @result{} #<<person> age: 60 email: "rms@@gnu.org"
2494 address: #<<address> street: "Temple Place" city: "Boston" country: "USA">>
2495 @end example
2496
2497 @noindent
2498 Notice how the above changed two fields of @var{rms}, including the
2499 @code{street} field of its @code{address} field, in a concise way. Also
2500 note that @code{set-fields} works equally well for types defined with
2501 just @code{define-record-type}.
2502
2503 @node Records
2504 @subsection Records
2505
2506 A @dfn{record type} is a first class object representing a user-defined
2507 data type. A @dfn{record} is an instance of a record type.
2508
2509 Note that in many ways, this interface is too low-level for every-day
2510 use. Most uses of records are better served by SRFI-9 records.
2511 @xref{SRFI-9}.
2512
2513 @deffn {Scheme Procedure} record? obj
2514 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
2515 otherwise.
2516
2517 Note that @code{record?} may be true of any Scheme value; there is no
2518 promise that records are disjoint with other Scheme types.
2519 @end deffn
2520
2521 @deffn {Scheme Procedure} make-record-type type-name field-names [print]
2522 Create and return a new @dfn{record-type descriptor}.
2523
2524 @var{type-name} is a string naming the type. Currently it's only used
2525 in the printed representation of records, and in diagnostics.
2526 @var{field-names} is a list of symbols naming the fields of a record
2527 of the type. Duplicates are not allowed among these symbols.
2528
2529 @example
2530 (make-record-type "employee" '(name age salary))
2531 @end example
2532
2533 The optional @var{print} argument is a function used by
2534 @code{display}, @code{write}, etc, for printing a record of the new
2535 type. It's called as @code{(@var{print} record port)} and should look
2536 at @var{record} and write to @var{port}.
2537 @end deffn
2538
2539 @deffn {Scheme Procedure} record-constructor rtd [field-names]
2540 Return a procedure for constructing new members of the type represented
2541 by @var{rtd}. The returned procedure accepts exactly as many arguments
2542 as there are symbols in the given list, @var{field-names}; these are
2543 used, in order, as the initial values of those fields in a new record,
2544 which is returned by the constructor procedure. The values of any
2545 fields not named in that list are unspecified. The @var{field-names}
2546 argument defaults to the list of field names in the call to
2547 @code{make-record-type} that created the type represented by @var{rtd};
2548 if the @var{field-names} argument is provided, it is an error if it
2549 contains any duplicates or any symbols not in the default list.
2550 @end deffn
2551
2552 @deffn {Scheme Procedure} record-predicate rtd
2553 Return a procedure for testing membership in the type represented by
2554 @var{rtd}. The returned procedure accepts exactly one argument and
2555 returns a true value if the argument is a member of the indicated record
2556 type; it returns a false value otherwise.
2557 @end deffn
2558
2559 @deffn {Scheme Procedure} record-accessor rtd field-name
2560 Return a procedure for reading the value of a particular field of a
2561 member of the type represented by @var{rtd}. The returned procedure
2562 accepts exactly one argument which must be a record of the appropriate
2563 type; it returns the current value of the field named by the symbol
2564 @var{field-name} in that record. The symbol @var{field-name} must be a
2565 member of the list of field-names in the call to @code{make-record-type}
2566 that created the type represented by @var{rtd}.
2567 @end deffn
2568
2569 @deffn {Scheme Procedure} record-modifier rtd field-name
2570 Return a procedure for writing the value of a particular field of a
2571 member of the type represented by @var{rtd}. The returned procedure
2572 accepts exactly two arguments: first, a record of the appropriate type,
2573 and second, an arbitrary Scheme value; it modifies the field named by
2574 the symbol @var{field-name} in that record to contain the given value.
2575 The returned value of the modifier procedure is unspecified. The symbol
2576 @var{field-name} must be a member of the list of field-names in the call
2577 to @code{make-record-type} that created the type represented by
2578 @var{rtd}.
2579 @end deffn
2580
2581 @deffn {Scheme Procedure} record-type-descriptor record
2582 Return a record-type descriptor representing the type of the given
2583 record. That is, for example, if the returned descriptor were passed to
2584 @code{record-predicate}, the resulting predicate would return a true
2585 value when passed the given record. Note that it is not necessarily the
2586 case that the returned descriptor is the one that was passed to
2587 @code{record-constructor} in the call that created the constructor
2588 procedure that created the given record.
2589 @end deffn
2590
2591 @deffn {Scheme Procedure} record-type-name rtd
2592 Return the type-name associated with the type represented by rtd. The
2593 returned value is @code{eqv?} to the @var{type-name} argument given in
2594 the call to @code{make-record-type} that created the type represented by
2595 @var{rtd}.
2596 @end deffn
2597
2598 @deffn {Scheme Procedure} record-type-fields rtd
2599 Return a list of the symbols naming the fields in members of the type
2600 represented by @var{rtd}. The returned value is @code{equal?} to the
2601 field-names argument given in the call to @code{make-record-type} that
2602 created the type represented by @var{rtd}.
2603 @end deffn
2604
2605
2606 @node Structures
2607 @subsection Structures
2608 @tpindex Structures
2609
2610 A @dfn{structure} is a first class data type which holds Scheme values
2611 or C words in fields numbered 0 upwards. A @dfn{vtable} is a structure
2612 that represents a structure type, giving field types and permissions,
2613 and an optional print function for @code{write} etc.
2614
2615 Structures are lower level than records (@pxref{Records}). Usually,
2616 when you need to represent structured data, you just want to use
2617 records. But sometimes you need to implement new kinds of structured
2618 data abstractions, and for that purpose structures are useful. Indeed,
2619 records in Guile are implemented with structures.
2620
2621 @menu
2622 * Vtables::
2623 * Structure Basics::
2624 * Vtable Contents::
2625 * Meta-Vtables::
2626 * Vtable Example::
2627 * Tail Arrays::
2628 @end menu
2629
2630 @node Vtables
2631 @subsubsection Vtables
2632
2633 A vtable is a structure type, specifying its layout, and other
2634 information. A vtable is actually itself a structure, but there's no
2635 need to worry about that initially (@pxref{Vtable Contents}.)
2636
2637 @deffn {Scheme Procedure} make-vtable fields [print]
2638 Create a new vtable.
2639
2640 @var{fields} is a string describing the fields in the structures to be
2641 created. Each field is represented by two characters, a type letter
2642 and a permissions letter, for example @code{"pw"}. The types are as
2643 follows.
2644
2645 @itemize @bullet{}
2646 @item
2647 @code{p} -- a Scheme value. ``p'' stands for ``protected'' meaning
2648 it's protected against garbage collection.
2649
2650 @item
2651 @code{u} -- an arbitrary word of data (an @code{scm_t_bits}). At the
2652 Scheme level it's read and written as an unsigned integer. ``u''
2653 stands for ``uninterpreted'' (it's not treated as a Scheme value), or
2654 ``unprotected'' (it's not marked during GC), or ``unsigned long'' (its
2655 size), or all of these things.
2656
2657 @item
2658 @code{s} -- a self-reference. Such a field holds the @code{SCM} value
2659 of the structure itself (a circular reference). This can be useful in
2660 C code where you might have a pointer to the data array, and want to
2661 get the Scheme @code{SCM} handle for the structure. In Scheme code it
2662 has no use.
2663 @end itemize
2664
2665 The second letter for each field is a permission code,
2666
2667 @itemize @bullet{}
2668 @item
2669 @code{w} -- writable, the field can be read and written.
2670 @item
2671 @code{r} -- read-only, the field can be read but not written.
2672 @item
2673 @code{o} -- opaque, the field can be neither read nor written at the
2674 Scheme level. This can be used for fields which should only be used
2675 from C code.
2676 @end itemize
2677
2678 Here are some examples. @xref{Tail Arrays}, for information on the
2679 legacy tail array facility.
2680
2681 @example
2682 (make-vtable "pw") ;; one writable field
2683 (make-vtable "prpw") ;; one read-only and one writable
2684 (make-vtable "pwuwuw") ;; one scheme and two uninterpreted
2685 @end example
2686
2687 The optional @var{print} argument is a function called by
2688 @code{display} and @code{write} (etc) to give a printed representation
2689 of a structure created from this vtable. It's called
2690 @code{(@var{print} struct port)} and should look at @var{struct} and
2691 write to @var{port}. The default print merely gives a form like
2692 @samp{#<struct ADDR:ADDR>} with a pair of machine addresses.
2693
2694 The following print function for example shows the two fields of its
2695 structure.
2696
2697 @example
2698 (make-vtable "prpw"
2699 (lambda (struct port)
2700 (format port "#<~a and ~a>"
2701 (struct-ref struct 0)
2702 (struct-ref struct 1))))
2703 @end example
2704 @end deffn
2705
2706
2707 @node Structure Basics
2708 @subsubsection Structure Basics
2709
2710 This section describes the basic procedures for working with
2711 structures. @code{make-struct} creates a structure, and
2712 @code{struct-ref} and @code{struct-set!} access its fields.
2713
2714 @deffn {Scheme Procedure} make-struct vtable tail-size init @dots{}
2715 @deffnx {Scheme Procedure} make-struct/no-tail vtable init @dots{}
2716 Create a new structure, with layout per the given @var{vtable}
2717 (@pxref{Vtables}).
2718
2719 The optional @var{init}@dots{} arguments are initial values for the
2720 fields of the structure. This is the only way to
2721 put values in read-only fields. If there are fewer @var{init}
2722 arguments than fields then the defaults are @code{#f} for a Scheme
2723 field (type @code{p}) or 0 for an uninterpreted field (type @code{u}).
2724
2725 Structures also have the ability to allocate a variable number of
2726 additional cells at the end, at their tails. However, this legacy
2727 @dfn{tail array} facilty is confusing and inefficient, and so we do not
2728 recommend it. @xref{Tail Arrays}, for more on the legacy tail array
2729 interface.
2730
2731 Type @code{s} self-reference fields, permission @code{o} opaque
2732 fields, and the count field of a tail array are all ignored for the
2733 @var{init} arguments, ie.@: an argument is not consumed by such a
2734 field. An @code{s} is always set to the structure itself, an @code{o}
2735 is always set to @code{#f} or 0 (with the intention that C code will
2736 do something to it later), and the tail count is always the given
2737 @var{tail-size}.
2738
2739 For example,
2740
2741 @example
2742 (define v (make-vtable "prpwpw"))
2743 (define s (make-struct v 0 123 "abc" 456))
2744 (struct-ref s 0) @result{} 123
2745 (struct-ref s 1) @result{} "abc"
2746 @end example
2747 @end deffn
2748
2749 @deftypefn {C Function} SCM scm_make_struct (SCM vtable, SCM tail_size, SCM init_list)
2750 @deftypefnx {C Function} SCM scm_c_make_struct (SCM vtable, SCM tail_size, SCM init, ...)
2751 @deftypefnx {C Function} SCM scm_c_make_structv (SCM vtable, SCM tail_size, size_t n_inits, scm_t_bits init[])
2752 There are a few ways to make structures from C. @code{scm_make_struct}
2753 takes a list, @code{scm_c_make_struct} takes variable arguments
2754 terminated with SCM_UNDEFINED, and @code{scm_c_make_structv} takes a
2755 packed array.
2756 @end deftypefn
2757
2758 @deffn {Scheme Procedure} struct? obj
2759 @deffnx {C Function} scm_struct_p (obj)
2760 Return @code{#t} if @var{obj} is a structure, or @code{#f} if not.
2761 @end deffn
2762
2763 @deffn {Scheme Procedure} struct-ref struct n
2764 @deffnx {C Function} scm_struct_ref (struct, n)
2765 Return the contents of field number @var{n} in @var{struct}. The
2766 first field is number 0.
2767
2768 An error is thrown if @var{n} is out of range, or if the field cannot
2769 be read because it's @code{o} opaque.
2770 @end deffn
2771
2772 @deffn {Scheme Procedure} struct-set! struct n value
2773 @deffnx {C Function} scm_struct_set_x (struct, n, value)
2774 Set field number @var{n} in @var{struct} to @var{value}. The first
2775 field is number 0.
2776
2777 An error is thrown if @var{n} is out of range, or if the field cannot
2778 be written because it's @code{r} read-only or @code{o} opaque.
2779 @end deffn
2780
2781 @deffn {Scheme Procedure} struct-vtable struct
2782 @deffnx {C Function} scm_struct_vtable (struct)
2783 Return the vtable that describes @var{struct}.
2784
2785 The vtable is effectively the type of the structure. See @ref{Vtable
2786 Contents}, for more on vtables.
2787 @end deffn
2788
2789
2790 @node Vtable Contents
2791 @subsubsection Vtable Contents
2792
2793 A vtable is itself a structure. It has a specific set of fields
2794 describing various aspects of its @dfn{instances}: the structures
2795 created from a vtable. Some of the fields are internal to Guile, some
2796 of them are part of the public interface, and there may be additional
2797 fields added on by the user.
2798
2799 Every vtable has a field for the layout of their instances, a field for
2800 the procedure used to print its instances, and a field for the name of
2801 the vtable itself. Access to the layout and printer is exposed directly
2802 via field indexes. Access to the vtable name is exposed via accessor
2803 procedures.
2804
2805 @defvr {Scheme Variable} vtable-index-layout
2806 @defvrx {C Macro} scm_vtable_index_layout
2807 The field number of the layout specification in a vtable. The layout
2808 specification is a symbol like @code{pwpw} formed from the fields
2809 string passed to @code{make-vtable}, or created by
2810 @code{make-struct-layout} (@pxref{Meta-Vtables}).
2811
2812 @example
2813 (define v (make-vtable "pwpw" 0))
2814 (struct-ref v vtable-index-layout) @result{} pwpw
2815 @end example
2816
2817 This field is read-only, since the layout of structures using a vtable
2818 cannot be changed.
2819 @end defvr
2820
2821 @defvr {Scheme Variable} vtable-index-printer
2822 @defvrx {C Macro} scm_vtable_index_printer
2823 The field number of the printer function. This field contains @code{#f}
2824 if the default print function should be used.
2825
2826 @example
2827 (define (my-print-func struct port)
2828 ...)
2829 (define v (make-vtable "pwpw" my-print-func))
2830 (struct-ref v vtable-index-printer) @result{} my-print-func
2831 @end example
2832
2833 This field is writable, allowing the print function to be changed
2834 dynamically.
2835 @end defvr
2836
2837 @deffn {Scheme Procedure} struct-vtable-name vtable
2838 @deffnx {Scheme Procedure} set-struct-vtable-name! vtable name
2839 @deffnx {C Function} scm_struct_vtable_name (vtable)
2840 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
2841 Get or set the name of @var{vtable}. @var{name} is a symbol and is
2842 used in the default print function when printing structures created
2843 from @var{vtable}.
2844
2845 @example
2846 (define v (make-vtable "pw"))
2847 (set-struct-vtable-name! v 'my-name)
2848
2849 (define s (make-struct v 0))
2850 (display s) @print{} #<my-name b7ab3ae0:b7ab3730>
2851 @end example
2852 @end deffn
2853
2854
2855 @node Meta-Vtables
2856 @subsubsection Meta-Vtables
2857
2858 As a structure, a vtable also has a vtable, which is also a structure.
2859 Structures, their vtables, the vtables of the vtables, and so on form a
2860 tree of structures. Making a new structure adds a leaf to the tree, and
2861 if that structure is a vtable, it may be used to create other leaves.
2862
2863 If you traverse up the tree of vtables, via calling
2864 @code{struct-vtable}, eventually you reach a root which is the vtable of
2865 itself:
2866
2867 @example
2868 scheme@@(guile-user)> (current-module)
2869 $1 = #<directory (guile-user) 221b090>
2870 scheme@@(guile-user)> (struct-vtable $1)
2871 $2 = #<record-type module>
2872 scheme@@(guile-user)> (struct-vtable $2)
2873 $3 = #<<standard-vtable> 12c30a0>
2874 scheme@@(guile-user)> (struct-vtable $3)
2875 $4 = #<<standard-vtable> 12c3fa0>
2876 scheme@@(guile-user)> (struct-vtable $4)
2877 $5 = #<<standard-vtable> 12c3fa0>
2878 scheme@@(guile-user)> <standard-vtable>
2879 $6 = #<<standard-vtable> 12c3fa0>
2880 @end example
2881
2882 In this example, we can say that @code{$1} is an instance of @code{$2},
2883 @code{$2} is an instance of @code{$3}, @code{$3} is an instance of
2884 @code{$4}, and @code{$4}, strangely enough, is an instance of itself.
2885 The value bound to @code{$4} in this console session also bound to
2886 @code{<standard-vtable>} in the default environment.
2887
2888 @defvr {Scheme Variable} <standard-vtable>
2889 A meta-vtable, useful for making new vtables.
2890 @end defvr
2891
2892 All of these values are structures. All but @code{$1} are vtables. As
2893 @code{$2} is an instance of @code{$3}, and @code{$3} is a vtable, we can
2894 say that @code{$3} is a @dfn{meta-vtable}: a vtable that can create
2895 vtables.
2896
2897 With this definition, we can specify more precisely what a vtable is: a
2898 vtable is a structure made from a meta-vtable. Making a structure from
2899 a meta-vtable runs some special checks to ensure that the first field of
2900 the structure is a valid layout. Additionally, if these checks see that
2901 the layout of the child vtable contains all the required fields of a
2902 vtable, in the correct order, then the child vtable will also be a
2903 meta-table, inheriting a magical bit from the parent.
2904
2905 @deffn {Scheme Procedure} struct-vtable? obj
2906 @deffnx {C Function} scm_struct_vtable_p (obj)
2907 Return @code{#t} if @var{obj} is a vtable structure: an instance of a
2908 meta-vtable.
2909 @end deffn
2910
2911 @code{<standard-vtable>} is a root of the vtable tree. (Normally there
2912 is only one root in a given Guile process, but due to some legacy
2913 interfaces there may be more than one.)
2914
2915 The set of required fields of a vtable is the set of fields in the
2916 @code{<standard-vtable>}, and is bound to @code{standard-vtable-fields}
2917 in the default environment. It is possible to create a meta-vtable that
2918 with additional fields in its layout, which can be used to create
2919 vtables with additional data:
2920
2921 @example
2922 scheme@@(guile-user)> (struct-ref $3 vtable-index-layout)
2923 $6 = pruhsruhpwphuhuhprprpw
2924 scheme@@(guile-user)> (struct-ref $4 vtable-index-layout)
2925 $7 = pruhsruhpwphuhuh
2926 scheme@@(guile-user)> standard-vtable-fields
2927 $8 = "pruhsruhpwphuhuh"
2928 scheme@@(guile-user)> (struct-ref $2 vtable-offset-user)
2929 $9 = module
2930 @end example
2931
2932 In this continuation of our earlier example, @code{$2} is a vtable that
2933 has extra fields, because its vtable, @code{$3}, was made from a
2934 meta-vtable with an extended layout. @code{vtable-offset-user} is a
2935 convenient definition that indicates the number of fields in
2936 @code{standard-vtable-fields}.
2937
2938 @defvr {Scheme Variable} standard-vtable-fields
2939 A string containing the orderedq set of fields that a vtable must have.
2940 @end defvr
2941
2942 @defvr {Scheme Variable} vtable-offset-user
2943 The first index in a vtable that is available for a user.
2944 @end defvr
2945
2946 @deffn {Scheme Procedure} make-struct-layout fields
2947 @deffnx {C Function} scm_make_struct_layout (fields)
2948 Return a structure layout symbol, from a @var{fields} string.
2949 @var{fields} is as described under @code{make-vtable}
2950 (@pxref{Vtables}). An invalid @var{fields} string is an error.
2951 @end deffn
2952
2953 With these definitions, one can define @code{make-vtable} in this way:
2954
2955 @example
2956 (define* (make-vtable fields #:optional printer)
2957 (make-struct/no-tail <standard-vtable>
2958 (make-struct-layout fields)
2959 printer))
2960 @end example
2961
2962
2963 @node Vtable Example
2964 @subsubsection Vtable Example
2965
2966 Let us bring these points together with an example. Consider a simple
2967 object system with single inheritance. Objects will be normal
2968 structures, and classes will be vtables with three extra class fields:
2969 the name of the class, the parent class, and the list of fields.
2970
2971 So, first we need a meta-vtable that allocates instances with these
2972 extra class fields.
2973
2974 @example
2975 (define <class>
2976 (make-vtable
2977 (string-append standard-vtable-fields "pwpwpw")
2978 (lambda (x port)
2979 (format port "<<class> ~a>" (class-name x)))))
2980
2981 (define (class? x)
2982 (and (struct? x)
2983 (eq? (struct-vtable x) <class>)))
2984 @end example
2985
2986 To make a structure with a specific meta-vtable, we will use
2987 @code{make-struct/no-tail}, passing it the computed instance layout and
2988 printer, as with @code{make-vtable}, and additionally the extra three
2989 class fields.
2990
2991 @example
2992 (define (make-class name parent fields)
2993 (let* ((fields (compute-fields parent fields))
2994 (layout (compute-layout fields)))
2995 (make-struct/no-tail <class>
2996 layout
2997 (lambda (x port)
2998 (print-instance x port))
2999 name
3000 parent
3001 fields)))
3002 @end example
3003
3004 Instances will store their associated data in slots in the structure: as
3005 many slots as there are fields. The @code{compute-layout} procedure
3006 below can compute a layout, and @code{field-index} returns the slot
3007 corresponding to a field.
3008
3009 @example
3010 (define-syntax-rule (define-accessor name n)
3011 (define (name obj)
3012 (struct-ref obj n)))
3013
3014 ;; Accessors for classes
3015 (define-accessor class-name (+ vtable-offset-user 0))
3016 (define-accessor class-parent (+ vtable-offset-user 1))
3017 (define-accessor class-fields (+ vtable-offset-user 2))
3018
3019 (define (compute-fields parent fields)
3020 (if parent
3021 (append (class-fields parent) fields)
3022 fields))
3023
3024 (define (compute-layout fields)
3025 (make-struct-layout
3026 (string-concatenate (make-list (length fields) "pw"))))
3027
3028 (define (field-index class field)
3029 (list-index (class-fields class) field))
3030
3031 (define (print-instance x port)
3032 (format port "<~a" (class-name (struct-vtable x)))
3033 (for-each (lambda (field idx)
3034 (format port " ~a: ~a" field (struct-ref x idx)))
3035 (class-fields (struct-vtable x))
3036 (iota (length (class-fields (struct-vtable x)))))
3037 (format port ">"))
3038 @end example
3039
3040 So, at this point we can actually make a few classes:
3041
3042 @example
3043 (define-syntax-rule (define-class name parent field ...)
3044 (define name (make-class 'name parent '(field ...))))
3045
3046 (define-class <surface> #f
3047 width height)
3048
3049 (define-class <window> <surface>
3050 x y)
3051 @end example
3052
3053 And finally, make an instance:
3054
3055 @example
3056 (make-struct/no-tail <window> 400 300 10 20)
3057 @result{} <<window> width: 400 height: 300 x: 10 y: 20>
3058 @end example
3059
3060 And that's that. Note that there are many possible optimizations and
3061 feature enhancements that can be made to this object system, and the
3062 included GOOPS system does make most of them. For more simple use
3063 cases, the records facility is usually sufficient. But sometimes you
3064 need to make new kinds of data abstractions, and for that purpose,
3065 structs are here.
3066
3067 @node Tail Arrays
3068 @subsubsection Tail Arrays
3069
3070 Guile's structures have a facility whereby each instance of a vtable can
3071 contain a variable-length tail array of values. The length of the tail
3072 array is stored in the structure. This facility was originally intended
3073 to allow C code to expose raw C structures with word-sized tail arrays
3074 to Scheme.
3075
3076 However, the tail array facility is confusing and doesn't work very
3077 well. It is very rarely used, but it insinuates itself into all
3078 invocations of @code{make-struct}. For this reason the clumsily-named
3079 @code{make-struct/no-tail} procedure can actually be more elegant in
3080 actual use, because it doesn't have a random @code{0} argument stuck in
3081 the middle.
3082
3083 Tail arrays also inhibit optimization by allowing instances to affect
3084 their shapes. In the absence of tail arrays, all instances of a given
3085 vtable have the same number and kinds of fields. This uniformity can be
3086 exploited by the runtime and the optimizer. The presence of tail arrays
3087 make some of these optimizations more difficult.
3088
3089 Finally, the tail array facility is ad-hoc and does not compose with the
3090 rest of Guile. If a Guile user wants an array with user-specified
3091 length, it's best to use a vector. It is more clear in the code, and
3092 the standard optimization techniques will do a good job with it.
3093
3094 That said, we should mention some details about the interface. A vtable
3095 that has tail array has upper-case permission descriptors: @code{W},
3096 @code{R} or @code{O}, correspoding to tail arrays of writable,
3097 read-only, or opaque elements. A tail array permission descriptor may
3098 only appear in the last element of a vtable layout.
3099
3100 For exampple, @samp{pW} indicates a tail of writable Scheme-valued
3101 fields. The @samp{pW} field itself holds the tail size, and the tail
3102 fields come after it.
3103
3104 @example
3105 (define v (make-vtable "prpW")) ;; one fixed then a tail array
3106 (define s (make-struct v 6 "fixed field" 'x 'y))
3107 (struct-ref s 0) @result{} "fixed field"
3108 (struct-ref s 1) @result{} 2 ;; tail size
3109 (struct-ref s 2) @result{} x ;; tail array ...
3110 (struct-ref s 3) @result{} y
3111 (struct-ref s 4) @result{} #f
3112 @end example
3113
3114
3115 @node Dictionary Types
3116 @subsection Dictionary Types
3117
3118 A @dfn{dictionary} object is a data structure used to index
3119 information in a user-defined way. In standard Scheme, the main
3120 aggregate data types are lists and vectors. Lists are not really
3121 indexed at all, and vectors are indexed only by number
3122 (e.g.@: @code{(vector-ref foo 5)}). Often you will find it useful
3123 to index your data on some other type; for example, in a library
3124 catalog you might want to look up a book by the name of its
3125 author. Dictionaries are used to help you organize information in
3126 such a way.
3127
3128 An @dfn{association list} (or @dfn{alist} for short) is a list of
3129 key-value pairs. Each pair represents a single quantity or
3130 object; the @code{car} of the pair is a key which is used to
3131 identify the object, and the @code{cdr} is the object's value.
3132
3133 A @dfn{hash table} also permits you to index objects with
3134 arbitrary keys, but in a way that makes looking up any one object
3135 extremely fast. A well-designed hash system makes hash table
3136 lookups almost as fast as conventional array or vector references.
3137
3138 Alists are popular among Lisp programmers because they use only
3139 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
3140 and the equality primitives). No changes to the language core are
3141 necessary. Therefore, with Scheme's built-in list manipulation
3142 facilities, it is very convenient to handle data stored in an
3143 association list. Also, alists are highly portable and can be
3144 easily implemented on even the most minimal Lisp systems.
3145
3146 However, alists are inefficient, especially for storing large
3147 quantities of data. Because we want Guile to be useful for large
3148 software systems as well as small ones, Guile provides a rich set
3149 of tools for using either association lists or hash tables.
3150
3151 @node Association Lists
3152 @subsection Association Lists
3153 @tpindex Association Lists
3154 @tpindex Alist
3155 @cindex association List
3156 @cindex alist
3157 @cindex database
3158
3159 An association list is a conventional data structure that is often used
3160 to implement simple key-value databases. It consists of a list of
3161 entries in which each entry is a pair. The @dfn{key} of each entry is
3162 the @code{car} of the pair and the @dfn{value} of each entry is the
3163 @code{cdr}.
3164
3165 @example
3166 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
3167 (KEY2 . VALUE2)
3168 (KEY3 . VALUE3)
3169 @dots{}
3170 )
3171 @end example
3172
3173 @noindent
3174 Association lists are also known, for short, as @dfn{alists}.
3175
3176 The structure of an association list is just one example of the infinite
3177 number of possible structures that can be built using pairs and lists.
3178 As such, the keys and values in an association list can be manipulated
3179 using the general list structure procedures @code{cons}, @code{car},
3180 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
3181 because association lists are so useful, Guile also provides specific
3182 procedures for manipulating them.
3183
3184 @menu
3185 * Alist Key Equality::
3186 * Adding or Setting Alist Entries::
3187 * Retrieving Alist Entries::
3188 * Removing Alist Entries::
3189 * Sloppy Alist Functions::
3190 * Alist Example::
3191 @end menu
3192
3193 @node Alist Key Equality
3194 @subsubsection Alist Key Equality
3195
3196 All of Guile's dedicated association list procedures, apart from
3197 @code{acons}, come in three flavours, depending on the level of equality
3198 that is required to decide whether an existing key in the association
3199 list is the same as the key that the procedure call uses to identify the
3200 required entry.
3201
3202 @itemize @bullet
3203 @item
3204 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
3205 equality.
3206
3207 @item
3208 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
3209 key equality.
3210
3211 @item
3212 Procedures with @dfn{assoc} in their name use @code{equal?} to
3213 determine key equality.
3214 @end itemize
3215
3216 @code{acons} is an exception because it is used to build association
3217 lists which do not require their entries' keys to be unique.
3218
3219 @node Adding or Setting Alist Entries
3220 @subsubsection Adding or Setting Alist Entries
3221
3222 @code{acons} adds a new entry to an association list and returns the
3223 combined association list. The combined alist is formed by consing the
3224 new entry onto the head of the alist specified in the @code{acons}
3225 procedure call. So the specified alist is not modified, but its
3226 contents become shared with the tail of the combined alist that
3227 @code{acons} returns.
3228
3229 In the most common usage of @code{acons}, a variable holding the
3230 original association list is updated with the combined alist:
3231
3232 @example
3233 (set! address-list (acons name address address-list))
3234 @end example
3235
3236 In such cases, it doesn't matter that the old and new values of
3237 @code{address-list} share some of their contents, since the old value is
3238 usually no longer independently accessible.
3239
3240 Note that @code{acons} adds the specified new entry regardless of
3241 whether the alist may already contain entries with keys that are, in
3242 some sense, the same as that of the new entry. Thus @code{acons} is
3243 ideal for building alists where there is no concept of key uniqueness.
3244
3245 @example
3246 (set! task-list (acons 3 "pay gas bill" '()))
3247 task-list
3248 @result{}
3249 ((3 . "pay gas bill"))
3250
3251 (set! task-list (acons 3 "tidy bedroom" task-list))
3252 task-list
3253 @result{}
3254 ((3 . "tidy bedroom") (3 . "pay gas bill"))
3255 @end example
3256
3257 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
3258 or replace an entry in an association list where there @emph{is} a
3259 concept of key uniqueness. If the specified association list already
3260 contains an entry whose key is the same as that specified in the
3261 procedure call, the existing entry is replaced by the new one.
3262 Otherwise, the new entry is consed onto the head of the old association
3263 list to create the combined alist. In all cases, these procedures
3264 return the combined alist.
3265
3266 @code{assq-set!} and friends @emph{may} destructively modify the
3267 structure of the old association list in such a way that an existing
3268 variable is correctly updated without having to @code{set!} it to the
3269 value returned:
3270
3271 @example
3272 address-list
3273 @result{}
3274 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
3275
3276 (assoc-set! address-list "james" "1a London Road")
3277 @result{}
3278 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3279
3280 address-list
3281 @result{}
3282 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3283 @end example
3284
3285 Or they may not:
3286
3287 @example
3288 (assoc-set! address-list "bob" "11 Newington Avenue")
3289 @result{}
3290 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3291 ("james" . "1a London Road"))
3292
3293 address-list
3294 @result{}
3295 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3296 @end example
3297
3298 The only safe way to update an association list variable when adding or
3299 replacing an entry like this is to @code{set!} the variable to the
3300 returned value:
3301
3302 @example
3303 (set! address-list
3304 (assoc-set! address-list "bob" "11 Newington Avenue"))
3305 address-list
3306 @result{}
3307 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3308 ("james" . "1a London Road"))
3309 @end example
3310
3311 Because of this slight inconvenience, you may find it more convenient to
3312 use hash tables to store dictionary data. If your application will not
3313 be modifying the contents of an alist very often, this may not make much
3314 difference to you.
3315
3316 If you need to keep the old value of an association list in a form
3317 independent from the list that results from modification by
3318 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
3319 use @code{list-copy} to copy the old association list before modifying
3320 it.
3321
3322 @deffn {Scheme Procedure} acons key value alist
3323 @deffnx {C Function} scm_acons (key, value, alist)
3324 Add a new key-value pair to @var{alist}. A new pair is
3325 created whose car is @var{key} and whose cdr is @var{value}, and the
3326 pair is consed onto @var{alist}, and the new list is returned. This
3327 function is @emph{not} destructive; @var{alist} is not modified.
3328 @end deffn
3329
3330 @deffn {Scheme Procedure} assq-set! alist key val
3331 @deffnx {Scheme Procedure} assv-set! alist key value
3332 @deffnx {Scheme Procedure} assoc-set! alist key value
3333 @deffnx {C Function} scm_assq_set_x (alist, key, val)
3334 @deffnx {C Function} scm_assv_set_x (alist, key, val)
3335 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
3336 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
3337 @var{alist} entry for @var{key} and associate it with the new
3338 @var{value}. If @var{alist} does not contain an entry for @var{key},
3339 add a new one. Return the (possibly new) alist.
3340
3341 These functions do not attempt to verify the structure of @var{alist},
3342 and so may cause unusual results if passed an object that is not an
3343 association list.
3344 @end deffn
3345
3346 @node Retrieving Alist Entries
3347 @subsubsection Retrieving Alist Entries
3348 @rnindex assq
3349 @rnindex assv
3350 @rnindex assoc
3351
3352 @code{assq}, @code{assv} and @code{assoc} find the entry in an alist
3353 for a given key, and return the @code{(@var{key} . @var{value})} pair.
3354 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref} do a similar
3355 lookup, but return just the @var{value}.
3356
3357 @deffn {Scheme Procedure} assq key alist
3358 @deffnx {Scheme Procedure} assv key alist
3359 @deffnx {Scheme Procedure} assoc key alist
3360 @deffnx {C Function} scm_assq (key, alist)
3361 @deffnx {C Function} scm_assv (key, alist)
3362 @deffnx {C Function} scm_assoc (key, alist)
3363 Return the first entry in @var{alist} with the given @var{key}. The
3364 return is the pair @code{(KEY . VALUE)} from @var{alist}. If there's
3365 no matching entry the return is @code{#f}.
3366
3367 @code{assq} compares keys with @code{eq?}, @code{assv} uses
3368 @code{eqv?} and @code{assoc} uses @code{equal?}. See also SRFI-1
3369 which has an extended @code{assoc} (@ref{SRFI-1 Association Lists}).
3370 @end deffn
3371
3372 @deffn {Scheme Procedure} assq-ref alist key
3373 @deffnx {Scheme Procedure} assv-ref alist key
3374 @deffnx {Scheme Procedure} assoc-ref alist key
3375 @deffnx {C Function} scm_assq_ref (alist, key)
3376 @deffnx {C Function} scm_assv_ref (alist, key)
3377 @deffnx {C Function} scm_assoc_ref (alist, key)
3378 Return the value from the first entry in @var{alist} with the given
3379 @var{key}, or @code{#f} if there's no such entry.
3380
3381 @code{assq-ref} compares keys with @code{eq?}, @code{assv-ref} uses
3382 @code{eqv?} and @code{assoc-ref} uses @code{equal?}.
3383
3384 Notice these functions have the @var{key} argument last, like other
3385 @code{-ref} functions, but this is opposite to what @code{assq}
3386 etc above use.
3387
3388 When the return is @code{#f} it can be either @var{key} not found, or
3389 an entry which happens to have value @code{#f} in the @code{cdr}. Use
3390 @code{assq} etc above if you need to differentiate these cases.
3391 @end deffn
3392
3393
3394 @node Removing Alist Entries
3395 @subsubsection Removing Alist Entries
3396
3397 To remove the element from an association list whose key matches a
3398 specified key, use @code{assq-remove!}, @code{assv-remove!} or
3399 @code{assoc-remove!} (depending, as usual, on the level of equality
3400 required between the key that you specify and the keys in the
3401 association list).
3402
3403 As with @code{assq-set!} and friends, the specified alist may or may not
3404 be modified destructively, and the only safe way to update a variable
3405 containing the alist is to @code{set!} it to the value that
3406 @code{assq-remove!} and friends return.
3407
3408 @example
3409 address-list
3410 @result{}
3411 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3412 ("james" . "1a London Road"))
3413
3414 (set! address-list (assoc-remove! address-list "mary"))
3415 address-list
3416 @result{}
3417 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
3418 @end example
3419
3420 Note that, when @code{assq/v/oc-remove!} is used to modify an
3421 association list that has been constructed only using the corresponding
3422 @code{assq/v/oc-set!}, there can be at most one matching entry in the
3423 alist, so the question of multiple entries being removed in one go does
3424 not arise. If @code{assq/v/oc-remove!} is applied to an association
3425 list that has been constructed using @code{acons}, or an
3426 @code{assq/v/oc-set!} with a different level of equality, or any mixture
3427 of these, it removes only the first matching entry from the alist, even
3428 if the alist might contain further matching entries. For example:
3429
3430 @example
3431 (define address-list '())
3432 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
3433 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
3434 address-list
3435 @result{}
3436 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
3437
3438 (set! address-list (assoc-remove! address-list "mary"))
3439 address-list
3440 @result{}
3441 (("mary" . "11 Elm Street"))
3442 @end example
3443
3444 In this example, the two instances of the string "mary" are not the same
3445 when compared using @code{eq?}, so the two @code{assq-set!} calls add
3446 two distinct entries to @code{address-list}. When compared using
3447 @code{equal?}, both "mary"s in @code{address-list} are the same as the
3448 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
3449 after removing the first matching entry that it finds, and so one of the
3450 "mary" entries is left in place.
3451
3452 @deffn {Scheme Procedure} assq-remove! alist key
3453 @deffnx {Scheme Procedure} assv-remove! alist key
3454 @deffnx {Scheme Procedure} assoc-remove! alist key
3455 @deffnx {C Function} scm_assq_remove_x (alist, key)
3456 @deffnx {C Function} scm_assv_remove_x (alist, key)
3457 @deffnx {C Function} scm_assoc_remove_x (alist, key)
3458 Delete the first entry in @var{alist} associated with @var{key}, and return
3459 the resulting alist.
3460 @end deffn
3461
3462 @node Sloppy Alist Functions
3463 @subsubsection Sloppy Alist Functions
3464
3465 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
3466 like the corresponding non-@code{sloppy-} procedures, except that they
3467 return @code{#f} when the specified association list is not well-formed,
3468 where the non-@code{sloppy-} versions would signal an error.
3469
3470 Specifically, there are two conditions for which the non-@code{sloppy-}
3471 procedures signal an error, which the @code{sloppy-} procedures handle
3472 instead by returning @code{#f}. Firstly, if the specified alist as a
3473 whole is not a proper list:
3474
3475 @example
3476 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3477 @result{}
3478 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
3479 ERROR: Wrong type argument in position 2 (expecting
3480 association list): ((1 . 2) ("key" . "door") . "open sesame")
3481
3482 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3483 @result{}
3484 #f
3485 @end example
3486
3487 @noindent
3488 Secondly, if one of the entries in the specified alist is not a pair:
3489
3490 @example
3491 (assoc 2 '((1 . 1) 2 (3 . 9)))
3492 @result{}
3493 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
3494 ERROR: Wrong type argument in position 2 (expecting
3495 association list): ((1 . 1) 2 (3 . 9))
3496
3497 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
3498 @result{}
3499 #f
3500 @end example
3501
3502 Unless you are explicitly working with badly formed association lists,
3503 it is much safer to use the non-@code{sloppy-} procedures, because they
3504 help to highlight coding and data errors that the @code{sloppy-}
3505 versions would silently cover up.
3506
3507 @deffn {Scheme Procedure} sloppy-assq key alist
3508 @deffnx {C Function} scm_sloppy_assq (key, alist)
3509 Behaves like @code{assq} but does not do any error checking.
3510 Recommended only for use in Guile internals.
3511 @end deffn
3512
3513 @deffn {Scheme Procedure} sloppy-assv key alist
3514 @deffnx {C Function} scm_sloppy_assv (key, alist)
3515 Behaves like @code{assv} but does not do any error checking.
3516 Recommended only for use in Guile internals.
3517 @end deffn
3518
3519 @deffn {Scheme Procedure} sloppy-assoc key alist
3520 @deffnx {C Function} scm_sloppy_assoc (key, alist)
3521 Behaves like @code{assoc} but does not do any error checking.
3522 Recommended only for use in Guile internals.
3523 @end deffn
3524
3525 @node Alist Example
3526 @subsubsection Alist Example
3527
3528 Here is a longer example of how alists may be used in practice.
3529
3530 @lisp
3531 (define capitals '(("New York" . "Albany")
3532 ("Oregon" . "Salem")
3533 ("Florida" . "Miami")))
3534
3535 ;; What's the capital of Oregon?
3536 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
3537 (assoc-ref capitals "Oregon") @result{} "Salem"
3538
3539 ;; We left out South Dakota.
3540 (set! capitals
3541 (assoc-set! capitals "South Dakota" "Pierre"))
3542 capitals
3543 @result{} (("South Dakota" . "Pierre")
3544 ("New York" . "Albany")
3545 ("Oregon" . "Salem")
3546 ("Florida" . "Miami"))
3547
3548 ;; And we got Florida wrong.
3549 (set! capitals
3550 (assoc-set! capitals "Florida" "Tallahassee"))
3551 capitals
3552 @result{} (("South Dakota" . "Pierre")
3553 ("New York" . "Albany")
3554 ("Oregon" . "Salem")
3555 ("Florida" . "Tallahassee"))
3556
3557 ;; After Oregon secedes, we can remove it.
3558 (set! capitals
3559 (assoc-remove! capitals "Oregon"))
3560 capitals
3561 @result{} (("South Dakota" . "Pierre")
3562 ("New York" . "Albany")
3563 ("Florida" . "Tallahassee"))
3564 @end lisp
3565
3566 @node VHashes
3567 @subsection VList-Based Hash Lists or ``VHashes''
3568
3569 @cindex VList-based hash lists
3570 @cindex VHash
3571
3572 The @code{(ice-9 vlist)} module provides an implementation of @dfn{VList-based
3573 hash lists} (@pxref{VLists}). VList-based hash lists, or @dfn{vhashes}, are an
3574 immutable dictionary type similar to association lists that maps @dfn{keys} to
3575 @dfn{values}. However, unlike association lists, accessing a value given its
3576 key is typically a constant-time operation.
3577
3578 The VHash programming interface of @code{(ice-9 vlist)} is mostly the same as
3579 that of association lists found in SRFI-1, with procedure names prefixed by
3580 @code{vhash-} instead of @code{alist-} (@pxref{SRFI-1 Association Lists}).
3581
3582 In addition, vhashes can be manipulated using VList operations:
3583
3584 @example
3585 (vlist-head (vhash-consq 'a 1 vlist-null))
3586 @result{} (a . 1)
3587
3588 (define vh1 (vhash-consq 'b 2 (vhash-consq 'a 1 vlist-null)))
3589 (define vh2 (vhash-consq 'c 3 (vlist-tail vh1)))
3590
3591 (vhash-assq 'a vh2)
3592 @result{} (a . 1)
3593 (vhash-assq 'b vh2)
3594 @result{} #f
3595 (vhash-assq 'c vh2)
3596 @result{} (c . 3)
3597 (vlist->list vh2)
3598 @result{} ((c . 3) (a . 1))
3599 @end example
3600
3601 However, keep in mind that procedures that construct new VLists
3602 (@code{vlist-map}, @code{vlist-filter}, etc.) return raw VLists, not vhashes:
3603
3604 @example
3605 (define vh (alist->vhash '((a . 1) (b . 2) (c . 3)) hashq))
3606 (vhash-assq 'a vh)
3607 @result{} (a . 1)
3608
3609 (define vl
3610 ;; This will create a raw vlist.
3611 (vlist-filter (lambda (key+value) (odd? (cdr key+value))) vh))
3612 (vhash-assq 'a vl)
3613 @result{} ERROR: Wrong type argument in position 2
3614
3615 (vlist->list vl)
3616 @result{} ((a . 1) (c . 3))
3617 @end example
3618
3619 @deffn {Scheme Procedure} vhash? obj
3620 Return true if @var{obj} is a vhash.
3621 @end deffn
3622
3623 @deffn {Scheme Procedure} vhash-cons key value vhash [hash-proc]
3624 @deffnx {Scheme Procedure} vhash-consq key value vhash
3625 @deffnx {Scheme Procedure} vhash-consv key value vhash
3626 Return a new hash list based on @var{vhash} where @var{key} is associated with
3627 @var{value}, using @var{hash-proc} to compute the hash of @var{key}.
3628 @var{vhash} must be either @code{vlist-null} or a vhash returned by a previous
3629 call to @code{vhash-cons}. @var{hash-proc} defaults to @code{hash} (@pxref{Hash
3630 Table Reference, @code{hash} procedure}). With @code{vhash-consq}, the
3631 @code{hashq} hash function is used; with @code{vhash-consv} the @code{hashv}
3632 hash function is used.
3633
3634 All @code{vhash-cons} calls made to construct a vhash should use the same
3635 @var{hash-proc}. Failing to do that, the result is undefined.
3636 @end deffn
3637
3638 @deffn {Scheme Procedure} vhash-assoc key vhash [equal? [hash-proc]]
3639 @deffnx {Scheme Procedure} vhash-assq key vhash
3640 @deffnx {Scheme Procedure} vhash-assv key vhash
3641 Return the first key/value pair from @var{vhash} whose key is equal to @var{key}
3642 according to the @var{equal?} equality predicate (which defaults to
3643 @code{equal?}), and using @var{hash-proc} (which defaults to @code{hash}) to
3644 compute the hash of @var{key}. The second form uses @code{eq?} as the equality
3645 predicate and @code{hashq} as the hash function; the last form uses @code{eqv?}
3646 and @code{hashv}.
3647
3648 Note that it is important to consistently use the same hash function for
3649 @var{hash-proc} as was passed to @code{vhash-cons}. Failing to do that, the
3650 result is unpredictable.
3651 @end deffn
3652
3653 @deffn {Scheme Procedure} vhash-delete key vhash [equal? [hash-proc]]
3654 @deffnx {Scheme Procedure} vhash-delq key vhash
3655 @deffnx {Scheme Procedure} vhash-delv key vhash
3656 Remove all associations from @var{vhash} with @var{key}, comparing keys with
3657 @var{equal?} (which defaults to @code{equal?}), and computing the hash of
3658 @var{key} using @var{hash-proc} (which defaults to @code{hash}). The second
3659 form uses @code{eq?} as the equality predicate and @code{hashq} as the hash
3660 function; the last one uses @code{eqv?} and @code{hashv}.
3661
3662 Again the choice of @var{hash-proc} must be consistent with previous calls to
3663 @code{vhash-cons}.
3664 @end deffn
3665
3666 @deffn {Scheme Procedure} vhash-fold proc init vhash
3667 @deffnx {Scheme Procedure} vhash-fold-right proc init vhash
3668 Fold over the key/value elements of @var{vhash} in the given direction,
3669 with each call to @var{proc} having the form @code{(@var{proc} key value
3670 result)}, where @var{result} is the result of the previous call to
3671 @var{proc} and @var{init} the value of @var{result} for the first call
3672 to @var{proc}.
3673 @end deffn
3674
3675 @deffn {Scheme Procedure} vhash-fold* proc init key vhash [equal? [hash]]
3676 @deffnx {Scheme Procedure} vhash-foldq* proc init key vhash
3677 @deffnx {Scheme Procedure} vhash-foldv* proc init key vhash
3678 Fold over all the values associated with @var{key} in @var{vhash}, with each
3679 call to @var{proc} having the form @code{(proc value result)}, where
3680 @var{result} is the result of the previous call to @var{proc} and @var{init} the
3681 value of @var{result} for the first call to @var{proc}.
3682
3683 Keys in @var{vhash} are hashed using @var{hash} are compared using @var{equal?}.
3684 The second form uses @code{eq?} as the equality predicate and @code{hashq} as
3685 the hash function; the third one uses @code{eqv?} and @code{hashv}.
3686
3687 Example:
3688
3689 @example
3690 (define vh
3691 (alist->vhash '((a . 1) (a . 2) (z . 0) (a . 3))))
3692
3693 (vhash-fold* cons '() 'a vh)
3694 @result{} (3 2 1)
3695
3696 (vhash-fold* cons '() 'z vh)
3697 @result{} (0)
3698 @end example
3699 @end deffn
3700
3701 @deffn {Scheme Procedure} alist->vhash alist [hash-proc]
3702 Return the vhash corresponding to @var{alist}, an association list, using
3703 @var{hash-proc} to compute key hashes. When omitted, @var{hash-proc} defaults
3704 to @code{hash}.
3705 @end deffn
3706
3707
3708 @node Hash Tables
3709 @subsection Hash Tables
3710 @tpindex Hash Tables
3711
3712 Hash tables are dictionaries which offer similar functionality as
3713 association lists: They provide a mapping from keys to values. The
3714 difference is that association lists need time linear in the size of
3715 elements when searching for entries, whereas hash tables can normally
3716 search in constant time. The drawback is that hash tables require a
3717 little bit more memory, and that you can not use the normal list
3718 procedures (@pxref{Lists}) for working with them.
3719
3720 Guile provides two types of hashtables. One is an abstract data type
3721 that can only be manipulated with the functions in this section. The
3722 other type is concrete: it uses a normal vector with alists as
3723 elements. The advantage of the abstract hash tables is that they will
3724 be automatically resized when they become too full or too empty.
3725
3726 @menu
3727 * Hash Table Examples:: Demonstration of hash table usage.
3728 * Hash Table Reference:: Hash table procedure descriptions.
3729 @end menu
3730
3731
3732 @node Hash Table Examples
3733 @subsubsection Hash Table Examples
3734
3735 For demonstration purposes, this section gives a few usage examples of
3736 some hash table procedures, together with some explanation what they do.
3737
3738 First we start by creating a new hash table with 31 slots, and
3739 populate it with two key/value pairs.
3740
3741 @lisp
3742 (define h (make-hash-table 31))
3743
3744 ;; This is an opaque object
3745 h
3746 @result{}
3747 #<hash-table 0/31>
3748
3749 ;; We can also use a vector of alists.
3750 (define h (make-vector 7 '()))
3751
3752 h
3753 @result{}
3754 #(() () () () () () ())
3755
3756 ;; Inserting into a hash table can be done with hashq-set!
3757 (hashq-set! h 'foo "bar")
3758 @result{}
3759 "bar"
3760
3761 (hashq-set! h 'braz "zonk")
3762 @result{}
3763 "zonk"
3764
3765 ;; Or with hash-create-handle!
3766 (hashq-create-handle! h 'frob #f)
3767 @result{}
3768 (frob . #f)
3769
3770 ;; The vector now contains three elements in the alists and the frob
3771 ;; entry is at index (hashq 'frob).
3772 h
3773 @result{}
3774 #(((braz . "zonk")) ((foo . "bar")) () () () () ((frob . #f)))
3775
3776 (hashq 'frob 7)
3777 @result{}
3778 6
3779
3780 @end lisp
3781
3782 You can get the value for a given key with the procedure
3783 @code{hashq-ref}, but the problem with this procedure is that you
3784 cannot reliably determine whether a key does exists in the table. The
3785 reason is that the procedure returns @code{#f} if the key is not in
3786 the table, but it will return the same value if the key is in the
3787 table and just happens to have the value @code{#f}, as you can see in
3788 the following examples.
3789
3790 @lisp
3791 (hashq-ref h 'foo)
3792 @result{}
3793 "bar"
3794
3795 (hashq-ref h 'frob)
3796 @result{}
3797 #f
3798
3799 (hashq-ref h 'not-there)
3800 @result{}
3801 #f
3802 @end lisp
3803
3804 Better is to use the procedure @code{hashq-get-handle}, which makes a
3805 distinction between the two cases. Just like @code{assq}, this
3806 procedure returns a key/value-pair on success, and @code{#f} if the
3807 key is not found.
3808
3809 @lisp
3810 (hashq-get-handle h 'foo)
3811 @result{}
3812 (foo . "bar")
3813
3814 (hashq-get-handle h 'not-there)
3815 @result{}
3816 #f
3817 @end lisp
3818
3819 There is no procedure for calculating the number of key/value-pairs in
3820 a hash table, but @code{hash-fold} can be used for doing exactly that.
3821
3822 @lisp
3823 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
3824 @result{}
3825 3
3826 @end lisp
3827
3828 @node Hash Table Reference
3829 @subsubsection Hash Table Reference
3830
3831 @c FIXME: Describe in broad terms what happens for resizing, and what
3832 @c the initial size means for this.
3833
3834 Like the association list functions, the hash table functions come in
3835 several varieties, according to the equality test used for the keys.
3836 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
3837 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
3838 the @code{hashx-} functions use an application supplied test.
3839
3840 A single @code{make-hash-table} creates a hash table suitable for use
3841 with any set of functions, but it's imperative that just one set is
3842 then used consistently, or results will be unpredictable.
3843
3844 Hash tables are implemented as a vector indexed by a hash value formed
3845 from the key, with an association list of key/value pairs for each
3846 bucket in case distinct keys hash together. Direct access to the
3847 pairs in those lists is provided by the @code{-handle-} functions.
3848 The abstract kind of hash tables hide the vector in an opaque object
3849 that represents the hash table, while for the concrete kind the vector
3850 @emph{is} the hashtable.
3851
3852 When the number of table entries in an abstract hash table goes above
3853 a threshold, the vector is made larger and the entries are rehashed,
3854 to prevent the bucket lists from becoming too long and slowing down
3855 accesses. When the number of entries goes below a threshold, the
3856 vector is shrunk to save space.
3857
3858 A abstract hash table is created with @code{make-hash-table}. To
3859 create a vector that is suitable as a hash table, use
3860 @code{(make-vector @var{size} '())}, for example.
3861
3862 For the @code{hashx-} ``extended'' routines, an application supplies a
3863 @var{hash} function producing an integer index like @code{hashq} etc
3864 below, and an @var{assoc} alist search function like @code{assq} etc
3865 (@pxref{Retrieving Alist Entries}). Here's an example of such
3866 functions implementing case-insensitive hashing of string keys,
3867
3868 @example
3869 (use-modules (srfi srfi-1)
3870 (srfi srfi-13))
3871
3872 (define (my-hash str size)
3873 (remainder (string-hash-ci str) size))
3874 (define (my-assoc str alist)
3875 (find (lambda (pair) (string-ci=? str (car pair))) alist))
3876
3877 (define my-table (make-hash-table))
3878 (hashx-set! my-hash my-assoc my-table "foo" 123)
3879
3880 (hashx-ref my-hash my-assoc my-table "FOO")
3881 @result{} 123
3882 @end example
3883
3884 In a @code{hashx-} @var{hash} function the aim is to spread keys
3885 across the vector, so bucket lists don't become long. But the actual
3886 values are arbitrary as long as they're in the range 0 to
3887 @math{@var{size}-1}. Helpful functions for forming a hash value, in
3888 addition to @code{hashq} etc below, include @code{symbol-hash}
3889 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
3890 (@pxref{String Comparison}), and @code{char-set-hash}
3891 (@pxref{Character Set Predicates/Comparison}).
3892
3893 @sp 1
3894 @deffn {Scheme Procedure} make-hash-table [size]
3895 Create a new abstract hash table object, with an optional minimum
3896 vector @var{size}.
3897
3898 When @var{size} is given, the table vector will still grow and shrink
3899 automatically, as described above, but with @var{size} as a minimum.
3900 If an application knows roughly how many entries the table will hold
3901 then it can use @var{size} to avoid rehashing when initial entries are
3902 added.
3903 @end deffn
3904
3905 @deffn {Scheme Procedure} hash-table? obj
3906 @deffnx {C Function} scm_hash_table_p (obj)
3907 Return @code{#t} if @var{obj} is a abstract hash table object.
3908 @end deffn
3909
3910 @deffn {Scheme Procedure} hash-clear! table
3911 @deffnx {C Function} scm_hash_clear_x (table)
3912 Remove all items from @var{table} (without triggering a resize).
3913 @end deffn
3914
3915 @deffn {Scheme Procedure} hash-ref table key [dflt]
3916 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
3917 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
3918 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
3919 @deffnx {C Function} scm_hash_ref (table, key, dflt)
3920 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
3921 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
3922 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
3923 Lookup @var{key} in the given hash @var{table}, and return the
3924 associated value. If @var{key} is not found, return @var{dflt}, or
3925 @code{#f} if @var{dflt} is not given.
3926 @end deffn
3927
3928 @deffn {Scheme Procedure} hash-set! table key val
3929 @deffnx {Scheme Procedure} hashq-set! table key val
3930 @deffnx {Scheme Procedure} hashv-set! table key val
3931 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
3932 @deffnx {C Function} scm_hash_set_x (table, key, val)
3933 @deffnx {C Function} scm_hashq_set_x (table, key, val)
3934 @deffnx {C Function} scm_hashv_set_x (table, key, val)
3935 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
3936 Associate @var{val} with @var{key} in the given hash @var{table}. If
3937 @var{key} is already present then it's associated value is changed.
3938 If it's not present then a new entry is created.
3939 @end deffn
3940
3941 @deffn {Scheme Procedure} hash-remove! table key
3942 @deffnx {Scheme Procedure} hashq-remove! table key
3943 @deffnx {Scheme Procedure} hashv-remove! table key
3944 @deffnx {Scheme Procedure} hashx-remove! hash assoc table key
3945 @deffnx {C Function} scm_hash_remove_x (table, key)
3946 @deffnx {C Function} scm_hashq_remove_x (table, key)
3947 @deffnx {C Function} scm_hashv_remove_x (table, key)
3948 @deffnx {C Function} scm_hashx_remove_x (hash, assoc, table, key)
3949 Remove any association for @var{key} in the given hash @var{table}.
3950 If @var{key} is not in @var{table} then nothing is done.
3951 @end deffn
3952
3953 @deffn {Scheme Procedure} hash key size
3954 @deffnx {Scheme Procedure} hashq key size
3955 @deffnx {Scheme Procedure} hashv key size
3956 @deffnx {C Function} scm_hash (key, size)
3957 @deffnx {C Function} scm_hashq (key, size)
3958 @deffnx {C Function} scm_hashv (key, size)
3959 Return a hash value for @var{key}. This is a number in the range
3960 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
3961 table of the given @var{size}.
3962
3963 Note that @code{hashq} and @code{hashv} may use internal addresses of
3964 objects, so if an object is garbage collected and re-created it can
3965 have a different hash value, even when the two are notionally
3966 @code{eq?}. For instance with symbols,
3967
3968 @example
3969 (hashq 'something 123) @result{} 19
3970 (gc)
3971 (hashq 'something 123) @result{} 62
3972 @end example
3973
3974 In normal use this is not a problem, since an object entered into a
3975 hash table won't be garbage collected until removed. It's only if
3976 hashing calculations are somehow separated from normal references that
3977 its lifetime needs to be considered.
3978 @end deffn
3979
3980 @deffn {Scheme Procedure} hash-get-handle table key
3981 @deffnx {Scheme Procedure} hashq-get-handle table key
3982 @deffnx {Scheme Procedure} hashv-get-handle table key
3983 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
3984 @deffnx {C Function} scm_hash_get_handle (table, key)
3985 @deffnx {C Function} scm_hashq_get_handle (table, key)
3986 @deffnx {C Function} scm_hashv_get_handle (table, key)
3987 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
3988 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3989 given hash @var{table}, or @code{#f} if @var{key} is not in
3990 @var{table}.
3991 @end deffn
3992
3993 @deffn {Scheme Procedure} hash-create-handle! table key init
3994 @deffnx {Scheme Procedure} hashq-create-handle! table key init
3995 @deffnx {Scheme Procedure} hashv-create-handle! table key init
3996 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
3997 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
3998 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
3999 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
4000 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
4001 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
4002 given hash @var{table}. If @var{key} is not in @var{table} then
4003 create an entry for it with @var{init} as the value, and return that
4004 pair.
4005 @end deffn
4006
4007 @deffn {Scheme Procedure} hash-map->list proc table
4008 @deffnx {Scheme Procedure} hash-for-each proc table
4009 @deffnx {C Function} scm_hash_map_to_list (proc, table)
4010 @deffnx {C Function} scm_hash_for_each (proc, table)
4011 Apply @var{proc} to the entries in the given hash @var{table}. Each
4012 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
4013 returns a list of the results from these calls, @code{hash-for-each}
4014 discards the results and returns an unspecified value.
4015
4016 Calls are made over the table entries in an unspecified order, and for
4017 @code{hash-map->list} the order of the values in the returned list is
4018 unspecified. Results will be unpredictable if @var{table} is modified
4019 while iterating.
4020
4021 For example the following returns a new alist comprising all the
4022 entries from @code{mytable}, in no particular order.
4023
4024 @example
4025 (hash-map->list cons mytable)
4026 @end example
4027 @end deffn
4028
4029 @deffn {Scheme Procedure} hash-for-each-handle proc table
4030 @deffnx {C Function} scm_hash_for_each_handle (proc, table)
4031 Apply @var{proc} to the entries in the given hash @var{table}. Each
4032 call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
4033 @code{(@var{key} . @var{value})} pair. Return an unspecified value.
4034
4035 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
4036 the argument list of @var{proc}.
4037 @end deffn
4038
4039 @deffn {Scheme Procedure} hash-fold proc init table
4040 @deffnx {C Function} scm_hash_fold (proc, init, table)
4041 Accumulate a result by applying @var{proc} to the elements of the
4042 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
4043 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
4044 from the @var{table} and @var{prior-result} is the return from the
4045 previous @var{proc} call. For the first call, @var{prior-result} is
4046 the given @var{init} value.
4047
4048 Calls are made over the table entries in an unspecified order.
4049 Results will be unpredictable if @var{table} is modified while
4050 @code{hash-fold} is running.
4051
4052 For example, the following returns a count of how many keys in
4053 @code{mytable} are strings.
4054
4055 @example
4056 (hash-fold (lambda (key value prior)
4057 (if (string? key) (1+ prior) prior))
4058 0 mytable)
4059 @end example
4060 @end deffn
4061
4062
4063 @c Local Variables:
4064 @c TeX-master: "guile.texi"
4065 @c End: