2 @node Compound Data Types
3 @chapter Compound Data Types
5 This chapter describes Guile's compound data types. By @dfn{compound}
6 we mean that the primary purpose of these data types is to act as
7 containers for other kinds of data (including other compound objects).
8 For instance, a (non-uniform) vector with length 5 is a container that
9 can hold five arbitrary Scheme objects.
11 The various kinds of container object differ from each other in how
12 their memory is allocated, how they are indexed, and how particular
13 values can be looked up within them.
16 * Pairs:: Scheme's basic building block.
17 * Lists:: Special list functions supported by Guile.
18 * Vectors:: One-dimensional arrays of Scheme objects.
21 * Arrays:: Arrays of values.
22 * Association Lists and Hash Tables:: Dictionary data types.
30 Pairs are used to combine two Scheme objects into one compound object.
31 Hence the name: A pair stores a pair of objects.
33 The data type @dfn{pair} is extremely important in Scheme, just like in
34 any other Lisp dialect. The reason is that pairs are not only used to
35 make two values available as one object, but that pairs are used for
36 constructing lists of values. Because lists are so important in Scheme,
37 they are described in a section of their own (@pxref{Lists}).
39 Pairs can literally get entered in source code or at the REPL, in the
40 so-called @dfn{dotted list} syntax. This syntax consists of an opening
41 parentheses, the first element of the pair, a dot, the second element
42 and a closing parentheses. The following example shows how a pair
43 consisting of the two numbers 1 and 2, and a pair containing the symbols
44 @code{foo} and @code{bar} can be entered. It is very important to write
45 the whitespace before and after the dot, because otherwise the Scheme
46 parser would not be able to figure out where to split the tokens.
53 But beware, if you want to try out these examples, you have to
54 @dfn{quote} the expressions. More information about quotation is
55 available in the section (REFFIXME). The correct way to try these
56 examples is as follows.
67 A new pair is made by calling the procedure @code{cons} with two
68 arguments. Then the argument values are stored into a newly allocated
69 pair, and the pair is returned. The name @code{cons} stands for
70 "construct". Use the procedure @code{pair?} to test whether a
71 given Scheme object is a pair or not.
74 @deffn {Scheme Procedure} cons x y
75 @deffnx {C Function} scm_cons (x, y)
76 Return a newly allocated pair whose car is @var{x} and whose
77 cdr is @var{y}. The pair is guaranteed to be different (in the
78 sense of @code{eq?}) from every previously existing object.
82 @deffn {Scheme Procedure} pair? x
83 @deffnx {C Function} scm_pair_p (x)
84 Return @code{#t} if @var{x} is a pair; otherwise return
88 The two parts of a pair are traditionally called @dfn{car} and
89 @dfn{cdr}. They can be retrieved with procedures of the same name
90 (@code{car} and @code{cdr}), and can be modified with the procedures
91 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
92 Scheme programs is to access the car of a pair, or the car of the cdr of
93 a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
98 @deffn {Scheme Procedure} car pair
99 @deffnx {Scheme Procedure} cdr pair
100 Return the car or the cdr of @var{pair}, respectively.
103 @deffn {Scheme Procedure} caar pair
104 @deffnx {Scheme Procedure} cadr pair @dots{}
105 @deffnx {Scheme Procedure} cdddar pair
106 @deffnx {Scheme Procedure} cddddr pair
107 These procedures are compositions of @code{car} and @code{cdr}, where
108 for example @code{caddr} could be defined by
111 (define caddr (lambda (x) (car (cdr (cdr x)))))
116 @deffn {Scheme Procedure} set-car! pair value
117 @deffnx {C Function} scm_set_car_x (pair, value)
118 Stores @var{value} in the car field of @var{pair}. The value returned
119 by @code{set-car!} is unspecified.
123 @deffn {Scheme Procedure} set-cdr! pair value
124 @deffnx {C Function} scm_set_cdr_x (pair, value)
125 Stores @var{value} in the cdr field of @var{pair}. The value returned
126 by @code{set-cdr!} is unspecified.
134 A very important data type in Scheme---as well as in all other Lisp
135 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
136 Scheme does not have a real datatype @dfn{list}. Lists are made up of
137 @dfn{chained pairs}, and only exist by definition---a list is a chain
138 of pairs which looks like a list.}
140 This is the short definition of what a list is:
144 Either the empty list @code{()},
147 or a pair which has a list in its cdr.
150 @c FIXME::martin: Describe the pair chaining in more detail.
152 @c FIXME::martin: What is a proper, what an improper list?
153 @c What is a circular list?
155 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
159 * List Syntax:: Writing literal lists.
160 * List Predicates:: Testing lists.
161 * List Constructors:: Creating new lists.
162 * List Selection:: Selecting from lists, getting their length.
163 * Append/Reverse:: Appending and reversing lists.
164 * List Modification:: Modifying existing lists.
165 * List Searching:: Searching for list elements
166 * List Mapping:: Applying procedures to lists.
170 @subsection List Read Syntax
172 The syntax for lists is an opening parentheses, then all the elements of
173 the list (separated by whitespace) and finally a closing
174 parentheses.@footnote{Note that there is no separation character between
175 the list elements, like a comma or a semicolon.}.
178 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
179 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
180 () ; @r{the empty list}
183 The last example needs a bit more explanation. A list with no elements,
184 called the @dfn{empty list}, is special in some ways. It is used for
185 terminating lists by storing it into the cdr of the last pair that makes
186 up a list. An example will clear that up:
197 This example also shows that lists have to be quoted (REFFIXME) when
198 written, because they would otherwise be mistakingly taken as procedure
199 applications (@pxref{Simple Invocation}).
202 @node List Predicates
203 @subsection List Predicates
205 Often it is useful to test whether a given Scheme object is a list or
206 not. List-processing procedures could use this information to test
207 whether their input is valid, or they could do different things
208 depending on the datatype of their arguments.
211 @deffn {Scheme Procedure} list? x
212 @deffnx {C Function} scm_list_p (x)
213 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
216 The predicate @code{null?} is often used in list-processing code to
217 tell whether a given list has run out of elements. That is, a loop
218 somehow deals with the elements of a list until the list satisfies
219 @code{null?}. Then, the algorithm terminates.
222 @deffn {Scheme Procedure} null? x
223 @deffnx {C Function} scm_null_p (x)
224 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
227 @node List Constructors
228 @subsection List Constructors
230 This section describes the procedures for constructing new lists.
231 @code{list} simply returns a list where the elements are the arguments,
232 @code{cons*} is similar, but the last argument is stored in the cdr of
233 the last pair of the list.
235 @c C Function scm_list(rest) used to be documented here, but it's a
236 @c no-op since it does nothing but return the list the caller must
237 @c have already created.
239 @deffn {Scheme Procedure} list elem1 @dots{} elemN
240 @deffnx {C Function} scm_list_1 (elem1)
241 @deffnx {C Function} scm_list_2 (elem1, elem2)
242 @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
243 @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
244 @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
245 @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
247 Return a new list containing elements @var{elem1} to @var{elemN}.
249 @code{scm_list_n} takes a variable number of arguments, terminated by
250 the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
251 not included in the list. None of @var{elem1} to @var{elemN} can
252 themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
253 terminate at that point.
256 @c C Function scm_cons_star(arg1,rest) used to be documented here,
257 @c but it's not really a useful interface, since it expects the
258 @c caller to have already consed up all but the first argument
261 @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
262 Like @code{list}, but the last arg provides the tail of the
263 constructed list, returning @code{(cons @var{arg1} (cons
264 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
265 argument. If given one argument, that argument is returned as
266 result. This function is called @code{list*} in some other
267 Schemes and in Common LISP.
270 @deffn {Scheme Procedure} list-copy lst
271 @deffnx {C Function} scm_list_copy (lst)
272 Return a (newly-created) copy of @var{lst}.
275 @deffn {Scheme Procedure} make-list n [init]
276 Create a list containing of @var{n} elements, where each element is
277 initialized to @var{init}. @var{init} defaults to the empty list
278 @code{()} if not given.
281 Note that @code{list-copy} only makes a copy of the pairs which make up
282 the spine of the lists. The list elements are not copied, which means
283 that modifying the elements of the new list also modifies the elements
284 of the old list. On the other hand, applying procedures like
285 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
286 list. If you also need to copy the list elements (making a deep copy),
287 use the procedure @code{copy-tree} (@pxref{Copying}).
290 @subsection List Selection
292 These procedures are used to get some information about a list, or to
293 retrieve one or more elements of a list.
296 @deffn {Scheme Procedure} length lst
297 @deffnx {C Function} scm_length (lst)
298 Return the number of elements in list @var{lst}.
301 @deffn {Scheme Procedure} last-pair lst
302 @deffnx {C Function} scm_last_pair (lst)
303 Return a pointer to the last pair in @var{lst}, signalling an error if
304 @var{lst} is circular.
308 @deffn {Scheme Procedure} list-ref list k
309 @deffnx {C Function} scm_list_ref (list, k)
310 Return the @var{k}th element from @var{list}.
314 @deffn {Scheme Procedure} list-tail lst k
315 @deffnx {Scheme Procedure} list-cdr-ref lst k
316 @deffnx {C Function} scm_list_tail (lst, k)
317 Return the "tail" of @var{lst} beginning with its @var{k}th element.
318 The first element of the list is considered to be element 0.
320 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
321 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
322 or returning the results of cdring @var{k} times down @var{lst}.
325 @deffn {Scheme Procedure} list-head lst k
326 @deffnx {C Function} scm_list_head (lst, k)
327 Copy the first @var{k} elements from @var{lst} into a new list, and
332 @subsection Append and Reverse
334 @code{append} and @code{append!} are used to concatenate two or more
335 lists in order to form a new list. @code{reverse} and @code{reverse!}
336 return lists with the same elements as their arguments, but in reverse
337 order. The procedure variants with an @code{!} directly modify the
338 pairs which form the list, whereas the other procedures create new
339 pairs. This is why you should be careful when using the side-effecting
343 @deffn {Scheme Procedure} append . args
344 @deffnx {C Function} scm_append (args)
345 Return a list consisting of the elements the lists passed as
348 (append '(x) '(y)) @result{} (x y)
349 (append '(a) '(b c d)) @result{} (a b c d)
350 (append '(a (b)) '((c))) @result{} (a (b) (c))
352 The resulting list is always newly allocated, except that it
353 shares structure with the last list argument. The last
354 argument may actually be any object; an improper list results
355 if the last argument is not a proper list.
357 (append '(a b) '(c . d)) @result{} (a b c . d)
358 (append '() 'a) @result{} a
362 @deffn {Scheme Procedure} append! . lists
363 @deffnx {C Function} scm_append_x (lists)
364 A destructive version of @code{append} (@pxref{Pairs and
365 lists,,,r5rs, The Revised^5 Report on Scheme}). The cdr field
366 of each list's final pair is changed to point to the head of
367 the next list, so no consing is performed. Return a pointer to
372 @deffn {Scheme Procedure} reverse lst
373 @deffnx {C Function} scm_reverse (lst)
374 Return a new list that contains the elements of @var{lst} but
378 @c NJFIXME explain new_tail
379 @deffn {Scheme Procedure} reverse! lst [new_tail]
380 @deffnx {C Function} scm_reverse_x (lst, new_tail)
381 A destructive version of @code{reverse} (@pxref{Pairs and lists,,,r5rs,
382 The Revised^5 Report on Scheme}). The cdr of each cell in @var{lst} is
383 modified to point to the previous list element. Return a pointer to the
384 head of the reversed list.
386 Caveat: because the list is modified in place, the tail of the original
387 list now becomes its head, and the head of the original list now becomes
388 the tail. Therefore, the @var{lst} symbol to which the head of the
389 original list was bound now points to the tail. To ensure that the head
390 of the modified list is not lost, it is wise to save the return value of
394 @node List Modification
395 @subsection List Modification
397 The following procedures modify an existing list, either by changing
398 elements of the list, or by changing the list structure itself.
400 @deffn {Scheme Procedure} list-set! list k val
401 @deffnx {C Function} scm_list_set_x (list, k, val)
402 Set the @var{k}th element of @var{list} to @var{val}.
405 @deffn {Scheme Procedure} list-cdr-set! list k val
406 @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
407 Set the @var{k}th cdr of @var{list} to @var{val}.
410 @deffn {Scheme Procedure} delq item lst
411 @deffnx {C Function} scm_delq (item, lst)
412 Return a newly-created copy of @var{lst} with elements
413 @code{eq?} to @var{item} removed. This procedure mirrors
414 @code{memq}: @code{delq} compares elements of @var{lst} against
415 @var{item} with @code{eq?}.
418 @deffn {Scheme Procedure} delv item lst
419 @deffnx {C Function} scm_delv (item, lst)
420 Return a newly-created copy of @var{lst} with elements
421 @code{eqv?} to @var{item} removed. This procedure mirrors
422 @code{memv}: @code{delv} compares elements of @var{lst} against
423 @var{item} with @code{eqv?}.
426 @deffn {Scheme Procedure} delete item lst
427 @deffnx {C Function} scm_delete (item, lst)
428 Return a newly-created copy of @var{lst} with elements
429 @code{equal?} to @var{item} removed. This procedure mirrors
430 @code{member}: @code{delete} compares elements of @var{lst}
431 against @var{item} with @code{equal?}.
434 @deffn {Scheme Procedure} delq! item lst
435 @deffnx {Scheme Procedure} delv! item lst
436 @deffnx {Scheme Procedure} delete! item lst
437 @deffnx {C Function} scm_delq_x (item, lst)
438 @deffnx {C Function} scm_delv_x (item, lst)
439 @deffnx {C Function} scm_delete_x (item, lst)
440 These procedures are destructive versions of @code{delq}, @code{delv}
441 and @code{delete}: they modify the pointers in the existing @var{lst}
442 rather than creating a new list. Caveat evaluator: Like other
443 destructive list functions, these functions cannot modify the binding of
444 @var{lst}, and so cannot be used to delete the first element of
445 @var{lst} destructively.
448 @deffn {Scheme Procedure} delq1! item lst
449 @deffnx {C Function} scm_delq1_x (item, lst)
450 Like @code{delq!}, but only deletes the first occurrence of
451 @var{item} from @var{lst}. Tests for equality using
452 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
455 @deffn {Scheme Procedure} delv1! item lst
456 @deffnx {C Function} scm_delv1_x (item, lst)
457 Like @code{delv!}, but only deletes the first occurrence of
458 @var{item} from @var{lst}. Tests for equality using
459 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
462 @deffn {Scheme Procedure} delete1! item lst
463 @deffnx {C Function} scm_delete1_x (item, lst)
464 Like @code{delete!}, but only deletes the first occurrence of
465 @var{item} from @var{lst}. Tests for equality using
466 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
470 @subsection List Searching
472 The following procedures search lists for particular elements. They use
473 different comparison predicates for comparing list elements with the
474 object to be searched. When they fail, they return @code{#f}, otherwise
475 they return the sublist whose car is equal to the search object, where
476 equality depends on the equality predicate used.
479 @deffn {Scheme Procedure} memq x lst
480 @deffnx {C Function} scm_memq (x, lst)
481 Return the first sublist of @var{lst} whose car is @code{eq?}
482 to @var{x} where the sublists of @var{lst} are the non-empty
483 lists returned by @code{(list-tail @var{lst} @var{k})} for
484 @var{k} less than the length of @var{lst}. If @var{x} does not
485 occur in @var{lst}, then @code{#f} (not the empty list) is
490 @deffn {Scheme Procedure} memv x lst
491 @deffnx {C Function} scm_memv (x, lst)
492 Return the first sublist of @var{lst} whose car is @code{eqv?}
493 to @var{x} where the sublists of @var{lst} are the non-empty
494 lists returned by @code{(list-tail @var{lst} @var{k})} for
495 @var{k} less than the length of @var{lst}. If @var{x} does not
496 occur in @var{lst}, then @code{#f} (not the empty list) is
501 @deffn {Scheme Procedure} member x lst
502 @deffnx {C Function} scm_member (x, lst)
503 Return the first sublist of @var{lst} whose car is
504 @code{equal?} to @var{x} where the sublists of @var{lst} are
505 the non-empty lists returned by @code{(list-tail @var{lst}
506 @var{k})} for @var{k} less than the length of @var{lst}. If
507 @var{x} does not occur in @var{lst}, then @code{#f} (not the
508 empty list) is returned.
513 @subsection List Mapping
515 List processing is very convenient in Scheme because the process of
516 iterating over the elements of a list can be highly abstracted. The
517 procedures in this section are the most basic iterating procedures for
518 lists. They take a procedure and one or more lists as arguments, and
519 apply the procedure to each element of the list. They differ in their
523 @c begin (texi-doc-string "guile" "map")
524 @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
525 @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
526 @deffnx {C Function} scm_map (proc, arg1, args)
527 Apply @var{proc} to each element of the list @var{arg1} (if only two
528 arguments are given), or to the corresponding elements of the argument
529 lists (if more than two arguments are given). The result(s) of the
530 procedure applications are saved and returned in a list. For
531 @code{map}, the order of procedure applications is not specified,
532 @code{map-in-order} applies the procedure from left to right to the list
537 @c begin (texi-doc-string "guile" "for-each")
538 @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
539 Like @code{map}, but the procedure is always applied from left to right,
540 and the result(s) of the procedure applications are thrown away. The
541 return value is not specified.
549 Vectors are sequences of Scheme objects. Unlike lists, the length of a
550 vector, once the vector is created, cannot be changed. The advantage of
551 vectors over lists is that the time required to access one element of a vector
552 given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
553 is constant, whereas lists have an access time linear to the position of the
554 accessed element in the list.
556 Vectors can contain any kind of Scheme object; it is even possible to have
557 different types of objects in the same vector. For vectors containing
558 vectors, you may wish to use arrays, instead. Note, too, that some array
559 procedures operate happily on vectors (@pxref{Arrays}).
562 * Vector Syntax:: Read syntax for vectors.
563 * Vector Creation:: Dynamic vector creation and validation.
564 * Vector Accessors:: Accessing and modifying vector contents.
569 @subsection Read Syntax for Vectors
571 Vectors can literally be entered in source code, just like strings,
572 characters or some of the other data types. The read syntax for vectors
573 is as follows: A sharp sign (@code{#}), followed by an opening
574 parentheses, all elements of the vector in their respective read syntax,
575 and finally a closing parentheses. The following are examples of the
576 read syntax for vectors; where the first vector only contains numbers
577 and the second three different object types: a string, a symbol and a
578 number in hexadecimal notation.
582 #("Hello" foo #xdeadbeef)
585 Like lists, vectors have to be quoted (REFFIXME):
588 '#(a b c) @result{} #(a b c)
591 @node Vector Creation
592 @subsection Dynamic Vector Creation and Validation
594 Instead of creating a vector implicitly by using the read syntax just
595 described, you can create a vector dynamically by calling one of the
596 @code{vector} and @code{list->vector} primitives with the list of Scheme
597 values that you want to place into a vector. The size of the vector
598 thus created is determined implicitly by the number of arguments given.
601 @rnindex list->vector
602 @deffn {Scheme Procedure} vector . l
603 @deffnx {Scheme Procedure} list->vector l
604 @deffnx {C Function} scm_vector (l)
605 Return a newly allocated vector composed of the
606 given arguments. Analogous to @code{list}.
609 (vector 'a 'b 'c) @result{} #(a b c)
613 (As an aside, an interesting implementation detail is that the Guile
614 reader reads the @code{#(@dots{})} syntax by reading everything but the
615 initial @code{#} as a @emph{list}, and then passing the list that
616 results to @code{list->vector}. Notice how neatly this fits with the
617 similarity between the read (and print) syntaxes for lists and vectors.)
619 The inverse operation is @code{vector->list}:
621 @rnindex vector->list
622 @deffn {Scheme Procedure} vector->list v
623 @deffnx {C Function} scm_vector_to_list (v)
624 Return a newly allocated list composed of the elements of @var{v}.
627 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
628 (list->vector '(dididit dah)) @result{} #(dididit dah)
632 To allocate a vector with an explicitly specified size, use
633 @code{make-vector}. With this primitive you can also specify an initial
634 value for the vector elements (the same value for all elements, that
638 @deffn {Scheme Procedure} make-vector k [fill]
639 @deffnx {C Function} scm_make_vector (k, fill)
640 Return a newly allocated vector of @var{k} elements. If a
641 second argument is given, then each position is initialized to
642 @var{fill}. Otherwise the initial contents of each position is
646 To check whether an arbitrary Scheme value @emph{is} a vector, use the
647 @code{vector?} primitive:
650 @deffn {Scheme Procedure} vector? obj
651 @deffnx {C Function} scm_vector_p (obj)
652 Return @code{#t} if @var{obj} is a vector, otherwise return
657 @node Vector Accessors
658 @subsection Accessing and Modifying Vector Contents
660 @code{vector-length} and @code{vector-ref} return information about a
661 given vector, respectively its size and the elements that are contained
664 @rnindex vector-length
665 @deffn {Scheme Procedure} vector-length vector
666 @deffnx {C Function} scm_vector_length vector
667 Return the number of elements in @var{vector} as an exact integer.
671 @deffn {Scheme Procedure} vector-ref vector k
672 @deffnx {C Function} scm_vector_ref vector k
673 Return the contents of position @var{k} of @var{vector}.
674 @var{k} must be a valid index of @var{vector}.
676 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
677 (vector-ref '#(1 1 2 3 5 8 13 21)
678 (let ((i (round (* 2 (acos -1)))))
685 A vector created by one of the dynamic vector constructor procedures
686 (@pxref{Vector Creation}) can be modified using the following
689 @emph{NOTE:} According to R5RS, it is an error to use any of these
690 procedures on a literally read vector, because such vectors should be
691 considered as constants. Currently, however, Guile does not detect this
695 @deffn {Scheme Procedure} vector-set! vector k obj
696 @deffnx {C Function} scm_vector_set_x vector k obj
697 Store @var{obj} in position @var{k} of @var{vector}.
698 @var{k} must be a valid index of @var{vector}.
699 The value returned by @samp{vector-set!} is unspecified.
701 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
702 (vector-set! vec 1 '("Sue" "Sue"))
703 vec) @result{} #(0 ("Sue" "Sue") "Anna")
707 @rnindex vector-fill!
708 @deffn {Scheme Procedure} vector-fill! v fill
709 @deffnx {C Function} scm_vector_fill_x (v, fill)
710 Store @var{fill} in every position of @var{vector}. The value
711 returned by @code{vector-fill!} is unspecified.
714 @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
715 @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
716 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
717 to @var{vec2} starting at position @var{start2}. @var{start1} and
718 @var{start2} are inclusive indices; @var{end1} is exclusive.
720 @code{vector-move-left!} copies elements in leftmost order.
721 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
722 same vector, @code{vector-move-left!} is usually appropriate when
723 @var{start1} is greater than @var{start2}.
726 @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
727 @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
728 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
729 to @var{vec2} starting at position @var{start2}. @var{start1} and
730 @var{start2} are inclusive indices; @var{end1} is exclusive.
732 @code{vector-move-right!} copies elements in rightmost order.
733 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
734 same vector, @code{vector-move-right!} is usually appropriate when
735 @var{start1} is less than @var{start2}.
742 A @dfn{record type} is a first class object representing a user-defined
743 data type. A @dfn{record} is an instance of a record type.
745 @deffn {Scheme Procedure} record? obj
746 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
749 Note that @code{record?} may be true of any Scheme value; there is no
750 promise that records are disjoint with other Scheme types.
753 @deffn {Scheme Procedure} make-record-type type-name field-names
754 Return a @dfn{record-type descriptor}, a value representing a new data
755 type disjoint from all others. The @var{type-name} argument must be a
756 string, but is only used for debugging purposes (such as the printed
757 representation of a record of the new type). The @var{field-names}
758 argument is a list of symbols naming the @dfn{fields} of a record of the
759 new type. It is an error if the list contains any duplicates. It is
760 unspecified how record-type descriptors are represented.
763 @deffn {Scheme Procedure} record-constructor rtd [field-names]
764 Return a procedure for constructing new members of the type represented
765 by @var{rtd}. The returned procedure accepts exactly as many arguments
766 as there are symbols in the given list, @var{field-names}; these are
767 used, in order, as the initial values of those fields in a new record,
768 which is returned by the constructor procedure. The values of any
769 fields not named in that list are unspecified. The @var{field-names}
770 argument defaults to the list of field names in the call to
771 @code{make-record-type} that created the type represented by @var{rtd};
772 if the @var{field-names} argument is provided, it is an error if it
773 contains any duplicates or any symbols not in the default list.
776 @deffn {Scheme Procedure} record-predicate rtd
777 Return a procedure for testing membership in the type represented by
778 @var{rtd}. The returned procedure accepts exactly one argument and
779 returns a true value if the argument is a member of the indicated record
780 type; it returns a false value otherwise.
783 @deffn {Scheme Procedure} record-accessor rtd field-name
784 Return a procedure for reading the value of a particular field of a
785 member of the type represented by @var{rtd}. The returned procedure
786 accepts exactly one argument which must be a record of the appropriate
787 type; it returns the current value of the field named by the symbol
788 @var{field-name} in that record. The symbol @var{field-name} must be a
789 member of the list of field-names in the call to @code{make-record-type}
790 that created the type represented by @var{rtd}.
793 @deffn {Scheme Procedure} record-modifier rtd field-name
794 Return a procedure for writing the value of a particular field of a
795 member of the type represented by @var{rtd}. The returned procedure
796 accepts exactly two arguments: first, a record of the appropriate type,
797 and second, an arbitrary Scheme value; it modifies the field named by
798 the symbol @var{field-name} in that record to contain the given value.
799 The returned value of the modifier procedure is unspecified. The symbol
800 @var{field-name} must be a member of the list of field-names in the call
801 to @code{make-record-type} that created the type represented by
805 @deffn {Scheme Procedure} record-type-descriptor record
806 Return a record-type descriptor representing the type of the given
807 record. That is, for example, if the returned descriptor were passed to
808 @code{record-predicate}, the resulting predicate would return a true
809 value when passed the given record. Note that it is not necessarily the
810 case that the returned descriptor is the one that was passed to
811 @code{record-constructor} in the call that created the constructor
812 procedure that created the given record.
815 @deffn {Scheme Procedure} record-type-name rtd
816 Return the type-name associated with the type represented by rtd. The
817 returned value is @code{eqv?} to the @var{type-name} argument given in
818 the call to @code{make-record-type} that created the type represented by
822 @deffn {Scheme Procedure} record-type-fields rtd
823 Return a list of the symbols naming the fields in members of the type
824 represented by @var{rtd}. The returned value is @code{equal?} to the
825 field-names argument given in the call to @code{make-record-type} that
826 created the type represented by @var{rtd}.
834 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
837 A @dfn{structure type} is a first class user-defined data type. A
838 @dfn{structure} is an instance of a structure type. A structure type is
841 Structures are less abstract and more general than traditional records.
842 In fact, in Guile Scheme, records are implemented using structures.
845 * Structure Concepts:: The structure of Structures
846 * Structure Layout:: Defining the layout of structure types
847 * Structure Basics:: make-, -ref and -set! procedures for structs
848 * Vtables:: Accessing type-specific data
851 @node Structure Concepts
852 @subsection Structure Concepts
854 A structure object consists of a handle, structure data, and a vtable.
855 The handle is a Scheme value which points to both the vtable and the
856 structure's data. Structure data is a dynamically allocated region of
857 memory, private to the structure, divided up into typed fields. A
858 vtable is another structure used to hold type-specific data. Multiple
859 structures can share a common vtable.
861 Three concepts are key to understanding structures.
864 @item @dfn{layout specifications}
866 Layout specifications determine how memory allocated to structures is
867 divided up into fields. Programmers must write a layout specification
868 whenever a new type of structure is defined.
870 @item @dfn{structural accessors}
872 Structure access is by field number. There is only one set of
873 accessors common to all structure objects.
877 Vtables, themselves structures, are first class representations of
878 disjoint sub-types of structures in general. In most cases, when a
879 new structure is created, programmers must specify a vtable for the
880 new structure. Each vtable has a field describing the layout of its
881 instances. Vtables can have additional, user-defined fields as well.
886 @node Structure Layout
887 @subsection Structure Layout
889 When a structure is created, a region of memory is allocated to hold its
890 state. The @dfn{layout} of the structure's type determines how that
891 memory is divided into fields.
893 Each field has a specified type. There are only three types allowed, each
894 corresponding to a one letter code. The allowed types are:
897 @item 'u' -- unprotected
899 The field holds binary data that is not GC protected.
901 @item 'p' -- protected
903 The field holds a Scheme value and is GC protected.
907 The field holds a Scheme value and is GC protected. When a structure is
908 created with this type of field, the field is initialized to refer to
909 the structure's own handle. This kind of field is mainly useful when
910 mixing Scheme and C code in which the C code may need to compute a
911 structure's handle given only the address of its malloc'd data.
915 Each field also has an associated access protection. There are only
916 three kinds of protection, each corresponding to a one letter code.
917 The allowed protections are:
920 @item 'w' -- writable
922 The field can be read and written.
924 @item 'r' -- readable
926 The field can be read, but not written.
930 The field can be neither read nor written. This kind
931 of protection is for fields useful only to built-in routines.
934 A layout specification is described by stringing together pairs
935 of letters: one to specify a field type and one to specify a field
936 protection. For example, a traditional cons pair type object could
940 ; cons pairs have two writable fields of Scheme data
944 A pair object in which the first field is held constant could be:
950 Binary fields, (fields of type "u"), hold one @dfn{word} each. The
951 size of a word is a machine dependent value defined to be equal to the
952 value of the C expression: @code{sizeof (long)}.
954 The last field of a structure layout may specify a tail array.
955 A tail array is indicated by capitalizing the field's protection
956 code ('W', 'R' or 'O'). A tail-array field is replaced by
957 a read-only binary data field containing an array size. The array
958 size is determined at the time the structure is created. It is followed
959 by a corresponding number of fields of the type specified for the
960 tail array. For example, a conventional Scheme vector can be
964 ; A vector is an arbitrary number of writable fields holding Scheme
969 In the above example, field 0 contains the size of the vector and
970 fields beginning at 1 contain the vector elements.
972 A kind of tagged vector (a constant tag followed by conventional
973 vector elements) might be:
980 Structure layouts are represented by specially interned symbols whose
981 name is a string of type and protection codes. To create a new
982 structure layout, use this procedure:
984 @deffn {Scheme Procedure} make-struct-layout fields
985 @deffnx {C Function} scm_make_struct_layout (fields)
986 Return a new structure layout object.
988 @var{fields} must be a string made up of pairs of characters
989 strung together. The first character of each pair describes a field
990 type, the second a field protection. Allowed types are 'p' for
991 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
992 a field that points to the structure itself. Allowed protections
993 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
994 fields. The last field protection specification may be capitalized to
995 indicate that the field is a tail-array.
1000 @node Structure Basics
1001 @subsection Structure Basics
1003 This section describes the basic procedures for creating and accessing
1006 @deffn {Scheme Procedure} make-struct vtable tail_array_size . init
1007 @deffnx {C Function} scm_make_struct (vtable, tail_array_size, init)
1008 Create a new structure.
1010 @var{type} must be a vtable structure (@pxref{Vtables}).
1012 @var{tail-elts} must be a non-negative integer. If the layout
1013 specification indicated by @var{type} includes a tail-array,
1014 this is the number of elements allocated to that array.
1016 The @var{init1}, @dots{} are optional arguments describing how
1017 successive fields of the structure should be initialized. Only fields
1018 with protection 'r' or 'w' can be initialized, except for fields of
1019 type 's', which are automatically initialized to point to the new
1020 structure itself; fields with protection 'o' can not be initialized by
1023 If fewer optional arguments than initializable fields are supplied,
1024 fields of type 'p' get default value #f while fields of type 'u' are
1027 Structs are currently the basic representation for record-like data
1028 structures in Guile. The plan is to eventually replace them with a
1029 new representation which will at the same time be easier to use and
1032 For more information, see the documentation for @code{make-vtable-vtable}.
1035 @deffn {Scheme Procedure} struct? x
1036 @deffnx {C Function} scm_struct_p (x)
1037 Return @code{#t} iff @var{x} is a structure object, else
1042 @deffn {Scheme Procedure} struct-ref handle pos
1043 @deffnx {Scheme Procedure} struct-set! struct n value
1044 @deffnx {C Function} scm_struct_ref (handle, pos)
1045 @deffnx {C Function} scm_struct_set_x (struct, n, value)
1046 Access (or modify) the @var{n}th field of @var{struct}.
1048 If the field is of type 'p', then it can be set to an arbitrary value.
1050 If the field is of type 'u', then it can only be set to a non-negative
1051 integer value small enough to fit in one machine word.
1059 Vtables are structures that are used to represent structure types. Each
1060 vtable contains a layout specification in field
1061 @code{vtable-index-layout} -- instances of the type are laid out
1062 according to that specification. Vtables contain additional fields
1063 which are used only internally to libguile. The variable
1064 @code{vtable-offset-user} is bound to a field number. Vtable fields
1065 at that position or greater are user definable.
1067 @deffn {Scheme Procedure} struct-vtable handle
1068 @deffnx {C Function} scm_struct_vtable (handle)
1069 Return the vtable structure that describes the type of @var{struct}.
1072 @deffn {Scheme Procedure} struct-vtable? x
1073 @deffnx {C Function} scm_struct_vtable_p (x)
1074 Return @code{#t} iff @var{x} is a vtable structure.
1077 If you have a vtable structure, @code{V}, you can create an instance of
1078 the type it describes by using @code{(make-struct V ...)}. But where
1079 does @code{V} itself come from? One possibility is that @code{V} is an
1080 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
1081 created by using @code{(make-struct V' ...)}. Another possibility is
1082 that @code{V} is an instance of the type it itself describes. Vtable
1083 structures of the second sort are created by this procedure:
1085 @deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init
1086 @deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init)
1087 Return a new, self-describing vtable structure.
1089 @var{user-fields} is a string describing user defined fields of the
1090 vtable beginning at index @code{vtable-offset-user}
1091 (see @code{make-struct-layout}).
1093 @var{tail-size} specifies the size of the tail-array (if any) of
1096 @var{init1}, @dots{} are the optional initializers for the fields of
1099 Vtables have one initializable system field---the struct printer.
1100 This field comes before the user fields in the initializers passed
1101 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
1102 a third optional argument to @code{make-vtable-vtable} and a fourth to
1103 @code{make-struct} when creating vtables:
1105 If the value is a procedure, it will be called instead of the standard
1106 printer whenever a struct described by this vtable is printed.
1107 The procedure will be called with arguments STRUCT and PORT.
1109 The structure of a struct is described by a vtable, so the vtable is
1110 in essence the type of the struct. The vtable is itself a struct with
1111 a vtable. This could go on forever if it weren't for the
1112 vtable-vtables which are self-describing vtables, and thus terminate
1115 There are several potential ways of using structs, but the standard
1116 one is to use three kinds of structs, together building up a type
1117 sub-system: one vtable-vtable working as the root and one or several
1118 "types", each with a set of "instances". (The vtable-vtable should be
1119 compared to the class <class> which is the class of itself.)
1122 (define ball-root (make-vtable-vtable "pr" 0))
1124 (define (make-ball-type ball-color)
1125 (make-struct ball-root 0
1126 (make-struct-layout "pw")
1128 (format port "#<a ~A ball owned by ~A>"
1132 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
1133 (define (owner ball) (struct-ref ball 0))
1135 (define red (make-ball-type 'red))
1136 (define green (make-ball-type 'green))
1138 (define (make-ball type owner) (make-struct type 0 owner))
1140 (define ball (make-ball green 'Nisse))
1141 ball @result{} #<a green ball owned by Nisse>
1145 @deffn {Scheme Procedure} struct-vtable-name vtable
1146 @deffnx {C Function} scm_struct_vtable_name (vtable)
1147 Return the name of the vtable @var{vtable}.
1150 @deffn {Scheme Procedure} set-struct-vtable-name! vtable name
1151 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
1152 Set the name of the vtable @var{vtable} to @var{name}.
1155 @deffn {Scheme Procedure} struct-vtable-tag handle
1156 @deffnx {C Function} scm_struct_vtable_tag (handle)
1157 Return the vtable tag of the structure @var{handle}.
1166 * Conventional Arrays:: Arrays with arbitrary data.
1167 * Array Mapping:: Applying a procedure to the contents of an array.
1168 * Uniform Arrays:: Arrays with data of a single type.
1169 * Bit Vectors:: Vectors of bits.
1172 @node Conventional Arrays
1173 @subsection Conventional Arrays
1175 @dfn{Conventional arrays} are a collection of cells organized into an
1176 arbitrary number of dimensions. Each cell can hold any kind of Scheme
1177 value and can be accessed in constant time by supplying an index for
1178 each dimension. This contrasts with uniform arrays, which use memory
1179 more efficiently but can hold data of only a single type, and lists
1180 where inserting and deleting cells is more efficient, but more time
1181 is usually required to access a particular cell.
1183 A conventional array is displayed as @code{#} followed by the @dfn{rank}
1184 (number of dimensions) followed by the cells, organized into dimensions
1185 using parentheses. The nesting depth of the parentheses is equal to
1188 When an array is created, the number of dimensions and range of each
1189 dimension must be specified, e.g., to create a 2x3 array with a
1193 (make-array 'ho 2 3) @result{}
1194 #2((ho ho ho) (ho ho ho))
1197 The range of each dimension can also be given explicitly, e.g., another
1198 way to create the same array:
1201 (make-array 'ho '(0 1) '(0 2)) @result{}
1202 #2((ho ho ho) (ho ho ho))
1205 A conventional array with one dimension based at zero is identical to
1209 (make-array 'ho 3) @result{}
1213 The following procedures can be used with conventional arrays (or vectors).
1215 @deffn {Scheme Procedure} array? v [prot]
1216 @deffnx {C Function} scm_array_p (v, prot)
1217 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1218 not. The @var{prototype} argument is used with uniform arrays
1219 and is described elsewhere.
1222 @deffn {Scheme Procedure} make-array initial-value bound1 bound2 @dots{}
1223 Create and return an array that has as many dimensions as there are
1224 @var{bound}s and fill it with @var{initial-value}. Each @var{bound}
1225 may be a positive non-zero integer @var{N}, in which case the index for
1226 that dimension can range from 0 through @var{N-1}; or an explicit index
1227 range specifier in the form @code{(LOWER UPPER)}, where both @var{lower}
1228 and @var{upper} are integers, possibly less than zero, and possibly the
1229 same number (however, @var{lower} cannot be greater than @var{upper}).
1232 @c array-ref's type is `compiled-closure'. There's some weird stuff
1233 @c going on in array.c, too. Let's call it a primitive. -twp
1235 @deffn {Scheme Procedure} uniform-vector-ref v args
1236 @deffnx {Scheme Procedure} array-ref v . args
1237 @deffnx {C Function} scm_uniform_vector_ref (v, args)
1238 Return the element at the @code{(index1, index2)} element in
1242 @deffn {Scheme Procedure} array-in-bounds? v . args
1243 @deffnx {C Function} scm_array_in_bounds_p (v, args)
1244 Return @code{#t} if its arguments would be acceptable to
1248 @c fixme: why do these sigs differ? -ttn 2001/07/19 01:14:12
1249 @deffn {Scheme Procedure} array-set! v obj . args
1250 @deffnx {Scheme Procedure} uniform-array-set1! v obj args
1251 @deffnx {C Function} scm_array_set_x (v, obj, args)
1252 Set the element at the @code{(index1, index2)} element in @var{array} to
1253 @var{new-value}. The value returned by array-set! is unspecified.
1256 @deffn {Scheme Procedure} make-shared-array oldra mapfunc . dims
1257 @deffnx {C Function} scm_make_shared_array (oldra, mapfunc, dims)
1258 @code{make-shared-array} can be used to create shared subarrays of other
1259 arrays. The @var{mapper} is a function that translates coordinates in
1260 the new array into coordinates in the old array. A @var{mapper} must be
1261 linear, and its range must stay within the bounds of the old array, but
1262 it can be otherwise arbitrary. A simple example:
1264 (define fred (make-array #f 8 8))
1265 (define freds-diagonal
1266 (make-shared-array fred (lambda (i) (list i i)) 8))
1267 (array-set! freds-diagonal 'foo 3)
1268 (array-ref fred 3 3) @result{} foo
1269 (define freds-center
1270 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
1271 (array-ref freds-center 0 0) @result{} foo
1275 @deffn {Scheme Procedure} shared-array-increments ra
1276 @deffnx {C Function} scm_shared_array_increments (ra)
1277 For each dimension, return the distance between elements in the root vector.
1280 @deffn {Scheme Procedure} shared-array-offset ra
1281 @deffnx {C Function} scm_shared_array_offset (ra)
1282 Return the root vector index of the first element in the array.
1285 @deffn {Scheme Procedure} shared-array-root ra
1286 @deffnx {C Function} scm_shared_array_root (ra)
1287 Return the root vector of a shared array.
1290 @deffn {Scheme Procedure} transpose-array ra . args
1291 @deffnx {C Function} scm_transpose_array (ra, args)
1292 Return an array sharing contents with @var{array}, but with
1293 dimensions arranged in a different order. There must be one
1294 @var{dim} argument for each dimension of @var{array}.
1295 @var{dim0}, @var{dim1}, @dots{} should be integers between 0
1296 and the rank of the array to be returned. Each integer in that
1297 range must appear at least once in the argument list.
1299 The values of @var{dim0}, @var{dim1}, @dots{} correspond to
1300 dimensions in the array to be returned, their positions in the
1301 argument list to dimensions of @var{array}. Several @var{dim}s
1302 may have the same value, in which case the returned array will
1303 have smaller rank than @var{array}.
1306 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1307 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1308 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1309 #2((a 4) (b 5) (c 6))
1313 @deffn {Scheme Procedure} enclose-array ra . axes
1314 @deffnx {C Function} scm_enclose_array (ra, axes)
1315 @var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
1316 the rank of @var{array}. @var{enclose-array} returns an array
1317 resembling an array of shared arrays. The dimensions of each shared
1318 array are the same as the @var{dim}th dimensions of the original array,
1319 the dimensions of the outer array are the same as those of the original
1320 array that did not match a @var{dim}.
1322 An enclosed array is not a general Scheme array. Its elements may not
1323 be set using @code{array-set!}. Two references to the same element of
1324 an enclosed array will be @code{equal?} but will not in general be
1325 @code{eq?}. The value returned by @var{array-prototype} when given an
1326 enclosed array is unspecified.
1330 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
1331 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1333 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
1334 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1338 @deffn {Scheme Procedure} array-shape array
1339 Return a list of inclusive bounds of integers.
1341 (array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
1345 @deffn {Scheme Procedure} array-dimensions ra
1346 @deffnx {C Function} scm_array_dimensions (ra)
1347 @code{Array-dimensions} is similar to @code{array-shape} but replaces
1348 elements with a @code{0} minimum with one greater than the maximum. So:
1350 (array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
1354 @deffn {Scheme Procedure} array-rank ra
1355 @deffnx {C Function} scm_array_rank (ra)
1356 Return the number of dimensions of @var{obj}. If @var{obj} is
1357 not an array, @code{0} is returned.
1360 @deffn {Scheme Procedure} array->list v
1361 @deffnx {C Function} scm_array_to_list (v)
1362 Return a list consisting of all the elements, in order, of
1366 @deffn {Scheme Procedure} array-copy! src dst
1367 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1368 @deffnx {C Function} scm_array_copy_x (src, dst)
1369 Copy every element from vector or array @var{source} to the
1370 corresponding element of @var{destination}. @var{destination} must have
1371 the same rank as @var{source}, and be at least as large in each
1372 dimension. The order is unspecified.
1375 @deffn {Scheme Procedure} array-fill! ra fill
1376 @deffnx {C Function} scm_array_fill_x (ra, fill)
1377 Store @var{fill} in every element of @var{array}. The value returned
1381 @c begin (texi-doc-string "guile" "array-equal?")
1382 @deffn {Scheme Procedure} array-equal? ra0 ra1
1383 Return @code{#t} iff all arguments are arrays with the same shape, the
1384 same type, and have corresponding elements which are either
1385 @code{equal?} or @code{array-equal?}. This function differs from
1386 @code{equal?} in that a one dimensional shared array may be
1387 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
1390 @deffn {Scheme Procedure} array-contents array [strict]
1391 @deffnx {C Function} scm_array_contents (array, strict)
1392 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1393 without changing their order (last subscript changing fastest), then
1394 @code{array-contents} returns that shared array, otherwise it returns
1395 @code{#f}. All arrays made by @var{make-array} and
1396 @var{make-uniform-array} may be unrolled, some arrays made by
1397 @var{make-shared-array} may not be.
1399 If the optional argument @var{strict} is provided, a shared array will
1400 be returned only if its elements are stored internally contiguous in
1405 @subsection Array Mapping
1407 @c FIXME: array-map! accepts no source arrays at all, and in that
1408 @c case makes calls "(proc)". Is that meant to be a documented
1411 @c FIXME: array-for-each doesn't say what happens if the sources have
1412 @c different index ranges. The code currently iterates over the
1413 @c indices of the first and expects the others to cover those. That
1414 @c at least vaguely matches array-map!, but is is meant to be a
1415 @c documented feature?
1417 @deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN
1418 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1419 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1420 Set each element of the @var{dst} array to values obtained from calls
1421 to @var{proc}. The value returned is unspecified.
1423 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1424 where each @var{elem} is from the corresponding @var{src} array, at
1425 the @var{dst} index. @code{array-map-in-order!} makes the calls in
1426 row-major order, @code{array-map!} makes them in an unspecified order.
1428 The @var{src} arrays must have the same number of dimensions as
1429 @var{dst}, and must have a range for each dimension which covers the
1430 range in @var{dst}. This ensures all @var{dst} indices are valid in
1434 @deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN
1435 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1436 Apply @var{proc} to each tuple of elements of @var{src1} @dots{}
1437 @var{srcN}, in row-major order. The value returned is unspecified.
1440 @deffn {Scheme Procedure} array-index-map! dst proc
1441 @deffnx {C Function} scm_array_index_map_x (dst, proc)
1442 Set each element of the @var{dst} array to values returned by calls to
1443 @var{proc}. The value returned is unspecified.
1445 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1446 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
1447 each dimension. The order in which the calls are made is unspecified.
1449 For example, to create a @m{4\times4, 4x4} matrix representing a
1453 \advance\leftskip by 2\lispnarrowing {
1471 (define a (make-array #f 4 4))
1472 (array-index-map! a (lambda (i j)
1473 (modulo (+ i j) 4)))
1477 @node Uniform Arrays
1478 @subsection Uniform Arrays
1479 @tpindex Uniform Arrays
1482 @dfn{Uniform arrays} have elements all of the
1483 same type and occupy less storage than conventional
1484 arrays. Uniform arrays with a single zero-based dimension
1485 are also known as @dfn{uniform vectors}. The procedures in
1486 this section can also be used on conventional arrays, vectors,
1487 bit-vectors and strings.
1490 When creating a uniform array, the type of data to be stored
1491 is indicated with a @var{prototype} argument. The following table
1492 lists the types available and example prototypes:
1495 prototype type printing character
1497 #t boolean (bit-vector) b
1499 #\nul byte (integer) y
1500 's short (integer) h
1501 1 unsigned long (integer) u
1502 -1 signed long (integer) e
1503 'l signed long long (integer) l
1504 1.0 float (single precision) s
1505 1/3 double (double precision float) i
1506 0+i complex (double precision) c
1507 () conventional vector
1511 Unshared uniform arrays of characters with a single zero-based dimension
1512 are identical to strings:
1515 (make-uniform-array #\a 3) @result{}
1520 Unshared uniform arrays of booleans with a single zero-based dimension
1521 are identical to @ref{Bit Vectors, bit-vectors}.
1524 (make-uniform-array #t 3) @result{}
1529 Other uniform vectors are written in a form similar to that of vectors,
1530 except that a single character from the above table is put between
1531 @code{#} and @code{(}. For example, a uniform vector of signed
1532 long integers is displayed in the form @code{'#e(3 5 9)}.
1534 @deffn {Scheme Procedure} array? v [prot]
1535 Return @code{#t} if the @var{obj} is an array, and @code{#f} if not.
1537 The @var{prototype} argument is used with uniform arrays and is described
1541 @deffn {Scheme Procedure} make-uniform-array prototype bound1 bound2 @dots{}
1542 Create and return a uniform array of type corresponding to
1543 @var{prototype} that has as many dimensions as there are @var{bound}s
1544 and fill it with @var{prototype}.
1547 @deffn {Scheme Procedure} array-prototype ra
1548 @deffnx {C Function} scm_array_prototype (ra)
1549 Return an object that would produce an array of the same type
1550 as @var{array}, if used as the @var{prototype} for
1551 @code{make-uniform-array}.
1554 @deffn {Scheme Procedure} list->uniform-array ndim prot lst
1555 @deffnx {Scheme Procedure} list->uniform-vector prot lst
1556 @deffnx {C Function} scm_list_to_uniform_array (ndim, prot, lst)
1557 Return a uniform array of the type indicated by prototype
1558 @var{prot} with elements the same as those of @var{lst}.
1559 Elements must be of the appropriate type, no coercions are
1563 @deffn {Scheme Procedure} uniform-vector-fill! uve fill
1564 Store @var{fill} in every element of @var{uve}. The value returned is
1568 @deffn {Scheme Procedure} uniform-vector-length v
1569 @deffnx {C Function} scm_uniform_vector_length (v)
1570 Return the number of elements in @var{uve}.
1573 @deffn {Scheme Procedure} dimensions->uniform-array dims prot [fill]
1574 @deffnx {Scheme Procedure} make-uniform-vector length prototype [fill]
1575 @deffnx {C Function} scm_dimensions_to_uniform_array (dims, prot, fill)
1576 Create and return a uniform array or vector of type
1577 corresponding to @var{prototype} with dimensions @var{dims} or
1578 length @var{length}. If @var{fill} is supplied, it's used to
1579 fill the array, otherwise @var{prototype} is used.
1582 @c Another compiled-closure. -twp
1584 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
1585 @deffnx {Scheme Procedure} uniform-vector-read! uve [port-or-fdes] [start] [end]
1586 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
1587 Attempt to read all elements of @var{ura}, in lexicographic order, as
1588 binary objects from @var{port-or-fdes}.
1589 If an end of file is encountered,
1590 the objects up to that point are put into @var{ura}
1591 (starting at the beginning) and the remainder of the array is
1594 The optional arguments @var{start} and @var{end} allow
1595 a specified region of a vector (or linearized array) to be read,
1596 leaving the remainder of the vector unchanged.
1598 @code{uniform-array-read!} returns the number of objects read.
1599 @var{port-or-fdes} may be omitted, in which case it defaults to the value
1600 returned by @code{(current-input-port)}.
1603 @deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]]
1604 @deffnx {Scheme Procedure} uniform-vector-write uve [port-or-fdes] [start] [end]
1605 @deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end)
1606 Writes all elements of @var{ura} as binary objects to
1609 The optional arguments @var{start}
1611 a specified region of a vector (or linearized array) to be written.
1613 The number of objects actually written is returned.
1614 @var{port-or-fdes} may be
1615 omitted, in which case it defaults to the value returned by
1616 @code{(current-output-port)}.
1620 @subsection Bit Vectors
1623 Bit vectors are a specific type of uniform array: an array of booleans
1624 with a single zero-based index.
1627 They are displayed as a sequence of @code{0}s and
1628 @code{1}s prefixed by @code{#*}, e.g.,
1631 (make-uniform-vector 8 #t #f) @result{}
1634 #b(#t #f #t) @result{}
1638 @deffn {Scheme Procedure} bit-count b bitvector
1639 @deffnx {C Function} scm_bit_count (b, bitvector)
1640 Return the number of occurrences of the boolean @var{b} in
1644 @deffn {Scheme Procedure} bit-position item v k
1645 @deffnx {C Function} scm_bit_position (item, v, k)
1646 Return the minimum index of an occurrence of @var{bool} in
1647 @var{bv} which is at least @var{k}. If no @var{bool} occurs
1648 within the specified range @code{#f} is returned.
1651 @deffn {Scheme Procedure} bit-invert! v
1652 @deffnx {C Function} scm_bit_invert_x (v)
1653 Modify @var{bv} by replacing each element with its negation.
1656 @deffn {Scheme Procedure} bit-set*! v kv obj
1657 @deffnx {C Function} scm_bit_set_star_x (v, kv, obj)
1658 If uve is a bit-vector @var{bv} and uve must be of the same
1659 length. If @var{bool} is @code{#t}, uve is OR'ed into
1660 @var{bv}; If @var{bool} is @code{#f}, the inversion of uve is
1661 AND'ed into @var{bv}.
1663 If uve is a unsigned long integer vector all the elements of uve
1664 must be between 0 and the @code{length} of @var{bv}. The bits
1665 of @var{bv} corresponding to the indexes in uve are set to
1666 @var{bool}. The return value is unspecified.
1669 @deffn {Scheme Procedure} bit-count* v kv obj
1670 @deffnx {C Function} scm_bit_count_star (v, kv, obj)
1673 (bit-count (bit-set*! (if bool bv (bit-invert! bv)) uve #t) #t).
1675 @var{bv} is not modified.
1679 @node Association Lists and Hash Tables
1680 @section Association Lists and Hash Tables
1682 This chapter discusses dictionary objects: data structures that are
1683 useful for organizing and indexing large bodies of information.
1686 * Dictionary Types:: About dictionary types; what they're good for.
1687 * Association Lists:: List-based dictionaries.
1688 * Hash Tables:: Table-based dictionaries.
1691 @node Dictionary Types
1692 @subsection Dictionary Types
1694 A @dfn{dictionary} object is a data structure used to index
1695 information in a user-defined way. In standard Scheme, the main
1696 aggregate data types are lists and vectors. Lists are not really
1697 indexed at all, and vectors are indexed only by number
1698 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
1699 to index your data on some other type; for example, in a library
1700 catalog you might want to look up a book by the name of its
1701 author. Dictionaries are used to help you organize information in
1704 An @dfn{association list} (or @dfn{alist} for short) is a list of
1705 key-value pairs. Each pair represents a single quantity or
1706 object; the @code{car} of the pair is a key which is used to
1707 identify the object, and the @code{cdr} is the object's value.
1709 A @dfn{hash table} also permits you to index objects with
1710 arbitrary keys, but in a way that makes looking up any one object
1711 extremely fast. A well-designed hash system makes hash table
1712 lookups almost as fast as conventional array or vector references.
1714 Alists are popular among Lisp programmers because they use only
1715 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
1716 and the equality primitives). No changes to the language core are
1717 necessary. Therefore, with Scheme's built-in list manipulation
1718 facilities, it is very convenient to handle data stored in an
1719 association list. Also, alists are highly portable and can be
1720 easily implemented on even the most minimal Lisp systems.
1722 However, alists are inefficient, especially for storing large
1723 quantities of data. Because we want Guile to be useful for large
1724 software systems as well as small ones, Guile provides a rich set
1725 of tools for using either association lists or hash tables.
1727 @node Association Lists
1728 @subsection Association Lists
1729 @tpindex Association Lists
1732 @cindex Association List
1736 An association list is a conventional data structure that is often used
1737 to implement simple key-value databases. It consists of a list of
1738 entries in which each entry is a pair. The @dfn{key} of each entry is
1739 the @code{car} of the pair and the @dfn{value} of each entry is the
1743 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
1751 Association lists are also known, for short, as @dfn{alists}.
1753 The structure of an association list is just one example of the infinite
1754 number of possible structures that can be built using pairs and lists.
1755 As such, the keys and values in an association list can be manipulated
1756 using the general list structure procedures @code{cons}, @code{car},
1757 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
1758 because association lists are so useful, Guile also provides specific
1759 procedures for manipulating them.
1762 * Alist Key Equality::
1763 * Adding or Setting Alist Entries::
1764 * Retrieving Alist Entries::
1765 * Removing Alist Entries::
1766 * Sloppy Alist Functions::
1770 @node Alist Key Equality
1771 @subsubsection Alist Key Equality
1773 All of Guile's dedicated association list procedures, apart from
1774 @code{acons}, come in three flavours, depending on the level of equality
1775 that is required to decide whether an existing key in the association
1776 list is the same as the key that the procedure call uses to identify the
1781 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
1785 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
1789 Procedures with @dfn{assoc} in their name use @code{equal?} to
1790 determine key equality.
1793 @code{acons} is an exception because it is used to build association
1794 lists which do not require their entries' keys to be unique.
1796 @node Adding or Setting Alist Entries
1797 @subsubsection Adding or Setting Alist Entries
1799 @code{acons} adds a new entry to an association list and returns the
1800 combined association list. The combined alist is formed by consing the
1801 new entry onto the head of the alist specified in the @code{acons}
1802 procedure call. So the specified alist is not modified, but its
1803 contents become shared with the tail of the combined alist that
1804 @code{acons} returns.
1806 In the most common usage of @code{acons}, a variable holding the
1807 original association list is updated with the combined alist:
1810 (set! address-list (acons name address address-list))
1813 In such cases, it doesn't matter that the old and new values of
1814 @code{address-list} share some of their contents, since the old value is
1815 usually no longer independently accessible.
1817 Note that @code{acons} adds the specified new entry regardless of
1818 whether the alist may already contain entries with keys that are, in
1819 some sense, the same as that of the new entry. Thus @code{acons} is
1820 ideal for building alists where there is no concept of key uniqueness.
1823 (set! task-list (acons 3 "pay gas bill" '()))
1826 ((3 . "pay gas bill"))
1828 (set! task-list (acons 3 "tidy bedroom" task-list))
1831 ((3 . "tidy bedroom") (3 . "pay gas bill"))
1834 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
1835 or replace an entry in an association list where there @emph{is} a
1836 concept of key uniqueness. If the specified association list already
1837 contains an entry whose key is the same as that specified in the
1838 procedure call, the existing entry is replaced by the new one.
1839 Otherwise, the new entry is consed onto the head of the old association
1840 list to create the combined alist. In all cases, these procedures
1841 return the combined alist.
1843 @code{assq-set!} and friends @emph{may} destructively modify the
1844 structure of the old association list in such a way that an existing
1845 variable is correctly updated without having to @code{set!} it to the
1851 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
1853 (assoc-set! address-list "james" "1a London Road")
1855 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1859 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1865 (assoc-set! address-list "bob" "11 Newington Avenue")
1867 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1868 ("james" . "1a London Road"))
1872 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
1875 The only safe way to update an association list variable when adding or
1876 replacing an entry like this is to @code{set!} the variable to the
1881 (assoc-set! address-list "bob" "11 Newington Avenue"))
1884 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1885 ("james" . "1a London Road"))
1888 Because of this slight inconvenience, you may find it more convenient to
1889 use hash tables to store dictionary data. If your application will not
1890 be modifying the contents of an alist very often, this may not make much
1893 If you need to keep the old value of an association list in a form
1894 independent from the list that results from modification by
1895 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
1896 use @code{list-copy} to copy the old association list before modifying
1899 @deffn {Scheme Procedure} acons key value alist
1900 @deffnx {C Function} scm_acons (key, value, alist)
1901 Add a new key-value pair to @var{alist}. A new pair is
1902 created whose car is @var{key} and whose cdr is @var{value}, and the
1903 pair is consed onto @var{alist}, and the new list is returned. This
1904 function is @emph{not} destructive; @var{alist} is not modified.
1907 @deffn {Scheme Procedure} assq-set! alist key val
1908 @deffnx {Scheme Procedure} assv-set! alist key value
1909 @deffnx {Scheme Procedure} assoc-set! alist key value
1910 @deffnx {C Function} scm_assq_set_x (alist, key, val)
1911 @deffnx {C Function} scm_assv_set_x (alist, key, val)
1912 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
1913 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
1914 @var{alist} entry for @var{key} and associate it with the new
1915 @var{value}. If @var{alist} does not contain an entry for @var{key},
1916 add a new one. Return the (possibly new) alist.
1918 These functions do not attempt to verify the structure of @var{alist},
1919 and so may cause unusual results if passed an object that is not an
1923 @node Retrieving Alist Entries
1924 @subsubsection Retrieving Alist Entries
1929 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
1930 arguments and return the entry for that key if an entry exists, or
1931 @code{#f} if there is no entry for that key. Note that, in the cases
1932 where an entry exists, these procedures return the complete entry, that
1933 is @code{(KEY . VALUE)}, not just the value.
1935 @deffn {Scheme Procedure} assq key alist
1936 @deffnx {Scheme Procedure} assv key alist
1937 @deffnx {Scheme Procedure} assoc key alist
1938 @deffnx {C Function} scm_assq (key, alist)
1939 @deffnx {C Function} scm_assv (key, alist)
1940 @deffnx {C Function} scm_assoc (key, alist)
1941 Fetch the entry in @var{alist} that is associated with @var{key}. To
1942 decide whether the argument @var{key} matches a particular entry in
1943 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
1944 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
1945 cannot be found in @var{alist} (according to whichever equality
1946 predicate is in use), then return @code{#f}. These functions
1947 return the entire alist entry found (i.e. both the key and the value).
1950 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
1951 hand, take an alist and a key and return @emph{just the value} for that
1952 key, if an entry exists. If there is no entry for the specified key,
1953 these procedures return @code{#f}.
1955 This creates an ambiguity: if the return value is @code{#f}, it means
1956 either that there is no entry with the specified key, or that there
1957 @emph{is} an entry for the specified key, with value @code{#f}.
1958 Consequently, @code{assq-ref} and friends should only be used where it
1959 is known that an entry exists, or where the ambiguity doesn't matter
1960 for some other reason.
1962 @deffn {Scheme Procedure} assq-ref alist key
1963 @deffnx {Scheme Procedure} assv-ref alist key
1964 @deffnx {Scheme Procedure} assoc-ref alist key
1965 @deffnx {C Function} scm_assq_ref (alist, key)
1966 @deffnx {C Function} scm_assv_ref (alist, key)
1967 @deffnx {C Function} scm_assoc_ref (alist, key)
1968 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
1969 value associated with @var{key} in @var{alist} is returned. These
1970 functions are equivalent to
1973 (let ((ent (@var{associator} @var{key} @var{alist})))
1974 (and ent (cdr ent)))
1977 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
1980 @node Removing Alist Entries
1981 @subsubsection Removing Alist Entries
1983 To remove the element from an association list whose key matches a
1984 specified key, use @code{assq-remove!}, @code{assv-remove!} or
1985 @code{assoc-remove!} (depending, as usual, on the level of equality
1986 required between the key that you specify and the keys in the
1989 As with @code{assq-set!} and friends, the specified alist may or may not
1990 be modified destructively, and the only safe way to update a variable
1991 containing the alist is to @code{set!} it to the value that
1992 @code{assq-remove!} and friends return.
1997 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1998 ("james" . "1a London Road"))
2000 (set! address-list (assoc-remove! address-list "mary"))
2003 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
2006 Note that, when @code{assq/v/oc-remove!} is used to modify an
2007 association list that has been constructed only using the corresponding
2008 @code{assq/v/oc-set!}, there can be at most one matching entry in the
2009 alist, so the question of multiple entries being removed in one go does
2010 not arise. If @code{assq/v/oc-remove!} is applied to an association
2011 list that has been constructed using @code{acons}, or an
2012 @code{assq/v/oc-set!} with a different level of equality, or any mixture
2013 of these, it removes only the first matching entry from the alist, even
2014 if the alist might contain further matching entries. For example:
2017 (define address-list '())
2018 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
2019 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
2022 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
2024 (set! address-list (assoc-remove! address-list "mary"))
2027 (("mary" . "11 Elm Street"))
2030 In this example, the two instances of the string "mary" are not the same
2031 when compared using @code{eq?}, so the two @code{assq-set!} calls add
2032 two distinct entries to @code{address-list}. When compared using
2033 @code{equal?}, both "mary"s in @code{address-list} are the same as the
2034 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
2035 after removing the first matching entry that it finds, and so one of the
2036 "mary" entries is left in place.
2038 @deffn {Scheme Procedure} assq-remove! alist key
2039 @deffnx {Scheme Procedure} assv-remove! alist key
2040 @deffnx {Scheme Procedure} assoc-remove! alist key
2041 @deffnx {C Function} scm_assq_remove_x (alist, key)
2042 @deffnx {C Function} scm_assv_remove_x (alist, key)
2043 @deffnx {C Function} scm_assoc_remove_x (alist, key)
2044 Delete the first entry in @var{alist} associated with @var{key}, and return
2045 the resulting alist.
2048 @node Sloppy Alist Functions
2049 @subsubsection Sloppy Alist Functions
2051 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
2052 like the corresponding non-@code{sloppy-} procedures, except that they
2053 return @code{#f} when the specified association list is not well-formed,
2054 where the non-@code{sloppy-} versions would signal an error.
2056 Specifically, there are two conditions for which the non-@code{sloppy-}
2057 procedures signal an error, which the @code{sloppy-} procedures handle
2058 instead by returning @code{#f}. Firstly, if the specified alist as a
2059 whole is not a proper list:
2062 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2064 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
2065 ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
2066 ABORT: (wrong-type-arg)
2068 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2074 Secondly, if one of the entries in the specified alist is not a pair:
2077 (assoc 2 '((1 . 1) 2 (3 . 9)))
2079 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
2080 ERROR: Wrong type argument in position 2 (expecting CONSP): 2
2081 ABORT: (wrong-type-arg)
2083 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
2088 Unless you are explicitly working with badly formed association lists,
2089 it is much safer to use the non-@code{sloppy-} procedures, because they
2090 help to highlight coding and data errors that the @code{sloppy-}
2091 versions would silently cover up.
2093 @deffn {Scheme Procedure} sloppy-assq key alist
2094 @deffnx {C Function} scm_sloppy_assq (key, alist)
2095 Behaves like @code{assq} but does not do any error checking.
2096 Recommended only for use in Guile internals.
2099 @deffn {Scheme Procedure} sloppy-assv key alist
2100 @deffnx {C Function} scm_sloppy_assv (key, alist)
2101 Behaves like @code{assv} but does not do any error checking.
2102 Recommended only for use in Guile internals.
2105 @deffn {Scheme Procedure} sloppy-assoc key alist
2106 @deffnx {C Function} scm_sloppy_assoc (key, alist)
2107 Behaves like @code{assoc} but does not do any error checking.
2108 Recommended only for use in Guile internals.
2112 @subsubsection Alist Example
2114 Here is a longer example of how alists may be used in practice.
2117 (define capitals '(("New York" . "Albany")
2118 ("Oregon" . "Salem")
2119 ("Florida" . "Miami")))
2121 ;; What's the capital of Oregon?
2122 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
2123 (assoc-ref capitals "Oregon") @result{} "Salem"
2125 ;; We left out South Dakota.
2127 (assoc-set! capitals "South Dakota" "Pierre"))
2129 @result{} (("South Dakota" . "Pierre")
2130 ("New York" . "Albany")
2131 ("Oregon" . "Salem")
2132 ("Florida" . "Miami"))
2134 ;; And we got Florida wrong.
2136 (assoc-set! capitals "Florida" "Tallahassee"))
2138 @result{} (("South Dakota" . "Pierre")
2139 ("New York" . "Albany")
2140 ("Oregon" . "Salem")
2141 ("Florida" . "Tallahassee"))
2143 ;; After Oregon secedes, we can remove it.
2145 (assoc-remove! capitals "Oregon"))
2147 @result{} (("South Dakota" . "Pierre")
2148 ("New York" . "Albany")
2149 ("Florida" . "Tallahassee"))
2153 @subsection Hash Tables
2154 @tpindex Hash Tables
2156 @c FIXME::martin: Review me!
2158 Hash tables are dictionaries which offer similar functionality as
2159 association lists: They provide a mapping from keys to values. The
2160 difference is that association lists need time linear in the size of
2161 elements when searching for entries, whereas hash tables can normally
2162 search in constant time. The drawback is that hash tables require a
2163 little bit more memory, and that you can not use the normal list
2164 procedures (@pxref{Lists}) for working with them.
2167 * Hash Table Examples:: Demonstration of hash table usage.
2168 * Hash Table Reference:: Hash table procedure descriptions.
2172 @node Hash Table Examples
2173 @subsubsection Hash Table Examples
2175 @c FIXME::martin: Review me!
2177 For demonstration purposes, this section gives a few usage examples of
2178 some hash table procedures, together with some explanation what they do.
2180 First we start by creating a new hash table with 31 slots, and
2181 populate it with two key/value pairs.
2184 (define h (make-hash-table 31))
2186 (hashq-create-handle! h 'foo "bar")
2190 (hashq-create-handle! h 'braz "zonk")
2194 (hashq-create-handle! h 'frob #f)
2199 You can get the value for a given key with the procedure
2200 @code{hashq-ref}, but the problem with this procedure is that you
2201 cannot reliably determine whether a key does exists in the table. The
2202 reason is that the procedure returns @code{#f} if the key is not in
2203 the table, but it will return the same value if the key is in the
2204 table and just happens to have the value @code{#f}, as you can see in
2205 the following examples.
2216 (hashq-ref h 'not-there)
2221 Better is to use the procedure @code{hashq-get-handle}, which makes a
2222 distinction between the two cases. Just like @code{assq}, this
2223 procedure returns a key/value-pair on success, and @code{#f} if the
2227 (hashq-get-handle h 'foo)
2231 (hashq-get-handle h 'not-there)
2236 There is no procedure for calculating the number of key/value-pairs in
2237 a hash table, but @code{hash-fold} can be used for doing exactly that.
2240 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
2245 @node Hash Table Reference
2246 @subsubsection Hash Table Reference
2248 @c FIXME: Describe in broad terms what happens for resizing, and what
2249 @c the initial size means for this.
2251 Like the association list functions, the hash table functions come in
2252 several varieties, according to the equality test used for the keys.
2253 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
2254 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
2255 the @code{hashx-} functions use an application supplied test.
2257 A single @code{make-hash-table} creates a hash table suitable for use
2258 with any set of functions, but it's imperative that just one set is
2259 then used consistently, or results will be unpredictable.
2262 Hash tables are implemented as a vector indexed by an integer formed
2263 from the key, with an association list of key/value pairs for each
2264 bucket in case distinct keys hash together. Direct access to the
2265 pairs in those lists is provided by the @code{-handle-} functions.
2267 For the @code{hashx-} ``extended'' routines, an application supplies a
2268 @var{hash} function producing an integer index like @code{hashq} etc
2269 below, and an @var{assoc} alist search function like @code{assq} etc
2270 (@pxref{Retrieving Alist Entries}). Here's an example of such
2271 functions implementing case-insensitive hashing of string keys,
2274 (use-modules (srfi srfi-1)
2276 (define (my-hash str size)
2277 (remainder (string-hash-ci str) size))
2278 (define (my-assoc str alist)
2279 (find (lambda (pair) (string-ci=? str (car pair))) alist))
2281 (define my-table (make-hash-table))
2282 (hashx-set! my-hash my-assoc my-table "foo" 123)
2284 (hashx-ref my-hash my-assoc my-table "FOO")
2288 In a @code{hashx-} @var{hash} function the aim is to spread keys
2289 across the vector, so bucket lists don't become long, but the actual
2290 values are arbitrary (so long as they're in the range 0 to
2291 @math{@var{size}-1}). Helpful functions for forming a hash value, in
2292 addition to @code{hashq} etc below, include @code{symbol-hash}
2293 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
2294 (@pxref{SRFI-13 Comparison}), and @code{char-set-hash} (@pxref{SRFI-14
2295 Predicates/Comparison}).
2298 @deffn {Scheme Procedure} make-hash-table [size]
2299 Create a new hash table, with an optional initial vector @var{size}.
2301 @var{size} doesn't limit the entries in the table, merely gives a
2302 starting size for the internal vector. A prime number bigger than the
2303 expected number of entries would be a good choice.
2306 @deffn {Scheme Procedure} hash-ref table key [dflt]
2307 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
2308 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
2309 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
2310 @deffnx {C Function} scm_hash_ref (table, key, dflt)
2311 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
2312 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
2313 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
2314 Lookup @var{key} in the given hash @var{table}, and return the
2315 associated value. If @var{key} is not found, return @var{dflt}, or
2316 @code{#f} if @var{dflt} is not given. (For the C functions,
2317 @var{dflt} must be given.)
2320 @deffn {Scheme Procedure} hash-set! table key val
2321 @deffnx {Scheme Procedure} hashq-set! table key val
2322 @deffnx {Scheme Procedure} hashv-set! table key val
2323 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
2324 @deffnx {C Function} scm_hash_set_x (table, key, val)
2325 @deffnx {C Function} scm_hashq_set_x (table, key, val)
2326 @deffnx {C Function} scm_hashv_set_x (table, key, val)
2327 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
2328 Associate @var{val} with @var{key} in the given hash @var{table}. If
2329 @var{key} is already present then it's associated value is changed.
2330 If it's not present then a new entry is created.
2333 @deffn {Scheme Procedure} hash-remove! table key
2334 @deffnx {Scheme Procedure} hashq-remove! table key
2335 @deffnx {Scheme Procedure} hashv-remove! table key
2336 @deffnx {C Function} scm_hash_remove_x (table, key)
2337 @deffnx {C Function} scm_hashq_remove_x (table, key)
2338 @deffnx {C Function} scm_hashv_remove_x (table, key)
2339 Remove any association for @var{key} in the given hash @var{table}.
2340 If @var{key} is not in @var{table} then nothing is done.
2343 @deffn {Scheme Procedure} hash key size
2344 @deffnx {Scheme Procedure} hashq key size
2345 @deffnx {Scheme Procedure} hashv key size
2346 @deffnx {C Function} scm_hash (key, size)
2347 @deffnx {C Function} scm_hashq (key, size)
2348 @deffnx {C Function} scm_hashv (key, size)
2349 Return a hash value for @var{key}. This is a number in the range
2350 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
2351 table of the given @var{size}.
2353 Note that @code{hashq} and @code{hashv} may use internal addresses of
2354 objects, so if an object is garbage collected and re-created it can
2355 have a different hash value, even when the two are notionally
2356 @code{eq?}. For instance with symbols,
2359 (hashq 'something 123) @result{} 19
2361 (hashq 'something 123) @result{} 62
2364 In normal use this is not a problem, since an object entered into a
2365 hash table won't be garbage collected until removed. It's only if
2366 hashing calculations are somehow separated from normal references that
2367 its lifetime needs to be considered.
2370 @deffn {Scheme Procedure} hash-get-handle table key
2371 @deffnx {Scheme Procedure} hashq-get-handle table key
2372 @deffnx {Scheme Procedure} hashv-get-handle table key
2373 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
2374 @deffnx {C Function} scm_hash_get_handle (table, key)
2375 @deffnx {C Function} scm_hashq_get_handle (table, key)
2376 @deffnx {C Function} scm_hashv_get_handle (table, key)
2377 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
2378 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2379 given hash @var{table}, or @code{#f} if @var{key} is not in
2383 @deffn {Scheme Procedure} hash-create-handle! table key init
2384 @deffnx {Scheme Procedure} hashq-create-handle! table key init
2385 @deffnx {Scheme Procedure} hashv-create-handle! table key init
2386 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
2387 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
2388 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
2389 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
2390 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
2391 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2392 given hash @var{table}. If @var{key} is not in @var{table} then
2393 create an entry for it with @var{init} as the value, and return that
2397 @deffn {Scheme Procedure} hash-map proc table
2398 @deffnx {Scheme Procedure} hash-for-each proc table
2399 @deffnx {C Function} scm_hash_map (proc, table)
2400 @deffnx {C Function} scm_hash_for_each (proc, table)
2401 Apply @var{proc} to the entries in the given hash @var{table}. Each
2402 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map}
2403 returns a list of the results from these calls, @code{hash-for-each}
2404 discards the results and returns an unspecified value.
2406 Calls are made over the table entries in an unspecified order, and for
2407 @code{hash-map} the order of the values in the returned list is
2408 unspecified. Results will be unpredictable if @var{table} is modified
2411 For example the following returns a new alist comprising all the
2412 entries from @code{mytable}, in no particular order.
2415 (hash-map cons mytable)
2419 @deffn {Scheme Procedure} hash-fold proc init table
2420 @deffnx {C Function} scm_hash_fold (proc, init, table)
2421 Accumulate a result by applying @var{proc} to the elements of the
2422 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
2423 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
2424 from the @var{table} and @var{prior-result} is the return from the
2425 previous @var{proc} call. For the first call, @var{prior-result} is
2426 the given @var{init} value.
2428 Calls are made over the table entries in an unspecified order.
2429 Results will be unpredictable if @var{table} is modified while
2430 @code{hash-fold} is running.
2432 For example, the following returns a count of how many keys in
2433 @code{mytable} are strings.
2436 (hash-fold (lambda (key value prior)
2437 (if (string? key) (1+ prior) prior))
2444 @c TeX-master: "guile.texi"