2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 @c 2007, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
7 @node Compound Data Types
8 @section Compound Data Types
10 This chapter describes Guile's compound data types. By @dfn{compound}
11 we mean that the primary purpose of these data types is to act as
12 containers for other kinds of data (including other compound objects).
13 For instance, a (non-uniform) vector with length 5 is a container that
14 can hold five arbitrary Scheme objects.
16 The various kinds of container object differ from each other in how
17 their memory is allocated, how they are indexed, and how particular
18 values can be looked up within them.
21 * Pairs:: Scheme's basic building block.
22 * Lists:: Special list functions supported by Guile.
23 * Vectors:: One-dimensional arrays of Scheme objects.
24 * Bit Vectors:: Vectors of bits.
25 * Generalized Vectors:: Treating all vector-like things uniformly.
26 * Arrays:: Matrices, etc.
27 * VLists:: Vector-like lists.
28 * Record Overview:: Walking through the maze of record APIs.
29 * SRFI-9 Records:: The standard, recommended record API.
30 * Records:: Guile's historical record API.
31 * Structures:: Low-level record representation.
32 * Dictionary Types:: About dictionary types in general.
33 * Association Lists:: List-based dictionaries.
34 * VHashes:: VList-based dictionaries.
35 * Hash Tables:: Table-based dictionaries.
43 Pairs are used to combine two Scheme objects into one compound object.
44 Hence the name: A pair stores a pair of objects.
46 The data type @dfn{pair} is extremely important in Scheme, just like in
47 any other Lisp dialect. The reason is that pairs are not only used to
48 make two values available as one object, but that pairs are used for
49 constructing lists of values. Because lists are so important in Scheme,
50 they are described in a section of their own (@pxref{Lists}).
52 Pairs can literally get entered in source code or at the REPL, in the
53 so-called @dfn{dotted list} syntax. This syntax consists of an opening
54 parentheses, the first element of the pair, a dot, the second element
55 and a closing parentheses. The following example shows how a pair
56 consisting of the two numbers 1 and 2, and a pair containing the symbols
57 @code{foo} and @code{bar} can be entered. It is very important to write
58 the whitespace before and after the dot, because otherwise the Scheme
59 parser would not be able to figure out where to split the tokens.
66 But beware, if you want to try out these examples, you have to
67 @dfn{quote} the expressions. More information about quotation is
68 available in the section @ref{Expression Syntax}. The correct way
69 to try these examples is as follows.
80 A new pair is made by calling the procedure @code{cons} with two
81 arguments. Then the argument values are stored into a newly allocated
82 pair, and the pair is returned. The name @code{cons} stands for
83 "construct". Use the procedure @code{pair?} to test whether a
84 given Scheme object is a pair or not.
87 @deffn {Scheme Procedure} cons x y
88 @deffnx {C Function} scm_cons (x, y)
89 Return a newly allocated pair whose car is @var{x} and whose
90 cdr is @var{y}. The pair is guaranteed to be different (in the
91 sense of @code{eq?}) from every previously existing object.
95 @deffn {Scheme Procedure} pair? x
96 @deffnx {C Function} scm_pair_p (x)
97 Return @code{#t} if @var{x} is a pair; otherwise return
101 @deftypefn {C Function} int scm_is_pair (SCM x)
102 Return 1 when @var{x} is a pair; otherwise return 0.
105 The two parts of a pair are traditionally called @dfn{car} and
106 @dfn{cdr}. They can be retrieved with procedures of the same name
107 (@code{car} and @code{cdr}), and can be modified with the procedures
108 @code{set-car!} and @code{set-cdr!}.
110 Since a very common operation in Scheme programs is to access the car of
111 a car of a pair, or the car of the cdr of a pair, etc., the procedures
112 called @code{caar}, @code{cadr} and so on are also predefined. However,
113 using these procedures is often detrimental to readability, and
114 error-prone. Thus, accessing the contents of a list is usually better
115 achieved using pattern matching techniques (@pxref{Pattern Matching}).
119 @deffn {Scheme Procedure} car pair
120 @deffnx {Scheme Procedure} cdr pair
121 @deffnx {C Function} scm_car (pair)
122 @deffnx {C Function} scm_cdr (pair)
123 Return the car or the cdr of @var{pair}, respectively.
126 @deftypefn {C Macro} SCM SCM_CAR (SCM pair)
127 @deftypefnx {C Macro} SCM SCM_CDR (SCM pair)
128 These two macros are the fastest way to access the car or cdr of a
129 pair; they can be thought of as compiling into a single memory
132 These macros do no checking at all. The argument @var{pair} must be a
136 @deffn {Scheme Procedure} cddr pair
137 @deffnx {Scheme Procedure} cdar pair
138 @deffnx {Scheme Procedure} cadr pair
139 @deffnx {Scheme Procedure} caar pair
140 @deffnx {Scheme Procedure} cdddr pair
141 @deffnx {Scheme Procedure} cddar pair
142 @deffnx {Scheme Procedure} cdadr pair
143 @deffnx {Scheme Procedure} cdaar pair
144 @deffnx {Scheme Procedure} caddr pair
145 @deffnx {Scheme Procedure} cadar pair
146 @deffnx {Scheme Procedure} caadr pair
147 @deffnx {Scheme Procedure} caaar pair
148 @deffnx {Scheme Procedure} cddddr pair
149 @deffnx {Scheme Procedure} cdddar pair
150 @deffnx {Scheme Procedure} cddadr pair
151 @deffnx {Scheme Procedure} cddaar pair
152 @deffnx {Scheme Procedure} cdaddr pair
153 @deffnx {Scheme Procedure} cdadar pair
154 @deffnx {Scheme Procedure} cdaadr pair
155 @deffnx {Scheme Procedure} cdaaar pair
156 @deffnx {Scheme Procedure} cadddr pair
157 @deffnx {Scheme Procedure} caddar pair
158 @deffnx {Scheme Procedure} cadadr pair
159 @deffnx {Scheme Procedure} cadaar pair
160 @deffnx {Scheme Procedure} caaddr pair
161 @deffnx {Scheme Procedure} caadar pair
162 @deffnx {Scheme Procedure} caaadr pair
163 @deffnx {Scheme Procedure} caaaar pair
164 @deffnx {C Function} scm_cddr (pair)
165 @deffnx {C Function} scm_cdar (pair)
166 @deffnx {C Function} scm_cadr (pair)
167 @deffnx {C Function} scm_caar (pair)
168 @deffnx {C Function} scm_cdddr (pair)
169 @deffnx {C Function} scm_cddar (pair)
170 @deffnx {C Function} scm_cdadr (pair)
171 @deffnx {C Function} scm_cdaar (pair)
172 @deffnx {C Function} scm_caddr (pair)
173 @deffnx {C Function} scm_cadar (pair)
174 @deffnx {C Function} scm_caadr (pair)
175 @deffnx {C Function} scm_caaar (pair)
176 @deffnx {C Function} scm_cddddr (pair)
177 @deffnx {C Function} scm_cdddar (pair)
178 @deffnx {C Function} scm_cddadr (pair)
179 @deffnx {C Function} scm_cddaar (pair)
180 @deffnx {C Function} scm_cdaddr (pair)
181 @deffnx {C Function} scm_cdadar (pair)
182 @deffnx {C Function} scm_cdaadr (pair)
183 @deffnx {C Function} scm_cdaaar (pair)
184 @deffnx {C Function} scm_cadddr (pair)
185 @deffnx {C Function} scm_caddar (pair)
186 @deffnx {C Function} scm_cadadr (pair)
187 @deffnx {C Function} scm_cadaar (pair)
188 @deffnx {C Function} scm_caaddr (pair)
189 @deffnx {C Function} scm_caadar (pair)
190 @deffnx {C Function} scm_caaadr (pair)
191 @deffnx {C Function} scm_caaaar (pair)
192 These procedures are compositions of @code{car} and @code{cdr}, where
193 for example @code{caddr} could be defined by
196 (define caddr (lambda (x) (car (cdr (cdr x)))))
199 @code{cadr}, @code{caddr} and @code{cadddr} pick out the second, third
200 or fourth elements of a list, respectively. SRFI-1 provides the same
201 under the names @code{second}, @code{third} and @code{fourth}
202 (@pxref{SRFI-1 Selectors}).
206 @deffn {Scheme Procedure} set-car! pair value
207 @deffnx {C Function} scm_set_car_x (pair, value)
208 Stores @var{value} in the car field of @var{pair}. The value returned
209 by @code{set-car!} is unspecified.
213 @deffn {Scheme Procedure} set-cdr! pair value
214 @deffnx {C Function} scm_set_cdr_x (pair, value)
215 Stores @var{value} in the cdr field of @var{pair}. The value returned
216 by @code{set-cdr!} is unspecified.
224 A very important data type in Scheme---as well as in all other Lisp
225 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
226 Scheme does not have a real datatype @dfn{list}. Lists are made up of
227 @dfn{chained pairs}, and only exist by definition---a list is a chain
228 of pairs which looks like a list.}
230 This is the short definition of what a list is:
234 Either the empty list @code{()},
237 or a pair which has a list in its cdr.
240 @c FIXME::martin: Describe the pair chaining in more detail.
242 @c FIXME::martin: What is a proper, what an improper list?
243 @c What is a circular list?
245 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
249 * List Syntax:: Writing literal lists.
250 * List Predicates:: Testing lists.
251 * List Constructors:: Creating new lists.
252 * List Selection:: Selecting from lists, getting their length.
253 * Append/Reverse:: Appending and reversing lists.
254 * List Modification:: Modifying existing lists.
255 * List Searching:: Searching for list elements
256 * List Mapping:: Applying procedures to lists.
260 @subsubsection List Read Syntax
262 The syntax for lists is an opening parentheses, then all the elements of
263 the list (separated by whitespace) and finally a closing
264 parentheses.@footnote{Note that there is no separation character between
265 the list elements, like a comma or a semicolon.}.
268 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
269 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
270 () ; @r{the empty list}
273 The last example needs a bit more explanation. A list with no elements,
274 called the @dfn{empty list}, is special in some ways. It is used for
275 terminating lists by storing it into the cdr of the last pair that makes
276 up a list. An example will clear that up:
287 This example also shows that lists have to be quoted when written
288 (@pxref{Expression Syntax}), because they would otherwise be
289 mistakingly taken as procedure applications (@pxref{Simple
293 @node List Predicates
294 @subsubsection List Predicates
296 Often it is useful to test whether a given Scheme object is a list or
297 not. List-processing procedures could use this information to test
298 whether their input is valid, or they could do different things
299 depending on the datatype of their arguments.
302 @deffn {Scheme Procedure} list? x
303 @deffnx {C Function} scm_list_p (x)
304 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
307 The predicate @code{null?} is often used in list-processing code to
308 tell whether a given list has run out of elements. That is, a loop
309 somehow deals with the elements of a list until the list satisfies
310 @code{null?}. Then, the algorithm terminates.
313 @deffn {Scheme Procedure} null? x
314 @deffnx {C Function} scm_null_p (x)
315 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
318 @deftypefn {C Function} int scm_is_null (SCM x)
319 Return 1 when @var{x} is the empty list; otherwise return 0.
323 @node List Constructors
324 @subsubsection List Constructors
326 This section describes the procedures for constructing new lists.
327 @code{list} simply returns a list where the elements are the arguments,
328 @code{cons*} is similar, but the last argument is stored in the cdr of
329 the last pair of the list.
331 @c C Function scm_list(rest) used to be documented here, but it's a
332 @c no-op since it does nothing but return the list the caller must
333 @c have already created.
335 @deffn {Scheme Procedure} list elem @dots{}
336 @deffnx {C Function} scm_list_1 (elem1)
337 @deffnx {C Function} scm_list_2 (elem1, elem2)
338 @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
339 @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
340 @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
341 @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
343 Return a new list containing elements @var{elem} @enddots{}.
345 @code{scm_list_n} takes a variable number of arguments, terminated by
346 the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
347 not included in the list. None of @var{elem} @dots{} can
348 themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
349 terminate at that point.
352 @c C Function scm_cons_star(arg1,rest) used to be documented here,
353 @c but it's not really a useful interface, since it expects the
354 @c caller to have already consed up all but the first argument
357 @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
358 Like @code{list}, but the last arg provides the tail of the
359 constructed list, returning @code{(cons @var{arg1} (cons
360 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
361 argument. If given one argument, that argument is returned as
362 result. This function is called @code{list*} in some other
363 Schemes and in Common LISP.
366 @deffn {Scheme Procedure} list-copy lst
367 @deffnx {C Function} scm_list_copy (lst)
368 Return a (newly-created) copy of @var{lst}.
371 @deffn {Scheme Procedure} make-list n [init]
372 Create a list containing of @var{n} elements, where each element is
373 initialized to @var{init}. @var{init} defaults to the empty list
374 @code{()} if not given.
377 Note that @code{list-copy} only makes a copy of the pairs which make up
378 the spine of the lists. The list elements are not copied, which means
379 that modifying the elements of the new list also modifies the elements
380 of the old list. On the other hand, applying procedures like
381 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
382 list. If you also need to copy the list elements (making a deep copy),
383 use the procedure @code{copy-tree} (@pxref{Copying}).
386 @subsubsection List Selection
388 These procedures are used to get some information about a list, or to
389 retrieve one or more elements of a list.
392 @deffn {Scheme Procedure} length lst
393 @deffnx {C Function} scm_length (lst)
394 Return the number of elements in list @var{lst}.
397 @deffn {Scheme Procedure} last-pair lst
398 @deffnx {C Function} scm_last_pair (lst)
399 Return the last pair in @var{lst}, signalling an error if
400 @var{lst} is circular.
404 @deffn {Scheme Procedure} list-ref list k
405 @deffnx {C Function} scm_list_ref (list, k)
406 Return the @var{k}th element from @var{list}.
410 @deffn {Scheme Procedure} list-tail lst k
411 @deffnx {Scheme Procedure} list-cdr-ref lst k
412 @deffnx {C Function} scm_list_tail (lst, k)
413 Return the "tail" of @var{lst} beginning with its @var{k}th element.
414 The first element of the list is considered to be element 0.
416 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
417 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
418 or returning the results of cdring @var{k} times down @var{lst}.
421 @deffn {Scheme Procedure} list-head lst k
422 @deffnx {C Function} scm_list_head (lst, k)
423 Copy the first @var{k} elements from @var{lst} into a new list, and
428 @subsubsection Append and Reverse
430 @code{append} and @code{append!} are used to concatenate two or more
431 lists in order to form a new list. @code{reverse} and @code{reverse!}
432 return lists with the same elements as their arguments, but in reverse
433 order. The procedure variants with an @code{!} directly modify the
434 pairs which form the list, whereas the other procedures create new
435 pairs. This is why you should be careful when using the side-effecting
439 @deffn {Scheme Procedure} append lst @dots{} obj
440 @deffnx {Scheme Procedure} append
441 @deffnx {Scheme Procedure} append! lst @dots{} obj
442 @deffnx {Scheme Procedure} append!
443 @deffnx {C Function} scm_append (lstlst)
444 @deffnx {C Function} scm_append_x (lstlst)
445 Return a list comprising all the elements of lists @var{lst} @dots{}
446 @var{obj}. If called with no arguments, return the empty list.
449 (append '(x) '(y)) @result{} (x y)
450 (append '(a) '(b c d)) @result{} (a b c d)
451 (append '(a (b)) '((c))) @result{} (a (b) (c))
454 The last argument @var{obj} may actually be any object; an improper
455 list results if the last argument is not a proper list.
458 (append '(a b) '(c . d)) @result{} (a b c . d)
459 (append '() 'a) @result{} a
462 @code{append} doesn't modify the given lists, but the return may share
463 structure with the final @var{obj}. @code{append!} modifies the
464 given lists to form its return.
466 For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
467 of the list operands @var{lst} @dots{} @var{obj}. That @var{lstlst}
468 itself is not modified or used in the return.
472 @deffn {Scheme Procedure} reverse lst
473 @deffnx {Scheme Procedure} reverse! lst [newtail]
474 @deffnx {C Function} scm_reverse (lst)
475 @deffnx {C Function} scm_reverse_x (lst, newtail)
476 Return a list comprising the elements of @var{lst}, in reverse order.
478 @code{reverse} constructs a new list, @code{reverse!} modifies
479 @var{lst} in constructing its return.
481 For @code{reverse!}, the optional @var{newtail} is appended to the
482 result. @var{newtail} isn't reversed, it simply becomes the list
483 tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
484 mandatory, but can be @code{SCM_EOL} if no further tail is required.
487 @node List Modification
488 @subsubsection List Modification
490 The following procedures modify an existing list, either by changing
491 elements of the list, or by changing the list structure itself.
493 @deffn {Scheme Procedure} list-set! list k val
494 @deffnx {C Function} scm_list_set_x (list, k, val)
495 Set the @var{k}th element of @var{list} to @var{val}.
498 @deffn {Scheme Procedure} list-cdr-set! list k val
499 @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
500 Set the @var{k}th cdr of @var{list} to @var{val}.
503 @deffn {Scheme Procedure} delq item lst
504 @deffnx {C Function} scm_delq (item, lst)
505 Return a newly-created copy of @var{lst} with elements
506 @code{eq?} to @var{item} removed. This procedure mirrors
507 @code{memq}: @code{delq} compares elements of @var{lst} against
508 @var{item} with @code{eq?}.
511 @deffn {Scheme Procedure} delv item lst
512 @deffnx {C Function} scm_delv (item, lst)
513 Return a newly-created copy of @var{lst} with elements
514 @code{eqv?} to @var{item} removed. This procedure mirrors
515 @code{memv}: @code{delv} compares elements of @var{lst} against
516 @var{item} with @code{eqv?}.
519 @deffn {Scheme Procedure} delete item lst
520 @deffnx {C Function} scm_delete (item, lst)
521 Return a newly-created copy of @var{lst} with elements
522 @code{equal?} to @var{item} removed. This procedure mirrors
523 @code{member}: @code{delete} compares elements of @var{lst}
524 against @var{item} with @code{equal?}.
526 See also SRFI-1 which has an extended @code{delete} (@ref{SRFI-1
527 Deleting}), and also an @code{lset-difference} which can delete
528 multiple @var{item}s in one call (@ref{SRFI-1 Set Operations}).
531 @deffn {Scheme Procedure} delq! item lst
532 @deffnx {Scheme Procedure} delv! item lst
533 @deffnx {Scheme Procedure} delete! item lst
534 @deffnx {C Function} scm_delq_x (item, lst)
535 @deffnx {C Function} scm_delv_x (item, lst)
536 @deffnx {C Function} scm_delete_x (item, lst)
537 These procedures are destructive versions of @code{delq}, @code{delv}
538 and @code{delete}: they modify the pointers in the existing @var{lst}
539 rather than creating a new list. Caveat evaluator: Like other
540 destructive list functions, these functions cannot modify the binding of
541 @var{lst}, and so cannot be used to delete the first element of
542 @var{lst} destructively.
545 @deffn {Scheme Procedure} delq1! item lst
546 @deffnx {C Function} scm_delq1_x (item, lst)
547 Like @code{delq!}, but only deletes the first occurrence of
548 @var{item} from @var{lst}. Tests for equality using
549 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
552 @deffn {Scheme Procedure} delv1! item lst
553 @deffnx {C Function} scm_delv1_x (item, lst)
554 Like @code{delv!}, but only deletes the first occurrence of
555 @var{item} from @var{lst}. Tests for equality using
556 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
559 @deffn {Scheme Procedure} delete1! item lst
560 @deffnx {C Function} scm_delete1_x (item, lst)
561 Like @code{delete!}, but only deletes the first occurrence of
562 @var{item} from @var{lst}. Tests for equality using
563 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
566 @deffn {Scheme Procedure} filter pred lst
567 @deffnx {Scheme Procedure} filter! pred lst
568 Return a list containing all elements from @var{lst} which satisfy the
569 predicate @var{pred}. The elements in the result list have the same
570 order as in @var{lst}. The order in which @var{pred} is applied to
571 the list elements is not specified.
573 @code{filter} does not change @var{lst}, but the result may share a
574 tail with it. @code{filter!} may modify @var{lst} to construct its
579 @subsubsection List Searching
581 The following procedures search lists for particular elements. They use
582 different comparison predicates for comparing list elements with the
583 object to be searched. When they fail, they return @code{#f}, otherwise
584 they return the sublist whose car is equal to the search object, where
585 equality depends on the equality predicate used.
588 @deffn {Scheme Procedure} memq x lst
589 @deffnx {C Function} scm_memq (x, lst)
590 Return the first sublist of @var{lst} whose car is @code{eq?}
591 to @var{x} where the sublists of @var{lst} are the non-empty
592 lists returned by @code{(list-tail @var{lst} @var{k})} for
593 @var{k} less than the length of @var{lst}. If @var{x} does not
594 occur in @var{lst}, then @code{#f} (not the empty list) is
599 @deffn {Scheme Procedure} memv x lst
600 @deffnx {C Function} scm_memv (x, lst)
601 Return the first sublist of @var{lst} whose car is @code{eqv?}
602 to @var{x} where the sublists of @var{lst} are the non-empty
603 lists returned by @code{(list-tail @var{lst} @var{k})} for
604 @var{k} less than the length of @var{lst}. If @var{x} does not
605 occur in @var{lst}, then @code{#f} (not the empty list) is
610 @deffn {Scheme Procedure} member x lst
611 @deffnx {C Function} scm_member (x, lst)
612 Return the first sublist of @var{lst} whose car is
613 @code{equal?} to @var{x} where the sublists of @var{lst} are
614 the non-empty lists returned by @code{(list-tail @var{lst}
615 @var{k})} for @var{k} less than the length of @var{lst}. If
616 @var{x} does not occur in @var{lst}, then @code{#f} (not the
617 empty list) is returned.
619 See also SRFI-1 which has an extended @code{member} function
620 (@ref{SRFI-1 Searching}).
625 @subsubsection List Mapping
627 List processing is very convenient in Scheme because the process of
628 iterating over the elements of a list can be highly abstracted. The
629 procedures in this section are the most basic iterating procedures for
630 lists. They take a procedure and one or more lists as arguments, and
631 apply the procedure to each element of the list. They differ in their
635 @c begin (texi-doc-string "guile" "map")
636 @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
637 @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
638 @deffnx {C Function} scm_map (proc, arg1, args)
639 Apply @var{proc} to each element of the list @var{arg1} (if only two
640 arguments are given), or to the corresponding elements of the argument
641 lists (if more than two arguments are given). The result(s) of the
642 procedure applications are saved and returned in a list. For
643 @code{map}, the order of procedure applications is not specified,
644 @code{map-in-order} applies the procedure from left to right to the list
649 @c begin (texi-doc-string "guile" "for-each")
650 @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
651 Like @code{map}, but the procedure is always applied from left to right,
652 and the result(s) of the procedure applications are thrown away. The
653 return value is not specified.
656 See also SRFI-1 which extends these functions to take lists of unequal
657 lengths (@ref{SRFI-1 Fold and Map}).
663 Vectors are sequences of Scheme objects. Unlike lists, the length of a
664 vector, once the vector is created, cannot be changed. The advantage of
665 vectors over lists is that the time required to access one element of a vector
666 given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
667 is constant, whereas lists have an access time linear to the position of the
668 accessed element in the list.
670 Vectors can contain any kind of Scheme object; it is even possible to
671 have different types of objects in the same vector. For vectors
672 containing vectors, you may wish to use arrays, instead. Note, too,
673 that vectors are the special case of one dimensional non-uniform arrays
674 and that most array procedures operate happily on vectors
678 * Vector Syntax:: Read syntax for vectors.
679 * Vector Creation:: Dynamic vector creation and validation.
680 * Vector Accessors:: Accessing and modifying vector contents.
681 * Vector Accessing from C:: Ways to work with vectors from C.
682 * Uniform Numeric Vectors:: Vectors of unboxed numeric values.
687 @subsubsection Read Syntax for Vectors
689 Vectors can literally be entered in source code, just like strings,
690 characters or some of the other data types. The read syntax for vectors
691 is as follows: A sharp sign (@code{#}), followed by an opening
692 parentheses, all elements of the vector in their respective read syntax,
693 and finally a closing parentheses. The following are examples of the
694 read syntax for vectors; where the first vector only contains numbers
695 and the second three different object types: a string, a symbol and a
696 number in hexadecimal notation.
700 #("Hello" foo #xdeadbeef)
703 Like lists, vectors have to be quoted:
706 '#(a b c) @result{} #(a b c)
709 @node Vector Creation
710 @subsubsection Dynamic Vector Creation and Validation
712 Instead of creating a vector implicitly by using the read syntax just
713 described, you can create a vector dynamically by calling one of the
714 @code{vector} and @code{list->vector} primitives with the list of Scheme
715 values that you want to place into a vector. The size of the vector
716 thus created is determined implicitly by the number of arguments given.
719 @rnindex list->vector
720 @deffn {Scheme Procedure} vector arg @dots{}
721 @deffnx {Scheme Procedure} list->vector l
722 @deffnx {C Function} scm_vector (l)
723 Return a newly allocated vector composed of the
724 given arguments. Analogous to @code{list}.
727 (vector 'a 'b 'c) @result{} #(a b c)
731 The inverse operation is @code{vector->list}:
733 @rnindex vector->list
734 @deffn {Scheme Procedure} vector->list v
735 @deffnx {C Function} scm_vector_to_list (v)
736 Return a newly allocated list composed of the elements of @var{v}.
739 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
740 (list->vector '(dididit dah)) @result{} #(dididit dah)
744 To allocate a vector with an explicitly specified size, use
745 @code{make-vector}. With this primitive you can also specify an initial
746 value for the vector elements (the same value for all elements, that
750 @deffn {Scheme Procedure} make-vector len [fill]
751 @deffnx {C Function} scm_make_vector (len, fill)
752 Return a newly allocated vector of @var{len} elements. If a
753 second argument is given, then each position is initialized to
754 @var{fill}. Otherwise the initial contents of each position is
758 @deftypefn {C Function} SCM scm_c_make_vector (size_t k, SCM fill)
759 Like @code{scm_make_vector}, but the length is given as a @code{size_t}.
762 To check whether an arbitrary Scheme value @emph{is} a vector, use the
763 @code{vector?} primitive:
766 @deffn {Scheme Procedure} vector? obj
767 @deffnx {C Function} scm_vector_p (obj)
768 Return @code{#t} if @var{obj} is a vector, otherwise return
772 @deftypefn {C Function} int scm_is_vector (SCM obj)
773 Return non-zero when @var{obj} is a vector, otherwise return
777 @node Vector Accessors
778 @subsubsection Accessing and Modifying Vector Contents
780 @code{vector-length} and @code{vector-ref} return information about a
781 given vector, respectively its size and the elements that are contained
784 @rnindex vector-length
785 @deffn {Scheme Procedure} vector-length vector
786 @deffnx {C Function} scm_vector_length (vector)
787 Return the number of elements in @var{vector} as an exact integer.
790 @deftypefn {C Function} size_t scm_c_vector_length (SCM vec)
791 Return the number of elements in @var{vec} as a @code{size_t}.
795 @deffn {Scheme Procedure} vector-ref vec k
796 @deffnx {C Function} scm_vector_ref (vec, k)
797 Return the contents of position @var{k} of @var{vec}.
798 @var{k} must be a valid index of @var{vec}.
800 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
801 (vector-ref '#(1 1 2 3 5 8 13 21)
802 (let ((i (round (* 2 (acos -1)))))
809 @deftypefn {C Function} SCM scm_c_vector_ref (SCM vec, size_t k)
810 Return the contents of position @var{k} (a @code{size_t}) of
814 A vector created by one of the dynamic vector constructor procedures
815 (@pxref{Vector Creation}) can be modified using the following
818 @emph{NOTE:} According to R5RS, it is an error to use any of these
819 procedures on a literally read vector, because such vectors should be
820 considered as constants. Currently, however, Guile does not detect this
824 @deffn {Scheme Procedure} vector-set! vec k obj
825 @deffnx {C Function} scm_vector_set_x (vec, k, obj)
826 Store @var{obj} in position @var{k} of @var{vec}.
827 @var{k} must be a valid index of @var{vec}.
828 The value returned by @samp{vector-set!} is unspecified.
830 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
831 (vector-set! vec 1 '("Sue" "Sue"))
832 vec) @result{} #(0 ("Sue" "Sue") "Anna")
836 @deftypefn {C Function} void scm_c_vector_set_x (SCM vec, size_t k, SCM obj)
837 Store @var{obj} in position @var{k} (a @code{size_t}) of @var{vec}.
840 @rnindex vector-fill!
841 @deffn {Scheme Procedure} vector-fill! vec fill
842 @deffnx {C Function} scm_vector_fill_x (vec, fill)
843 Store @var{fill} in every position of @var{vec}. The value
844 returned by @code{vector-fill!} is unspecified.
847 @deffn {Scheme Procedure} vector-copy vec
848 @deffnx {C Function} scm_vector_copy (vec)
849 Return a copy of @var{vec}.
852 @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
853 @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
854 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
855 to @var{vec2} starting at position @var{start2}. @var{start1} and
856 @var{start2} are inclusive indices; @var{end1} is exclusive.
858 @code{vector-move-left!} copies elements in leftmost order.
859 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
860 same vector, @code{vector-move-left!} is usually appropriate when
861 @var{start1} is greater than @var{start2}.
864 @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
865 @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
866 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
867 to @var{vec2} starting at position @var{start2}. @var{start1} and
868 @var{start2} are inclusive indices; @var{end1} is exclusive.
870 @code{vector-move-right!} copies elements in rightmost order.
871 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
872 same vector, @code{vector-move-right!} is usually appropriate when
873 @var{start1} is less than @var{start2}.
876 @node Vector Accessing from C
877 @subsubsection Vector Accessing from C
879 A vector can be read and modified from C with the functions
880 @code{scm_c_vector_ref} and @code{scm_c_vector_set_x}, for example. In
881 addition to these functions, there are two more ways to access vectors
882 from C that might be more efficient in certain situations: you can
883 restrict yourself to @dfn{simple vectors} and then use the very fast
884 @emph{simple vector macros}; or you can use the very general framework
885 for accessing all kinds of arrays (@pxref{Accessing Arrays from C}),
886 which is more verbose, but can deal efficiently with all kinds of
887 vectors (and arrays). For vectors, you can use the
888 @code{scm_vector_elements} and @code{scm_vector_writable_elements}
889 functions as shortcuts.
891 @deftypefn {C Function} int scm_is_simple_vector (SCM obj)
892 Return non-zero if @var{obj} is a simple vector, else return zero. A
893 simple vector is a vector that can be used with the @code{SCM_SIMPLE_*}
896 The following functions are guaranteed to return simple vectors:
897 @code{scm_make_vector}, @code{scm_c_make_vector}, @code{scm_vector},
898 @code{scm_list_to_vector}.
901 @deftypefn {C Macro} size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)
902 Evaluates to the length of the simple vector @var{vec}. No type
906 @deftypefn {C Macro} SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)
907 Evaluates to the element at position @var{idx} in the simple vector
908 @var{vec}. No type or range checking is done.
911 @deftypefn {C Macro} void SCM_SIMPLE_VECTOR_SET (SCM vec, size_t idx, SCM val)
912 Sets the element at position @var{idx} in the simple vector
913 @var{vec} to @var{val}. No type or range checking is done.
916 @deftypefn {C Function} {const SCM *} scm_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
917 Acquire a handle for the vector @var{vec} and return a pointer to the
918 elements of it. This pointer can only be used to read the elements of
919 @var{vec}. When @var{vec} is not a vector, an error is signaled. The
920 handle must eventually be released with
921 @code{scm_array_handle_release}.
923 The variables pointed to by @var{lenp} and @var{incp} are filled with
924 the number of elements of the vector and the increment (number of
925 elements) between successive elements, respectively. Successive
926 elements of @var{vec} need not be contiguous in their underlying
927 ``root vector'' returned here; hence the increment is not necessarily
928 equal to 1 and may well be negative too (@pxref{Shared Arrays}).
930 The following example shows the typical way to use this function. It
931 creates a list of all elements of @var{vec} (in reverse order).
934 scm_t_array_handle handle;
940 elt = scm_vector_elements (vec, &handle, &len, &inc);
942 for (i = 0; i < len; i++, elt += inc)
943 list = scm_cons (*elt, list);
944 scm_array_handle_release (&handle);
949 @deftypefn {C Function} {SCM *} scm_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
950 Like @code{scm_vector_elements} but the pointer can be used to modify
953 The following example shows the typical way to use this function. It
954 fills a vector with @code{#t}.
957 scm_t_array_handle handle;
962 elt = scm_vector_writable_elements (vec, &handle, &len, &inc);
963 for (i = 0; i < len; i++, elt += inc)
965 scm_array_handle_release (&handle);
970 @node Uniform Numeric Vectors
971 @subsubsection Uniform Numeric Vectors
973 A uniform numeric vector is a vector whose elements are all of a single
974 numeric type. Guile offers uniform numeric vectors for signed and
975 unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
976 floating point values, and complex floating-point numbers of these two
977 sizes. @xref{SRFI-4}, for more information.
979 For many purposes, bytevectors work just as well as uniform vectors, and have
980 the advantage that they integrate well with binary input and output.
981 @xref{Bytevectors}, for more information on bytevectors.
984 @subsection Bit Vectors
987 Bit vectors are zero-origin, one-dimensional arrays of booleans. They
988 are displayed as a sequence of @code{0}s and @code{1}s prefixed by
992 (make-bitvector 8 #f) @result{}
996 Bit vectors are also generalized vectors, @xref{Generalized
997 Vectors}, and can thus be used with the array procedures, @xref{Arrays}.
998 Bit vectors are the special case of one dimensional bit arrays.
1000 @deffn {Scheme Procedure} bitvector? obj
1001 @deffnx {C Function} scm_bitvector_p (obj)
1002 Return @code{#t} when @var{obj} is a bitvector, else
1006 @deftypefn {C Function} int scm_is_bitvector (SCM obj)
1007 Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
1010 @deffn {Scheme Procedure} make-bitvector len [fill]
1011 @deffnx {C Function} scm_make_bitvector (len, fill)
1012 Create a new bitvector of length @var{len} and
1013 optionally initialize all elements to @var{fill}.
1016 @deftypefn {C Function} SCM scm_c_make_bitvector (size_t len, SCM fill)
1017 Like @code{scm_make_bitvector}, but the length is given as a
1021 @deffn {Scheme Procedure} bitvector bit @dots{}
1022 @deffnx {C Function} scm_bitvector (bits)
1023 Create a new bitvector with the arguments as elements.
1026 @deffn {Scheme Procedure} bitvector-length vec
1027 @deffnx {C Function} scm_bitvector_length (vec)
1028 Return the length of the bitvector @var{vec}.
1031 @deftypefn {C Function} size_t scm_c_bitvector_length (SCM vec)
1032 Like @code{scm_bitvector_length}, but the length is returned as a
1036 @deffn {Scheme Procedure} bitvector-ref vec idx
1037 @deffnx {C Function} scm_bitvector_ref (vec, idx)
1038 Return the element at index @var{idx} of the bitvector
1042 @deftypefn {C Function} SCM scm_c_bitvector_ref (SCM vec, size_t idx)
1043 Return the element at index @var{idx} of the bitvector
1047 @deffn {Scheme Procedure} bitvector-set! vec idx val
1048 @deffnx {C Function} scm_bitvector_set_x (vec, idx, val)
1049 Set the element at index @var{idx} of the bitvector
1050 @var{vec} when @var{val} is true, else clear it.
1053 @deftypefn {C Function} SCM scm_c_bitvector_set_x (SCM vec, size_t idx, SCM val)
1054 Set the element at index @var{idx} of the bitvector
1055 @var{vec} when @var{val} is true, else clear it.
1058 @deffn {Scheme Procedure} bitvector-fill! vec val
1059 @deffnx {C Function} scm_bitvector_fill_x (vec, val)
1060 Set all elements of the bitvector
1061 @var{vec} when @var{val} is true, else clear them.
1064 @deffn {Scheme Procedure} list->bitvector list
1065 @deffnx {C Function} scm_list_to_bitvector (list)
1066 Return a new bitvector initialized with the elements
1070 @deffn {Scheme Procedure} bitvector->list vec
1071 @deffnx {C Function} scm_bitvector_to_list (vec)
1072 Return a new list initialized with the elements
1073 of the bitvector @var{vec}.
1076 @deffn {Scheme Procedure} bit-count bool bitvector
1077 @deffnx {C Function} scm_bit_count (bool, bitvector)
1078 Return a count of how many entries in @var{bitvector} are equal to
1079 @var{bool}. For example,
1082 (bit-count #f #*000111000) @result{} 6
1086 @deffn {Scheme Procedure} bit-position bool bitvector start
1087 @deffnx {C Function} scm_bit_position (bool, bitvector, start)
1088 Return the index of the first occurrence of @var{bool} in
1089 @var{bitvector}, starting from @var{start}. If there is no @var{bool}
1090 entry between @var{start} and the end of @var{bitvector}, then return
1091 @code{#f}. For example,
1094 (bit-position #t #*000101 0) @result{} 3
1095 (bit-position #f #*0001111 3) @result{} #f
1099 @deffn {Scheme Procedure} bit-invert! bitvector
1100 @deffnx {C Function} scm_bit_invert_x (bitvector)
1101 Modify @var{bitvector} by replacing each element with its negation.
1104 @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1105 @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1106 Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1107 selecting the entries to change. The return value is unspecified.
1109 If @var{uvec} is a bit vector, then those entries where it has
1110 @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1111 @var{uvec} and @var{bitvector} must be the same length. When
1112 @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1113 @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1117 (define bv #*01000010)
1118 (bit-set*! bv #*10010001 #t)
1120 @result{} #*11010011
1123 If @var{uvec} is a uniform vector of unsigned long integers, then
1124 they're indexes into @var{bitvector} which are set to @var{bool}.
1127 (define bv #*01000010)
1128 (bit-set*! bv #u(5 2 7) #t)
1130 @result{} #*01100111
1134 @deffn {Scheme Procedure} bit-count* bitvector uvec bool
1135 @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1136 Return a count of how many entries in @var{bitvector} are equal to
1137 @var{bool}, with @var{uvec} selecting the entries to consider.
1139 @var{uvec} is interpreted in the same way as for @code{bit-set*!}
1140 above. Namely, if @var{uvec} is a bit vector then entries which have
1141 @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1142 is a uniform vector of unsigned long integers then it's the indexes in
1143 @var{bitvector} to consider.
1148 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1149 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1153 @deftypefn {C Function} {const scm_t_uint32 *} scm_bitvector_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
1154 Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
1155 for bitvectors. The variable pointed to by @var{offp} is set to the
1156 value returned by @code{scm_array_handle_bit_elements_offset}. See
1157 @code{scm_array_handle_bit_elements} for how to use the returned
1158 pointer and the offset.
1161 @deftypefn {C Function} {scm_t_uint32 *} scm_bitvector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *offp, size_t *lenp, ssize_t *incp)
1162 Like @code{scm_bitvector_elements}, but the pointer is good for reading
1166 @node Generalized Vectors
1167 @subsection Generalized Vectors
1169 Guile has a number of data types that are generally vector-like:
1170 strings, uniform numeric vectors, bytevectors, bitvectors, and of course
1171 ordinary vectors of arbitrary Scheme values. These types are disjoint:
1172 a Scheme value belongs to at most one of the five types listed above.
1174 If you want to gloss over this distinction and want to treat all four
1175 types with common code, you can use the procedures in this section.
1176 They work with the @emph{generalized vector} type, which is the union
1177 of the five vector-like types.
1179 @deffn {Scheme Procedure} generalized-vector? obj
1180 @deffnx {C Function} scm_generalized_vector_p (obj)
1181 Return @code{#t} if @var{obj} is a vector, bytevector, string,
1182 bitvector, or uniform numeric vector.
1185 @deffn {Scheme Procedure} generalized-vector-length v
1186 @deffnx {C Function} scm_generalized_vector_length (v)
1187 Return the length of the generalized vector @var{v}.
1190 @deffn {Scheme Procedure} generalized-vector-ref v idx
1191 @deffnx {C Function} scm_generalized_vector_ref (v, idx)
1192 Return the element at index @var{idx} of the
1193 generalized vector @var{v}.
1196 @deffn {Scheme Procedure} generalized-vector-set! v idx val
1197 @deffnx {C Function} scm_generalized_vector_set_x (v, idx, val)
1198 Set the element at index @var{idx} of the
1199 generalized vector @var{v} to @var{val}.
1202 @deffn {Scheme Procedure} generalized-vector->list v
1203 @deffnx {C Function} scm_generalized_vector_to_list (v)
1204 Return a new list whose elements are the elements of the
1205 generalized vector @var{v}.
1208 @deftypefn {C Function} int scm_is_generalized_vector (SCM obj)
1209 Return @code{1} if @var{obj} is a vector, string,
1210 bitvector, or uniform numeric vector; else return @code{0}.
1213 @deftypefn {C Function} size_t scm_c_generalized_vector_length (SCM v)
1214 Return the length of the generalized vector @var{v}.
1217 @deftypefn {C Function} SCM scm_c_generalized_vector_ref (SCM v, size_t idx)
1218 Return the element at index @var{idx} of the generalized vector @var{v}.
1221 @deftypefn {C Function} void scm_c_generalized_vector_set_x (SCM v, size_t idx, SCM val)
1222 Set the element at index @var{idx} of the generalized vector @var{v}
1226 @deftypefn {C Function} void scm_generalized_vector_get_handle (SCM v, scm_t_array_handle *handle)
1227 Like @code{scm_array_get_handle} but an error is signalled when @var{v}
1228 is not of rank one. You can use @code{scm_array_handle_ref} and
1229 @code{scm_array_handle_set} to read and write the elements of @var{v},
1230 or you can use functions like @code{scm_array_handle_<foo>_elements} to
1231 deal with specific types of vectors.
1238 @dfn{Arrays} are a collection of cells organized into an arbitrary
1239 number of dimensions. Each cell can be accessed in constant time by
1240 supplying an index for each dimension.
1242 In the current implementation, an array uses a generalized vector for
1243 the actual storage of its elements. Any kind of generalized vector
1244 will do, so you can have arrays of uniform numeric values, arrays of
1245 characters, arrays of bits, and of course, arrays of arbitrary Scheme
1246 values. For example, arrays with an underlying @code{c64vector} might
1247 be nice for digital signal processing, while arrays made from a
1248 @code{u8vector} might be used to hold gray-scale images.
1250 The number of dimensions of an array is called its @dfn{rank}. Thus,
1251 a matrix is an array of rank 2, while a vector has rank 1. When
1252 accessing an array element, you have to specify one exact integer for
1253 each dimension. These integers are called the @dfn{indices} of the
1254 element. An array specifies the allowed range of indices for each
1255 dimension via an inclusive lower and upper bound. These bounds can
1256 well be negative, but the upper bound must be greater than or equal to
1257 the lower bound minus one. When all lower bounds of an array are
1258 zero, it is called a @dfn{zero-origin} array.
1260 Arrays can be of rank 0, which could be interpreted as a scalar.
1261 Thus, a zero-rank array can store exactly one object and the list of
1262 indices of this element is the empty list.
1264 Arrays contain zero elements when one of their dimensions has a zero
1265 length. These empty arrays maintain information about their shape: a
1266 matrix with zero columns and 3 rows is different from a matrix with 3
1267 columns and zero rows, which again is different from a vector of
1270 Generalized vectors, such as strings, uniform numeric vectors,
1271 bytevectors, bit vectors and ordinary vectors, are the special case of
1272 one dimensional arrays.
1276 * Array Procedures::
1278 * Accessing Arrays from C::
1282 @subsubsection Array Syntax
1284 An array is displayed as @code{#} followed by its rank, followed by a
1285 tag that describes the underlying vector, optionally followed by
1286 information about its shape, and finally followed by the cells,
1287 organized into dimensions using parentheses.
1289 In more words, the array tag is of the form
1292 #<rank><vectag><@@lower><:len><@@lower><:len>...
1295 where @code{<rank>} is a positive integer in decimal giving the rank of
1296 the array. It is omitted when the rank is 1 and the array is non-shared
1297 and has zero-origin (see below). For shared arrays and for a non-zero
1298 origin, the rank is always printed even when it is 1 to distinguish
1299 them from ordinary vectors.
1301 The @code{<vectag>} part is the tag for a uniform numeric vector, like
1302 @code{u8}, @code{s16}, etc, @code{b} for bitvectors, or @code{a} for
1303 strings. It is empty for ordinary vectors.
1305 The @code{<@@lower>} part is a @samp{@@} character followed by a signed
1306 integer in decimal giving the lower bound of a dimension. There is one
1307 @code{<@@lower>} for each dimension. When all lower bounds are zero,
1308 all @code{<@@lower>} parts are omitted.
1310 The @code{<:len>} part is a @samp{:} character followed by an unsigned
1311 integer in decimal giving the length of a dimension. Like for the lower
1312 bounds, there is one @code{<:len>} for each dimension, and the
1313 @code{<:len>} part always follows the @code{<@@lower>} part for a
1314 dimension. Lengths are only then printed when they can't be deduced
1315 from the nested lists of elements of the array literal, which can happen
1316 when at least one length is zero.
1318 As a special case, an array of rank 0 is printed as
1319 @code{#0<vectag>(<scalar>)}, where @code{<scalar>} is the result of
1320 printing the single element of the array.
1326 is an ordinary array of rank 1 with lower bound 0 in dimension 0.
1327 (I.e., a regular vector.)
1330 is an ordinary array of rank 1 with lower bound 2 in dimension 0.
1332 @item #2((1 2 3) (4 5 6))
1333 is a non-uniform array of rank 2; a 3@cross{}3 matrix with index ranges 0..2
1337 is a uniform u8 array of rank 1.
1339 @item #2u32@@2@@3((1 2) (2 3))
1340 is a uniform u8 array of rank 2 with index ranges 2..3 and 3..4.
1343 is a two-dimensional array with index ranges 0..-1 and 0..-1, i.e.@:
1344 both dimensions have length zero.
1347 is a two-dimensional array with index ranges 0..-1 and 0..1, i.e.@: the
1348 first dimension has length zero, but the second has length 2.
1351 is a rank-zero array with contents 12.
1355 In addition, bytevectors are also arrays, but use a different syntax
1356 (@pxref{Bytevectors}):
1361 is a 3-byte long bytevector, with contents 1, 2, 3.
1365 @node Array Procedures
1366 @subsubsection Array Procedures
1368 When an array is created, the range of each dimension must be
1369 specified, e.g., to create a 2@cross{}3 array with a zero-based index:
1372 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1375 The range of each dimension can also be given explicitly, e.g., another
1376 way to create the same array:
1379 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1382 The following procedures can be used with arrays (or vectors). An
1383 argument shown as @var{idx}@dots{} means one parameter for each
1384 dimension in the array. A @var{idxlist} argument means a list of such
1385 values, one for each dimension.
1388 @deffn {Scheme Procedure} array? obj
1389 @deffnx {C Function} scm_array_p (obj, unused)
1390 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1393 The second argument to scm_array_p is there for historical reasons,
1394 but it is not used. You should always pass @code{SCM_UNDEFINED} as
1398 @deffn {Scheme Procedure} typed-array? obj type
1399 @deffnx {C Function} scm_typed_array_p (obj, type)
1400 Return @code{#t} if the @var{obj} is an array of type @var{type}, and
1404 @deftypefn {C Function} int scm_is_array (SCM obj)
1405 Return @code{1} if the @var{obj} is an array and @code{0} if not.
1408 @deftypefn {C Function} int scm_is_typed_array (SCM obj, SCM type)
1409 Return @code{0} if the @var{obj} is an array of type @var{type}, and
1413 @deffn {Scheme Procedure} make-array fill bound @dots{}
1414 @deffnx {C Function} scm_make_array (fill, bounds)
1415 Equivalent to @code{(make-typed-array #t @var{fill} @var{bound} ...)}.
1418 @deffn {Scheme Procedure} make-typed-array type fill bound @dots{}
1419 @deffnx {C Function} scm_make_typed_array (type, fill, bounds)
1420 Create and return an array that has as many dimensions as there are
1421 @var{bound}s and (maybe) fill it with @var{fill}.
1423 The underlying storage vector is created according to @var{type},
1424 which must be a symbol whose name is the `vectag' of the array as
1425 explained above, or @code{#t} for ordinary, non-specialized arrays.
1427 For example, using the symbol @code{f64} for @var{type} will create an
1428 array that uses a @code{f64vector} for storing its elements, and
1429 @code{a} will use a string.
1431 When @var{fill} is not the special @emph{unspecified} value, the new
1432 array is filled with @var{fill}. Otherwise, the initial contents of
1433 the array is unspecified. The special @emph{unspecified} value is
1434 stored in the variable @code{*unspecified*} so that for example
1435 @code{(make-typed-array 'u32 *unspecified* 4)} creates a uninitialized
1436 @code{u32} vector of length 4.
1438 Each @var{bound} may be a positive non-zero integer @var{n}, in which
1439 case the index for that dimension can range from 0 through @var{n}-1; or
1440 an explicit index range specifier in the form @code{(LOWER UPPER)},
1441 where both @var{lower} and @var{upper} are integers, possibly less than
1442 zero, and possibly the same number (however, @var{lower} cannot be
1443 greater than @var{upper}).
1446 @deffn {Scheme Procedure} list->array dimspec list
1447 Equivalent to @code{(list->typed-array #t @var{dimspec}
1451 @deffn {Scheme Procedure} list->typed-array type dimspec list
1452 @deffnx {C Function} scm_list_to_typed_array (type, dimspec, list)
1453 Return an array of the type indicated by @var{type} with elements the
1454 same as those of @var{list}.
1456 The argument @var{dimspec} determines the number of dimensions of the
1457 array and their lower bounds. When @var{dimspec} is an exact integer,
1458 it gives the number of dimensions directly and all lower bounds are
1459 zero. When it is a list of exact integers, then each element is the
1460 lower index bound of a dimension, and there will be as many dimensions
1461 as elements in the list.
1464 @deffn {Scheme Procedure} array-type array
1465 Return the type of @var{array}. This is the `vectag' used for
1466 printing @var{array} (or @code{#t} for ordinary arrays) and can be
1467 used with @code{make-typed-array} to create an array of the same kind
1471 @deffn {Scheme Procedure} array-ref array idx @dots{}
1472 Return the element at @code{(idx @dots{})} in @var{array}.
1475 (define a (make-array 999 '(1 2) '(3 4)))
1476 (array-ref a 2 4) @result{} 999
1480 @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
1481 @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
1482 Return @code{#t} if the given index would be acceptable to
1486 (define a (make-array #f '(1 2) '(3 4)))
1487 (array-in-bounds? a 2 3) @result{} #t
1488 (array-in-bounds? a 0 0) @result{} #f
1492 @deffn {Scheme Procedure} array-set! array obj idx @dots{}
1493 @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
1494 Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
1495 The return value is unspecified.
1498 (define a (make-array #f '(0 1) '(0 1)))
1499 (array-set! a #t 1 1)
1500 a @result{} #2((#f #f) (#f #t))
1504 @deffn {Scheme Procedure} array-shape array
1505 @deffnx {Scheme Procedure} array-dimensions array
1506 @deffnx {C Function} scm_array_dimensions (array)
1507 Return a list of the bounds for each dimension of @var{array}.
1509 @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
1510 dimension. @code{array-dimensions} instead returns just
1511 @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
1512 suitable as input to @code{make-array}.
1517 (define a (make-array 'foo '(-1 3) 5))
1518 (array-shape a) @result{} ((-1 3) (0 4))
1519 (array-dimensions a) @result{} ((-1 3) 5)
1523 @deffn {Scheme Procedure} array-rank array
1524 @deffnx {C Function} scm_array_rank (array)
1525 Return the rank of @var{array}.
1528 @deftypefn {C Function} size_t scm_c_array_rank (SCM array)
1529 Return the rank of @var{array} as a @code{size_t}.
1532 @deffn {Scheme Procedure} array->list array
1533 @deffnx {C Function} scm_array_to_list (array)
1534 Return a list consisting of all the elements, in order, of
1538 @c FIXME: Describe how the order affects the copying (it matters for
1539 @c shared arrays with the same underlying root vector, presumably).
1541 @deffn {Scheme Procedure} array-copy! src dst
1542 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1543 @deffnx {C Function} scm_array_copy_x (src, dst)
1544 Copy every element from vector or array @var{src} to the corresponding
1545 element of @var{dst}. @var{dst} must have the same rank as @var{src},
1546 and be at least as large in each dimension. The return value is
1550 @deffn {Scheme Procedure} array-fill! array fill
1551 @deffnx {C Function} scm_array_fill_x (array, fill)
1552 Store @var{fill} in every element of @var{array}. The value returned
1556 @c begin (texi-doc-string "guile" "array-equal?")
1557 @deffn {Scheme Procedure} array-equal? array @dots{}
1558 Return @code{#t} if all arguments are arrays with the same shape, the
1559 same type, and have corresponding elements which are either
1560 @code{equal?} or @code{array-equal?}. This function differs from
1561 @code{equal?} (@pxref{Equality}) in that all arguments must be arrays.
1564 @c FIXME: array-map! accepts no source arrays at all, and in that
1565 @c case makes calls "(proc)". Is that meant to be a documented
1568 @c FIXME: array-for-each doesn't say what happens if the sources have
1569 @c different index ranges. The code currently iterates over the
1570 @c indices of the first and expects the others to cover those. That
1571 @c at least vaguely matches array-map!, but is it meant to be a
1572 @c documented feature?
1574 @deffn {Scheme Procedure} array-map! dst proc src @dots{}
1575 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1576 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1577 Set each element of the @var{dst} array to values obtained from calls
1578 to @var{proc}. The value returned is unspecified.
1580 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1581 where each @var{elem} is from the corresponding @var{src} array, at
1582 the @var{dst} index. @code{array-map-in-order!} makes the calls in
1583 row-major order, @code{array-map!} makes them in an unspecified order.
1585 The @var{src} arrays must have the same number of dimensions as
1586 @var{dst}, and must have a range for each dimension which covers the
1587 range in @var{dst}. This ensures all @var{dst} indices are valid in
1591 @deffn {Scheme Procedure} array-for-each proc src1 src2 @dots{}
1592 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1593 Apply @var{proc} to each tuple of elements of @var{src1} @var{src2}
1594 @dots{}, in row-major order. The value returned is unspecified.
1597 @deffn {Scheme Procedure} array-index-map! dst proc
1598 @deffnx {C Function} scm_array_index_map_x (dst, proc)
1599 Set each element of the @var{dst} array to values returned by calls to
1600 @var{proc}. The value returned is unspecified.
1602 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1603 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
1604 each dimension. The order in which the calls are made is unspecified.
1606 For example, to create a @m{4\times4, 4x4} matrix representing a
1610 \advance\leftskip by 2\lispnarrowing {
1628 (define a (make-array #f 4 4))
1629 (array-index-map! a (lambda (i j)
1630 (modulo (+ i j) 4)))
1634 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
1635 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
1636 Attempt to read all elements of array @var{ra}, in lexicographic order, as
1637 binary objects from @var{port_or_fd}.
1638 If an end of file is encountered,
1639 the objects up to that point are put into @var{ra}
1640 (starting at the beginning) and the remainder of the array is
1643 The optional arguments @var{start} and @var{end} allow
1644 a specified region of a vector (or linearized array) to be read,
1645 leaving the remainder of the vector unchanged.
1647 @code{uniform-array-read!} returns the number of objects read.
1648 @var{port_or_fd} may be omitted, in which case it defaults to the value
1649 returned by @code{(current-input-port)}.
1652 @deffn {Scheme Procedure} uniform-array-write ra [port_or_fd [start [end]]]
1653 @deffnx {C Function} scm_uniform_array_write (ra, port_or_fd, start, end)
1654 Writes all elements of @var{ra} as binary objects to
1657 The optional arguments @var{start}
1659 a specified region of a vector (or linearized array) to be written.
1661 The number of objects actually written is returned.
1662 @var{port_or_fd} may be
1663 omitted, in which case it defaults to the value returned by
1664 @code{(current-output-port)}.
1668 @subsubsection Shared Arrays
1670 @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
1671 @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
1672 Return a new array which shares the storage of @var{oldarray}.
1673 Changes made through either affect the same underlying storage. The
1674 @var{bound} @dots{} arguments are the shape of the new array, the same
1675 as @code{make-array} (@pxref{Array Procedures}).
1677 @var{mapfunc} translates coordinates from the new array to the
1678 @var{oldarray}. It's called as @code{(@var{mapfunc} newidx1 @dots{})}
1679 with one parameter for each dimension of the new array, and should
1680 return a list of indices for @var{oldarray}, one for each dimension of
1683 @var{mapfunc} must be affine linear, meaning that each @var{oldarray}
1684 index must be formed by adding integer multiples (possibly negative)
1685 of some or all of @var{newidx1} etc, plus a possible integer offset.
1686 The multiples and offset must be the same in each call.
1689 One good use for a shared array is to restrict the range of some
1690 dimensions, so as to apply say @code{array-for-each} or
1691 @code{array-fill!} to only part of an array. The plain @code{list}
1692 function can be used for @var{mapfunc} in this case, making no changes
1693 to the index values. For example,
1696 (make-shared-array #2((a b c) (d e f) (g h i)) list 3 2)
1697 @result{} #2((a b) (d e) (g h))
1700 The new array can have fewer dimensions than @var{oldarray}, for
1701 example to take a column from an array.
1704 (make-shared-array #2((a b c) (d e f) (g h i))
1705 (lambda (i) (list i 2))
1710 A diagonal can be taken by using the single new array index for both
1711 row and column in the old array. For example,
1714 (make-shared-array #2((a b c) (d e f) (g h i))
1715 (lambda (i) (list i i))
1720 Dimensions can be increased by for instance considering portions of a
1721 one dimensional array as rows in a two dimensional array.
1722 (@code{array-contents} below can do the opposite, flattening an
1726 (make-shared-array #1(a b c d e f g h i j k l)
1727 (lambda (i j) (list (+ (* i 3) j)))
1729 @result{} #2((a b c) (d e f) (g h i) (j k l))
1732 By negating an index the order that elements appear can be reversed.
1733 The following just reverses the column order,
1736 (make-shared-array #2((a b c) (d e f) (g h i))
1737 (lambda (i j) (list i (- 2 j)))
1739 @result{} #2((c b a) (f e d) (i h g))
1742 A fixed offset on indexes allows for instance a change from a 0 based
1746 (define x #2((a b c) (d e f) (g h i)))
1747 (define y (make-shared-array x
1748 (lambda (i j) (list (1- i) (1- j)))
1750 (array-ref x 0 0) @result{} a
1751 (array-ref y 1 1) @result{} a
1754 A multiple on an index allows every Nth element of an array to be
1755 taken. The following is every third element,
1758 (make-shared-array #1(a b c d e f g h i j k l)
1759 (lambda (i) (list (* i 3)))
1761 @result{} #1(a d g j)
1764 The above examples can be combined to make weird and wonderful
1765 selections from an array, but it's important to note that because
1766 @var{mapfunc} must be affine linear, arbitrary permutations are not
1769 In the current implementation, @var{mapfunc} is not called for every
1770 access to the new array but only on some sample points to establish a
1771 base and stride for new array indices in @var{oldarray} data. A few
1772 sample points are enough because @var{mapfunc} is linear.
1775 @deffn {Scheme Procedure} shared-array-increments array
1776 @deffnx {C Function} scm_shared_array_increments (array)
1777 For each dimension, return the distance between elements in the root vector.
1780 @deffn {Scheme Procedure} shared-array-offset array
1781 @deffnx {C Function} scm_shared_array_offset (array)
1782 Return the root vector index of the first element in the array.
1785 @deffn {Scheme Procedure} shared-array-root array
1786 @deffnx {C Function} scm_shared_array_root (array)
1787 Return the root vector of a shared array.
1790 @deffn {Scheme Procedure} array-contents array [strict]
1791 @deffnx {C Function} scm_array_contents (array, strict)
1792 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1793 without changing their order (last subscript changing fastest), then
1794 @code{array-contents} returns that shared array, otherwise it returns
1795 @code{#f}. All arrays made by @code{make-array} and
1796 @code{make-typed-array} may be unrolled, some arrays made by
1797 @code{make-shared-array} may not be.
1799 If the optional argument @var{strict} is provided, a shared array will
1800 be returned only if its elements are stored internally contiguous in
1804 @deffn {Scheme Procedure} transpose-array array dim1 dim2 @dots{}
1805 @deffnx {C Function} scm_transpose_array (array, dimlist)
1806 Return an array sharing contents with @var{array}, but with
1807 dimensions arranged in a different order. There must be one
1808 @var{dim} argument for each dimension of @var{array}.
1809 @var{dim1}, @var{dim2}, @dots{} should be integers between 0
1810 and the rank of the array to be returned. Each integer in that
1811 range must appear at least once in the argument list.
1813 The values of @var{dim1}, @var{dim2}, @dots{} correspond to
1814 dimensions in the array to be returned, and their positions in the
1815 argument list to dimensions of @var{array}. Several @var{dim}s
1816 may have the same value, in which case the returned array will
1817 have smaller rank than @var{array}.
1820 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1821 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1822 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1823 #2((a 4) (b 5) (c 6))
1827 @node Accessing Arrays from C
1828 @subsubsection Accessing Arrays from C
1830 For interworking with external C code, Guile provides an API to allow C
1831 code to access the elements of a Scheme array. In particular, for
1832 uniform numeric arrays, the API exposes the underlying uniform data as a
1833 C array of numbers of the relevant type.
1835 While pointers to the elements of an array are in use, the array itself
1836 must be protected so that the pointer remains valid. Such a protected
1837 array is said to be @dfn{reserved}. A reserved array can be read but
1838 modifications to it that would cause the pointer to its elements to
1839 become invalid are prevented. When you attempt such a modification, an
1842 (This is similar to locking the array while it is in use, but without
1843 the danger of a deadlock. In a multi-threaded program, you will need
1844 additional synchronization to avoid modifying reserved arrays.)
1846 You must take care to always unreserve an array after reserving it,
1847 even in the presence of non-local exits. If a non-local exit can
1848 happen between these two calls, you should install a dynwind context
1849 that releases the array when it is left (@pxref{Dynamic Wind}).
1851 In addition, array reserving and unreserving must be properly
1852 paired. For instance, when reserving two or more arrays in a certain
1853 order, you need to unreserve them in the opposite order.
1855 Once you have reserved an array and have retrieved the pointer to its
1856 elements, you must figure out the layout of the elements in memory.
1857 Guile allows slices to be taken out of arrays without actually making a
1858 copy, such as making an alias for the diagonal of a matrix that can be
1859 treated as a vector. Arrays that result from such an operation are not
1860 stored contiguously in memory and when working with their elements
1861 directly, you need to take this into account.
1863 The layout of array elements in memory can be defined via a
1864 @emph{mapping function} that computes a scalar position from a vector of
1865 indices. The scalar position then is the offset of the element with the
1866 given indices from the start of the storage block of the array.
1868 In Guile, this mapping function is restricted to be @dfn{affine}: all
1869 mapping functions of Guile arrays can be written as @code{p = b +
1870 c[0]*i[0] + c[1]*i[1] + ... + c[n-1]*i[n-1]} where @code{i[k]} is the
1871 @nicode{k}th index and @code{n} is the rank of the array. For
1872 example, a matrix of size 3x3 would have @code{b == 0}, @code{c[0] ==
1873 3} and @code{c[1] == 1}. When you transpose this matrix (with
1874 @code{transpose-array}, say), you will get an array whose mapping
1875 function has @code{b == 0}, @code{c[0] == 1} and @code{c[1] == 3}.
1877 The function @code{scm_array_handle_dims} gives you (indirect) access to
1878 the coefficients @code{c[k]}.
1881 Note that there are no functions for accessing the elements of a
1882 character array yet. Once the string implementation of Guile has been
1883 changed to use Unicode, we will provide them.
1885 @deftp {C Type} scm_t_array_handle
1886 This is a structure type that holds all information necessary to manage
1887 the reservation of arrays as explained above. Structures of this type
1888 must be allocated on the stack and must only be accessed by the
1889 functions listed below.
1892 @deftypefn {C Function} void scm_array_get_handle (SCM array, scm_t_array_handle *handle)
1893 Reserve @var{array}, which must be an array, and prepare @var{handle} to
1894 be used with the functions below. You must eventually call
1895 @code{scm_array_handle_release} on @var{handle}, and do this in a
1896 properly nested fashion, as explained above. The structure pointed to
1897 by @var{handle} does not need to be initialized before calling this
1901 @deftypefn {C Function} void scm_array_handle_release (scm_t_array_handle *handle)
1902 End the array reservation represented by @var{handle}. After a call to
1903 this function, @var{handle} might be used for another reservation.
1906 @deftypefn {C Function} size_t scm_array_handle_rank (scm_t_array_handle *handle)
1907 Return the rank of the array represented by @var{handle}.
1910 @deftp {C Type} scm_t_array_dim
1911 This structure type holds information about the layout of one dimension
1912 of an array. It includes the following fields:
1917 The lower and upper bounds (both inclusive) of the permissible index
1918 range for the given dimension. Both values can be negative, but
1919 @var{lbnd} is always less than or equal to @var{ubnd}.
1922 The distance from one element of this dimension to the next. Note, too,
1923 that this can be negative.
1927 @deftypefn {C Function} {const scm_t_array_dim *} scm_array_handle_dims (scm_t_array_handle *handle)
1928 Return a pointer to a C vector of information about the dimensions of
1929 the array represented by @var{handle}. This pointer is valid as long as
1930 the array remains reserved. As explained above, the
1931 @code{scm_t_array_dim} structures returned by this function can be used
1932 calculate the position of an element in the storage block of the array
1935 This position can then be used as an index into the C array pointer
1936 returned by the various @code{scm_array_handle_<foo>_elements}
1937 functions, or with @code{scm_array_handle_ref} and
1938 @code{scm_array_handle_set}.
1940 Here is how one can compute the position @var{pos} of an element given
1941 its indices in the vector @var{indices}:
1944 ssize_t indices[RANK];
1945 scm_t_array_dim *dims;
1950 for (i = 0; i < RANK; i++)
1952 if (indices[i] < dims[i].lbnd || indices[i] > dims[i].ubnd)
1954 pos += (indices[i] - dims[i].lbnd) * dims[i].inc;
1959 @deftypefn {C Function} ssize_t scm_array_handle_pos (scm_t_array_handle *handle, SCM indices)
1960 Compute the position corresponding to @var{indices}, a list of
1961 indices. The position is computed as described above for
1962 @code{scm_array_handle_dims}. The number of the indices and their
1963 range is checked and an appropriate error is signalled for invalid
1967 @deftypefn {C Function} SCM scm_array_handle_ref (scm_t_array_handle *handle, ssize_t pos)
1968 Return the element at position @var{pos} in the storage block of the
1969 array represented by @var{handle}. Any kind of array is acceptable. No
1970 range checking is done on @var{pos}.
1973 @deftypefn {C Function} void scm_array_handle_set (scm_t_array_handle *handle, ssize_t pos, SCM val)
1974 Set the element at position @var{pos} in the storage block of the array
1975 represented by @var{handle} to @var{val}. Any kind of array is
1976 acceptable. No range checking is done on @var{pos}. An error is
1977 signalled when the array can not store @var{val}.
1980 @deftypefn {C Function} {const SCM *} scm_array_handle_elements (scm_t_array_handle *handle)
1981 Return a pointer to the elements of a ordinary array of general Scheme
1982 values (i.e., a non-uniform array) for reading. This pointer is valid
1983 as long as the array remains reserved.
1986 @deftypefn {C Function} {SCM *} scm_array_handle_writable_elements (scm_t_array_handle *handle)
1987 Like @code{scm_array_handle_elements}, but the pointer is good for
1988 reading and writing.
1991 @deftypefn {C Function} {const void *} scm_array_handle_uniform_elements (scm_t_array_handle *handle)
1992 Return a pointer to the elements of a uniform numeric array for reading.
1993 This pointer is valid as long as the array remains reserved. The size
1994 of each element is given by @code{scm_array_handle_uniform_element_size}.
1997 @deftypefn {C Function} {void *} scm_array_handle_uniform_writable_elements (scm_t_array_handle *handle)
1998 Like @code{scm_array_handle_uniform_elements}, but the pointer is good
1999 reading and writing.
2002 @deftypefn {C Function} size_t scm_array_handle_uniform_element_size (scm_t_array_handle *handle)
2003 Return the size of one element of the uniform numeric array represented
2007 @deftypefn {C Function} {const scm_t_uint8 *} scm_array_handle_u8_elements (scm_t_array_handle *handle)
2008 @deftypefnx {C Function} {const scm_t_int8 *} scm_array_handle_s8_elements (scm_t_array_handle *handle)
2009 @deftypefnx {C Function} {const scm_t_uint16 *} scm_array_handle_u16_elements (scm_t_array_handle *handle)
2010 @deftypefnx {C Function} {const scm_t_int16 *} scm_array_handle_s16_elements (scm_t_array_handle *handle)
2011 @deftypefnx {C Function} {const scm_t_uint32 *} scm_array_handle_u32_elements (scm_t_array_handle *handle)
2012 @deftypefnx {C Function} {const scm_t_int32 *} scm_array_handle_s32_elements (scm_t_array_handle *handle)
2013 @deftypefnx {C Function} {const scm_t_uint64 *} scm_array_handle_u64_elements (scm_t_array_handle *handle)
2014 @deftypefnx {C Function} {const scm_t_int64 *} scm_array_handle_s64_elements (scm_t_array_handle *handle)
2015 @deftypefnx {C Function} {const float *} scm_array_handle_f32_elements (scm_t_array_handle *handle)
2016 @deftypefnx {C Function} {const double *} scm_array_handle_f64_elements (scm_t_array_handle *handle)
2017 @deftypefnx {C Function} {const float *} scm_array_handle_c32_elements (scm_t_array_handle *handle)
2018 @deftypefnx {C Function} {const double *} scm_array_handle_c64_elements (scm_t_array_handle *handle)
2019 Return a pointer to the elements of a uniform numeric array of the
2020 indicated kind for reading. This pointer is valid as long as the array
2023 The pointers for @code{c32} and @code{c64} uniform numeric arrays point
2024 to pairs of floating point numbers. The even index holds the real part,
2025 the odd index the imaginary part of the complex number.
2028 @deftypefn {C Function} {scm_t_uint8 *} scm_array_handle_u8_writable_elements (scm_t_array_handle *handle)
2029 @deftypefnx {C Function} {scm_t_int8 *} scm_array_handle_s8_writable_elements (scm_t_array_handle *handle)
2030 @deftypefnx {C Function} {scm_t_uint16 *} scm_array_handle_u16_writable_elements (scm_t_array_handle *handle)
2031 @deftypefnx {C Function} {scm_t_int16 *} scm_array_handle_s16_writable_elements (scm_t_array_handle *handle)
2032 @deftypefnx {C Function} {scm_t_uint32 *} scm_array_handle_u32_writable_elements (scm_t_array_handle *handle)
2033 @deftypefnx {C Function} {scm_t_int32 *} scm_array_handle_s32_writable_elements (scm_t_array_handle *handle)
2034 @deftypefnx {C Function} {scm_t_uint64 *} scm_array_handle_u64_writable_elements (scm_t_array_handle *handle)
2035 @deftypefnx {C Function} {scm_t_int64 *} scm_array_handle_s64_writable_elements (scm_t_array_handle *handle)
2036 @deftypefnx {C Function} {float *} scm_array_handle_f32_writable_elements (scm_t_array_handle *handle)
2037 @deftypefnx {C Function} {double *} scm_array_handle_f64_writable_elements (scm_t_array_handle *handle)
2038 @deftypefnx {C Function} {float *} scm_array_handle_c32_writable_elements (scm_t_array_handle *handle)
2039 @deftypefnx {C Function} {double *} scm_array_handle_c64_writable_elements (scm_t_array_handle *handle)
2040 Like @code{scm_array_handle_<kind>_elements}, but the pointer is good
2041 for reading and writing.
2044 @deftypefn {C Function} {const scm_t_uint32 *} scm_array_handle_bit_elements (scm_t_array_handle *handle)
2045 Return a pointer to the words that store the bits of the represented
2046 array, which must be a bit array.
2048 Unlike other arrays, bit arrays have an additional offset that must be
2049 figured into index calculations. That offset is returned by
2050 @code{scm_array_handle_bit_elements_offset}.
2052 To find a certain bit you first need to calculate its position as
2053 explained above for @code{scm_array_handle_dims} and then add the
2054 offset. This gives the absolute position of the bit, which is always a
2055 non-negative integer.
2057 Each word of the bit array storage block contains exactly 32 bits, with
2058 the least significant bit in that word having the lowest absolute
2059 position number. The next word contains the next 32 bits.
2061 Thus, the following code can be used to access a bit whose position
2062 according to @code{scm_array_handle_dims} is given in @var{pos}:
2066 scm_t_array_handle handle;
2070 size_t word_pos, mask;
2072 scm_array_get_handle (&bit_array, &handle);
2073 bits = scm_array_handle_bit_elements (&handle);
2076 abs_pos = pos + scm_array_handle_bit_elements_offset (&handle);
2077 word_pos = abs_pos / 32;
2078 mask = 1L << (abs_pos % 32);
2080 if (bits[word_pos] & mask)
2083 scm_array_handle_release (&handle);
2088 @deftypefn {C Function} {scm_t_uint32 *} scm_array_handle_bit_writable_elements (scm_t_array_handle *handle)
2089 Like @code{scm_array_handle_bit_elements} but the pointer is good for
2090 reading and writing. You must take care not to modify bits outside of
2091 the allowed index range of the array, even for contiguous arrays.
2099 The @code{(ice-9 vlist)} module provides an implementation of the @dfn{VList}
2100 data structure designed by Phil Bagwell in 2002. VLists are immutable lists,
2101 which can contain any Scheme object. They improve on standard Scheme linked
2102 lists in several areas:
2106 Random access has typically constant-time complexity.
2109 Computing the length of a VList has time complexity logarithmic in the number of
2113 VLists use less storage space than standard lists.
2116 VList elements are stored in contiguous regions, which improves memory locality
2117 and leads to more efficient use of hardware caches.
2120 The idea behind VLists is to store vlist elements in increasingly large
2121 contiguous blocks (implemented as vectors here). These blocks are linked to one
2122 another using a pointer to the next block and an offset within that block. The
2123 size of these blocks form a geometric series with ratio
2124 @code{block-growth-factor} (2 by default).
2126 The VList structure also serves as the basis for the @dfn{VList-based hash
2127 lists} or ``vhashes'', an immutable dictionary type (@pxref{VHashes}).
2129 However, the current implementation in @code{(ice-9 vlist)} has several
2130 noteworthy shortcomings:
2135 It is @emph{not} thread-safe. Although operations on vlists are all
2136 @dfn{referentially transparent} (i.e., purely functional), adding elements to a
2137 vlist with @code{vlist-cons} mutates part of its internal structure, which makes
2138 it non-thread-safe. This could be fixed, but it would slow down
2142 @code{vlist-cons} always allocates at least as much memory as @code{cons}.
2143 Again, Phil Bagwell describes how to fix it, but that would require tuning the
2144 garbage collector in a way that may not be generally beneficial.
2147 @code{vlist-cons} is a Scheme procedure compiled to bytecode, and it does not
2148 compete with the straightforward C implementation of @code{cons}, and with the
2149 fact that the VM has a special @code{cons} instruction.
2153 We hope to address these in the future.
2155 The programming interface exported by @code{(ice-9 vlist)} is defined below.
2156 Most of it is the same as SRFI-1 with an added @code{vlist-} prefix to function
2159 @deffn {Scheme Procedure} vlist? obj
2160 Return true if @var{obj} is a VList.
2163 @defvr {Scheme Variable} vlist-null
2164 The empty VList. Note that it's possible to create an empty VList not
2165 @code{eq?} to @code{vlist-null}; thus, callers should always use
2166 @code{vlist-null?} when testing whether a VList is empty.
2169 @deffn {Scheme Procedure} vlist-null? vlist
2170 Return true if @var{vlist} is empty.
2173 @deffn {Scheme Procedure} vlist-cons item vlist
2174 Return a new vlist with @var{item} as its head and @var{vlist} as its tail.
2177 @deffn {Scheme Procedure} vlist-head vlist
2178 Return the head of @var{vlist}.
2181 @deffn {Scheme Procedure} vlist-tail vlist
2182 Return the tail of @var{vlist}.
2185 @defvr {Scheme Variable} block-growth-factor
2186 A fluid that defines the growth factor of VList blocks, 2 by default.
2189 The functions below provide the usual set of higher-level list operations.
2191 @deffn {Scheme Procedure} vlist-fold proc init vlist
2192 @deffnx {Scheme Procedure} vlist-fold-right proc init vlist
2193 Fold over @var{vlist}, calling @var{proc} for each element, as for SRFI-1
2194 @code{fold} and @code{fold-right} (@pxref{SRFI-1, @code{fold}}).
2197 @deffn {Scheme Procedure} vlist-ref vlist index
2198 Return the element at index @var{index} in @var{vlist}. This is typically a
2199 constant-time operation.
2202 @deffn {Scheme Procedure} vlist-length vlist
2203 Return the length of @var{vlist}. This is typically logarithmic in the number
2204 of elements in @var{vlist}.
2207 @deffn {Scheme Procedure} vlist-reverse vlist
2208 Return a new @var{vlist} whose content are those of @var{vlist} in reverse
2212 @deffn {Scheme Procedure} vlist-map proc vlist
2213 Map @var{proc} over the elements of @var{vlist} and return a new vlist.
2216 @deffn {Scheme Procedure} vlist-for-each proc vlist
2217 Call @var{proc} on each element of @var{vlist}. The result is unspecified.
2220 @deffn {Scheme Procedure} vlist-drop vlist count
2221 Return a new vlist that does not contain the @var{count} first elements of
2222 @var{vlist}. This is typically a constant-time operation.
2225 @deffn {Scheme Procedure} vlist-take vlist count
2226 Return a new vlist that contains only the @var{count} first elements of
2230 @deffn {Scheme Procedure} vlist-filter pred vlist
2231 Return a new vlist containing all the elements from @var{vlist} that satisfy
2235 @deffn {Scheme Procedure} vlist-delete x vlist [equal?]
2236 Return a new vlist corresponding to @var{vlist} without the elements
2237 @var{equal?} to @var{x}.
2240 @deffn {Scheme Procedure} vlist-unfold p f g seed [tail-gen]
2241 @deffnx {Scheme Procedure} vlist-unfold-right p f g seed [tail]
2242 Return a new vlist, as for SRFI-1 @code{unfold} and @code{unfold-right}
2243 (@pxref{SRFI-1, @code{unfold}}).
2246 @deffn {Scheme Procedure} vlist-append vlist @dots{}
2247 Append the given vlists and return the resulting vlist.
2250 @deffn {Scheme Procedure} list->vlist lst
2251 Return a new vlist whose contents correspond to @var{lst}.
2254 @deffn {Scheme Procedure} vlist->list vlist
2255 Return a new list whose contents match those of @var{vlist}.
2258 @node Record Overview
2259 @subsection Record Overview
2264 @dfn{Records}, also called @dfn{structures}, are Scheme's primary
2265 mechanism to define new disjoint types. A @dfn{record type} defines a
2266 list of @dfn{fields} that instances of the type consist of. This is like
2269 Historically, Guile has offered several different ways to define record
2270 types and to create records, offering different features, and making
2271 different trade-offs. Over the years, each ``standard'' has also come
2272 with its own new record interface, leading to a maze of record APIs.
2274 At the highest level is SRFI-9, a high-level record interface
2275 implemented by most Scheme implementations (@pxref{SRFI-9}). It defines
2276 a simple and efficient syntactic abstraction of record types and their
2277 associated type predicate, fields, and field accessors. SRFI-9 is
2278 suitable for most uses, and this is the recommended way to create record
2279 types in Guile. Similar high-level record APIs include SRFI-35
2280 (@pxref{SRFI-35}) and R6RS records (@pxref{rnrs records syntactic}).
2282 Then comes Guile's historical ``records'' API (@pxref{Records}). Record
2283 types defined this way are first-class objects. Introspection
2284 facilities are available, allowing users to query the list of fields or
2285 the value of a specific field at run-time, without prior knowledge of
2288 Finally, the common denominator of these interfaces is Guile's
2289 @dfn{structure} API (@pxref{Structures}). Guile's structures are the
2290 low-level building block for all other record APIs. Application writers
2291 will normally not need to use it.
2293 Records created with these APIs may all be pattern-matched using Guile's
2294 standard pattern matcher (@pxref{Pattern Matching}).
2297 @node SRFI-9 Records
2298 @subsection SRFI-9 Records
2303 SRFI-9 standardizes a syntax for defining new record types and creating
2304 predicate, constructor, and field getter and setter functions. In Guile
2305 this is the recommended option to create new record types (@pxref{Record
2306 Overview}). It can be used with:
2309 (use-modules (srfi srfi-9))
2312 @deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
2314 Create a new record type, and make various @code{define}s for using
2315 it. This syntax can only occur at the top-level, not nested within
2318 @var{type} is bound to the record type, which is as per the return
2319 from the core @code{make-record-type}. @var{type} also provides the
2320 name for the record, as per @code{record-type-name}.
2322 @var{constructor} is bound to a function to be called as
2323 @code{(@var{constructor} fieldval @dots{})} to create a new record of
2324 this type. The arguments are initial values for the fields, one
2325 argument for each field, in the order they appear in the
2326 @code{define-record-type} form.
2328 The @var{fieldname}s provide the names for the record fields, as per
2329 the core @code{record-type-fields} etc, and are referred to in the
2330 subsequent accessor/modifier forms.
2332 @var{predicate} is bound to a function to be called as
2333 @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
2334 according to whether @var{obj} is a record of this type.
2336 Each @var{accessor} is bound to a function to be called
2337 @code{(@var{accessor} record)} to retrieve the respective field from a
2338 @var{record}. Similarly each @var{modifier} is bound to a function to
2339 be called @code{(@var{modifier} record val)} to set the respective
2340 field in a @var{record}.
2344 An example will illustrate typical usage,
2347 (define-record-type employee-type
2348 (make-employee name age salary)
2350 (name get-employee-name)
2351 (age get-employee-age set-employee-age)
2352 (salary get-employee-salary set-employee-salary))
2355 This creates a new employee data type, with name, age and salary
2356 fields. Accessor functions are created for each field, but no
2357 modifier function for the name (the intention in this example being
2358 that it's established only when an employee object is created). These
2359 can all then be used as for example,
2362 employee-type @result{} #<record-type employee-type>
2364 (define fred (make-employee "Fred" 45 20000.00))
2366 (employee? fred) @result{} #t
2367 (get-employee-age fred) @result{} 45
2368 (set-employee-salary fred 25000.00) ;; pay rise
2371 The functions created by @code{define-record-type} are ordinary
2372 top-level @code{define}s. They can be redefined or @code{set!} as
2373 desired, exported from a module, etc.
2375 @unnumberedsubsubsec Non-toplevel Record Definitions
2377 The SRFI-9 specification explicitly disallows record definitions in a
2378 non-toplevel context, such as inside @code{lambda} body or inside a
2379 @var{let} block. However, Guile's implementation does not enforce that
2382 @unnumberedsubsubsec Custom Printers
2384 You may use @code{set-record-type-printer!} to customize the default printing
2385 behavior of records. This is a Guile extension and is not part of SRFI-9. It
2386 is located in the @nicode{(srfi srfi-9 gnu)} module.
2388 @deffn {Scheme Syntax} set-record-type-printer! name proc
2389 Where @var{type} corresponds to the first argument of @code{define-record-type},
2390 and @var{proc} is a procedure accepting two arguments, the record to print, and
2395 This example prints the employee's name in brackets, for instance @code{[Fred]}.
2398 (set-record-type-printer! employee-type
2399 (lambda (record port)
2400 (write-char #\[ port)
2401 (display (get-employee-name record) port)
2402 (write-char #\] port)))
2405 @unnumberedsubsubsec Functional ``Setters''
2407 @cindex functional setters
2409 When writing code in a functional style, it is desirable to never alter
2410 the contents of records. For such code, a simple way to return new
2411 record instances based on existing ones is highly desirable.
2413 The @code{(srfi srfi-9 gnu)} module extends SRFI-9 with facilities to
2414 return new record instances based on existing ones, only with one or
2415 more field values changed---@dfn{functional setters}. First, the
2416 @code{define-immutable-record-type} works like
2417 @code{define-record-type}, except that fields are immutable and setters
2418 are defined as functional setters.
2420 @deffn {Scheme Syntax} define-immutable-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
2421 Define @var{type} as a new record type, like @code{define-record-type}.
2422 However, the record type is made @emph{immutable} (records may not be
2423 mutated, even with @code{struct-set!}), and any @var{modifier} is
2424 defined to be a functional setter---a procedure that returns a new
2425 record instance with the specified field changed, and leaves the
2426 original unchanged (see example below.)
2430 In addition, the generic @code{set-field} and @code{set-fields} macros
2431 may be applied to any SRFI-9 record.
2433 @deffn {Scheme Syntax} set-field record (field sub-fields ...) value
2434 Return a new record of @var{record}'s type whose fields are equal to
2435 the corresponding fields of @var{record} except for the one specified by
2438 @var{field} must be the name of the getter corresponding to the field of
2439 @var{record} being ``set''. Subsequent @var{sub-fields} must be record
2440 getters designating sub-fields within that field value to be set (see
2444 @deffn {Scheme Syntax} set-fields record ((field sub-fields ...) value) ...
2445 Like @code{set-field}, but can be used to set more than one field at a
2446 time. This expands to code that is more efficient than a series of
2447 single @code{set-field} calls.
2450 To illustrate the use of functional setters, let's assume these two
2451 record type definitions:
2454 (define-record-type <address>
2455 (address street city country)
2457 (street address-street)
2459 (country address-country))
2461 (define-immutable-record-type <person>
2462 (person age email address)
2464 (age person-age set-person-age)
2465 (email person-email set-person-email)
2466 (address person-address set-person-address))
2470 First, note that the @code{<person>} record type definition introduces
2471 named functional setters. These may be used like this:
2475 (address "Franklin Street" "Boston" "USA"))
2478 (person 30 "rms@@gnu.org" fsf-address))
2480 (and (equal? (set-person-age rms 60)
2481 (person 60 "rms@@gnu.org" fsf-address))
2482 (= (person-age rms) 30))
2487 Here, the original @code{<person>} record, to which @var{rms} is bound,
2490 Now, suppose we want to change both the street and age of @var{rms}.
2491 This can be achieved using @code{set-fields}:
2496 ((person-address address-street) "Temple Place"))
2497 @result{} #<<person> age: 60 email: "rms@@gnu.org"
2498 address: #<<address> street: "Temple Place" city: "Boston" country: "USA">>
2502 Notice how the above changed two fields of @var{rms}, including the
2503 @code{street} field of its @code{address} field, in a concise way. Also
2504 note that @code{set-fields} works equally well for types defined with
2505 just @code{define-record-type}.
2510 A @dfn{record type} is a first class object representing a user-defined
2511 data type. A @dfn{record} is an instance of a record type.
2513 Note that in many ways, this interface is too low-level for every-day
2514 use. Most uses of records are better served by SRFI-9 records.
2517 @deffn {Scheme Procedure} record? obj
2518 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
2521 Note that @code{record?} may be true of any Scheme value; there is no
2522 promise that records are disjoint with other Scheme types.
2525 @deffn {Scheme Procedure} make-record-type type-name field-names [print]
2526 Create and return a new @dfn{record-type descriptor}.
2528 @var{type-name} is a string naming the type. Currently it's only used
2529 in the printed representation of records, and in diagnostics.
2530 @var{field-names} is a list of symbols naming the fields of a record
2531 of the type. Duplicates are not allowed among these symbols.
2534 (make-record-type "employee" '(name age salary))
2537 The optional @var{print} argument is a function used by
2538 @code{display}, @code{write}, etc, for printing a record of the new
2539 type. It's called as @code{(@var{print} record port)} and should look
2540 at @var{record} and write to @var{port}.
2543 @deffn {Scheme Procedure} record-constructor rtd [field-names]
2544 Return a procedure for constructing new members of the type represented
2545 by @var{rtd}. The returned procedure accepts exactly as many arguments
2546 as there are symbols in the given list, @var{field-names}; these are
2547 used, in order, as the initial values of those fields in a new record,
2548 which is returned by the constructor procedure. The values of any
2549 fields not named in that list are unspecified. The @var{field-names}
2550 argument defaults to the list of field names in the call to
2551 @code{make-record-type} that created the type represented by @var{rtd};
2552 if the @var{field-names} argument is provided, it is an error if it
2553 contains any duplicates or any symbols not in the default list.
2556 @deffn {Scheme Procedure} record-predicate rtd
2557 Return a procedure for testing membership in the type represented by
2558 @var{rtd}. The returned procedure accepts exactly one argument and
2559 returns a true value if the argument is a member of the indicated record
2560 type; it returns a false value otherwise.
2563 @deffn {Scheme Procedure} record-accessor rtd field-name
2564 Return a procedure for reading the value of a particular field of a
2565 member of the type represented by @var{rtd}. The returned procedure
2566 accepts exactly one argument which must be a record of the appropriate
2567 type; it returns the current value of the field named by the symbol
2568 @var{field-name} in that record. The symbol @var{field-name} must be a
2569 member of the list of field-names in the call to @code{make-record-type}
2570 that created the type represented by @var{rtd}.
2573 @deffn {Scheme Procedure} record-modifier rtd field-name
2574 Return a procedure for writing the value of a particular field of a
2575 member of the type represented by @var{rtd}. The returned procedure
2576 accepts exactly two arguments: first, a record of the appropriate type,
2577 and second, an arbitrary Scheme value; it modifies the field named by
2578 the symbol @var{field-name} in that record to contain the given value.
2579 The returned value of the modifier procedure is unspecified. The symbol
2580 @var{field-name} must be a member of the list of field-names in the call
2581 to @code{make-record-type} that created the type represented by
2585 @deffn {Scheme Procedure} record-type-descriptor record
2586 Return a record-type descriptor representing the type of the given
2587 record. That is, for example, if the returned descriptor were passed to
2588 @code{record-predicate}, the resulting predicate would return a true
2589 value when passed the given record. Note that it is not necessarily the
2590 case that the returned descriptor is the one that was passed to
2591 @code{record-constructor} in the call that created the constructor
2592 procedure that created the given record.
2595 @deffn {Scheme Procedure} record-type-name rtd
2596 Return the type-name associated with the type represented by rtd. The
2597 returned value is @code{eqv?} to the @var{type-name} argument given in
2598 the call to @code{make-record-type} that created the type represented by
2602 @deffn {Scheme Procedure} record-type-fields rtd
2603 Return a list of the symbols naming the fields in members of the type
2604 represented by @var{rtd}. The returned value is @code{equal?} to the
2605 field-names argument given in the call to @code{make-record-type} that
2606 created the type represented by @var{rtd}.
2611 @subsection Structures
2614 A @dfn{structure} is a first class data type which holds Scheme values
2615 or C words in fields numbered 0 upwards. A @dfn{vtable} is a structure
2616 that represents a structure type, giving field types and permissions,
2617 and an optional print function for @code{write} etc.
2619 Structures are lower level than records (@pxref{Records}). Usually,
2620 when you need to represent structured data, you just want to use
2621 records. But sometimes you need to implement new kinds of structured
2622 data abstractions, and for that purpose structures are useful. Indeed,
2623 records in Guile are implemented with structures.
2627 * Structure Basics::
2635 @subsubsection Vtables
2637 A vtable is a structure type, specifying its layout, and other
2638 information. A vtable is actually itself a structure, but there's no
2639 need to worry about that initially (@pxref{Vtable Contents}.)
2641 @deffn {Scheme Procedure} make-vtable fields [print]
2642 Create a new vtable.
2644 @var{fields} is a string describing the fields in the structures to be
2645 created. Each field is represented by two characters, a type letter
2646 and a permissions letter, for example @code{"pw"}. The types are as
2651 @code{p} -- a Scheme value. ``p'' stands for ``protected'' meaning
2652 it's protected against garbage collection.
2655 @code{u} -- an arbitrary word of data (an @code{scm_t_bits}). At the
2656 Scheme level it's read and written as an unsigned integer. ``u''
2657 stands for ``uninterpreted'' (it's not treated as a Scheme value), or
2658 ``unprotected'' (it's not marked during GC), or ``unsigned long'' (its
2659 size), or all of these things.
2662 @code{s} -- a self-reference. Such a field holds the @code{SCM} value
2663 of the structure itself (a circular reference). This can be useful in
2664 C code where you might have a pointer to the data array, and want to
2665 get the Scheme @code{SCM} handle for the structure. In Scheme code it
2669 The second letter for each field is a permission code,
2673 @code{w} -- writable, the field can be read and written.
2675 @code{r} -- read-only, the field can be read but not written.
2677 @code{o} -- opaque, the field can be neither read nor written at the
2678 Scheme level. This can be used for fields which should only be used
2682 Here are some examples. @xref{Tail Arrays}, for information on the
2683 legacy tail array facility.
2686 (make-vtable "pw") ;; one writable field
2687 (make-vtable "prpw") ;; one read-only and one writable
2688 (make-vtable "pwuwuw") ;; one scheme and two uninterpreted
2691 The optional @var{print} argument is a function called by
2692 @code{display} and @code{write} (etc) to give a printed representation
2693 of a structure created from this vtable. It's called
2694 @code{(@var{print} struct port)} and should look at @var{struct} and
2695 write to @var{port}. The default print merely gives a form like
2696 @samp{#<struct ADDR:ADDR>} with a pair of machine addresses.
2698 The following print function for example shows the two fields of its
2703 (lambda (struct port)
2704 (format port "#<~a and ~a>"
2705 (struct-ref struct 0)
2706 (struct-ref struct 1))))
2711 @node Structure Basics
2712 @subsubsection Structure Basics
2714 This section describes the basic procedures for working with
2715 structures. @code{make-struct} creates a structure, and
2716 @code{struct-ref} and @code{struct-set!} access its fields.
2718 @deffn {Scheme Procedure} make-struct vtable tail-size init @dots{}
2719 @deffnx {Scheme Procedure} make-struct/no-tail vtable init @dots{}
2720 Create a new structure, with layout per the given @var{vtable}
2723 The optional @var{init}@dots{} arguments are initial values for the
2724 fields of the structure. This is the only way to
2725 put values in read-only fields. If there are fewer @var{init}
2726 arguments than fields then the defaults are @code{#f} for a Scheme
2727 field (type @code{p}) or 0 for an uninterpreted field (type @code{u}).
2729 Structures also have the ability to allocate a variable number of
2730 additional cells at the end, at their tails. However, this legacy
2731 @dfn{tail array} facilty is confusing and inefficient, and so we do not
2732 recommend it. @xref{Tail Arrays}, for more on the legacy tail array
2735 Type @code{s} self-reference fields, permission @code{o} opaque
2736 fields, and the count field of a tail array are all ignored for the
2737 @var{init} arguments, ie.@: an argument is not consumed by such a
2738 field. An @code{s} is always set to the structure itself, an @code{o}
2739 is always set to @code{#f} or 0 (with the intention that C code will
2740 do something to it later), and the tail count is always the given
2746 (define v (make-vtable "prpwpw"))
2747 (define s (make-struct v 0 123 "abc" 456))
2748 (struct-ref s 0) @result{} 123
2749 (struct-ref s 1) @result{} "abc"
2753 @deftypefn {C Function} SCM scm_make_struct (SCM vtable, SCM tail_size, SCM init_list)
2754 @deftypefnx {C Function} SCM scm_c_make_struct (SCM vtable, SCM tail_size, SCM init, ...)
2755 @deftypefnx {C Function} SCM scm_c_make_structv (SCM vtable, SCM tail_size, size_t n_inits, scm_t_bits init[])
2756 There are a few ways to make structures from C. @code{scm_make_struct}
2757 takes a list, @code{scm_c_make_struct} takes variable arguments
2758 terminated with SCM_UNDEFINED, and @code{scm_c_make_structv} takes a
2762 @deffn {Scheme Procedure} struct? obj
2763 @deffnx {C Function} scm_struct_p (obj)
2764 Return @code{#t} if @var{obj} is a structure, or @code{#f} if not.
2767 @deffn {Scheme Procedure} struct-ref struct n
2768 @deffnx {C Function} scm_struct_ref (struct, n)
2769 Return the contents of field number @var{n} in @var{struct}. The
2770 first field is number 0.
2772 An error is thrown if @var{n} is out of range, or if the field cannot
2773 be read because it's @code{o} opaque.
2776 @deffn {Scheme Procedure} struct-set! struct n value
2777 @deffnx {C Function} scm_struct_set_x (struct, n, value)
2778 Set field number @var{n} in @var{struct} to @var{value}. The first
2781 An error is thrown if @var{n} is out of range, or if the field cannot
2782 be written because it's @code{r} read-only or @code{o} opaque.
2785 @deffn {Scheme Procedure} struct-vtable struct
2786 @deffnx {C Function} scm_struct_vtable (struct)
2787 Return the vtable that describes @var{struct}.
2789 The vtable is effectively the type of the structure. See @ref{Vtable
2790 Contents}, for more on vtables.
2794 @node Vtable Contents
2795 @subsubsection Vtable Contents
2797 A vtable is itself a structure. It has a specific set of fields
2798 describing various aspects of its @dfn{instances}: the structures
2799 created from a vtable. Some of the fields are internal to Guile, some
2800 of them are part of the public interface, and there may be additional
2801 fields added on by the user.
2803 Every vtable has a field for the layout of their instances, a field for
2804 the procedure used to print its instances, and a field for the name of
2805 the vtable itself. Access to the layout and printer is exposed directly
2806 via field indexes. Access to the vtable name is exposed via accessor
2809 @defvr {Scheme Variable} vtable-index-layout
2810 @defvrx {C Macro} scm_vtable_index_layout
2811 The field number of the layout specification in a vtable. The layout
2812 specification is a symbol like @code{pwpw} formed from the fields
2813 string passed to @code{make-vtable}, or created by
2814 @code{make-struct-layout} (@pxref{Meta-Vtables}).
2817 (define v (make-vtable "pwpw" 0))
2818 (struct-ref v vtable-index-layout) @result{} pwpw
2821 This field is read-only, since the layout of structures using a vtable
2825 @defvr {Scheme Variable} vtable-index-printer
2826 @defvrx {C Macro} scm_vtable_index_printer
2827 The field number of the printer function. This field contains @code{#f}
2828 if the default print function should be used.
2831 (define (my-print-func struct port)
2833 (define v (make-vtable "pwpw" my-print-func))
2834 (struct-ref v vtable-index-printer) @result{} my-print-func
2837 This field is writable, allowing the print function to be changed
2841 @deffn {Scheme Procedure} struct-vtable-name vtable
2842 @deffnx {Scheme Procedure} set-struct-vtable-name! vtable name
2843 @deffnx {C Function} scm_struct_vtable_name (vtable)
2844 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
2845 Get or set the name of @var{vtable}. @var{name} is a symbol and is
2846 used in the default print function when printing structures created
2850 (define v (make-vtable "pw"))
2851 (set-struct-vtable-name! v 'my-name)
2853 (define s (make-struct v 0))
2854 (display s) @print{} #<my-name b7ab3ae0:b7ab3730>
2860 @subsubsection Meta-Vtables
2862 As a structure, a vtable also has a vtable, which is also a structure.
2863 Structures, their vtables, the vtables of the vtables, and so on form a
2864 tree of structures. Making a new structure adds a leaf to the tree, and
2865 if that structure is a vtable, it may be used to create other leaves.
2867 If you traverse up the tree of vtables, via calling
2868 @code{struct-vtable}, eventually you reach a root which is the vtable of
2872 scheme@@(guile-user)> (current-module)
2873 $1 = #<directory (guile-user) 221b090>
2874 scheme@@(guile-user)> (struct-vtable $1)
2875 $2 = #<record-type module>
2876 scheme@@(guile-user)> (struct-vtable $2)
2877 $3 = #<<standard-vtable> 12c30a0>
2878 scheme@@(guile-user)> (struct-vtable $3)
2879 $4 = #<<standard-vtable> 12c3fa0>
2880 scheme@@(guile-user)> (struct-vtable $4)
2881 $5 = #<<standard-vtable> 12c3fa0>
2882 scheme@@(guile-user)> <standard-vtable>
2883 $6 = #<<standard-vtable> 12c3fa0>
2886 In this example, we can say that @code{$1} is an instance of @code{$2},
2887 @code{$2} is an instance of @code{$3}, @code{$3} is an instance of
2888 @code{$4}, and @code{$4}, strangely enough, is an instance of itself.
2889 The value bound to @code{$4} in this console session also bound to
2890 @code{<standard-vtable>} in the default environment.
2892 @defvr {Scheme Variable} <standard-vtable>
2893 A meta-vtable, useful for making new vtables.
2896 All of these values are structures. All but @code{$1} are vtables. As
2897 @code{$2} is an instance of @code{$3}, and @code{$3} is a vtable, we can
2898 say that @code{$3} is a @dfn{meta-vtable}: a vtable that can create
2901 With this definition, we can specify more precisely what a vtable is: a
2902 vtable is a structure made from a meta-vtable. Making a structure from
2903 a meta-vtable runs some special checks to ensure that the first field of
2904 the structure is a valid layout. Additionally, if these checks see that
2905 the layout of the child vtable contains all the required fields of a
2906 vtable, in the correct order, then the child vtable will also be a
2907 meta-table, inheriting a magical bit from the parent.
2909 @deffn {Scheme Procedure} struct-vtable? obj
2910 @deffnx {C Function} scm_struct_vtable_p (obj)
2911 Return @code{#t} if @var{obj} is a vtable structure: an instance of a
2915 @code{<standard-vtable>} is a root of the vtable tree. (Normally there
2916 is only one root in a given Guile process, but due to some legacy
2917 interfaces there may be more than one.)
2919 The set of required fields of a vtable is the set of fields in the
2920 @code{<standard-vtable>}, and is bound to @code{standard-vtable-fields}
2921 in the default environment. It is possible to create a meta-vtable that
2922 with additional fields in its layout, which can be used to create
2923 vtables with additional data:
2926 scheme@@(guile-user)> (struct-ref $3 vtable-index-layout)
2927 $6 = pruhsruhpwphuhuhprprpw
2928 scheme@@(guile-user)> (struct-ref $4 vtable-index-layout)
2929 $7 = pruhsruhpwphuhuh
2930 scheme@@(guile-user)> standard-vtable-fields
2931 $8 = "pruhsruhpwphuhuh"
2932 scheme@@(guile-user)> (struct-ref $2 vtable-offset-user)
2936 In this continuation of our earlier example, @code{$2} is a vtable that
2937 has extra fields, because its vtable, @code{$3}, was made from a
2938 meta-vtable with an extended layout. @code{vtable-offset-user} is a
2939 convenient definition that indicates the number of fields in
2940 @code{standard-vtable-fields}.
2942 @defvr {Scheme Variable} standard-vtable-fields
2943 A string containing the orderedq set of fields that a vtable must have.
2946 @defvr {Scheme Variable} vtable-offset-user
2947 The first index in a vtable that is available for a user.
2950 @deffn {Scheme Procedure} make-struct-layout fields
2951 @deffnx {C Function} scm_make_struct_layout (fields)
2952 Return a structure layout symbol, from a @var{fields} string.
2953 @var{fields} is as described under @code{make-vtable}
2954 (@pxref{Vtables}). An invalid @var{fields} string is an error.
2957 With these definitions, one can define @code{make-vtable} in this way:
2960 (define* (make-vtable fields #:optional printer)
2961 (make-struct/no-tail <standard-vtable>
2962 (make-struct-layout fields)
2967 @node Vtable Example
2968 @subsubsection Vtable Example
2970 Let us bring these points together with an example. Consider a simple
2971 object system with single inheritance. Objects will be normal
2972 structures, and classes will be vtables with three extra class fields:
2973 the name of the class, the parent class, and the list of fields.
2975 So, first we need a meta-vtable that allocates instances with these
2981 (string-append standard-vtable-fields "pwpwpw")
2983 (format port "<<class> ~a>" (class-name x)))))
2987 (eq? (struct-vtable x) <class>)))
2990 To make a structure with a specific meta-vtable, we will use
2991 @code{make-struct/no-tail}, passing it the computed instance layout and
2992 printer, as with @code{make-vtable}, and additionally the extra three
2996 (define (make-class name parent fields)
2997 (let* ((fields (compute-fields parent fields))
2998 (layout (compute-layout fields)))
2999 (make-struct/no-tail <class>
3002 (print-instance x port))
3008 Instances will store their associated data in slots in the structure: as
3009 many slots as there are fields. The @code{compute-layout} procedure
3010 below can compute a layout, and @code{field-index} returns the slot
3011 corresponding to a field.
3014 (define-syntax-rule (define-accessor name n)
3016 (struct-ref obj n)))
3018 ;; Accessors for classes
3019 (define-accessor class-name (+ vtable-offset-user 0))
3020 (define-accessor class-parent (+ vtable-offset-user 1))
3021 (define-accessor class-fields (+ vtable-offset-user 2))
3023 (define (compute-fields parent fields)
3025 (append (class-fields parent) fields)
3028 (define (compute-layout fields)
3030 (string-concatenate (make-list (length fields) "pw"))))
3032 (define (field-index class field)
3033 (list-index (class-fields class) field))
3035 (define (print-instance x port)
3036 (format port "<~a" (class-name (struct-vtable x)))
3037 (for-each (lambda (field idx)
3038 (format port " ~a: ~a" field (struct-ref x idx)))
3039 (class-fields (struct-vtable x))
3040 (iota (length (class-fields (struct-vtable x)))))
3044 So, at this point we can actually make a few classes:
3047 (define-syntax-rule (define-class name parent field ...)
3048 (define name (make-class 'name parent '(field ...))))
3050 (define-class <surface> #f
3053 (define-class <window> <surface>
3057 And finally, make an instance:
3060 (make-struct/no-tail <window> 400 300 10 20)
3061 @result{} <<window> width: 400 height: 300 x: 10 y: 20>
3064 And that's that. Note that there are many possible optimizations and
3065 feature enhancements that can be made to this object system, and the
3066 included GOOPS system does make most of them. For more simple use
3067 cases, the records facility is usually sufficient. But sometimes you
3068 need to make new kinds of data abstractions, and for that purpose,
3072 @subsubsection Tail Arrays
3074 Guile's structures have a facility whereby each instance of a vtable can
3075 contain a variable-length tail array of values. The length of the tail
3076 array is stored in the structure. This facility was originally intended
3077 to allow C code to expose raw C structures with word-sized tail arrays
3080 However, the tail array facility is confusing and doesn't work very
3081 well. It is very rarely used, but it insinuates itself into all
3082 invocations of @code{make-struct}. For this reason the clumsily-named
3083 @code{make-struct/no-tail} procedure can actually be more elegant in
3084 actual use, because it doesn't have a random @code{0} argument stuck in
3087 Tail arrays also inhibit optimization by allowing instances to affect
3088 their shapes. In the absence of tail arrays, all instances of a given
3089 vtable have the same number and kinds of fields. This uniformity can be
3090 exploited by the runtime and the optimizer. The presence of tail arrays
3091 make some of these optimizations more difficult.
3093 Finally, the tail array facility is ad-hoc and does not compose with the
3094 rest of Guile. If a Guile user wants an array with user-specified
3095 length, it's best to use a vector. It is more clear in the code, and
3096 the standard optimization techniques will do a good job with it.
3098 That said, we should mention some details about the interface. A vtable
3099 that has tail array has upper-case permission descriptors: @code{W},
3100 @code{R} or @code{O}, correspoding to tail arrays of writable,
3101 read-only, or opaque elements. A tail array permission descriptor may
3102 only appear in the last element of a vtable layout.
3104 For exampple, @samp{pW} indicates a tail of writable Scheme-valued
3105 fields. The @samp{pW} field itself holds the tail size, and the tail
3106 fields come after it.
3109 (define v (make-vtable "prpW")) ;; one fixed then a tail array
3110 (define s (make-struct v 6 "fixed field" 'x 'y))
3111 (struct-ref s 0) @result{} "fixed field"
3112 (struct-ref s 1) @result{} 2 ;; tail size
3113 (struct-ref s 2) @result{} x ;; tail array ...
3114 (struct-ref s 3) @result{} y
3115 (struct-ref s 4) @result{} #f
3119 @node Dictionary Types
3120 @subsection Dictionary Types
3122 A @dfn{dictionary} object is a data structure used to index
3123 information in a user-defined way. In standard Scheme, the main
3124 aggregate data types are lists and vectors. Lists are not really
3125 indexed at all, and vectors are indexed only by number
3126 (e.g.@: @code{(vector-ref foo 5)}). Often you will find it useful
3127 to index your data on some other type; for example, in a library
3128 catalog you might want to look up a book by the name of its
3129 author. Dictionaries are used to help you organize information in
3132 An @dfn{association list} (or @dfn{alist} for short) is a list of
3133 key-value pairs. Each pair represents a single quantity or
3134 object; the @code{car} of the pair is a key which is used to
3135 identify the object, and the @code{cdr} is the object's value.
3137 A @dfn{hash table} also permits you to index objects with
3138 arbitrary keys, but in a way that makes looking up any one object
3139 extremely fast. A well-designed hash system makes hash table
3140 lookups almost as fast as conventional array or vector references.
3142 Alists are popular among Lisp programmers because they use only
3143 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
3144 and the equality primitives). No changes to the language core are
3145 necessary. Therefore, with Scheme's built-in list manipulation
3146 facilities, it is very convenient to handle data stored in an
3147 association list. Also, alists are highly portable and can be
3148 easily implemented on even the most minimal Lisp systems.
3150 However, alists are inefficient, especially for storing large
3151 quantities of data. Because we want Guile to be useful for large
3152 software systems as well as small ones, Guile provides a rich set
3153 of tools for using either association lists or hash tables.
3155 @node Association Lists
3156 @subsection Association Lists
3157 @tpindex Association Lists
3159 @cindex association List
3163 An association list is a conventional data structure that is often used
3164 to implement simple key-value databases. It consists of a list of
3165 entries in which each entry is a pair. The @dfn{key} of each entry is
3166 the @code{car} of the pair and the @dfn{value} of each entry is the
3170 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
3178 Association lists are also known, for short, as @dfn{alists}.
3180 The structure of an association list is just one example of the infinite
3181 number of possible structures that can be built using pairs and lists.
3182 As such, the keys and values in an association list can be manipulated
3183 using the general list structure procedures @code{cons}, @code{car},
3184 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
3185 because association lists are so useful, Guile also provides specific
3186 procedures for manipulating them.
3189 * Alist Key Equality::
3190 * Adding or Setting Alist Entries::
3191 * Retrieving Alist Entries::
3192 * Removing Alist Entries::
3193 * Sloppy Alist Functions::
3197 @node Alist Key Equality
3198 @subsubsection Alist Key Equality
3200 All of Guile's dedicated association list procedures, apart from
3201 @code{acons}, come in three flavours, depending on the level of equality
3202 that is required to decide whether an existing key in the association
3203 list is the same as the key that the procedure call uses to identify the
3208 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
3212 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
3216 Procedures with @dfn{assoc} in their name use @code{equal?} to
3217 determine key equality.
3220 @code{acons} is an exception because it is used to build association
3221 lists which do not require their entries' keys to be unique.
3223 @node Adding or Setting Alist Entries
3224 @subsubsection Adding or Setting Alist Entries
3226 @code{acons} adds a new entry to an association list and returns the
3227 combined association list. The combined alist is formed by consing the
3228 new entry onto the head of the alist specified in the @code{acons}
3229 procedure call. So the specified alist is not modified, but its
3230 contents become shared with the tail of the combined alist that
3231 @code{acons} returns.
3233 In the most common usage of @code{acons}, a variable holding the
3234 original association list is updated with the combined alist:
3237 (set! address-list (acons name address address-list))
3240 In such cases, it doesn't matter that the old and new values of
3241 @code{address-list} share some of their contents, since the old value is
3242 usually no longer independently accessible.
3244 Note that @code{acons} adds the specified new entry regardless of
3245 whether the alist may already contain entries with keys that are, in
3246 some sense, the same as that of the new entry. Thus @code{acons} is
3247 ideal for building alists where there is no concept of key uniqueness.
3250 (set! task-list (acons 3 "pay gas bill" '()))
3253 ((3 . "pay gas bill"))
3255 (set! task-list (acons 3 "tidy bedroom" task-list))
3258 ((3 . "tidy bedroom") (3 . "pay gas bill"))
3261 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
3262 or replace an entry in an association list where there @emph{is} a
3263 concept of key uniqueness. If the specified association list already
3264 contains an entry whose key is the same as that specified in the
3265 procedure call, the existing entry is replaced by the new one.
3266 Otherwise, the new entry is consed onto the head of the old association
3267 list to create the combined alist. In all cases, these procedures
3268 return the combined alist.
3270 @code{assq-set!} and friends @emph{may} destructively modify the
3271 structure of the old association list in such a way that an existing
3272 variable is correctly updated without having to @code{set!} it to the
3278 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
3280 (assoc-set! address-list "james" "1a London Road")
3282 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3286 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3292 (assoc-set! address-list "bob" "11 Newington Avenue")
3294 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3295 ("james" . "1a London Road"))
3299 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3302 The only safe way to update an association list variable when adding or
3303 replacing an entry like this is to @code{set!} the variable to the
3308 (assoc-set! address-list "bob" "11 Newington Avenue"))
3311 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3312 ("james" . "1a London Road"))
3315 Because of this slight inconvenience, you may find it more convenient to
3316 use hash tables to store dictionary data. If your application will not
3317 be modifying the contents of an alist very often, this may not make much
3320 If you need to keep the old value of an association list in a form
3321 independent from the list that results from modification by
3322 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
3323 use @code{list-copy} to copy the old association list before modifying
3326 @deffn {Scheme Procedure} acons key value alist
3327 @deffnx {C Function} scm_acons (key, value, alist)
3328 Add a new key-value pair to @var{alist}. A new pair is
3329 created whose car is @var{key} and whose cdr is @var{value}, and the
3330 pair is consed onto @var{alist}, and the new list is returned. This
3331 function is @emph{not} destructive; @var{alist} is not modified.
3334 @deffn {Scheme Procedure} assq-set! alist key val
3335 @deffnx {Scheme Procedure} assv-set! alist key value
3336 @deffnx {Scheme Procedure} assoc-set! alist key value
3337 @deffnx {C Function} scm_assq_set_x (alist, key, val)
3338 @deffnx {C Function} scm_assv_set_x (alist, key, val)
3339 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
3340 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
3341 @var{alist} entry for @var{key} and associate it with the new
3342 @var{value}. If @var{alist} does not contain an entry for @var{key},
3343 add a new one. Return the (possibly new) alist.
3345 These functions do not attempt to verify the structure of @var{alist},
3346 and so may cause unusual results if passed an object that is not an
3350 @node Retrieving Alist Entries
3351 @subsubsection Retrieving Alist Entries
3356 @code{assq}, @code{assv} and @code{assoc} find the entry in an alist
3357 for a given key, and return the @code{(@var{key} . @var{value})} pair.
3358 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref} do a similar
3359 lookup, but return just the @var{value}.
3361 @deffn {Scheme Procedure} assq key alist
3362 @deffnx {Scheme Procedure} assv key alist
3363 @deffnx {Scheme Procedure} assoc key alist
3364 @deffnx {C Function} scm_assq (key, alist)
3365 @deffnx {C Function} scm_assv (key, alist)
3366 @deffnx {C Function} scm_assoc (key, alist)
3367 Return the first entry in @var{alist} with the given @var{key}. The
3368 return is the pair @code{(KEY . VALUE)} from @var{alist}. If there's
3369 no matching entry the return is @code{#f}.
3371 @code{assq} compares keys with @code{eq?}, @code{assv} uses
3372 @code{eqv?} and @code{assoc} uses @code{equal?}. See also SRFI-1
3373 which has an extended @code{assoc} (@ref{SRFI-1 Association Lists}).
3376 @deffn {Scheme Procedure} assq-ref alist key
3377 @deffnx {Scheme Procedure} assv-ref alist key
3378 @deffnx {Scheme Procedure} assoc-ref alist key
3379 @deffnx {C Function} scm_assq_ref (alist, key)
3380 @deffnx {C Function} scm_assv_ref (alist, key)
3381 @deffnx {C Function} scm_assoc_ref (alist, key)
3382 Return the value from the first entry in @var{alist} with the given
3383 @var{key}, or @code{#f} if there's no such entry.
3385 @code{assq-ref} compares keys with @code{eq?}, @code{assv-ref} uses
3386 @code{eqv?} and @code{assoc-ref} uses @code{equal?}.
3388 Notice these functions have the @var{key} argument last, like other
3389 @code{-ref} functions, but this is opposite to what @code{assq}
3392 When the return is @code{#f} it can be either @var{key} not found, or
3393 an entry which happens to have value @code{#f} in the @code{cdr}. Use
3394 @code{assq} etc above if you need to differentiate these cases.
3398 @node Removing Alist Entries
3399 @subsubsection Removing Alist Entries
3401 To remove the element from an association list whose key matches a
3402 specified key, use @code{assq-remove!}, @code{assv-remove!} or
3403 @code{assoc-remove!} (depending, as usual, on the level of equality
3404 required between the key that you specify and the keys in the
3407 As with @code{assq-set!} and friends, the specified alist may or may not
3408 be modified destructively, and the only safe way to update a variable
3409 containing the alist is to @code{set!} it to the value that
3410 @code{assq-remove!} and friends return.
3415 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3416 ("james" . "1a London Road"))
3418 (set! address-list (assoc-remove! address-list "mary"))
3421 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
3424 Note that, when @code{assq/v/oc-remove!} is used to modify an
3425 association list that has been constructed only using the corresponding
3426 @code{assq/v/oc-set!}, there can be at most one matching entry in the
3427 alist, so the question of multiple entries being removed in one go does
3428 not arise. If @code{assq/v/oc-remove!} is applied to an association
3429 list that has been constructed using @code{acons}, or an
3430 @code{assq/v/oc-set!} with a different level of equality, or any mixture
3431 of these, it removes only the first matching entry from the alist, even
3432 if the alist might contain further matching entries. For example:
3435 (define address-list '())
3436 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
3437 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
3440 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
3442 (set! address-list (assoc-remove! address-list "mary"))
3445 (("mary" . "11 Elm Street"))
3448 In this example, the two instances of the string "mary" are not the same
3449 when compared using @code{eq?}, so the two @code{assq-set!} calls add
3450 two distinct entries to @code{address-list}. When compared using
3451 @code{equal?}, both "mary"s in @code{address-list} are the same as the
3452 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
3453 after removing the first matching entry that it finds, and so one of the
3454 "mary" entries is left in place.
3456 @deffn {Scheme Procedure} assq-remove! alist key
3457 @deffnx {Scheme Procedure} assv-remove! alist key
3458 @deffnx {Scheme Procedure} assoc-remove! alist key
3459 @deffnx {C Function} scm_assq_remove_x (alist, key)
3460 @deffnx {C Function} scm_assv_remove_x (alist, key)
3461 @deffnx {C Function} scm_assoc_remove_x (alist, key)
3462 Delete the first entry in @var{alist} associated with @var{key}, and return
3463 the resulting alist.
3466 @node Sloppy Alist Functions
3467 @subsubsection Sloppy Alist Functions
3469 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
3470 like the corresponding non-@code{sloppy-} procedures, except that they
3471 return @code{#f} when the specified association list is not well-formed,
3472 where the non-@code{sloppy-} versions would signal an error.
3474 Specifically, there are two conditions for which the non-@code{sloppy-}
3475 procedures signal an error, which the @code{sloppy-} procedures handle
3476 instead by returning @code{#f}. Firstly, if the specified alist as a
3477 whole is not a proper list:
3480 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3482 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
3483 ERROR: Wrong type argument in position 2 (expecting
3484 association list): ((1 . 2) ("key" . "door") . "open sesame")
3486 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3492 Secondly, if one of the entries in the specified alist is not a pair:
3495 (assoc 2 '((1 . 1) 2 (3 . 9)))
3497 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
3498 ERROR: Wrong type argument in position 2 (expecting
3499 association list): ((1 . 1) 2 (3 . 9))
3501 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
3506 Unless you are explicitly working with badly formed association lists,
3507 it is much safer to use the non-@code{sloppy-} procedures, because they
3508 help to highlight coding and data errors that the @code{sloppy-}
3509 versions would silently cover up.
3511 @deffn {Scheme Procedure} sloppy-assq key alist
3512 @deffnx {C Function} scm_sloppy_assq (key, alist)
3513 Behaves like @code{assq} but does not do any error checking.
3514 Recommended only for use in Guile internals.
3517 @deffn {Scheme Procedure} sloppy-assv key alist
3518 @deffnx {C Function} scm_sloppy_assv (key, alist)
3519 Behaves like @code{assv} but does not do any error checking.
3520 Recommended only for use in Guile internals.
3523 @deffn {Scheme Procedure} sloppy-assoc key alist
3524 @deffnx {C Function} scm_sloppy_assoc (key, alist)
3525 Behaves like @code{assoc} but does not do any error checking.
3526 Recommended only for use in Guile internals.
3530 @subsubsection Alist Example
3532 Here is a longer example of how alists may be used in practice.
3535 (define capitals '(("New York" . "Albany")
3536 ("Oregon" . "Salem")
3537 ("Florida" . "Miami")))
3539 ;; What's the capital of Oregon?
3540 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
3541 (assoc-ref capitals "Oregon") @result{} "Salem"
3543 ;; We left out South Dakota.
3545 (assoc-set! capitals "South Dakota" "Pierre"))
3547 @result{} (("South Dakota" . "Pierre")
3548 ("New York" . "Albany")
3549 ("Oregon" . "Salem")
3550 ("Florida" . "Miami"))
3552 ;; And we got Florida wrong.
3554 (assoc-set! capitals "Florida" "Tallahassee"))
3556 @result{} (("South Dakota" . "Pierre")
3557 ("New York" . "Albany")
3558 ("Oregon" . "Salem")
3559 ("Florida" . "Tallahassee"))
3561 ;; After Oregon secedes, we can remove it.
3563 (assoc-remove! capitals "Oregon"))
3565 @result{} (("South Dakota" . "Pierre")
3566 ("New York" . "Albany")
3567 ("Florida" . "Tallahassee"))
3571 @subsection VList-Based Hash Lists or ``VHashes''
3573 @cindex VList-based hash lists
3576 The @code{(ice-9 vlist)} module provides an implementation of @dfn{VList-based
3577 hash lists} (@pxref{VLists}). VList-based hash lists, or @dfn{vhashes}, are an
3578 immutable dictionary type similar to association lists that maps @dfn{keys} to
3579 @dfn{values}. However, unlike association lists, accessing a value given its
3580 key is typically a constant-time operation.
3582 The VHash programming interface of @code{(ice-9 vlist)} is mostly the same as
3583 that of association lists found in SRFI-1, with procedure names prefixed by
3584 @code{vhash-} instead of @code{alist-} (@pxref{SRFI-1 Association Lists}).
3586 In addition, vhashes can be manipulated using VList operations:
3589 (vlist-head (vhash-consq 'a 1 vlist-null))
3592 (define vh1 (vhash-consq 'b 2 (vhash-consq 'a 1 vlist-null)))
3593 (define vh2 (vhash-consq 'c 3 (vlist-tail vh1)))
3602 @result{} ((c . 3) (a . 1))
3605 However, keep in mind that procedures that construct new VLists
3606 (@code{vlist-map}, @code{vlist-filter}, etc.) return raw VLists, not vhashes:
3609 (define vh (alist->vhash '((a . 1) (b . 2) (c . 3)) hashq))
3614 ;; This will create a raw vlist.
3615 (vlist-filter (lambda (key+value) (odd? (cdr key+value))) vh))
3617 @result{} ERROR: Wrong type argument in position 2
3620 @result{} ((a . 1) (c . 3))
3623 @deffn {Scheme Procedure} vhash? obj
3624 Return true if @var{obj} is a vhash.
3627 @deffn {Scheme Procedure} vhash-cons key value vhash [hash-proc]
3628 @deffnx {Scheme Procedure} vhash-consq key value vhash
3629 @deffnx {Scheme Procedure} vhash-consv key value vhash
3630 Return a new hash list based on @var{vhash} where @var{key} is associated with
3631 @var{value}, using @var{hash-proc} to compute the hash of @var{key}.
3632 @var{vhash} must be either @code{vlist-null} or a vhash returned by a previous
3633 call to @code{vhash-cons}. @var{hash-proc} defaults to @code{hash} (@pxref{Hash
3634 Table Reference, @code{hash} procedure}). With @code{vhash-consq}, the
3635 @code{hashq} hash function is used; with @code{vhash-consv} the @code{hashv}
3636 hash function is used.
3638 All @code{vhash-cons} calls made to construct a vhash should use the same
3639 @var{hash-proc}. Failing to do that, the result is undefined.
3642 @deffn {Scheme Procedure} vhash-assoc key vhash [equal? [hash-proc]]
3643 @deffnx {Scheme Procedure} vhash-assq key vhash
3644 @deffnx {Scheme Procedure} vhash-assv key vhash
3645 Return the first key/value pair from @var{vhash} whose key is equal to @var{key}
3646 according to the @var{equal?} equality predicate (which defaults to
3647 @code{equal?}), and using @var{hash-proc} (which defaults to @code{hash}) to
3648 compute the hash of @var{key}. The second form uses @code{eq?} as the equality
3649 predicate and @code{hashq} as the hash function; the last form uses @code{eqv?}
3652 Note that it is important to consistently use the same hash function for
3653 @var{hash-proc} as was passed to @code{vhash-cons}. Failing to do that, the
3654 result is unpredictable.
3657 @deffn {Scheme Procedure} vhash-delete key vhash [equal? [hash-proc]]
3658 @deffnx {Scheme Procedure} vhash-delq key vhash
3659 @deffnx {Scheme Procedure} vhash-delv key vhash
3660 Remove all associations from @var{vhash} with @var{key}, comparing keys with
3661 @var{equal?} (which defaults to @code{equal?}), and computing the hash of
3662 @var{key} using @var{hash-proc} (which defaults to @code{hash}). The second
3663 form uses @code{eq?} as the equality predicate and @code{hashq} as the hash
3664 function; the last one uses @code{eqv?} and @code{hashv}.
3666 Again the choice of @var{hash-proc} must be consistent with previous calls to
3670 @deffn {Scheme Procedure} vhash-fold proc init vhash
3671 @deffnx {Scheme Procedure} vhash-fold-right proc init vhash
3672 Fold over the key/value elements of @var{vhash} in the given direction,
3673 with each call to @var{proc} having the form @code{(@var{proc} key value
3674 result)}, where @var{result} is the result of the previous call to
3675 @var{proc} and @var{init} the value of @var{result} for the first call
3679 @deffn {Scheme Procedure} vhash-fold* proc init key vhash [equal? [hash]]
3680 @deffnx {Scheme Procedure} vhash-foldq* proc init key vhash
3681 @deffnx {Scheme Procedure} vhash-foldv* proc init key vhash
3682 Fold over all the values associated with @var{key} in @var{vhash}, with each
3683 call to @var{proc} having the form @code{(proc value result)}, where
3684 @var{result} is the result of the previous call to @var{proc} and @var{init} the
3685 value of @var{result} for the first call to @var{proc}.
3687 Keys in @var{vhash} are hashed using @var{hash} are compared using @var{equal?}.
3688 The second form uses @code{eq?} as the equality predicate and @code{hashq} as
3689 the hash function; the third one uses @code{eqv?} and @code{hashv}.
3695 (alist->vhash '((a . 1) (a . 2) (z . 0) (a . 3))))
3697 (vhash-fold* cons '() 'a vh)
3700 (vhash-fold* cons '() 'z vh)
3705 @deffn {Scheme Procedure} alist->vhash alist [hash-proc]
3706 Return the vhash corresponding to @var{alist}, an association list, using
3707 @var{hash-proc} to compute key hashes. When omitted, @var{hash-proc} defaults
3713 @subsection Hash Tables
3714 @tpindex Hash Tables
3716 Hash tables are dictionaries which offer similar functionality as
3717 association lists: They provide a mapping from keys to values. The
3718 difference is that association lists need time linear in the size of
3719 elements when searching for entries, whereas hash tables can normally
3720 search in constant time. The drawback is that hash tables require a
3721 little bit more memory, and that you can not use the normal list
3722 procedures (@pxref{Lists}) for working with them.
3725 * Hash Table Examples:: Demonstration of hash table usage.
3726 * Hash Table Reference:: Hash table procedure descriptions.
3730 @node Hash Table Examples
3731 @subsubsection Hash Table Examples
3733 For demonstration purposes, this section gives a few usage examples of
3734 some hash table procedures, together with some explanation what they do.
3736 First we start by creating a new hash table with 31 slots, and
3737 populate it with two key/value pairs.
3740 (define h (make-hash-table 31))
3742 ;; This is an opaque object
3747 ;; Inserting into a hash table can be done with hashq-set!
3748 (hashq-set! h 'foo "bar")
3752 (hashq-set! h 'braz "zonk")
3756 ;; Or with hash-create-handle!
3757 (hashq-create-handle! h 'frob #f)
3762 You can get the value for a given key with the procedure
3763 @code{hashq-ref}, but the problem with this procedure is that you
3764 cannot reliably determine whether a key does exists in the table. The
3765 reason is that the procedure returns @code{#f} if the key is not in
3766 the table, but it will return the same value if the key is in the
3767 table and just happens to have the value @code{#f}, as you can see in
3768 the following examples.
3779 (hashq-ref h 'not-there)
3784 Better is to use the procedure @code{hashq-get-handle}, which makes a
3785 distinction between the two cases. Just like @code{assq}, this
3786 procedure returns a key/value-pair on success, and @code{#f} if the
3790 (hashq-get-handle h 'foo)
3794 (hashq-get-handle h 'not-there)
3799 There is no procedure for calculating the number of key/value-pairs in
3800 a hash table, but @code{hash-fold} can be used for doing exactly that.
3803 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
3808 @node Hash Table Reference
3809 @subsubsection Hash Table Reference
3811 @c FIXME: Describe in broad terms what happens for resizing, and what
3812 @c the initial size means for this.
3814 Like the association list functions, the hash table functions come in
3815 several varieties, according to the equality test used for the keys.
3816 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
3817 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
3818 the @code{hashx-} functions use an application supplied test.
3820 A single @code{make-hash-table} creates a hash table suitable for use
3821 with any set of functions, but it's imperative that just one set is
3822 then used consistently, or results will be unpredictable.
3824 Hash tables are implemented as a vector indexed by a hash value formed
3825 from the key, with an association list of key/value pairs for each
3826 bucket in case distinct keys hash together. Direct access to the
3827 pairs in those lists is provided by the @code{-handle-} functions.
3829 When the number of entries in a hash table goes above a threshold, the
3830 vector is made larger and the entries are rehashed, to prevent the
3831 bucket lists from becoming too long and slowing down accesses. When the
3832 number of entries goes below a threshold, the vector is shrunk to save
3835 For the @code{hashx-} ``extended'' routines, an application supplies a
3836 @var{hash} function producing an integer index like @code{hashq} etc
3837 below, and an @var{assoc} alist search function like @code{assq} etc
3838 (@pxref{Retrieving Alist Entries}). Here's an example of such
3839 functions implementing case-insensitive hashing of string keys,
3842 (use-modules (srfi srfi-1)
3845 (define (my-hash str size)
3846 (remainder (string-hash-ci str) size))
3847 (define (my-assoc str alist)
3848 (find (lambda (pair) (string-ci=? str (car pair))) alist))
3850 (define my-table (make-hash-table))
3851 (hashx-set! my-hash my-assoc my-table "foo" 123)
3853 (hashx-ref my-hash my-assoc my-table "FOO")
3857 In a @code{hashx-} @var{hash} function the aim is to spread keys
3858 across the vector, so bucket lists don't become long. But the actual
3859 values are arbitrary as long as they're in the range 0 to
3860 @math{@var{size}-1}. Helpful functions for forming a hash value, in
3861 addition to @code{hashq} etc below, include @code{symbol-hash}
3862 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
3863 (@pxref{String Comparison}), and @code{char-set-hash}
3864 (@pxref{Character Set Predicates/Comparison}).
3867 @deffn {Scheme Procedure} make-hash-table [size]
3868 Create a new hash table object, with an optional minimum
3871 When @var{size} is given, the table vector will still grow and shrink
3872 automatically, as described above, but with @var{size} as a minimum.
3873 If an application knows roughly how many entries the table will hold
3874 then it can use @var{size} to avoid rehashing when initial entries are
3878 @deffn {Scheme Procedure} hash-table? obj
3879 @deffnx {C Function} scm_hash_table_p (obj)
3880 Return @code{#t} if @var{obj} is a abstract hash table object.
3883 @deffn {Scheme Procedure} hash-clear! table
3884 @deffnx {C Function} scm_hash_clear_x (table)
3885 Remove all items from @var{table} (without triggering a resize).
3888 @deffn {Scheme Procedure} hash-ref table key [dflt]
3889 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
3890 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
3891 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
3892 @deffnx {C Function} scm_hash_ref (table, key, dflt)
3893 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
3894 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
3895 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
3896 Lookup @var{key} in the given hash @var{table}, and return the
3897 associated value. If @var{key} is not found, return @var{dflt}, or
3898 @code{#f} if @var{dflt} is not given.
3901 @deffn {Scheme Procedure} hash-set! table key val
3902 @deffnx {Scheme Procedure} hashq-set! table key val
3903 @deffnx {Scheme Procedure} hashv-set! table key val
3904 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
3905 @deffnx {C Function} scm_hash_set_x (table, key, val)
3906 @deffnx {C Function} scm_hashq_set_x (table, key, val)
3907 @deffnx {C Function} scm_hashv_set_x (table, key, val)
3908 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
3909 Associate @var{val} with @var{key} in the given hash @var{table}. If
3910 @var{key} is already present then it's associated value is changed.
3911 If it's not present then a new entry is created.
3914 @deffn {Scheme Procedure} hash-remove! table key
3915 @deffnx {Scheme Procedure} hashq-remove! table key
3916 @deffnx {Scheme Procedure} hashv-remove! table key
3917 @deffnx {Scheme Procedure} hashx-remove! hash assoc table key
3918 @deffnx {C Function} scm_hash_remove_x (table, key)
3919 @deffnx {C Function} scm_hashq_remove_x (table, key)
3920 @deffnx {C Function} scm_hashv_remove_x (table, key)
3921 @deffnx {C Function} scm_hashx_remove_x (hash, assoc, table, key)
3922 Remove any association for @var{key} in the given hash @var{table}.
3923 If @var{key} is not in @var{table} then nothing is done.
3926 @deffn {Scheme Procedure} hash key size
3927 @deffnx {Scheme Procedure} hashq key size
3928 @deffnx {Scheme Procedure} hashv key size
3929 @deffnx {C Function} scm_hash (key, size)
3930 @deffnx {C Function} scm_hashq (key, size)
3931 @deffnx {C Function} scm_hashv (key, size)
3932 Return a hash value for @var{key}. This is a number in the range
3933 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
3934 table of the given @var{size}.
3936 Note that @code{hashq} and @code{hashv} may use internal addresses of
3937 objects, so if an object is garbage collected and re-created it can
3938 have a different hash value, even when the two are notionally
3939 @code{eq?}. For instance with symbols,
3942 (hashq 'something 123) @result{} 19
3944 (hashq 'something 123) @result{} 62
3947 In normal use this is not a problem, since an object entered into a
3948 hash table won't be garbage collected until removed. It's only if
3949 hashing calculations are somehow separated from normal references that
3950 its lifetime needs to be considered.
3953 @deffn {Scheme Procedure} hash-get-handle table key
3954 @deffnx {Scheme Procedure} hashq-get-handle table key
3955 @deffnx {Scheme Procedure} hashv-get-handle table key
3956 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
3957 @deffnx {C Function} scm_hash_get_handle (table, key)
3958 @deffnx {C Function} scm_hashq_get_handle (table, key)
3959 @deffnx {C Function} scm_hashv_get_handle (table, key)
3960 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
3961 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3962 given hash @var{table}, or @code{#f} if @var{key} is not in
3966 @deffn {Scheme Procedure} hash-create-handle! table key init
3967 @deffnx {Scheme Procedure} hashq-create-handle! table key init
3968 @deffnx {Scheme Procedure} hashv-create-handle! table key init
3969 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
3970 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
3971 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
3972 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
3973 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
3974 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3975 given hash @var{table}. If @var{key} is not in @var{table} then
3976 create an entry for it with @var{init} as the value, and return that
3980 @deffn {Scheme Procedure} hash-map->list proc table
3981 @deffnx {Scheme Procedure} hash-for-each proc table
3982 @deffnx {C Function} scm_hash_map_to_list (proc, table)
3983 @deffnx {C Function} scm_hash_for_each (proc, table)
3984 Apply @var{proc} to the entries in the given hash @var{table}. Each
3985 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
3986 returns a list of the results from these calls, @code{hash-for-each}
3987 discards the results and returns an unspecified value.
3989 Calls are made over the table entries in an unspecified order, and for
3990 @code{hash-map->list} the order of the values in the returned list is
3991 unspecified. Results will be unpredictable if @var{table} is modified
3994 For example the following returns a new alist comprising all the
3995 entries from @code{mytable}, in no particular order.
3998 (hash-map->list cons mytable)
4002 @deffn {Scheme Procedure} hash-for-each-handle proc table
4003 @deffnx {C Function} scm_hash_for_each_handle (proc, table)
4004 Apply @var{proc} to the entries in the given hash @var{table}. Each
4005 call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
4006 @code{(@var{key} . @var{value})} pair. Return an unspecified value.
4008 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
4009 the argument list of @var{proc}.
4012 @deffn {Scheme Procedure} hash-fold proc init table
4013 @deffnx {C Function} scm_hash_fold (proc, init, table)
4014 Accumulate a result by applying @var{proc} to the elements of the
4015 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
4016 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
4017 from the @var{table} and @var{prior-result} is the return from the
4018 previous @var{proc} call. For the first call, @var{prior-result} is
4019 the given @var{init} value.
4021 Calls are made over the table entries in an unspecified order.
4022 Results will be unpredictable if @var{table} is modified while
4023 @code{hash-fold} is running.
4025 For example, the following returns a count of how many keys in
4026 @code{mytable} are strings.
4029 (hash-fold (lambda (key value prior)
4030 (if (string? key) (1+ prior) prior))
4037 @c TeX-master: "guile.texi"