* scheme-binding.texi: Renamed to api-binding.texi.
[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
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node Compound Data Types
9 @section Compound Data Types
10
11 This chapter describes Guile's compound data types. By @dfn{compound}
12 we mean that the primary purpose of these data types is to act as
13 containers for other kinds of data (including other compound objects).
14 For instance, a (non-uniform) vector with length 5 is a container that
15 can hold five arbitrary Scheme objects.
16
17 The various kinds of container object differ from each other in how
18 their memory is allocated, how they are indexed, and how particular
19 values can be looked up within them.
20
21 @menu
22 * Pairs:: Scheme's basic building block.
23 * Lists:: Special list functions supported by Guile.
24 * Vectors:: One-dimensional arrays of Scheme objects.
25 * Records::
26 * Structures::
27 * Arrays:: Arrays of values.
28 * Dictionary Types:: About dictionary types in general.
29 * Association Lists:: List-based dictionaries.
30 * Hash Tables:: Table-based dictionaries.
31 @end menu
32
33
34 @node Pairs
35 @subsection Pairs
36 @tpindex Pairs
37
38 Pairs are used to combine two Scheme objects into one compound object.
39 Hence the name: A pair stores a pair of objects.
40
41 The data type @dfn{pair} is extremely important in Scheme, just like in
42 any other Lisp dialect. The reason is that pairs are not only used to
43 make two values available as one object, but that pairs are used for
44 constructing lists of values. Because lists are so important in Scheme,
45 they are described in a section of their own (@pxref{Lists}).
46
47 Pairs can literally get entered in source code or at the REPL, in the
48 so-called @dfn{dotted list} syntax. This syntax consists of an opening
49 parentheses, the first element of the pair, a dot, the second element
50 and a closing parentheses. The following example shows how a pair
51 consisting of the two numbers 1 and 2, and a pair containing the symbols
52 @code{foo} and @code{bar} can be entered. It is very important to write
53 the whitespace before and after the dot, because otherwise the Scheme
54 parser would not be able to figure out where to split the tokens.
55
56 @lisp
57 (1 . 2)
58 (foo . bar)
59 @end lisp
60
61 But beware, if you want to try out these examples, you have to
62 @dfn{quote} the expressions. More information about quotation is
63 available in the section (REFFIXME). The correct way to try these
64 examples is as follows.
65
66 @lisp
67 '(1 . 2)
68 @result{}
69 (1 . 2)
70 '(foo . bar)
71 @result{}
72 (foo . bar)
73 @end lisp
74
75 A new pair is made by calling the procedure @code{cons} with two
76 arguments. Then the argument values are stored into a newly allocated
77 pair, and the pair is returned. The name @code{cons} stands for
78 "construct". Use the procedure @code{pair?} to test whether a
79 given Scheme object is a pair or not.
80
81 @rnindex cons
82 @deffn {Scheme Procedure} cons x y
83 @deffnx {C Function} scm_cons (x, y)
84 Return a newly allocated pair whose car is @var{x} and whose
85 cdr is @var{y}. The pair is guaranteed to be different (in the
86 sense of @code{eq?}) from every previously existing object.
87 @end deffn
88
89 @rnindex pair?
90 @deffn {Scheme Procedure} pair? x
91 @deffnx {C Function} scm_pair_p (x)
92 Return @code{#t} if @var{x} is a pair; otherwise return
93 @code{#f}.
94 @end deffn
95
96 The two parts of a pair are traditionally called @dfn{car} and
97 @dfn{cdr}. They can be retrieved with procedures of the same name
98 (@code{car} and @code{cdr}), and can be modified with the procedures
99 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
100 Scheme programs is to access the car of a pair, or the car of the cdr of
101 a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
102 are also predefined.
103
104 @rnindex car
105 @rnindex cdr
106 @deffn {Scheme Procedure} car pair
107 @deffnx {Scheme Procedure} cdr pair
108 Return the car or the cdr of @var{pair}, respectively.
109 @end deffn
110
111 @deffn {Scheme Procedure} caar pair
112 @deffnx {Scheme Procedure} cadr pair @dots{}
113 @deffnx {Scheme Procedure} cdddar pair
114 @deffnx {Scheme Procedure} cddddr pair
115 These procedures are compositions of @code{car} and @code{cdr}, where
116 for example @code{caddr} could be defined by
117
118 @lisp
119 (define caddr (lambda (x) (car (cdr (cdr x)))))
120 @end lisp
121 @end deffn
122
123 @rnindex set-car!
124 @deffn {Scheme Procedure} set-car! pair value
125 @deffnx {C Function} scm_set_car_x (pair, value)
126 Stores @var{value} in the car field of @var{pair}. The value returned
127 by @code{set-car!} is unspecified.
128 @end deffn
129
130 @rnindex set-cdr!
131 @deffn {Scheme Procedure} set-cdr! pair value
132 @deffnx {C Function} scm_set_cdr_x (pair, value)
133 Stores @var{value} in the cdr field of @var{pair}. The value returned
134 by @code{set-cdr!} is unspecified.
135 @end deffn
136
137
138 @node Lists
139 @subsection Lists
140 @tpindex Lists
141
142 A very important data type in Scheme---as well as in all other Lisp
143 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
144 Scheme does not have a real datatype @dfn{list}. Lists are made up of
145 @dfn{chained pairs}, and only exist by definition---a list is a chain
146 of pairs which looks like a list.}
147
148 This is the short definition of what a list is:
149
150 @itemize @bullet
151 @item
152 Either the empty list @code{()},
153
154 @item
155 or a pair which has a list in its cdr.
156 @end itemize
157
158 @c FIXME::martin: Describe the pair chaining in more detail.
159
160 @c FIXME::martin: What is a proper, what an improper list?
161 @c What is a circular list?
162
163 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
164 @c manual?
165
166 @menu
167 * List Syntax:: Writing literal lists.
168 * List Predicates:: Testing lists.
169 * List Constructors:: Creating new lists.
170 * List Selection:: Selecting from lists, getting their length.
171 * Append/Reverse:: Appending and reversing lists.
172 * List Modification:: Modifying existing lists.
173 * List Searching:: Searching for list elements
174 * List Mapping:: Applying procedures to lists.
175 @end menu
176
177 @node List Syntax
178 @subsubsection List Read Syntax
179
180 The syntax for lists is an opening parentheses, then all the elements of
181 the list (separated by whitespace) and finally a closing
182 parentheses.@footnote{Note that there is no separation character between
183 the list elements, like a comma or a semicolon.}.
184
185 @lisp
186 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
187 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
188 () ; @r{the empty list}
189 @end lisp
190
191 The last example needs a bit more explanation. A list with no elements,
192 called the @dfn{empty list}, is special in some ways. It is used for
193 terminating lists by storing it into the cdr of the last pair that makes
194 up a list. An example will clear that up:
195
196 @lisp
197 (car '(1))
198 @result{}
199 1
200 (cdr '(1))
201 @result{}
202 ()
203 @end lisp
204
205 This example also shows that lists have to be quoted (REFFIXME) when
206 written, because they would otherwise be mistakingly taken as procedure
207 applications (@pxref{Simple Invocation}).
208
209
210 @node List Predicates
211 @subsubsection List Predicates
212
213 Often it is useful to test whether a given Scheme object is a list or
214 not. List-processing procedures could use this information to test
215 whether their input is valid, or they could do different things
216 depending on the datatype of their arguments.
217
218 @rnindex list?
219 @deffn {Scheme Procedure} list? x
220 @deffnx {C Function} scm_list_p (x)
221 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
222 @end deffn
223
224 The predicate @code{null?} is often used in list-processing code to
225 tell whether a given list has run out of elements. That is, a loop
226 somehow deals with the elements of a list until the list satisfies
227 @code{null?}. Then, the algorithm terminates.
228
229 @rnindex null?
230 @deffn {Scheme Procedure} null? x
231 @deffnx {C Function} scm_null_p (x)
232 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
233 @end deffn
234
235 @node List Constructors
236 @subsubsection List Constructors
237
238 This section describes the procedures for constructing new lists.
239 @code{list} simply returns a list where the elements are the arguments,
240 @code{cons*} is similar, but the last argument is stored in the cdr of
241 the last pair of the list.
242
243 @c C Function scm_list(rest) used to be documented here, but it's a
244 @c no-op since it does nothing but return the list the caller must
245 @c have already created.
246 @c
247 @deffn {Scheme Procedure} list elem1 @dots{} elemN
248 @deffnx {C Function} scm_list_1 (elem1)
249 @deffnx {C Function} scm_list_2 (elem1, elem2)
250 @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
251 @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
252 @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
253 @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
254 @rnindex list
255 Return a new list containing elements @var{elem1} to @var{elemN}.
256
257 @code{scm_list_n} takes a variable number of arguments, terminated by
258 the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
259 not included in the list. None of @var{elem1} to @var{elemN} can
260 themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
261 terminate at that point.
262 @end deffn
263
264 @c C Function scm_cons_star(arg1,rest) used to be documented here,
265 @c but it's not really a useful interface, since it expects the
266 @c caller to have already consed up all but the first argument
267 @c already.
268 @c
269 @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
270 Like @code{list}, but the last arg provides the tail of the
271 constructed list, returning @code{(cons @var{arg1} (cons
272 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
273 argument. If given one argument, that argument is returned as
274 result. This function is called @code{list*} in some other
275 Schemes and in Common LISP.
276 @end deffn
277
278 @deffn {Scheme Procedure} list-copy lst
279 @deffnx {C Function} scm_list_copy (lst)
280 Return a (newly-created) copy of @var{lst}.
281 @end deffn
282
283 @deffn {Scheme Procedure} make-list n [init]
284 Create a list containing of @var{n} elements, where each element is
285 initialized to @var{init}. @var{init} defaults to the empty list
286 @code{()} if not given.
287 @end deffn
288
289 Note that @code{list-copy} only makes a copy of the pairs which make up
290 the spine of the lists. The list elements are not copied, which means
291 that modifying the elements of the new list also modifies the elements
292 of the old list. On the other hand, applying procedures like
293 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
294 list. If you also need to copy the list elements (making a deep copy),
295 use the procedure @code{copy-tree} (@pxref{Copying}).
296
297 @node List Selection
298 @subsubsection List Selection
299
300 These procedures are used to get some information about a list, or to
301 retrieve one or more elements of a list.
302
303 @rnindex length
304 @deffn {Scheme Procedure} length lst
305 @deffnx {C Function} scm_length (lst)
306 Return the number of elements in list @var{lst}.
307 @end deffn
308
309 @deffn {Scheme Procedure} last-pair lst
310 @deffnx {C Function} scm_last_pair (lst)
311 Return a pointer to the last pair in @var{lst}, signalling an error if
312 @var{lst} is circular.
313 @end deffn
314
315 @rnindex list-ref
316 @deffn {Scheme Procedure} list-ref list k
317 @deffnx {C Function} scm_list_ref (list, k)
318 Return the @var{k}th element from @var{list}.
319 @end deffn
320
321 @rnindex list-tail
322 @deffn {Scheme Procedure} list-tail lst k
323 @deffnx {Scheme Procedure} list-cdr-ref lst k
324 @deffnx {C Function} scm_list_tail (lst, k)
325 Return the "tail" of @var{lst} beginning with its @var{k}th element.
326 The first element of the list is considered to be element 0.
327
328 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
329 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
330 or returning the results of cdring @var{k} times down @var{lst}.
331 @end deffn
332
333 @deffn {Scheme Procedure} list-head lst k
334 @deffnx {C Function} scm_list_head (lst, k)
335 Copy the first @var{k} elements from @var{lst} into a new list, and
336 return it.
337 @end deffn
338
339 @node Append/Reverse
340 @subsubsection Append and Reverse
341
342 @code{append} and @code{append!} are used to concatenate two or more
343 lists in order to form a new list. @code{reverse} and @code{reverse!}
344 return lists with the same elements as their arguments, but in reverse
345 order. The procedure variants with an @code{!} directly modify the
346 pairs which form the list, whereas the other procedures create new
347 pairs. This is why you should be careful when using the side-effecting
348 variants.
349
350 @rnindex append
351 @deffn {Scheme Procedure} append lst1 @dots{} lstN
352 @deffnx {Scheme Procedure} append! lst1 @dots{} lstN
353 @deffnx {C Function} scm_append (lstlst)
354 @deffnx {C Function} scm_append_x (lstlst)
355 Return a list comprising all the elements of lists @var{lst1} to
356 @var{lstN}.
357
358 @lisp
359 (append '(x) '(y)) @result{} (x y)
360 (append '(a) '(b c d)) @result{} (a b c d)
361 (append '(a (b)) '((c))) @result{} (a (b) (c))
362 @end lisp
363
364 The last argument @var{lstN} may actually be any object; an improper
365 list results if the last argument is not a proper list.
366
367 @lisp
368 (append '(a b) '(c . d)) @result{} (a b c . d)
369 (append '() 'a) @result{} a
370 @end lisp
371
372 @code{append} doesn't modify the given lists, but the return may share
373 structure with the final @var{lstN}. @code{append!} modifies the
374 given lists to form its return.
375
376 For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
377 of the list operands @var{lst1} @dots{} @var{lstN}. That @var{lstlst}
378 itself is not modified or used in the return.
379 @end deffn
380
381 @rnindex reverse
382 @deffn {Scheme Procedure} reverse lst
383 @deffnx {Scheme Procedure} reverse! lst [newtail]
384 @deffnx {C Function} scm_reverse (lst)
385 @deffnx {C Function} scm_reverse_x (lst, newtail)
386 Return a list comprising the elements of @var{lst}, in reverse order.
387
388 @code{reverse} constructs a new list, @code{reverse!} modifies
389 @var{lst} in constructing its return.
390
391 For @code{reverse!}, the optional @var{newtail} is appended to to the
392 result. @var{newtail} isn't reversed, it simply becomes the list
393 tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
394 mandatory, but can be @code{SCM_EOL} if no further tail is required.
395 @end deffn
396
397 @node List Modification
398 @subsubsection List Modification
399
400 The following procedures modify an existing list, either by changing
401 elements of the list, or by changing the list structure itself.
402
403 @deffn {Scheme Procedure} list-set! list k val
404 @deffnx {C Function} scm_list_set_x (list, k, val)
405 Set the @var{k}th element of @var{list} to @var{val}.
406 @end deffn
407
408 @deffn {Scheme Procedure} list-cdr-set! list k val
409 @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
410 Set the @var{k}th cdr of @var{list} to @var{val}.
411 @end deffn
412
413 @deffn {Scheme Procedure} delq item lst
414 @deffnx {C Function} scm_delq (item, lst)
415 Return a newly-created copy of @var{lst} with elements
416 @code{eq?} to @var{item} removed. This procedure mirrors
417 @code{memq}: @code{delq} compares elements of @var{lst} against
418 @var{item} with @code{eq?}.
419 @end deffn
420
421 @deffn {Scheme Procedure} delv item lst
422 @deffnx {C Function} scm_delv (item, lst)
423 Return a newly-created copy of @var{lst} with elements
424 @code{eqv?} to @var{item} removed. This procedure mirrors
425 @code{memv}: @code{delv} compares elements of @var{lst} against
426 @var{item} with @code{eqv?}.
427 @end deffn
428
429 @deffn {Scheme Procedure} delete item lst
430 @deffnx {C Function} scm_delete (item, lst)
431 Return a newly-created copy of @var{lst} with elements
432 @code{equal?} to @var{item} removed. This procedure mirrors
433 @code{member}: @code{delete} compares elements of @var{lst}
434 against @var{item} with @code{equal?}.
435 @end deffn
436
437 @deffn {Scheme Procedure} delq! item lst
438 @deffnx {Scheme Procedure} delv! item lst
439 @deffnx {Scheme Procedure} delete! item lst
440 @deffnx {C Function} scm_delq_x (item, lst)
441 @deffnx {C Function} scm_delv_x (item, lst)
442 @deffnx {C Function} scm_delete_x (item, lst)
443 These procedures are destructive versions of @code{delq}, @code{delv}
444 and @code{delete}: they modify the pointers in the existing @var{lst}
445 rather than creating a new list. Caveat evaluator: Like other
446 destructive list functions, these functions cannot modify the binding of
447 @var{lst}, and so cannot be used to delete the first element of
448 @var{lst} destructively.
449 @end deffn
450
451 @deffn {Scheme Procedure} delq1! item lst
452 @deffnx {C Function} scm_delq1_x (item, lst)
453 Like @code{delq!}, but only deletes the first occurrence of
454 @var{item} from @var{lst}. Tests for equality using
455 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
456 @end deffn
457
458 @deffn {Scheme Procedure} delv1! item lst
459 @deffnx {C Function} scm_delv1_x (item, lst)
460 Like @code{delv!}, but only deletes the first occurrence of
461 @var{item} from @var{lst}. Tests for equality using
462 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
463 @end deffn
464
465 @deffn {Scheme Procedure} delete1! item lst
466 @deffnx {C Function} scm_delete1_x (item, lst)
467 Like @code{delete!}, but only deletes the first occurrence of
468 @var{item} from @var{lst}. Tests for equality using
469 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
470 @end deffn
471
472 @deffn {Scheme Procedure} filter pred lst
473 @deffnx {Scheme Procedure} filter! pred lst
474 Return a list containing all elements from @var{lst} which satisfy the
475 predicate @var{pred}. The elements in the result list have the same
476 order as in @var{lst}. The order in which @var{pred} is applied to
477 the list elements is not specified.
478
479 @code{filter!} is allowed, but not required to modify the structure of
480 @end deffn
481
482 @node List Searching
483 @subsubsection List Searching
484
485 The following procedures search lists for particular elements. They use
486 different comparison predicates for comparing list elements with the
487 object to be searched. When they fail, they return @code{#f}, otherwise
488 they return the sublist whose car is equal to the search object, where
489 equality depends on the equality predicate used.
490
491 @rnindex memq
492 @deffn {Scheme Procedure} memq x lst
493 @deffnx {C Function} scm_memq (x, lst)
494 Return the first sublist of @var{lst} whose car is @code{eq?}
495 to @var{x} where the sublists of @var{lst} are the non-empty
496 lists returned by @code{(list-tail @var{lst} @var{k})} for
497 @var{k} less than the length of @var{lst}. If @var{x} does not
498 occur in @var{lst}, then @code{#f} (not the empty list) is
499 returned.
500 @end deffn
501
502 @rnindex memv
503 @deffn {Scheme Procedure} memv x lst
504 @deffnx {C Function} scm_memv (x, lst)
505 Return the first sublist of @var{lst} whose car is @code{eqv?}
506 to @var{x} where the sublists of @var{lst} are the non-empty
507 lists returned by @code{(list-tail @var{lst} @var{k})} for
508 @var{k} less than the length of @var{lst}. If @var{x} does not
509 occur in @var{lst}, then @code{#f} (not the empty list) is
510 returned.
511 @end deffn
512
513 @rnindex member
514 @deffn {Scheme Procedure} member x lst
515 @deffnx {C Function} scm_member (x, lst)
516 Return the first sublist of @var{lst} whose car is
517 @code{equal?} to @var{x} where the sublists of @var{lst} are
518 the non-empty lists returned by @code{(list-tail @var{lst}
519 @var{k})} for @var{k} less than the length of @var{lst}. If
520 @var{x} does not occur in @var{lst}, then @code{#f} (not the
521 empty list) is returned.
522 @end deffn
523
524
525 @node List Mapping
526 @subsubsection List Mapping
527
528 List processing is very convenient in Scheme because the process of
529 iterating over the elements of a list can be highly abstracted. The
530 procedures in this section are the most basic iterating procedures for
531 lists. They take a procedure and one or more lists as arguments, and
532 apply the procedure to each element of the list. They differ in their
533 return value.
534
535 @rnindex map
536 @c begin (texi-doc-string "guile" "map")
537 @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
538 @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
539 @deffnx {C Function} scm_map (proc, arg1, args)
540 Apply @var{proc} to each element of the list @var{arg1} (if only two
541 arguments are given), or to the corresponding elements of the argument
542 lists (if more than two arguments are given). The result(s) of the
543 procedure applications are saved and returned in a list. For
544 @code{map}, the order of procedure applications is not specified,
545 @code{map-in-order} applies the procedure from left to right to the list
546 elements.
547 @end deffn
548
549 @rnindex for-each
550 @c begin (texi-doc-string "guile" "for-each")
551 @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
552 Like @code{map}, but the procedure is always applied from left to right,
553 and the result(s) of the procedure applications are thrown away. The
554 return value is not specified.
555 @end deffn
556
557
558 @node Vectors
559 @subsection Vectors
560 @tpindex Vectors
561
562 Vectors are sequences of Scheme objects. Unlike lists, the length of a
563 vector, once the vector is created, cannot be changed. The advantage of
564 vectors over lists is that the time required to access one element of a vector
565 given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
566 is constant, whereas lists have an access time linear to the position of the
567 accessed element in the list.
568
569 Vectors can contain any kind of Scheme object; it is even possible to have
570 different types of objects in the same vector. For vectors containing
571 vectors, you may wish to use arrays, instead. Note, too, that some array
572 procedures operate happily on vectors (@pxref{Arrays}).
573
574 @menu
575 * Vector Syntax:: Read syntax for vectors.
576 * Vector Creation:: Dynamic vector creation and validation.
577 * Vector Accessors:: Accessing and modifying vector contents.
578 @end menu
579
580
581 @node Vector Syntax
582 @subsubsection Read Syntax for Vectors
583
584 Vectors can literally be entered in source code, just like strings,
585 characters or some of the other data types. The read syntax for vectors
586 is as follows: A sharp sign (@code{#}), followed by an opening
587 parentheses, all elements of the vector in their respective read syntax,
588 and finally a closing parentheses. The following are examples of the
589 read syntax for vectors; where the first vector only contains numbers
590 and the second three different object types: a string, a symbol and a
591 number in hexadecimal notation.
592
593 @lisp
594 #(1 2 3)
595 #("Hello" foo #xdeadbeef)
596 @end lisp
597
598 Like lists, vectors have to be quoted (REFFIXME):
599
600 @lisp
601 '#(a b c) @result{} #(a b c)
602 @end lisp
603
604 @node Vector Creation
605 @subsubsection Dynamic Vector Creation and Validation
606
607 Instead of creating a vector implicitly by using the read syntax just
608 described, you can create a vector dynamically by calling one of the
609 @code{vector} and @code{list->vector} primitives with the list of Scheme
610 values that you want to place into a vector. The size of the vector
611 thus created is determined implicitly by the number of arguments given.
612
613 @rnindex vector
614 @rnindex list->vector
615 @deffn {Scheme Procedure} vector . l
616 @deffnx {Scheme Procedure} list->vector l
617 @deffnx {C Function} scm_vector (l)
618 Return a newly allocated vector composed of the
619 given arguments. Analogous to @code{list}.
620
621 @lisp
622 (vector 'a 'b 'c) @result{} #(a b c)
623 @end lisp
624 @end deffn
625
626 (As an aside, an interesting implementation detail is that the Guile
627 reader reads the @code{#(@dots{})} syntax by reading everything but the
628 initial @code{#} as a @emph{list}, and then passing the list that
629 results to @code{list->vector}. Notice how neatly this fits with the
630 similarity between the read (and print) syntaxes for lists and vectors.)
631
632 The inverse operation is @code{vector->list}:
633
634 @rnindex vector->list
635 @deffn {Scheme Procedure} vector->list v
636 @deffnx {C Function} scm_vector_to_list (v)
637 Return a newly allocated list composed of the elements of @var{v}.
638
639 @lisp
640 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
641 (list->vector '(dididit dah)) @result{} #(dididit dah)
642 @end lisp
643 @end deffn
644
645 To allocate a vector with an explicitly specified size, use
646 @code{make-vector}. With this primitive you can also specify an initial
647 value for the vector elements (the same value for all elements, that
648 is):
649
650 @rnindex make-vector
651 @deffn {Scheme Procedure} make-vector k [fill]
652 @deffnx {C Function} scm_make_vector (k, fill)
653 Return a newly allocated vector of @var{k} elements. If a
654 second argument is given, then each position is initialized to
655 @var{fill}. Otherwise the initial contents of each position is
656 unspecified.
657 @end deffn
658
659 To check whether an arbitrary Scheme value @emph{is} a vector, use the
660 @code{vector?} primitive:
661
662 @rnindex vector?
663 @deffn {Scheme Procedure} vector? obj
664 @deffnx {C Function} scm_vector_p (obj)
665 Return @code{#t} if @var{obj} is a vector, otherwise return
666 @code{#f}.
667 @end deffn
668
669
670 @node Vector Accessors
671 @subsubsection Accessing and Modifying Vector Contents
672
673 @code{vector-length} and @code{vector-ref} return information about a
674 given vector, respectively its size and the elements that are contained
675 in the vector.
676
677 @rnindex vector-length
678 @deffn {Scheme Procedure} vector-length vector
679 @deffnx {C Function} scm_vector_length vector
680 Return the number of elements in @var{vector} as an exact integer.
681 @end deffn
682
683 @rnindex vector-ref
684 @deffn {Scheme Procedure} vector-ref vector k
685 @deffnx {C Function} scm_vector_ref vector k
686 Return the contents of position @var{k} of @var{vector}.
687 @var{k} must be a valid index of @var{vector}.
688 @lisp
689 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
690 (vector-ref '#(1 1 2 3 5 8 13 21)
691 (let ((i (round (* 2 (acos -1)))))
692 (if (inexact? i)
693 (inexact->exact i)
694 i))) @result{} 13
695 @end lisp
696 @end deffn
697
698 A vector created by one of the dynamic vector constructor procedures
699 (@pxref{Vector Creation}) can be modified using the following
700 procedures.
701
702 @emph{NOTE:} According to R5RS, it is an error to use any of these
703 procedures on a literally read vector, because such vectors should be
704 considered as constants. Currently, however, Guile does not detect this
705 error.
706
707 @rnindex vector-set!
708 @deffn {Scheme Procedure} vector-set! vector k obj
709 @deffnx {C Function} scm_vector_set_x vector k obj
710 Store @var{obj} in position @var{k} of @var{vector}.
711 @var{k} must be a valid index of @var{vector}.
712 The value returned by @samp{vector-set!} is unspecified.
713 @lisp
714 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
715 (vector-set! vec 1 '("Sue" "Sue"))
716 vec) @result{} #(0 ("Sue" "Sue") "Anna")
717 @end lisp
718 @end deffn
719
720 @rnindex vector-fill!
721 @deffn {Scheme Procedure} vector-fill! v fill
722 @deffnx {C Function} scm_vector_fill_x (v, fill)
723 Store @var{fill} in every position of @var{vector}. The value
724 returned by @code{vector-fill!} is unspecified.
725 @end deffn
726
727 @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
728 @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
729 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
730 to @var{vec2} starting at position @var{start2}. @var{start1} and
731 @var{start2} are inclusive indices; @var{end1} is exclusive.
732
733 @code{vector-move-left!} copies elements in leftmost order.
734 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
735 same vector, @code{vector-move-left!} is usually appropriate when
736 @var{start1} is greater than @var{start2}.
737 @end deffn
738
739 @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
740 @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
741 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
742 to @var{vec2} starting at position @var{start2}. @var{start1} and
743 @var{start2} are inclusive indices; @var{end1} is exclusive.
744
745 @code{vector-move-right!} copies elements in rightmost order.
746 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
747 same vector, @code{vector-move-right!} is usually appropriate when
748 @var{start1} is less than @var{start2}.
749 @end deffn
750
751
752 @node Records
753 @subsection Records
754
755 A @dfn{record type} is a first class object representing a user-defined
756 data type. A @dfn{record} is an instance of a record type.
757
758 @deffn {Scheme Procedure} record? obj
759 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
760 otherwise.
761
762 Note that @code{record?} may be true of any Scheme value; there is no
763 promise that records are disjoint with other Scheme types.
764 @end deffn
765
766 @deffn {Scheme Procedure} make-record-type type-name field-names
767 Return a @dfn{record-type descriptor}, a value representing a new data
768 type disjoint from all others. The @var{type-name} argument must be a
769 string, but is only used for debugging purposes (such as the printed
770 representation of a record of the new type). The @var{field-names}
771 argument is a list of symbols naming the @dfn{fields} of a record of the
772 new type. It is an error if the list contains any duplicates. It is
773 unspecified how record-type descriptors are represented.
774 @end deffn
775
776 @deffn {Scheme Procedure} record-constructor rtd [field-names]
777 Return a procedure for constructing new members of the type represented
778 by @var{rtd}. The returned procedure accepts exactly as many arguments
779 as there are symbols in the given list, @var{field-names}; these are
780 used, in order, as the initial values of those fields in a new record,
781 which is returned by the constructor procedure. The values of any
782 fields not named in that list are unspecified. The @var{field-names}
783 argument defaults to the list of field names in the call to
784 @code{make-record-type} that created the type represented by @var{rtd};
785 if the @var{field-names} argument is provided, it is an error if it
786 contains any duplicates or any symbols not in the default list.
787 @end deffn
788
789 @deffn {Scheme Procedure} record-predicate rtd
790 Return a procedure for testing membership in the type represented by
791 @var{rtd}. The returned procedure accepts exactly one argument and
792 returns a true value if the argument is a member of the indicated record
793 type; it returns a false value otherwise.
794 @end deffn
795
796 @deffn {Scheme Procedure} record-accessor rtd field-name
797 Return a procedure for reading the value of a particular field of a
798 member of the type represented by @var{rtd}. The returned procedure
799 accepts exactly one argument which must be a record of the appropriate
800 type; it returns the current value of the field named by the symbol
801 @var{field-name} in that record. The symbol @var{field-name} must be a
802 member of the list of field-names in the call to @code{make-record-type}
803 that created the type represented by @var{rtd}.
804 @end deffn
805
806 @deffn {Scheme Procedure} record-modifier rtd field-name
807 Return a procedure for writing the value of a particular field of a
808 member of the type represented by @var{rtd}. The returned procedure
809 accepts exactly two arguments: first, a record of the appropriate type,
810 and second, an arbitrary Scheme value; it modifies the field named by
811 the symbol @var{field-name} in that record to contain the given value.
812 The returned value of the modifier procedure is unspecified. The symbol
813 @var{field-name} must be a member of the list of field-names in the call
814 to @code{make-record-type} that created the type represented by
815 @var{rtd}.
816 @end deffn
817
818 @deffn {Scheme Procedure} record-type-descriptor record
819 Return a record-type descriptor representing the type of the given
820 record. That is, for example, if the returned descriptor were passed to
821 @code{record-predicate}, the resulting predicate would return a true
822 value when passed the given record. Note that it is not necessarily the
823 case that the returned descriptor is the one that was passed to
824 @code{record-constructor} in the call that created the constructor
825 procedure that created the given record.
826 @end deffn
827
828 @deffn {Scheme Procedure} record-type-name rtd
829 Return the type-name associated with the type represented by rtd. The
830 returned value is @code{eqv?} to the @var{type-name} argument given in
831 the call to @code{make-record-type} that created the type represented by
832 @var{rtd}.
833 @end deffn
834
835 @deffn {Scheme Procedure} record-type-fields rtd
836 Return a list of the symbols naming the fields in members of the type
837 represented by @var{rtd}. The returned value is @code{equal?} to the
838 field-names argument given in the call to @code{make-record-type} that
839 created the type represented by @var{rtd}.
840 @end deffn
841
842
843 @node Structures
844 @subsection Structures
845 @tpindex Structures
846
847 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
848 be reviewed]
849
850 A @dfn{structure type} is a first class user-defined data type. A
851 @dfn{structure} is an instance of a structure type. A structure type is
852 itself a structure.
853
854 Structures are less abstract and more general than traditional records.
855 In fact, in Guile Scheme, records are implemented using structures.
856
857 @menu
858 * Structure Concepts:: The structure of Structures
859 * Structure Layout:: Defining the layout of structure types
860 * Structure Basics:: make-, -ref and -set! procedures for structs
861 * Vtables:: Accessing type-specific data
862 @end menu
863
864 @node Structure Concepts
865 @subsubsection Structure Concepts
866
867 A structure object consists of a handle, structure data, and a vtable.
868 The handle is a Scheme value which points to both the vtable and the
869 structure's data. Structure data is a dynamically allocated region of
870 memory, private to the structure, divided up into typed fields. A
871 vtable is another structure used to hold type-specific data. Multiple
872 structures can share a common vtable.
873
874 Three concepts are key to understanding structures.
875
876 @itemize @bullet{}
877 @item @dfn{layout specifications}
878
879 Layout specifications determine how memory allocated to structures is
880 divided up into fields. Programmers must write a layout specification
881 whenever a new type of structure is defined.
882
883 @item @dfn{structural accessors}
884
885 Structure access is by field number. There is only one set of
886 accessors common to all structure objects.
887
888 @item @dfn{vtables}
889
890 Vtables, themselves structures, are first class representations of
891 disjoint sub-types of structures in general. In most cases, when a
892 new structure is created, programmers must specify a vtable for the
893 new structure. Each vtable has a field describing the layout of its
894 instances. Vtables can have additional, user-defined fields as well.
895 @end itemize
896
897
898
899 @node Structure Layout
900 @subsubsection Structure Layout
901
902 When a structure is created, a region of memory is allocated to hold its
903 state. The @dfn{layout} of the structure's type determines how that
904 memory is divided into fields.
905
906 Each field has a specified type. There are only three types allowed, each
907 corresponding to a one letter code. The allowed types are:
908
909 @itemize @bullet{}
910 @item 'u' -- unprotected
911
912 The field holds binary data that is not GC protected.
913
914 @item 'p' -- protected
915
916 The field holds a Scheme value and is GC protected.
917
918 @item 's' -- self
919
920 The field holds a Scheme value and is GC protected. When a structure is
921 created with this type of field, the field is initialized to refer to
922 the structure's own handle. This kind of field is mainly useful when
923 mixing Scheme and C code in which the C code may need to compute a
924 structure's handle given only the address of its malloc'd data.
925 @end itemize
926
927
928 Each field also has an associated access protection. There are only
929 three kinds of protection, each corresponding to a one letter code.
930 The allowed protections are:
931
932 @itemize @bullet{}
933 @item 'w' -- writable
934
935 The field can be read and written.
936
937 @item 'r' -- readable
938
939 The field can be read, but not written.
940
941 @item 'o' -- opaque
942
943 The field can be neither read nor written. This kind
944 of protection is for fields useful only to built-in routines.
945 @end itemize
946
947 A layout specification is described by stringing together pairs
948 of letters: one to specify a field type and one to specify a field
949 protection. For example, a traditional cons pair type object could
950 be described as:
951
952 @example
953 ; cons pairs have two writable fields of Scheme data
954 "pwpw"
955 @end example
956
957 A pair object in which the first field is held constant could be:
958
959 @example
960 "prpw"
961 @end example
962
963 Binary fields, (fields of type "u"), hold one @dfn{word} each. The
964 size of a word is a machine dependent value defined to be equal to the
965 value of the C expression: @code{sizeof (long)}.
966
967 The last field of a structure layout may specify a tail array.
968 A tail array is indicated by capitalizing the field's protection
969 code ('W', 'R' or 'O'). A tail-array field is replaced by
970 a read-only binary data field containing an array size. The array
971 size is determined at the time the structure is created. It is followed
972 by a corresponding number of fields of the type specified for the
973 tail array. For example, a conventional Scheme vector can be
974 described as:
975
976 @example
977 ; A vector is an arbitrary number of writable fields holding Scheme
978 ; values:
979 "pW"
980 @end example
981
982 In the above example, field 0 contains the size of the vector and
983 fields beginning at 1 contain the vector elements.
984
985 A kind of tagged vector (a constant tag followed by conventional
986 vector elements) might be:
987
988 @example
989 "prpW"
990 @end example
991
992
993 Structure layouts are represented by specially interned symbols whose
994 name is a string of type and protection codes. To create a new
995 structure layout, use this procedure:
996
997 @deffn {Scheme Procedure} make-struct-layout fields
998 @deffnx {C Function} scm_make_struct_layout (fields)
999 Return a new structure layout object.
1000
1001 @var{fields} must be a string made up of pairs of characters
1002 strung together. The first character of each pair describes a field
1003 type, the second a field protection. Allowed types are 'p' for
1004 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
1005 a field that points to the structure itself. Allowed protections
1006 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
1007 fields. The last field protection specification may be capitalized to
1008 indicate that the field is a tail-array.
1009 @end deffn
1010
1011
1012
1013 @node Structure Basics
1014 @subsubsection Structure Basics
1015
1016 This section describes the basic procedures for creating and accessing
1017 structures.
1018
1019 @deffn {Scheme Procedure} make-struct vtable tail_array_size . init
1020 @deffnx {C Function} scm_make_struct (vtable, tail_array_size, init)
1021 Create a new structure.
1022
1023 @var{type} must be a vtable structure (@pxref{Vtables}).
1024
1025 @var{tail-elts} must be a non-negative integer. If the layout
1026 specification indicated by @var{type} includes a tail-array,
1027 this is the number of elements allocated to that array.
1028
1029 The @var{init1}, @dots{} are optional arguments describing how
1030 successive fields of the structure should be initialized. Only fields
1031 with protection 'r' or 'w' can be initialized, except for fields of
1032 type 's', which are automatically initialized to point to the new
1033 structure itself; fields with protection 'o' can not be initialized by
1034 Scheme programs.
1035
1036 If fewer optional arguments than initializable fields are supplied,
1037 fields of type 'p' get default value #f while fields of type 'u' are
1038 initialized to 0.
1039
1040 Structs are currently the basic representation for record-like data
1041 structures in Guile. The plan is to eventually replace them with a
1042 new representation which will at the same time be easier to use and
1043 more powerful.
1044
1045 For more information, see the documentation for @code{make-vtable-vtable}.
1046 @end deffn
1047
1048 @deffn {Scheme Procedure} struct? x
1049 @deffnx {C Function} scm_struct_p (x)
1050 Return @code{#t} iff @var{x} is a structure object, else
1051 @code{#f}.
1052 @end deffn
1053
1054
1055 @deffn {Scheme Procedure} struct-ref handle pos
1056 @deffnx {Scheme Procedure} struct-set! struct n value
1057 @deffnx {C Function} scm_struct_ref (handle, pos)
1058 @deffnx {C Function} scm_struct_set_x (struct, n, value)
1059 Access (or modify) the @var{n}th field of @var{struct}.
1060
1061 If the field is of type 'p', then it can be set to an arbitrary value.
1062
1063 If the field is of type 'u', then it can only be set to a non-negative
1064 integer value small enough to fit in one machine word.
1065 @end deffn
1066
1067
1068
1069 @node Vtables
1070 @subsubsection Vtables
1071
1072 Vtables are structures that are used to represent structure types. Each
1073 vtable contains a layout specification in field
1074 @code{vtable-index-layout} -- instances of the type are laid out
1075 according to that specification. Vtables contain additional fields
1076 which are used only internally to libguile. The variable
1077 @code{vtable-offset-user} is bound to a field number. Vtable fields
1078 at that position or greater are user definable.
1079
1080 @deffn {Scheme Procedure} struct-vtable handle
1081 @deffnx {C Function} scm_struct_vtable (handle)
1082 Return the vtable structure that describes the type of @var{struct}.
1083 @end deffn
1084
1085 @deffn {Scheme Procedure} struct-vtable? x
1086 @deffnx {C Function} scm_struct_vtable_p (x)
1087 Return @code{#t} iff @var{x} is a vtable structure.
1088 @end deffn
1089
1090 If you have a vtable structure, @code{V}, you can create an instance of
1091 the type it describes by using @code{(make-struct V ...)}. But where
1092 does @code{V} itself come from? One possibility is that @code{V} is an
1093 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
1094 created by using @code{(make-struct V' ...)}. Another possibility is
1095 that @code{V} is an instance of the type it itself describes. Vtable
1096 structures of the second sort are created by this procedure:
1097
1098 @deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init
1099 @deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init)
1100 Return a new, self-describing vtable structure.
1101
1102 @var{user-fields} is a string describing user defined fields of the
1103 vtable beginning at index @code{vtable-offset-user}
1104 (see @code{make-struct-layout}).
1105
1106 @var{tail-size} specifies the size of the tail-array (if any) of
1107 this vtable.
1108
1109 @var{init1}, @dots{} are the optional initializers for the fields of
1110 the vtable.
1111
1112 Vtables have one initializable system field---the struct printer.
1113 This field comes before the user fields in the initializers passed
1114 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
1115 a third optional argument to @code{make-vtable-vtable} and a fourth to
1116 @code{make-struct} when creating vtables:
1117
1118 If the value is a procedure, it will be called instead of the standard
1119 printer whenever a struct described by this vtable is printed.
1120 The procedure will be called with arguments STRUCT and PORT.
1121
1122 The structure of a struct is described by a vtable, so the vtable is
1123 in essence the type of the struct. The vtable is itself a struct with
1124 a vtable. This could go on forever if it weren't for the
1125 vtable-vtables which are self-describing vtables, and thus terminate
1126 the chain.
1127
1128 There are several potential ways of using structs, but the standard
1129 one is to use three kinds of structs, together building up a type
1130 sub-system: one vtable-vtable working as the root and one or several
1131 "types", each with a set of "instances". (The vtable-vtable should be
1132 compared to the class <class> which is the class of itself.)
1133
1134 @lisp
1135 (define ball-root (make-vtable-vtable "pr" 0))
1136
1137 (define (make-ball-type ball-color)
1138 (make-struct ball-root 0
1139 (make-struct-layout "pw")
1140 (lambda (ball port)
1141 (format port "#<a ~A ball owned by ~A>"
1142 (color ball)
1143 (owner ball)))
1144 ball-color))
1145 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
1146 (define (owner ball) (struct-ref ball 0))
1147
1148 (define red (make-ball-type 'red))
1149 (define green (make-ball-type 'green))
1150
1151 (define (make-ball type owner) (make-struct type 0 owner))
1152
1153 (define ball (make-ball green 'Nisse))
1154 ball @result{} #<a green ball owned by Nisse>
1155 @end lisp
1156 @end deffn
1157
1158 @deffn {Scheme Procedure} struct-vtable-name vtable
1159 @deffnx {C Function} scm_struct_vtable_name (vtable)
1160 Return the name of the vtable @var{vtable}.
1161 @end deffn
1162
1163 @deffn {Scheme Procedure} set-struct-vtable-name! vtable name
1164 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
1165 Set the name of the vtable @var{vtable} to @var{name}.
1166 @end deffn
1167
1168 @deffn {Scheme Procedure} struct-vtable-tag handle
1169 @deffnx {C Function} scm_struct_vtable_tag (handle)
1170 Return the vtable tag of the structure @var{handle}.
1171 @end deffn
1172
1173
1174 @node Arrays
1175 @subsection Arrays
1176 @tpindex Arrays
1177
1178 @menu
1179 * Conventional Arrays:: Arrays with arbitrary data.
1180 * Array Mapping:: Applying a procedure to the contents of an array.
1181 * Uniform Arrays:: Arrays with data of a single type.
1182 * Bit Vectors:: Vectors of bits.
1183 @end menu
1184
1185 @node Conventional Arrays
1186 @subsubsection Conventional Arrays
1187
1188 @dfn{Conventional arrays} are a collection of cells organized into an
1189 arbitrary number of dimensions. Each cell can hold any kind of Scheme
1190 value and can be accessed in constant time by supplying an index for
1191 each dimension.
1192
1193 This contrasts with uniform arrays, which use memory more efficiently
1194 but can hold data of only a single type. It contrasts also with lists
1195 where inserting and deleting cells is more efficient, but more time is
1196 usually required to access a particular cell.
1197
1198 A conventional array is displayed as @code{#} followed by the @dfn{rank}
1199 (number of dimensions) followed by the cells, organized into dimensions
1200 using parentheses. The nesting depth of the parentheses is equal to
1201 the rank.
1202
1203 When an array is created, the range of each dimension must be
1204 specified, e.g., to create a 2@cross{}3 array with a zero-based index:
1205
1206 @example
1207 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1208 @end example
1209
1210 The range of each dimension can also be given explicitly, e.g., another
1211 way to create the same array:
1212
1213 @example
1214 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1215 @end example
1216
1217 A conventional array with one dimension based at zero is identical to
1218 a vector:
1219
1220 @example
1221 (make-array 'ho 3) @result{} #(ho ho ho)
1222 @end example
1223
1224 The following procedures can be used with conventional arrays (or
1225 vectors). An argument shown as @var{idx}@dots{} means one parameter
1226 for each dimension in the array. Or a @var{idxlist} is a list of such
1227 values, one for each dimension.
1228
1229 @deffn {Scheme Procedure} array? obj [prot]
1230 @deffnx {C Function} scm_array_p (obj, prot)
1231 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1232 not.
1233
1234 The @var{prot} argument is used with uniform arrays (@pxref{Uniform
1235 Arrays}). If given then the return is @code{#t} if @var{obj} is an
1236 array and of that prototype.
1237 @end deffn
1238
1239 @deffn {Scheme Procedure} make-array initial-value bound @dots{}
1240 Create and return an array that has as many dimensions as there are
1241 @var{bound}s and fill it with @var{initial-value}.
1242
1243 Each @var{bound}
1244 may be a positive non-zero integer @var{N}, in which case the index for
1245 that dimension can range from 0 through @var{N-1}; or an explicit index
1246 range specifier in the form @code{(LOWER UPPER)}, where both @var{lower}
1247 and @var{upper} are integers, possibly less than zero, and possibly the
1248 same number (however, @var{lower} cannot be greater than @var{upper}).
1249 See examples above.
1250 @end deffn
1251
1252 @c array-ref's type is `compiled-closure'. There's some weird stuff
1253 @c going on in array.c, too. Let's call it a primitive. -twp
1254
1255 @deffn {Scheme Procedure} array-ref array idx @dots{}
1256 @deffnx {Scheme Procedure} uniform-vector-ref vec args
1257 @deffnx {C Function} scm_uniform_vector_ref (vec, args)
1258 Return the element at @code{(idx @dots{})} in @var{array}.
1259
1260 @example
1261 (define a (make-array 999 '(1 2) '(3 4)))
1262 (array-ref a 2 4) @result{} 999
1263 @end example
1264 @end deffn
1265
1266 @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
1267 @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
1268 Return @code{#t} if the given index would be acceptable to
1269 @code{array-ref}.
1270
1271 @example
1272 (define a (make-array #f '(1 2) '(3 4)))
1273 (array-in-bounds? a 2 3) @result{} #f
1274 (array-in-bounds? a 0 0) @result{} #f
1275 @end example
1276 @end deffn
1277
1278 @c fixme: why do these sigs differ? -ttn 2001/07/19 01:14:12
1279 @deffn {Scheme Procedure} array-set! array obj idx @dots{}
1280 @deffnx {Scheme Procedure} uniform-array-set1! array obj idxlist
1281 @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
1282 Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
1283 The return value is unspecified.
1284
1285 @example
1286 (define a (make-array #f '(0 1) '(0 1)))
1287 (array-set! a #t 1 1)
1288 a @result{} #2((#f #f) (#f #t))
1289 @end example
1290 @end deffn
1291
1292 @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
1293 @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
1294 @code{make-shared-array} can be used to create shared subarrays of other
1295 arrays. The @var{mapper} is a function that translates coordinates in
1296 the new array into coordinates in the old array. A @var{mapper} must be
1297 linear, and its range must stay within the bounds of the old array, but
1298 it can be otherwise arbitrary. A simple example:
1299
1300 @lisp
1301 (define fred (make-array #f 8 8))
1302 (define freds-diagonal
1303 (make-shared-array fred (lambda (i) (list i i)) 8))
1304 (array-set! freds-diagonal 'foo 3)
1305 (array-ref fred 3 3) @result{} foo
1306 (define freds-center
1307 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
1308 (array-ref freds-center 0 0) @result{} foo
1309 @end lisp
1310 @end deffn
1311
1312 @deffn {Scheme Procedure} shared-array-increments array
1313 @deffnx {C Function} scm_shared_array_increments (array)
1314 For each dimension, return the distance between elements in the root vector.
1315 @end deffn
1316
1317 @deffn {Scheme Procedure} shared-array-offset array
1318 @deffnx {C Function} scm_shared_array_offset (array)
1319 Return the root vector index of the first element in the array.
1320 @end deffn
1321
1322 @deffn {Scheme Procedure} shared-array-root array
1323 @deffnx {C Function} scm_shared_array_root (array)
1324 Return the root vector of a shared array.
1325 @end deffn
1326
1327 @deffn {Scheme Procedure} transpose-array array dim1 @dots{}
1328 @deffnx {C Function} scm_transpose_array (array, dimlist)
1329 Return an array sharing contents with @var{array}, but with
1330 dimensions arranged in a different order. There must be one
1331 @var{dim} argument for each dimension of @var{array}.
1332 @var{dim1}, @var{dim2}, @dots{} should be integers between 0
1333 and the rank of the array to be returned. Each integer in that
1334 range must appear at least once in the argument list.
1335
1336 The values of @var{dim1}, @var{dim2}, @dots{} correspond to
1337 dimensions in the array to be returned, and their positions in the
1338 argument list to dimensions of @var{array}. Several @var{dim}s
1339 may have the same value, in which case the returned array will
1340 have smaller rank than @var{array}.
1341
1342 @lisp
1343 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1344 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1345 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1346 #2((a 4) (b 5) (c 6))
1347 @end lisp
1348 @end deffn
1349
1350 @deffn {Scheme Procedure} enclose-array array dim1 @dots{}
1351 @deffnx {C Function} scm_enclose_array (array, dimlist)
1352 @var{dim1}, @var{dim2} @dots{} should be nonnegative integers less than
1353 the rank of @var{array}. @code{enclose-array} returns an array
1354 resembling an array of shared arrays. The dimensions of each shared
1355 array are the same as the @var{dim}th dimensions of the original array,
1356 the dimensions of the outer array are the same as those of the original
1357 array that did not match a @var{dim}.
1358
1359 An enclosed array is not a general Scheme array. Its elements may not
1360 be set using @code{array-set!}. Two references to the same element of
1361 an enclosed array will be @code{equal?} but will not in general be
1362 @code{eq?}. The value returned by @code{array-prototype} when given an
1363 enclosed array is unspecified.
1364
1365 For example,
1366
1367 @lisp
1368 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1)
1369 @result{}
1370 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1371
1372 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0)
1373 @result{}
1374 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1375 @end lisp
1376 @end deffn
1377
1378 @deffn {Scheme Procedure} array-shape array
1379 @deffnx {Scheme Procedure} array-dimensions array
1380 @deffnx {C Function} scm_array_dimensions (array)
1381 Return a list of the bounds for each dimenson of @var{array}.
1382
1383 @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
1384 dimension. @code{array-dimensions} instead returns just
1385 @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
1386 suitable as input to @code{make-array}.
1387
1388 For example,
1389
1390 @example
1391 (define a (make-array 'foo '(-1 3) 5))
1392 (array-shape a) @result{} ((-1 3) (0 4))
1393 (array-dimensions a) @result{} ((-1 3) 5)
1394 @end example
1395 @end deffn
1396
1397 @deffn {Scheme Procedure} array-rank obj
1398 @deffnx {C Function} scm_array_rank (obj)
1399 Return the number of dimensions of an array @var{obj}, or if @var{obj}
1400 is not an array then return 0.
1401 @end deffn
1402
1403 @deffn {Scheme Procedure} array->list array
1404 @deffnx {C Function} scm_array_to_list (array)
1405 Return a list consisting of all the elements, in order, of
1406 @var{array}.
1407 @end deffn
1408
1409 @c FIXME: Describe how the order affects the copying (it matters for
1410 @c shared arrays with the same underlying root vector, presumably).
1411 @c
1412 @deffn {Scheme Procedure} array-copy! src dst
1413 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1414 @deffnx {C Function} scm_array_copy_x (src, dst)
1415 Copy every element from vector or array @var{src} to the corresponding
1416 element of @var{dst}. @var{dst} must have the same rank as @var{src},
1417 and be at least as large in each dimension. The return value is
1418 unspecified.
1419 @end deffn
1420
1421 @deffn {Scheme Procedure} array-fill! array fill
1422 @deffnx {C Function} scm_array_fill_x (array, fill)
1423 Store @var{fill} in every element of @var{array}. The value returned
1424 is unspecified.
1425 @end deffn
1426
1427 @c begin (texi-doc-string "guile" "array-equal?")
1428 @deffn {Scheme Procedure} array-equal? array1 array2 @dots{}
1429 Return @code{#t} if all arguments are arrays with the same shape, the
1430 same type, and have corresponding elements which are either
1431 @code{equal?} or @code{array-equal?}. This function differs from
1432 @code{equal?} in that a one dimensional shared array may be
1433 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
1434 @end deffn
1435
1436 @deffn {Scheme Procedure} array-contents array [strict]
1437 @deffnx {C Function} scm_array_contents (array, strict)
1438 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1439 without changing their order (last subscript changing fastest), then
1440 @code{array-contents} returns that shared array, otherwise it returns
1441 @code{#f}. All arrays made by @code{make-array} and
1442 @code{make-uniform-array} may be unrolled, some arrays made by
1443 @code{make-shared-array} may not be.
1444
1445 If the optional argument @var{strict} is provided, a shared array will
1446 be returned only if its elements are stored internally contiguous in
1447 memory.
1448 @end deffn
1449
1450 @node Array Mapping
1451 @subsubsection Array Mapping
1452
1453 @c FIXME: array-map! accepts no source arrays at all, and in that
1454 @c case makes calls "(proc)". Is that meant to be a documented
1455 @c feature?
1456 @c
1457 @c FIXME: array-for-each doesn't say what happens if the sources have
1458 @c different index ranges. The code currently iterates over the
1459 @c indices of the first and expects the others to cover those. That
1460 @c at least vaguely matches array-map!, but is is meant to be a
1461 @c documented feature?
1462
1463 @deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN
1464 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1465 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1466 Set each element of the @var{dst} array to values obtained from calls
1467 to @var{proc}. The value returned is unspecified.
1468
1469 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1470 where each @var{elem} is from the corresponding @var{src} array, at
1471 the @var{dst} index. @code{array-map-in-order!} makes the calls in
1472 row-major order, @code{array-map!} makes them in an unspecified order.
1473
1474 The @var{src} arrays must have the same number of dimensions as
1475 @var{dst}, and must have a range for each dimension which covers the
1476 range in @var{dst}. This ensures all @var{dst} indices are valid in
1477 each @var{src}.
1478 @end deffn
1479
1480 @deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN
1481 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1482 Apply @var{proc} to each tuple of elements of @var{src1} @dots{}
1483 @var{srcN}, in row-major order. The value returned is unspecified.
1484 @end deffn
1485
1486 @deffn {Scheme Procedure} array-index-map! dst proc
1487 @deffnx {C Function} scm_array_index_map_x (dst, proc)
1488 Set each element of the @var{dst} array to values returned by calls to
1489 @var{proc}. The value returned is unspecified.
1490
1491 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1492 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
1493 each dimension. The order in which the calls are made is unspecified.
1494
1495 For example, to create a @m{4\times4, 4x4} matrix representing a
1496 cyclic group,
1497
1498 @tex
1499 \advance\leftskip by 2\lispnarrowing {
1500 $\left(\matrix{%
1501 0 & 1 & 2 & 3 \cr
1502 1 & 2 & 3 & 0 \cr
1503 2 & 3 & 0 & 1 \cr
1504 3 & 0 & 1 & 2 \cr
1505 }\right)$} \par
1506 @end tex
1507 @ifnottex
1508 @example
1509 / 0 1 2 3 \
1510 | 1 2 3 0 |
1511 | 2 3 0 1 |
1512 \ 3 0 1 2 /
1513 @end example
1514 @end ifnottex
1515
1516 @example
1517 (define a (make-array #f 4 4))
1518 (array-index-map! a (lambda (i j)
1519 (modulo (+ i j) 4)))
1520 @end example
1521 @end deffn
1522
1523 @node Uniform Arrays
1524 @subsubsection Uniform Arrays
1525 @tpindex Uniform Arrays
1526
1527 @noindent
1528 @dfn{Uniform arrays} have elements all of the
1529 same type and occupy less storage than conventional
1530 arrays. Uniform arrays with a single zero-based dimension
1531 are also known as @dfn{uniform vectors}. The procedures in
1532 this section can also be used on conventional arrays, vectors,
1533 bit-vectors and strings.
1534
1535 @noindent
1536 When creating a uniform array, the type of data to be stored
1537 is indicated with a @var{prototype} argument. The following table
1538 lists the types available and example prototypes:
1539
1540 @example
1541 prototype type printing character
1542
1543 #t boolean (bit-vector) b
1544 #\a char (string) a
1545 #\nul byte (integer) y
1546 's short (integer) h
1547 1 unsigned long (integer) u
1548 -1 signed long (integer) e
1549 'l signed long long (integer) l
1550 1.0 float (single precision) s
1551 1/3 double (double precision float) i
1552 0+i complex (double precision) c
1553 () conventional vector
1554 @end example
1555
1556 Note that with the introduction of exact fractions in Guile 1.8,
1557 @samp{1/3} here is now a fraction, where previously such an expression
1558 was a double @samp{0.333@dots{}}. For most normal usages this should
1559 be source code compatible.
1560
1561 Unshared uniform arrays of characters with a single zero-based dimension
1562 are identical to strings:
1563
1564 @example
1565 (make-uniform-array #\a 3) @result{}
1566 "aaa"
1567 @end example
1568
1569 @noindent
1570 Unshared uniform arrays of booleans with a single zero-based dimension
1571 are identical to @ref{Bit Vectors, bit-vectors}.
1572
1573 @example
1574 (make-uniform-array #t 3) @result{}
1575 #*111
1576 @end example
1577
1578 @noindent
1579 Other uniform vectors are written in a form similar to that of vectors,
1580 except that a single character from the above table is put between
1581 @code{#} and @code{(}. For example, a uniform vector of signed
1582 long integers is displayed in the form @code{'#e(3 5 9)}.
1583
1584 @deffn {Scheme Procedure} make-uniform-array prototype bound1 bound2 @dots{}
1585 Create and return a uniform array of type corresponding to
1586 @var{prototype} that has as many dimensions as there are @var{bound}s
1587 and fill it with @var{prototype}.
1588 @end deffn
1589
1590 @deffn {Scheme Procedure} array-prototype ra
1591 @deffnx {C Function} scm_array_prototype (ra)
1592 Return an object that would produce an array of the same type
1593 as @var{array}, if used as the @var{prototype} for
1594 @code{make-uniform-array}.
1595 @end deffn
1596
1597 @deffn {Scheme Procedure} list->uniform-array ndim prot lst
1598 @deffnx {Scheme Procedure} list->uniform-vector prot lst
1599 @deffnx {C Function} scm_list_to_uniform_array (ndim, prot, lst)
1600 Return a uniform array of the type indicated by prototype
1601 @var{prot} with elements the same as those of @var{lst}.
1602 Elements must be of the appropriate type, no coercions are
1603 done.
1604 @end deffn
1605
1606 @deffn {Scheme Procedure} uniform-vector-fill! uve fill
1607 Store @var{fill} in every element of @var{uve}. The value returned is
1608 unspecified.
1609 @end deffn
1610
1611 @deffn {Scheme Procedure} uniform-vector-length v
1612 @deffnx {C Function} scm_uniform_vector_length (v)
1613 Return the number of elements in @var{uve}.
1614 @end deffn
1615
1616 @deffn {Scheme Procedure} dimensions->uniform-array dims prot [fill]
1617 @deffnx {Scheme Procedure} make-uniform-vector length prototype [fill]
1618 @deffnx {C Function} scm_dimensions_to_uniform_array (dims, prot, fill)
1619 Create and return a uniform array or vector of type
1620 corresponding to @var{prototype} with dimensions @var{dims} or
1621 length @var{length}. If @var{fill} is supplied, it's used to
1622 fill the array, otherwise @var{prototype} is used.
1623 @end deffn
1624
1625 @c Another compiled-closure. -twp
1626
1627 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
1628 @deffnx {Scheme Procedure} uniform-vector-read! uve [port-or-fdes] [start] [end]
1629 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
1630 Attempt to read all elements of @var{ura}, in lexicographic order, as
1631 binary objects from @var{port-or-fdes}.
1632 If an end of file is encountered,
1633 the objects up to that point are put into @var{ura}
1634 (starting at the beginning) and the remainder of the array is
1635 unchanged.
1636
1637 The optional arguments @var{start} and @var{end} allow
1638 a specified region of a vector (or linearized array) to be read,
1639 leaving the remainder of the vector unchanged.
1640
1641 @code{uniform-array-read!} returns the number of objects read.
1642 @var{port-or-fdes} may be omitted, in which case it defaults to the value
1643 returned by @code{(current-input-port)}.
1644 @end deffn
1645
1646 @deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]]
1647 @deffnx {Scheme Procedure} uniform-vector-write uve [port-or-fdes] [start] [end]
1648 @deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end)
1649 Writes all elements of @var{ura} as binary objects to
1650 @var{port-or-fdes}.
1651
1652 The optional arguments @var{start}
1653 and @var{end} allow
1654 a specified region of a vector (or linearized array) to be written.
1655
1656 The number of objects actually written is returned.
1657 @var{port-or-fdes} may be
1658 omitted, in which case it defaults to the value returned by
1659 @code{(current-output-port)}.
1660 @end deffn
1661
1662 @node Bit Vectors
1663 @subsubsection Bit Vectors
1664
1665 @noindent
1666 Bit vectors are a specific type of uniform array: an array of booleans
1667 with a single zero-based index.
1668
1669 @noindent
1670 They are displayed as a sequence of @code{0}s and
1671 @code{1}s prefixed by @code{#*}, e.g.,
1672
1673 @example
1674 (make-uniform-vector 8 #t #f) @result{}
1675 #*00000000
1676 @end example
1677
1678 @deffn {Scheme Procedure} bit-count bool bitvector
1679 @deffnx {C Function} scm_bit_count (bool, bitvector)
1680 Return a count of how many entries in @var{bitvector} are equal to
1681 @var{bool}. For example,
1682
1683 @example
1684 (bit-count #f #*000111000) @result{} 6
1685 @end example
1686 @end deffn
1687
1688 @deffn {Scheme Procedure} bit-position bool bitvector start
1689 @deffnx {C Function} scm_bit_position (bool, bitvector, start)
1690 Return the index of the first occurrance of @var{bool} in
1691 @var{bitvector}, starting from @var{start}. If there is no @var{bool}
1692 entry between @var{start} and the end of @var{bitvector}, then return
1693 @code{#f}. For example,
1694
1695 @example
1696 (bit-position #t #*000101 0) @result{} 3
1697 (bit-position #f #*0001111 3) @result{} #f
1698 @end example
1699 @end deffn
1700
1701 @deffn {Scheme Procedure} bit-invert! bitvector
1702 @deffnx {C Function} scm_bit_invert_x (bitvector)
1703 Modify @var{bitvector} by replacing each element with its negation.
1704 @end deffn
1705
1706 @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1707 @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1708 Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1709 selecting the entries to change. The return value is unspecified.
1710
1711 If @var{uvec} is a bit vector, then those entries where it has
1712 @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1713 @var{uvec} and @var{bitvector} must be the same length. When
1714 @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1715 @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1716 ANDNOT.
1717
1718 @example
1719 (define bv #*01000010)
1720 (bit-set*! bv #*10010001 #t)
1721 bv
1722 @result{} #*11010011
1723 @end example
1724
1725 If @var{uvec} is a uniform vector of unsigned long integers, then
1726 they're indexes into @var{bitvector} which are set to @var{bool}.
1727
1728 @example
1729 (define bv #*01000010)
1730 (bit-set*! bv #u(5 2 7) #t)
1731 bv
1732 @result{} #*01100111
1733 @end example
1734 @end deffn
1735
1736 @deffn {Scheme Procedure} bit-count* bitvector uvec bool
1737 @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1738 Return a count of how many entries in @var{bitvector} are equal to
1739 @var{bool}, with @var{uvec} selecting the entries to consider.
1740
1741 @var{uvec} is interpreted in the same way as for @code{bit-set*!}
1742 above. Namely, if @var{uvec} is a bit vector then entries which have
1743 @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1744 is a uniform vector of unsigned long integers then it's the indexes in
1745 @var{bitvector} to consider.
1746
1747 For example,
1748
1749 @example
1750 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1751 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1752 @end example
1753 @end deffn
1754
1755
1756 @node Dictionary Types
1757 @subsection Dictionary Types
1758
1759 A @dfn{dictionary} object is a data structure used to index
1760 information in a user-defined way. In standard Scheme, the main
1761 aggregate data types are lists and vectors. Lists are not really
1762 indexed at all, and vectors are indexed only by number
1763 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
1764 to index your data on some other type; for example, in a library
1765 catalog you might want to look up a book by the name of its
1766 author. Dictionaries are used to help you organize information in
1767 such a way.
1768
1769 An @dfn{association list} (or @dfn{alist} for short) is a list of
1770 key-value pairs. Each pair represents a single quantity or
1771 object; the @code{car} of the pair is a key which is used to
1772 identify the object, and the @code{cdr} is the object's value.
1773
1774 A @dfn{hash table} also permits you to index objects with
1775 arbitrary keys, but in a way that makes looking up any one object
1776 extremely fast. A well-designed hash system makes hash table
1777 lookups almost as fast as conventional array or vector references.
1778
1779 Alists are popular among Lisp programmers because they use only
1780 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
1781 and the equality primitives). No changes to the language core are
1782 necessary. Therefore, with Scheme's built-in list manipulation
1783 facilities, it is very convenient to handle data stored in an
1784 association list. Also, alists are highly portable and can be
1785 easily implemented on even the most minimal Lisp systems.
1786
1787 However, alists are inefficient, especially for storing large
1788 quantities of data. Because we want Guile to be useful for large
1789 software systems as well as small ones, Guile provides a rich set
1790 of tools for using either association lists or hash tables.
1791
1792 @node Association Lists
1793 @subsection Association Lists
1794 @tpindex Association Lists
1795 @tpindex Alist
1796
1797 @cindex Association List
1798 @cindex Alist
1799 @cindex Database
1800
1801 An association list is a conventional data structure that is often used
1802 to implement simple key-value databases. It consists of a list of
1803 entries in which each entry is a pair. The @dfn{key} of each entry is
1804 the @code{car} of the pair and the @dfn{value} of each entry is the
1805 @code{cdr}.
1806
1807 @example
1808 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
1809 (KEY2 . VALUE2)
1810 (KEY3 . VALUE3)
1811 @dots{}
1812 )
1813 @end example
1814
1815 @noindent
1816 Association lists are also known, for short, as @dfn{alists}.
1817
1818 The structure of an association list is just one example of the infinite
1819 number of possible structures that can be built using pairs and lists.
1820 As such, the keys and values in an association list can be manipulated
1821 using the general list structure procedures @code{cons}, @code{car},
1822 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
1823 because association lists are so useful, Guile also provides specific
1824 procedures for manipulating them.
1825
1826 @menu
1827 * Alist Key Equality::
1828 * Adding or Setting Alist Entries::
1829 * Retrieving Alist Entries::
1830 * Removing Alist Entries::
1831 * Sloppy Alist Functions::
1832 * Alist Example::
1833 @end menu
1834
1835 @node Alist Key Equality
1836 @subsubsection Alist Key Equality
1837
1838 All of Guile's dedicated association list procedures, apart from
1839 @code{acons}, come in three flavours, depending on the level of equality
1840 that is required to decide whether an existing key in the association
1841 list is the same as the key that the procedure call uses to identify the
1842 required entry.
1843
1844 @itemize @bullet
1845 @item
1846 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
1847 equality.
1848
1849 @item
1850 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
1851 key equality.
1852
1853 @item
1854 Procedures with @dfn{assoc} in their name use @code{equal?} to
1855 determine key equality.
1856 @end itemize
1857
1858 @code{acons} is an exception because it is used to build association
1859 lists which do not require their entries' keys to be unique.
1860
1861 @node Adding or Setting Alist Entries
1862 @subsubsection Adding or Setting Alist Entries
1863
1864 @code{acons} adds a new entry to an association list and returns the
1865 combined association list. The combined alist is formed by consing the
1866 new entry onto the head of the alist specified in the @code{acons}
1867 procedure call. So the specified alist is not modified, but its
1868 contents become shared with the tail of the combined alist that
1869 @code{acons} returns.
1870
1871 In the most common usage of @code{acons}, a variable holding the
1872 original association list is updated with the combined alist:
1873
1874 @example
1875 (set! address-list (acons name address address-list))
1876 @end example
1877
1878 In such cases, it doesn't matter that the old and new values of
1879 @code{address-list} share some of their contents, since the old value is
1880 usually no longer independently accessible.
1881
1882 Note that @code{acons} adds the specified new entry regardless of
1883 whether the alist may already contain entries with keys that are, in
1884 some sense, the same as that of the new entry. Thus @code{acons} is
1885 ideal for building alists where there is no concept of key uniqueness.
1886
1887 @example
1888 (set! task-list (acons 3 "pay gas bill" '()))
1889 task-list
1890 @result{}
1891 ((3 . "pay gas bill"))
1892
1893 (set! task-list (acons 3 "tidy bedroom" task-list))
1894 task-list
1895 @result{}
1896 ((3 . "tidy bedroom") (3 . "pay gas bill"))
1897 @end example
1898
1899 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
1900 or replace an entry in an association list where there @emph{is} a
1901 concept of key uniqueness. If the specified association list already
1902 contains an entry whose key is the same as that specified in the
1903 procedure call, the existing entry is replaced by the new one.
1904 Otherwise, the new entry is consed onto the head of the old association
1905 list to create the combined alist. In all cases, these procedures
1906 return the combined alist.
1907
1908 @code{assq-set!} and friends @emph{may} destructively modify the
1909 structure of the old association list in such a way that an existing
1910 variable is correctly updated without having to @code{set!} it to the
1911 value returned:
1912
1913 @example
1914 address-list
1915 @result{}
1916 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
1917
1918 (assoc-set! address-list "james" "1a London Road")
1919 @result{}
1920 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1921
1922 address-list
1923 @result{}
1924 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1925 @end example
1926
1927 Or they may not:
1928
1929 @example
1930 (assoc-set! address-list "bob" "11 Newington Avenue")
1931 @result{}
1932 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1933 ("james" . "1a London Road"))
1934
1935 address-list
1936 @result{}
1937 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1938 @end example
1939
1940 The only safe way to update an association list variable when adding or
1941 replacing an entry like this is to @code{set!} the variable to the
1942 returned value:
1943
1944 @example
1945 (set! address-list
1946 (assoc-set! address-list "bob" "11 Newington Avenue"))
1947 address-list
1948 @result{}
1949 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1950 ("james" . "1a London Road"))
1951 @end example
1952
1953 Because of this slight inconvenience, you may find it more convenient to
1954 use hash tables to store dictionary data. If your application will not
1955 be modifying the contents of an alist very often, this may not make much
1956 difference to you.
1957
1958 If you need to keep the old value of an association list in a form
1959 independent from the list that results from modification by
1960 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
1961 use @code{list-copy} to copy the old association list before modifying
1962 it.
1963
1964 @deffn {Scheme Procedure} acons key value alist
1965 @deffnx {C Function} scm_acons (key, value, alist)
1966 Add a new key-value pair to @var{alist}. A new pair is
1967 created whose car is @var{key} and whose cdr is @var{value}, and the
1968 pair is consed onto @var{alist}, and the new list is returned. This
1969 function is @emph{not} destructive; @var{alist} is not modified.
1970 @end deffn
1971
1972 @deffn {Scheme Procedure} assq-set! alist key val
1973 @deffnx {Scheme Procedure} assv-set! alist key value
1974 @deffnx {Scheme Procedure} assoc-set! alist key value
1975 @deffnx {C Function} scm_assq_set_x (alist, key, val)
1976 @deffnx {C Function} scm_assv_set_x (alist, key, val)
1977 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
1978 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
1979 @var{alist} entry for @var{key} and associate it with the new
1980 @var{value}. If @var{alist} does not contain an entry for @var{key},
1981 add a new one. Return the (possibly new) alist.
1982
1983 These functions do not attempt to verify the structure of @var{alist},
1984 and so may cause unusual results if passed an object that is not an
1985 association list.
1986 @end deffn
1987
1988 @node Retrieving Alist Entries
1989 @subsubsection Retrieving Alist Entries
1990 @rnindex assq
1991 @rnindex assv
1992 @rnindex assoc
1993
1994 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
1995 arguments and return the entry for that key if an entry exists, or
1996 @code{#f} if there is no entry for that key. Note that, in the cases
1997 where an entry exists, these procedures return the complete entry, that
1998 is @code{(KEY . VALUE)}, not just the value.
1999
2000 @deffn {Scheme Procedure} assq key alist
2001 @deffnx {Scheme Procedure} assv key alist
2002 @deffnx {Scheme Procedure} assoc key alist
2003 @deffnx {C Function} scm_assq (key, alist)
2004 @deffnx {C Function} scm_assv (key, alist)
2005 @deffnx {C Function} scm_assoc (key, alist)
2006 Fetch the entry in @var{alist} that is associated with @var{key}. To
2007 decide whether the argument @var{key} matches a particular entry in
2008 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
2009 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
2010 cannot be found in @var{alist} (according to whichever equality
2011 predicate is in use), then return @code{#f}. These functions
2012 return the entire alist entry found (i.e. both the key and the value).
2013 @end deffn
2014
2015 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
2016 hand, take an alist and a key and return @emph{just the value} for that
2017 key, if an entry exists. If there is no entry for the specified key,
2018 these procedures return @code{#f}.
2019
2020 This creates an ambiguity: if the return value is @code{#f}, it means
2021 either that there is no entry with the specified key, or that there
2022 @emph{is} an entry for the specified key, with value @code{#f}.
2023 Consequently, @code{assq-ref} and friends should only be used where it
2024 is known that an entry exists, or where the ambiguity doesn't matter
2025 for some other reason.
2026
2027 @deffn {Scheme Procedure} assq-ref alist key
2028 @deffnx {Scheme Procedure} assv-ref alist key
2029 @deffnx {Scheme Procedure} assoc-ref alist key
2030 @deffnx {C Function} scm_assq_ref (alist, key)
2031 @deffnx {C Function} scm_assv_ref (alist, key)
2032 @deffnx {C Function} scm_assoc_ref (alist, key)
2033 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
2034 value associated with @var{key} in @var{alist} is returned. These
2035 functions are equivalent to
2036
2037 @lisp
2038 (let ((ent (@var{associator} @var{key} @var{alist})))
2039 (and ent (cdr ent)))
2040 @end lisp
2041
2042 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
2043 @end deffn
2044
2045 @node Removing Alist Entries
2046 @subsubsection Removing Alist Entries
2047
2048 To remove the element from an association list whose key matches a
2049 specified key, use @code{assq-remove!}, @code{assv-remove!} or
2050 @code{assoc-remove!} (depending, as usual, on the level of equality
2051 required between the key that you specify and the keys in the
2052 association list).
2053
2054 As with @code{assq-set!} and friends, the specified alist may or may not
2055 be modified destructively, and the only safe way to update a variable
2056 containing the alist is to @code{set!} it to the value that
2057 @code{assq-remove!} and friends return.
2058
2059 @example
2060 address-list
2061 @result{}
2062 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
2063 ("james" . "1a London Road"))
2064
2065 (set! address-list (assoc-remove! address-list "mary"))
2066 address-list
2067 @result{}
2068 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
2069 @end example
2070
2071 Note that, when @code{assq/v/oc-remove!} is used to modify an
2072 association list that has been constructed only using the corresponding
2073 @code{assq/v/oc-set!}, there can be at most one matching entry in the
2074 alist, so the question of multiple entries being removed in one go does
2075 not arise. If @code{assq/v/oc-remove!} is applied to an association
2076 list that has been constructed using @code{acons}, or an
2077 @code{assq/v/oc-set!} with a different level of equality, or any mixture
2078 of these, it removes only the first matching entry from the alist, even
2079 if the alist might contain further matching entries. For example:
2080
2081 @example
2082 (define address-list '())
2083 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
2084 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
2085 address-list
2086 @result{}
2087 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
2088
2089 (set! address-list (assoc-remove! address-list "mary"))
2090 address-list
2091 @result{}
2092 (("mary" . "11 Elm Street"))
2093 @end example
2094
2095 In this example, the two instances of the string "mary" are not the same
2096 when compared using @code{eq?}, so the two @code{assq-set!} calls add
2097 two distinct entries to @code{address-list}. When compared using
2098 @code{equal?}, both "mary"s in @code{address-list} are the same as the
2099 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
2100 after removing the first matching entry that it finds, and so one of the
2101 "mary" entries is left in place.
2102
2103 @deffn {Scheme Procedure} assq-remove! alist key
2104 @deffnx {Scheme Procedure} assv-remove! alist key
2105 @deffnx {Scheme Procedure} assoc-remove! alist key
2106 @deffnx {C Function} scm_assq_remove_x (alist, key)
2107 @deffnx {C Function} scm_assv_remove_x (alist, key)
2108 @deffnx {C Function} scm_assoc_remove_x (alist, key)
2109 Delete the first entry in @var{alist} associated with @var{key}, and return
2110 the resulting alist.
2111 @end deffn
2112
2113 @node Sloppy Alist Functions
2114 @subsubsection Sloppy Alist Functions
2115
2116 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
2117 like the corresponding non-@code{sloppy-} procedures, except that they
2118 return @code{#f} when the specified association list is not well-formed,
2119 where the non-@code{sloppy-} versions would signal an error.
2120
2121 Specifically, there are two conditions for which the non-@code{sloppy-}
2122 procedures signal an error, which the @code{sloppy-} procedures handle
2123 instead by returning @code{#f}. Firstly, if the specified alist as a
2124 whole is not a proper list:
2125
2126 @example
2127 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2128 @result{}
2129 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
2130 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 2) ("key" . "door") . "open sesame")
2131
2132 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2133 @result{}
2134 #f
2135 @end example
2136
2137 @noindent
2138 Secondly, if one of the entries in the specified alist is not a pair:
2139
2140 @example
2141 (assoc 2 '((1 . 1) 2 (3 . 9)))
2142 @result{}
2143 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
2144 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 1) 2 (3 . 9))
2145
2146 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
2147 @result{}
2148 #f
2149 @end example
2150
2151 Unless you are explicitly working with badly formed association lists,
2152 it is much safer to use the non-@code{sloppy-} procedures, because they
2153 help to highlight coding and data errors that the @code{sloppy-}
2154 versions would silently cover up.
2155
2156 @deffn {Scheme Procedure} sloppy-assq key alist
2157 @deffnx {C Function} scm_sloppy_assq (key, alist)
2158 Behaves like @code{assq} but does not do any error checking.
2159 Recommended only for use in Guile internals.
2160 @end deffn
2161
2162 @deffn {Scheme Procedure} sloppy-assv key alist
2163 @deffnx {C Function} scm_sloppy_assv (key, alist)
2164 Behaves like @code{assv} but does not do any error checking.
2165 Recommended only for use in Guile internals.
2166 @end deffn
2167
2168 @deffn {Scheme Procedure} sloppy-assoc key alist
2169 @deffnx {C Function} scm_sloppy_assoc (key, alist)
2170 Behaves like @code{assoc} but does not do any error checking.
2171 Recommended only for use in Guile internals.
2172 @end deffn
2173
2174 @node Alist Example
2175 @subsubsection Alist Example
2176
2177 Here is a longer example of how alists may be used in practice.
2178
2179 @lisp
2180 (define capitals '(("New York" . "Albany")
2181 ("Oregon" . "Salem")
2182 ("Florida" . "Miami")))
2183
2184 ;; What's the capital of Oregon?
2185 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
2186 (assoc-ref capitals "Oregon") @result{} "Salem"
2187
2188 ;; We left out South Dakota.
2189 (set! capitals
2190 (assoc-set! capitals "South Dakota" "Pierre"))
2191 capitals
2192 @result{} (("South Dakota" . "Pierre")
2193 ("New York" . "Albany")
2194 ("Oregon" . "Salem")
2195 ("Florida" . "Miami"))
2196
2197 ;; And we got Florida wrong.
2198 (set! capitals
2199 (assoc-set! capitals "Florida" "Tallahassee"))
2200 capitals
2201 @result{} (("South Dakota" . "Pierre")
2202 ("New York" . "Albany")
2203 ("Oregon" . "Salem")
2204 ("Florida" . "Tallahassee"))
2205
2206 ;; After Oregon secedes, we can remove it.
2207 (set! capitals
2208 (assoc-remove! capitals "Oregon"))
2209 capitals
2210 @result{} (("South Dakota" . "Pierre")
2211 ("New York" . "Albany")
2212 ("Florida" . "Tallahassee"))
2213 @end lisp
2214
2215 @node Hash Tables
2216 @subsection Hash Tables
2217 @tpindex Hash Tables
2218
2219 @c FIXME::martin: Review me!
2220
2221 Hash tables are dictionaries which offer similar functionality as
2222 association lists: They provide a mapping from keys to values. The
2223 difference is that association lists need time linear in the size of
2224 elements when searching for entries, whereas hash tables can normally
2225 search in constant time. The drawback is that hash tables require a
2226 little bit more memory, and that you can not use the normal list
2227 procedures (@pxref{Lists}) for working with them.
2228
2229 @menu
2230 * Hash Table Examples:: Demonstration of hash table usage.
2231 * Hash Table Reference:: Hash table procedure descriptions.
2232 @end menu
2233
2234
2235 @node Hash Table Examples
2236 @subsubsection Hash Table Examples
2237
2238 @c FIXME::martin: Review me!
2239
2240 For demonstration purposes, this section gives a few usage examples of
2241 some hash table procedures, together with some explanation what they do.
2242
2243 First we start by creating a new hash table with 31 slots, and
2244 populate it with two key/value pairs.
2245
2246 @lisp
2247 (define h (make-hash-table 31))
2248
2249 (hashq-create-handle! h 'foo "bar")
2250 @result{}
2251 (foo . "bar")
2252
2253 (hashq-create-handle! h 'braz "zonk")
2254 @result{}
2255 (braz . "zonk")
2256
2257 (hashq-create-handle! h 'frob #f)
2258 @result{}
2259 (frob . #f)
2260 @end lisp
2261
2262 You can get the value for a given key with the procedure
2263 @code{hashq-ref}, but the problem with this procedure is that you
2264 cannot reliably determine whether a key does exists in the table. The
2265 reason is that the procedure returns @code{#f} if the key is not in
2266 the table, but it will return the same value if the key is in the
2267 table and just happens to have the value @code{#f}, as you can see in
2268 the following examples.
2269
2270 @lisp
2271 (hashq-ref h 'foo)
2272 @result{}
2273 "bar"
2274
2275 (hashq-ref h 'frob)
2276 @result{}
2277 #f
2278
2279 (hashq-ref h 'not-there)
2280 @result{}
2281 #f
2282 @end lisp
2283
2284 Better is to use the procedure @code{hashq-get-handle}, which makes a
2285 distinction between the two cases. Just like @code{assq}, this
2286 procedure returns a key/value-pair on success, and @code{#f} if the
2287 key is not found.
2288
2289 @lisp
2290 (hashq-get-handle h 'foo)
2291 @result{}
2292 (foo . "bar")
2293
2294 (hashq-get-handle h 'not-there)
2295 @result{}
2296 #f
2297 @end lisp
2298
2299 There is no procedure for calculating the number of key/value-pairs in
2300 a hash table, but @code{hash-fold} can be used for doing exactly that.
2301
2302 @lisp
2303 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
2304 @result{}
2305 3
2306 @end lisp
2307
2308 @node Hash Table Reference
2309 @subsubsection Hash Table Reference
2310
2311 @c FIXME: Describe in broad terms what happens for resizing, and what
2312 @c the initial size means for this.
2313
2314 Like the association list functions, the hash table functions come in
2315 several varieties, according to the equality test used for the keys.
2316 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
2317 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
2318 the @code{hashx-} functions use an application supplied test.
2319
2320 A single @code{make-hash-table} creates a hash table suitable for use
2321 with any set of functions, but it's imperative that just one set is
2322 then used consistently, or results will be unpredictable.
2323
2324 @sp 1
2325 Hash tables are implemented as a vector indexed by a hash value formed
2326 from the key, with an association list of key/value pairs for each
2327 bucket in case distinct keys hash together. Direct access to the
2328 pairs in those lists is provided by the @code{-handle-} functions.
2329
2330 When the number of table entries goes above a threshold the vector is
2331 increased and the entries rehashed, to prevent the bucket lists
2332 becoming too long and slowing down accesses. When the number of
2333 entries goes below a threshold the vector is decreased to save space.
2334
2335 @sp 1
2336 For the @code{hashx-} ``extended'' routines, an application supplies a
2337 @var{hash} function producing an integer index like @code{hashq} etc
2338 below, and an @var{assoc} alist search function like @code{assq} etc
2339 (@pxref{Retrieving Alist Entries}). Here's an example of such
2340 functions implementing case-insensitive hashing of string keys,
2341
2342 @example
2343 (use-modules (srfi srfi-1)
2344 (srfi srfi-13))
2345
2346 (define (my-hash str size)
2347 (remainder (string-hash-ci str) size))
2348 (define (my-assoc str alist)
2349 (find (lambda (pair) (string-ci=? str (car pair))) alist))
2350
2351 (define my-table (make-hash-table))
2352 (hashx-set! my-hash my-assoc my-table "foo" 123)
2353
2354 (hashx-ref my-hash my-assoc my-table "FOO")
2355 @result{} 123
2356 @end example
2357
2358 In a @code{hashx-} @var{hash} function the aim is to spread keys
2359 across the vector, so bucket lists don't become long. But the actual
2360 values are arbitrary as long as they're in the range 0 to
2361 @math{@var{size}-1}. Helpful functions for forming a hash value, in
2362 addition to @code{hashq} etc below, include @code{symbol-hash}
2363 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
2364 (@pxref{SRFI-13 Comparison}), and @code{char-set-hash} (@pxref{SRFI-14
2365 Predicates/Comparison}).
2366
2367 Note that currently, unfortunately, there's no @code{hashx-remove!}
2368 function, which rather limits the usefulness of the @code{hashx-}
2369 routines.
2370
2371 @sp 1
2372 @deffn {Scheme Procedure} make-hash-table [size]
2373 Create a new hash table, with an optional minimum vector @var{size}.
2374
2375 When @var{size} is given, the table vector will still grow and shrink
2376 automatically, as described above, but with @var{size} as a minimum.
2377 If an application knows roughly how many entries the table will hold
2378 then it can use @var{size} to avoid rehashing when initial entries are
2379 added.
2380 @end deffn
2381
2382 @deffn {Scheme Procedure} hash-ref table key [dflt]
2383 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
2384 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
2385 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
2386 @deffnx {C Function} scm_hash_ref (table, key, dflt)
2387 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
2388 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
2389 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
2390 Lookup @var{key} in the given hash @var{table}, and return the
2391 associated value. If @var{key} is not found, return @var{dflt}, or
2392 @code{#f} if @var{dflt} is not given.
2393 @end deffn
2394
2395 @deffn {Scheme Procedure} hash-set! table key val
2396 @deffnx {Scheme Procedure} hashq-set! table key val
2397 @deffnx {Scheme Procedure} hashv-set! table key val
2398 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
2399 @deffnx {C Function} scm_hash_set_x (table, key, val)
2400 @deffnx {C Function} scm_hashq_set_x (table, key, val)
2401 @deffnx {C Function} scm_hashv_set_x (table, key, val)
2402 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
2403 Associate @var{val} with @var{key} in the given hash @var{table}. If
2404 @var{key} is already present then it's associated value is changed.
2405 If it's not present then a new entry is created.
2406 @end deffn
2407
2408 @deffn {Scheme Procedure} hash-remove! table key
2409 @deffnx {Scheme Procedure} hashq-remove! table key
2410 @deffnx {Scheme Procedure} hashv-remove! table key
2411 @deffnx {C Function} scm_hash_remove_x (table, key)
2412 @deffnx {C Function} scm_hashq_remove_x (table, key)
2413 @deffnx {C Function} scm_hashv_remove_x (table, key)
2414 Remove any association for @var{key} in the given hash @var{table}.
2415 If @var{key} is not in @var{table} then nothing is done.
2416 @end deffn
2417
2418 @deffn {Scheme Procedure} hash key size
2419 @deffnx {Scheme Procedure} hashq key size
2420 @deffnx {Scheme Procedure} hashv key size
2421 @deffnx {C Function} scm_hash (key, size)
2422 @deffnx {C Function} scm_hashq (key, size)
2423 @deffnx {C Function} scm_hashv (key, size)
2424 Return a hash value for @var{key}. This is a number in the range
2425 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
2426 table of the given @var{size}.
2427
2428 Note that @code{hashq} and @code{hashv} may use internal addresses of
2429 objects, so if an object is garbage collected and re-created it can
2430 have a different hash value, even when the two are notionally
2431 @code{eq?}. For instance with symbols,
2432
2433 @example
2434 (hashq 'something 123) @result{} 19
2435 (gc)
2436 (hashq 'something 123) @result{} 62
2437 @end example
2438
2439 In normal use this is not a problem, since an object entered into a
2440 hash table won't be garbage collected until removed. It's only if
2441 hashing calculations are somehow separated from normal references that
2442 its lifetime needs to be considered.
2443 @end deffn
2444
2445 @deffn {Scheme Procedure} hash-get-handle table key
2446 @deffnx {Scheme Procedure} hashq-get-handle table key
2447 @deffnx {Scheme Procedure} hashv-get-handle table key
2448 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
2449 @deffnx {C Function} scm_hash_get_handle (table, key)
2450 @deffnx {C Function} scm_hashq_get_handle (table, key)
2451 @deffnx {C Function} scm_hashv_get_handle (table, key)
2452 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
2453 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2454 given hash @var{table}, or @code{#f} if @var{key} is not in
2455 @var{table}.
2456 @end deffn
2457
2458 @deffn {Scheme Procedure} hash-create-handle! table key init
2459 @deffnx {Scheme Procedure} hashq-create-handle! table key init
2460 @deffnx {Scheme Procedure} hashv-create-handle! table key init
2461 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
2462 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
2463 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
2464 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
2465 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
2466 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2467 given hash @var{table}. If @var{key} is not in @var{table} then
2468 create an entry for it with @var{init} as the value, and return that
2469 pair.
2470 @end deffn
2471
2472 @deffn {Scheme Procedure} hash-map->list proc table
2473 @deffnx {Scheme Procedure} hash-for-each proc table
2474 @deffnx {C Function} scm_hash_map_to_list (proc, table)
2475 @deffnx {C Function} scm_hash_for_each (proc, table)
2476 Apply @var{proc} to the entries in the given hash @var{table}. Each
2477 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
2478 returns a list of the results from these calls, @code{hash-for-each}
2479 discards the results and returns an unspecified value.
2480
2481 Calls are made over the table entries in an unspecified order, and for
2482 @code{hash-map->list} the order of the values in the returned list is
2483 unspecified. Results will be unpredictable if @var{table} is modified
2484 while iterating.
2485
2486 For example the following returns a new alist comprising all the
2487 entries from @code{mytable}, in no particular order.
2488
2489 @example
2490 (hash-map->list cons mytable)
2491 @end example
2492 @end deffn
2493
2494 @deffn {Scheme Procedure} hash-for-each-handle proc table
2495 @deffnx {C Function} scm_hash_for_each_handle (proc, table)
2496 Apply @var{proc} to the entries in the given hash @var{table}. Each
2497 call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
2498 @code{(@var{key} . @var{value})} pair. Return an unspecified value.
2499
2500 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
2501 the argument list of @var{proc}.
2502 @end deffn
2503
2504 @deffn {Scheme Procedure} hash-fold proc init table
2505 @deffnx {C Function} scm_hash_fold (proc, init, table)
2506 Accumulate a result by applying @var{proc} to the elements of the
2507 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
2508 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
2509 from the @var{table} and @var{prior-result} is the return from the
2510 previous @var{proc} call. For the first call, @var{prior-result} is
2511 the given @var{init} value.
2512
2513 Calls are made over the table entries in an unspecified order.
2514 Results will be unpredictable if @var{table} is modified while
2515 @code{hash-fold} is running.
2516
2517 For example, the following returns a count of how many keys in
2518 @code{mytable} are strings.
2519
2520 @example
2521 (hash-fold (lambda (key value prior)
2522 (if (string? key) (1+ prior) prior))
2523 0 mytable)
2524 @end example
2525 @end deffn
2526
2527
2528 @c Local Variables:
2529 @c TeX-master: "guile.texi"
2530 @c End: