2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
8 @node Compound Data Types
9 @section Compound Data Types
11 This chapter describes Guile's compound data types. By @dfn{compound}
12 we mean that the primary purpose of these data types is to act as
13 containers for other kinds of data (including other compound objects).
14 For instance, a (non-uniform) vector with length 5 is a container that
15 can hold five arbitrary Scheme objects.
17 The various kinds of container object differ from each other in how
18 their memory is allocated, how they are indexed, and how particular
19 values can be looked up within them.
22 * Pairs:: Scheme's basic building block.
23 * Lists:: Special list functions supported by Guile.
24 * Vectors:: One-dimensional arrays of Scheme objects.
25 * Uniform Numeric Vectors:: Vectors with elements of a single numeric type.
26 * Bit Vectors:: Vectors of bits.
27 * Generalized Vectors:: Treating all vector-like things uniformly.
28 * Arrays:: Matrices, etc.
31 * Dictionary Types:: About dictionary types in general.
32 * Association Lists:: List-based dictionaries.
33 * Hash Tables:: Table-based dictionaries.
41 Pairs are used to combine two Scheme objects into one compound object.
42 Hence the name: A pair stores a pair of objects.
44 The data type @dfn{pair} is extremely important in Scheme, just like in
45 any other Lisp dialect. The reason is that pairs are not only used to
46 make two values available as one object, but that pairs are used for
47 constructing lists of values. Because lists are so important in Scheme,
48 they are described in a section of their own (@pxref{Lists}).
50 Pairs can literally get entered in source code or at the REPL, in the
51 so-called @dfn{dotted list} syntax. This syntax consists of an opening
52 parentheses, the first element of the pair, a dot, the second element
53 and a closing parentheses. The following example shows how a pair
54 consisting of the two numbers 1 and 2, and a pair containing the symbols
55 @code{foo} and @code{bar} can be entered. It is very important to write
56 the whitespace before and after the dot, because otherwise the Scheme
57 parser would not be able to figure out where to split the tokens.
64 But beware, if you want to try out these examples, you have to
65 @dfn{quote} the expressions. More information about quotation is
66 available in the section (REFFIXME). The correct way to try these
67 examples is as follows.
78 A new pair is made by calling the procedure @code{cons} with two
79 arguments. Then the argument values are stored into a newly allocated
80 pair, and the pair is returned. The name @code{cons} stands for
81 "construct". Use the procedure @code{pair?} to test whether a
82 given Scheme object is a pair or not.
85 @deffn {Scheme Procedure} cons x y
86 @deffnx {C Function} scm_cons (x, y)
87 Return a newly allocated pair whose car is @var{x} and whose
88 cdr is @var{y}. The pair is guaranteed to be different (in the
89 sense of @code{eq?}) from every previously existing object.
93 @deffn {Scheme Procedure} pair? x
94 @deffnx {C Function} scm_pair_p (x)
95 Return @code{#t} if @var{x} is a pair; otherwise return
99 @deftypefn {C Function} int scm_is_pair (SCM x)
100 Return 1 when @var{x} is a pair; otherwise return 0.
103 The two parts of a pair are traditionally called @dfn{car} and
104 @dfn{cdr}. They can be retrieved with procedures of the same name
105 (@code{car} and @code{cdr}), and can be modified with the procedures
106 @code{set-car!} and @code{set-cdr!}. Since a very common operation in
107 Scheme programs is to access the car of a pair, or the car of the cdr of
108 a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
113 @deffn {Scheme Procedure} car pair
114 @deffnx {Scheme Procedure} cdr pair
115 @deffnx {C Function} scm_car (pair)
116 @deffnx {C Function} scm_cdr (pair)
117 Return the car or the cdr of @var{pair}, respectively.
120 @deffn {Scheme Procedure} cddr pair
121 @deffnx {Scheme Procedure} cdar pair
122 @deffnx {Scheme Procedure} cadr pair
123 @deffnx {Scheme Procedure} caar pair
124 @deffnx {Scheme Procedure} cdddr pair
125 @deffnx {Scheme Procedure} cddar pair
126 @deffnx {Scheme Procedure} cdadr pair
127 @deffnx {Scheme Procedure} cdaar pair
128 @deffnx {Scheme Procedure} caddr pair
129 @deffnx {Scheme Procedure} cadar pair
130 @deffnx {Scheme Procedure} caadr pair
131 @deffnx {Scheme Procedure} caaar pair
132 @deffnx {Scheme Procedure} cddddr pair
133 @deffnx {Scheme Procedure} cdddar pair
134 @deffnx {Scheme Procedure} cddadr pair
135 @deffnx {Scheme Procedure} cddaar pair
136 @deffnx {Scheme Procedure} cdaddr pair
137 @deffnx {Scheme Procedure} cdadar pair
138 @deffnx {Scheme Procedure} cdaadr pair
139 @deffnx {Scheme Procedure} cdaaar pair
140 @deffnx {Scheme Procedure} cadddr pair
141 @deffnx {Scheme Procedure} caddar pair
142 @deffnx {Scheme Procedure} cadadr pair
143 @deffnx {Scheme Procedure} cadaar pair
144 @deffnx {Scheme Procedure} caaddr pair
145 @deffnx {Scheme Procedure} caadar pair
146 @deffnx {Scheme Procedure} caaadr pair
147 @deffnx {Scheme Procedure} caaaar pair
148 @deffnx {C Function} scm_cddr (pair)
149 @deffnx {C Function} scm_cdar (pair)
150 @deffnx {C Function} scm_cadr (pair)
151 @deffnx {C Function} scm_caar (pair)
152 @deffnx {C Function} scm_cdddr (pair)
153 @deffnx {C Function} scm_cddar (pair)
154 @deffnx {C Function} scm_cdadr (pair)
155 @deffnx {C Function} scm_cdaar (pair)
156 @deffnx {C Function} scm_caddr (pair)
157 @deffnx {C Function} scm_cadar (pair)
158 @deffnx {C Function} scm_caadr (pair)
159 @deffnx {C Function} scm_caaar (pair)
160 @deffnx {C Function} scm_cddddr (pair)
161 @deffnx {C Function} scm_cdddar (pair)
162 @deffnx {C Function} scm_cddadr (pair)
163 @deffnx {C Function} scm_cddaar (pair)
164 @deffnx {C Function} scm_cdaddr (pair)
165 @deffnx {C Function} scm_cdadar (pair)
166 @deffnx {C Function} scm_cdaadr (pair)
167 @deffnx {C Function} scm_cdaaar (pair)
168 @deffnx {C Function} scm_cadddr (pair)
169 @deffnx {C Function} scm_caddar (pair)
170 @deffnx {C Function} scm_cadadr (pair)
171 @deffnx {C Function} scm_cadaar (pair)
172 @deffnx {C Function} scm_caaddr (pair)
173 @deffnx {C Function} scm_caadar (pair)
174 @deffnx {C Function} scm_caaadr (pair)
175 @deffnx {C Function} scm_caaaar (pair)
176 These procedures are compositions of @code{car} and @code{cdr}, where
177 for example @code{caddr} could be defined by
180 (define caddr (lambda (x) (car (cdr (cdr x)))))
185 @deffn {Scheme Procedure} set-car! pair value
186 @deffnx {C Function} scm_set_car_x (pair, value)
187 Stores @var{value} in the car field of @var{pair}. The value returned
188 by @code{set-car!} is unspecified.
192 @deffn {Scheme Procedure} set-cdr! pair value
193 @deffnx {C Function} scm_set_cdr_x (pair, value)
194 Stores @var{value} in the cdr field of @var{pair}. The value returned
195 by @code{set-cdr!} is unspecified.
203 A very important data type in Scheme---as well as in all other Lisp
204 dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
205 Scheme does not have a real datatype @dfn{list}. Lists are made up of
206 @dfn{chained pairs}, and only exist by definition---a list is a chain
207 of pairs which looks like a list.}
209 This is the short definition of what a list is:
213 Either the empty list @code{()},
216 or a pair which has a list in its cdr.
219 @c FIXME::martin: Describe the pair chaining in more detail.
221 @c FIXME::martin: What is a proper, what an improper list?
222 @c What is a circular list?
224 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
228 * List Syntax:: Writing literal lists.
229 * List Predicates:: Testing lists.
230 * List Constructors:: Creating new lists.
231 * List Selection:: Selecting from lists, getting their length.
232 * Append/Reverse:: Appending and reversing lists.
233 * List Modification:: Modifying existing lists.
234 * List Searching:: Searching for list elements
235 * List Mapping:: Applying procedures to lists.
239 @subsubsection List Read Syntax
241 The syntax for lists is an opening parentheses, then all the elements of
242 the list (separated by whitespace) and finally a closing
243 parentheses.@footnote{Note that there is no separation character between
244 the list elements, like a comma or a semicolon.}.
247 (1 2 3) ; @r{a list of the numbers 1, 2 and 3}
248 ("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
249 () ; @r{the empty list}
252 The last example needs a bit more explanation. A list with no elements,
253 called the @dfn{empty list}, is special in some ways. It is used for
254 terminating lists by storing it into the cdr of the last pair that makes
255 up a list. An example will clear that up:
266 This example also shows that lists have to be quoted (REFFIXME) when
267 written, because they would otherwise be mistakingly taken as procedure
268 applications (@pxref{Simple Invocation}).
271 @node List Predicates
272 @subsubsection List Predicates
274 Often it is useful to test whether a given Scheme object is a list or
275 not. List-processing procedures could use this information to test
276 whether their input is valid, or they could do different things
277 depending on the datatype of their arguments.
280 @deffn {Scheme Procedure} list? x
281 @deffnx {C Function} scm_list_p (x)
282 Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
285 The predicate @code{null?} is often used in list-processing code to
286 tell whether a given list has run out of elements. That is, a loop
287 somehow deals with the elements of a list until the list satisfies
288 @code{null?}. Then, the algorithm terminates.
291 @deffn {Scheme Procedure} null? x
292 @deffnx {C Function} scm_null_p (x)
293 Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
296 @deftypefn {C Function} int scm_is_null (SCM x)
297 Return 1 when @var{x} is the empty list; otherwise return 0.
301 @node List Constructors
302 @subsubsection List Constructors
304 This section describes the procedures for constructing new lists.
305 @code{list} simply returns a list where the elements are the arguments,
306 @code{cons*} is similar, but the last argument is stored in the cdr of
307 the last pair of the list.
309 @c C Function scm_list(rest) used to be documented here, but it's a
310 @c no-op since it does nothing but return the list the caller must
311 @c have already created.
313 @deffn {Scheme Procedure} list elem1 @dots{} elemN
314 @deffnx {C Function} scm_list_1 (elem1)
315 @deffnx {C Function} scm_list_2 (elem1, elem2)
316 @deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
317 @deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
318 @deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
319 @deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
321 Return a new list containing elements @var{elem1} to @var{elemN}.
323 @code{scm_list_n} takes a variable number of arguments, terminated by
324 the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
325 not included in the list. None of @var{elem1} to @var{elemN} can
326 themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
327 terminate at that point.
330 @c C Function scm_cons_star(arg1,rest) used to be documented here,
331 @c but it's not really a useful interface, since it expects the
332 @c caller to have already consed up all but the first argument
335 @deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
336 Like @code{list}, but the last arg provides the tail of the
337 constructed list, returning @code{(cons @var{arg1} (cons
338 @var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
339 argument. If given one argument, that argument is returned as
340 result. This function is called @code{list*} in some other
341 Schemes and in Common LISP.
344 @deffn {Scheme Procedure} list-copy lst
345 @deffnx {C Function} scm_list_copy (lst)
346 Return a (newly-created) copy of @var{lst}.
349 @deffn {Scheme Procedure} make-list n [init]
350 Create a list containing of @var{n} elements, where each element is
351 initialized to @var{init}. @var{init} defaults to the empty list
352 @code{()} if not given.
355 Note that @code{list-copy} only makes a copy of the pairs which make up
356 the spine of the lists. The list elements are not copied, which means
357 that modifying the elements of the new list also modifies the elements
358 of the old list. On the other hand, applying procedures like
359 @code{set-cdr!} or @code{delv!} to the new list will not alter the old
360 list. If you also need to copy the list elements (making a deep copy),
361 use the procedure @code{copy-tree} (@pxref{Copying}).
364 @subsubsection List Selection
366 These procedures are used to get some information about a list, or to
367 retrieve one or more elements of a list.
370 @deffn {Scheme Procedure} length lst
371 @deffnx {C Function} scm_length (lst)
372 Return the number of elements in list @var{lst}.
375 @deffn {Scheme Procedure} last-pair lst
376 @deffnx {C Function} scm_last_pair (lst)
377 Return the last pair in @var{lst}, signalling an error if
378 @var{lst} is circular.
382 @deffn {Scheme Procedure} list-ref list k
383 @deffnx {C Function} scm_list_ref (list, k)
384 Return the @var{k}th element from @var{list}.
388 @deffn {Scheme Procedure} list-tail lst k
389 @deffnx {Scheme Procedure} list-cdr-ref lst k
390 @deffnx {C Function} scm_list_tail (lst, k)
391 Return the "tail" of @var{lst} beginning with its @var{k}th element.
392 The first element of the list is considered to be element 0.
394 @code{list-tail} and @code{list-cdr-ref} are identical. It may help to
395 think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
396 or returning the results of cdring @var{k} times down @var{lst}.
399 @deffn {Scheme Procedure} list-head lst k
400 @deffnx {C Function} scm_list_head (lst, k)
401 Copy the first @var{k} elements from @var{lst} into a new list, and
406 @subsubsection Append and Reverse
408 @code{append} and @code{append!} are used to concatenate two or more
409 lists in order to form a new list. @code{reverse} and @code{reverse!}
410 return lists with the same elements as their arguments, but in reverse
411 order. The procedure variants with an @code{!} directly modify the
412 pairs which form the list, whereas the other procedures create new
413 pairs. This is why you should be careful when using the side-effecting
417 @deffn {Scheme Procedure} append lst1 @dots{} lstN
418 @deffnx {Scheme Procedure} append! lst1 @dots{} lstN
419 @deffnx {C Function} scm_append (lstlst)
420 @deffnx {C Function} scm_append_x (lstlst)
421 Return a list comprising all the elements of lists @var{lst1} to
425 (append '(x) '(y)) @result{} (x y)
426 (append '(a) '(b c d)) @result{} (a b c d)
427 (append '(a (b)) '((c))) @result{} (a (b) (c))
430 The last argument @var{lstN} may actually be any object; an improper
431 list results if the last argument is not a proper list.
434 (append '(a b) '(c . d)) @result{} (a b c . d)
435 (append '() 'a) @result{} a
438 @code{append} doesn't modify the given lists, but the return may share
439 structure with the final @var{lstN}. @code{append!} modifies the
440 given lists to form its return.
442 For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
443 of the list operands @var{lst1} @dots{} @var{lstN}. That @var{lstlst}
444 itself is not modified or used in the return.
448 @deffn {Scheme Procedure} reverse lst
449 @deffnx {Scheme Procedure} reverse! lst [newtail]
450 @deffnx {C Function} scm_reverse (lst)
451 @deffnx {C Function} scm_reverse_x (lst, newtail)
452 Return a list comprising the elements of @var{lst}, in reverse order.
454 @code{reverse} constructs a new list, @code{reverse!} modifies
455 @var{lst} in constructing its return.
457 For @code{reverse!}, the optional @var{newtail} is appended to to the
458 result. @var{newtail} isn't reversed, it simply becomes the list
459 tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
460 mandatory, but can be @code{SCM_EOL} if no further tail is required.
463 @node List Modification
464 @subsubsection List Modification
466 The following procedures modify an existing list, either by changing
467 elements of the list, or by changing the list structure itself.
469 @deffn {Scheme Procedure} list-set! list k val
470 @deffnx {C Function} scm_list_set_x (list, k, val)
471 Set the @var{k}th element of @var{list} to @var{val}.
474 @deffn {Scheme Procedure} list-cdr-set! list k val
475 @deffnx {C Function} scm_list_cdr_set_x (list, k, val)
476 Set the @var{k}th cdr of @var{list} to @var{val}.
479 @deffn {Scheme Procedure} delq item lst
480 @deffnx {C Function} scm_delq (item, lst)
481 Return a newly-created copy of @var{lst} with elements
482 @code{eq?} to @var{item} removed. This procedure mirrors
483 @code{memq}: @code{delq} compares elements of @var{lst} against
484 @var{item} with @code{eq?}.
487 @deffn {Scheme Procedure} delv item lst
488 @deffnx {C Function} scm_delv (item, lst)
489 Return a newly-created copy of @var{lst} with elements
490 @code{eqv?} to @var{item} removed. This procedure mirrors
491 @code{memv}: @code{delv} compares elements of @var{lst} against
492 @var{item} with @code{eqv?}.
495 @deffn {Scheme Procedure} delete item lst
496 @deffnx {C Function} scm_delete (item, lst)
497 Return a newly-created copy of @var{lst} with elements
498 @code{equal?} to @var{item} removed. This procedure mirrors
499 @code{member}: @code{delete} compares elements of @var{lst}
500 against @var{item} with @code{equal?}.
503 @deffn {Scheme Procedure} delq! item lst
504 @deffnx {Scheme Procedure} delv! item lst
505 @deffnx {Scheme Procedure} delete! item lst
506 @deffnx {C Function} scm_delq_x (item, lst)
507 @deffnx {C Function} scm_delv_x (item, lst)
508 @deffnx {C Function} scm_delete_x (item, lst)
509 These procedures are destructive versions of @code{delq}, @code{delv}
510 and @code{delete}: they modify the pointers in the existing @var{lst}
511 rather than creating a new list. Caveat evaluator: Like other
512 destructive list functions, these functions cannot modify the binding of
513 @var{lst}, and so cannot be used to delete the first element of
514 @var{lst} destructively.
517 @deffn {Scheme Procedure} delq1! item lst
518 @deffnx {C Function} scm_delq1_x (item, lst)
519 Like @code{delq!}, but only deletes the first occurrence of
520 @var{item} from @var{lst}. Tests for equality using
521 @code{eq?}. See also @code{delv1!} and @code{delete1!}.
524 @deffn {Scheme Procedure} delv1! item lst
525 @deffnx {C Function} scm_delv1_x (item, lst)
526 Like @code{delv!}, but only deletes the first occurrence of
527 @var{item} from @var{lst}. Tests for equality using
528 @code{eqv?}. See also @code{delq1!} and @code{delete1!}.
531 @deffn {Scheme Procedure} delete1! item lst
532 @deffnx {C Function} scm_delete1_x (item, lst)
533 Like @code{delete!}, but only deletes the first occurrence of
534 @var{item} from @var{lst}. Tests for equality using
535 @code{equal?}. See also @code{delq1!} and @code{delv1!}.
538 @deffn {Scheme Procedure} filter pred lst
539 @deffnx {Scheme Procedure} filter! pred lst
540 Return a list containing all elements from @var{lst} which satisfy the
541 predicate @var{pred}. The elements in the result list have the same
542 order as in @var{lst}. The order in which @var{pred} is applied to
543 the list elements is not specified.
545 @code{filter!} is allowed, but not required to modify the structure of
549 @subsubsection List Searching
551 The following procedures search lists for particular elements. They use
552 different comparison predicates for comparing list elements with the
553 object to be searched. When they fail, they return @code{#f}, otherwise
554 they return the sublist whose car is equal to the search object, where
555 equality depends on the equality predicate used.
558 @deffn {Scheme Procedure} memq x lst
559 @deffnx {C Function} scm_memq (x, lst)
560 Return the first sublist of @var{lst} whose car is @code{eq?}
561 to @var{x} where the sublists of @var{lst} are the non-empty
562 lists returned by @code{(list-tail @var{lst} @var{k})} for
563 @var{k} less than the length of @var{lst}. If @var{x} does not
564 occur in @var{lst}, then @code{#f} (not the empty list) is
569 @deffn {Scheme Procedure} memv x lst
570 @deffnx {C Function} scm_memv (x, lst)
571 Return the first sublist of @var{lst} whose car is @code{eqv?}
572 to @var{x} where the sublists of @var{lst} are the non-empty
573 lists returned by @code{(list-tail @var{lst} @var{k})} for
574 @var{k} less than the length of @var{lst}. If @var{x} does not
575 occur in @var{lst}, then @code{#f} (not the empty list) is
580 @deffn {Scheme Procedure} member x lst
581 @deffnx {C Function} scm_member (x, lst)
582 Return the first sublist of @var{lst} whose car is
583 @code{equal?} to @var{x} where the sublists of @var{lst} are
584 the non-empty lists returned by @code{(list-tail @var{lst}
585 @var{k})} for @var{k} less than the length of @var{lst}. If
586 @var{x} does not occur in @var{lst}, then @code{#f} (not the
587 empty list) is returned.
592 @subsubsection List Mapping
594 List processing is very convenient in Scheme because the process of
595 iterating over the elements of a list can be highly abstracted. The
596 procedures in this section are the most basic iterating procedures for
597 lists. They take a procedure and one or more lists as arguments, and
598 apply the procedure to each element of the list. They differ in their
602 @c begin (texi-doc-string "guile" "map")
603 @deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
604 @deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
605 @deffnx {C Function} scm_map (proc, arg1, args)
606 Apply @var{proc} to each element of the list @var{arg1} (if only two
607 arguments are given), or to the corresponding elements of the argument
608 lists (if more than two arguments are given). The result(s) of the
609 procedure applications are saved and returned in a list. For
610 @code{map}, the order of procedure applications is not specified,
611 @code{map-in-order} applies the procedure from left to right to the list
616 @c begin (texi-doc-string "guile" "for-each")
617 @deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
618 Like @code{map}, but the procedure is always applied from left to right,
619 and the result(s) of the procedure applications are thrown away. The
620 return value is not specified.
628 Vectors are sequences of Scheme objects. Unlike lists, the length of a
629 vector, once the vector is created, cannot be changed. The advantage of
630 vectors over lists is that the time required to access one element of a vector
631 given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
632 is constant, whereas lists have an access time linear to the position of the
633 accessed element in the list.
635 Vectors can contain any kind of Scheme object; it is even possible to
636 have different types of objects in the same vector. For vectors
637 containing vectors, you may wish to use arrays, instead. Note, too,
638 that vectors are the special case of one dimensional non-uniform arrays
639 and that most array procedures operate happily on vectors
643 * Vector Syntax:: Read syntax for vectors.
644 * Vector Creation:: Dynamic vector creation and validation.
645 * Vector Accessors:: Accessing and modifying vector contents.
646 * Vector Accessing from C:: Ways to work with vectors from C.
651 @subsubsection Read Syntax for Vectors
653 Vectors can literally be entered in source code, just like strings,
654 characters or some of the other data types. The read syntax for vectors
655 is as follows: A sharp sign (@code{#}), followed by an opening
656 parentheses, all elements of the vector in their respective read syntax,
657 and finally a closing parentheses. The following are examples of the
658 read syntax for vectors; where the first vector only contains numbers
659 and the second three different object types: a string, a symbol and a
660 number in hexadecimal notation.
664 #("Hello" foo #xdeadbeef)
667 Like lists, vectors have to be quoted:
670 '#(a b c) @result{} #(a b c)
673 @node Vector Creation
674 @subsubsection Dynamic Vector Creation and Validation
676 Instead of creating a vector implicitly by using the read syntax just
677 described, you can create a vector dynamically by calling one of the
678 @code{vector} and @code{list->vector} primitives with the list of Scheme
679 values that you want to place into a vector. The size of the vector
680 thus created is determined implicitly by the number of arguments given.
683 @rnindex list->vector
684 @deffn {Scheme Procedure} vector . l
685 @deffnx {Scheme Procedure} list->vector l
686 @deffnx {C Function} scm_vector (l)
687 Return a newly allocated vector composed of the
688 given arguments. Analogous to @code{list}.
691 (vector 'a 'b 'c) @result{} #(a b c)
695 The inverse operation is @code{vector->list}:
697 @rnindex vector->list
698 @deffn {Scheme Procedure} vector->list v
699 @deffnx {C Function} scm_vector_to_list (v)
700 Return a newly allocated list composed of the elements of @var{v}.
703 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
704 (list->vector '(dididit dah)) @result{} #(dididit dah)
708 To allocate a vector with an explicitly specified size, use
709 @code{make-vector}. With this primitive you can also specify an initial
710 value for the vector elements (the same value for all elements, that
714 @deffn {Scheme Procedure} make-vector len [fill]
715 @deffnx {C Function} scm_make_vector (len, fill)
716 Return a newly allocated vector of @var{len} elements. If a
717 second argument is given, then each position is initialized to
718 @var{fill}. Otherwise the initial contents of each position is
722 @deftypefn {C Function} SCM scm_c_make_vector (size_t k, SCM fill)
723 Like @code{scm_make_vector}, but the length is given as a @code{size_t}.
726 To check whether an arbitrary Scheme value @emph{is} a vector, use the
727 @code{vector?} primitive:
730 @deffn {Scheme Procedure} vector? obj
731 @deffnx {C Function} scm_vector_p (obj)
732 Return @code{#t} if @var{obj} is a vector, otherwise return
736 @deftypefn {C Function} int scm_is_vector (SCM obj)
737 Return non-zero when @var{obj} is a vector, otherwise return
741 @node Vector Accessors
742 @subsubsection Accessing and Modifying Vector Contents
744 @code{vector-length} and @code{vector-ref} return information about a
745 given vector, respectively its size and the elements that are contained
748 @rnindex vector-length
749 @deffn {Scheme Procedure} vector-length vector
750 @deffnx {C Function} scm_vector_length vector
751 Return the number of elements in @var{vector} as an exact integer.
754 @deftypefn {C Function} size_t scm_c_vector_length (SCM v)
755 Return the number of elements in @var{vector} as a @code{size_t}.
759 @deffn {Scheme Procedure} vector-ref vector k
760 @deffnx {C Function} scm_vector_ref vector k
761 Return the contents of position @var{k} of @var{vector}.
762 @var{k} must be a valid index of @var{vector}.
764 (vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
765 (vector-ref '#(1 1 2 3 5 8 13 21)
766 (let ((i (round (* 2 (acos -1)))))
773 @deftypefn {C Function} SCM scm_c_vector_ref (SCM v, size_t k)
774 Return the contents of position @var{k} (a @code{size_t}) of
778 A vector created by one of the dynamic vector constructor procedures
779 (@pxref{Vector Creation}) can be modified using the following
782 @emph{NOTE:} According to R5RS, it is an error to use any of these
783 procedures on a literally read vector, because such vectors should be
784 considered as constants. Currently, however, Guile does not detect this
788 @deffn {Scheme Procedure} vector-set! vector k obj
789 @deffnx {C Function} scm_vector_set_x vector k obj
790 Store @var{obj} in position @var{k} of @var{vector}.
791 @var{k} must be a valid index of @var{vector}.
792 The value returned by @samp{vector-set!} is unspecified.
794 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
795 (vector-set! vec 1 '("Sue" "Sue"))
796 vec) @result{} #(0 ("Sue" "Sue") "Anna")
800 @deftypefn {C Function} void scm_c_vector_set_x (SCM v, size_t k, SCM obj)
801 Store @var{obj} in position @var{k} (a @code{size_t}) of @var{v}.
804 @rnindex vector-fill!
805 @deffn {Scheme Procedure} vector-fill! v fill
806 @deffnx {C Function} scm_vector_fill_x (v, fill)
807 Store @var{fill} in every position of @var{vector}. The value
808 returned by @code{vector-fill!} is unspecified.
811 @deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
812 @deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
813 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
814 to @var{vec2} starting at position @var{start2}. @var{start1} and
815 @var{start2} are inclusive indices; @var{end1} is exclusive.
817 @code{vector-move-left!} copies elements in leftmost order.
818 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
819 same vector, @code{vector-move-left!} is usually appropriate when
820 @var{start1} is greater than @var{start2}.
823 @deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
824 @deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
825 Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
826 to @var{vec2} starting at position @var{start2}. @var{start1} and
827 @var{start2} are inclusive indices; @var{end1} is exclusive.
829 @code{vector-move-right!} copies elements in rightmost order.
830 Therefore, in the case where @var{vec1} and @var{vec2} refer to the
831 same vector, @code{vector-move-right!} is usually appropriate when
832 @var{start1} is less than @var{start2}.
835 @node Vector Accessing from C
836 @subsubsection Vector Accessing from C
838 A vector can be read and modified from C with the functions
839 @code{scm_c_vector_ref} and @code{scm_c_vector_set_x}, for example. In
840 addition to these functions, there are two more ways to access vectors
841 from C that might be more efficient in certain situations: you can
842 restrict yourself to @dfn{simple vectors} and then use the very fast
843 @emph{simple vector macros}; or you can use the very general framework
844 for accessing all kinds of arrays (@pxref{Accessing Arrays from C}),
845 which is more verbose, but can deal efficiently with all kinds of
846 vectors (and arrays). For vectors, you can use the
847 @code{scm_vector_elements} and @code{scm_vector_writable_elements}
848 functions as shortcuts.
850 @deftypefn {C Function} int scm_is_simple_vector (SCM obj)
851 Return non-zero if @var{obj} is a simple vector, else return zero. A
852 simple vector is a vector that can be used with the @code{SCM_SIMPLE_*}
855 The following functions are guaranteed to return simple vectors:
856 @code{scm_make_vector}, @code{scm_c_make_vector}, @code{scm_vector},
857 @code{scm_list_to_vector}.
860 @deftypefn {C Macro} size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)
861 Evaluates to the length of the simple vector @var{vec}. No type
865 @deftypefn {C Macro} SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)
866 Evaluates to the element at position @var{idx} in the simple vector
867 @var{vec}. No type or range checking is done.
870 @deftypefn {C Macro} void SCM_SIMPLE_VECTOR_SET_X (SCM vec, size_t idx, SCM val)
871 Sets the element at position @var{idx} in the simple vector
872 @var{vec} to @var{val}. No type or range checking is done.
875 @deftypefn {C Function} {const SCM *} scm_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
876 Acquire a handle for the vector @var{vec} and return a pointer to the
877 elements of it. This pointer can only be used to read the elements of
878 @var{vec}. When @var{vec} is not a vector, an error is signaled. The
879 handle mustr eventually be released with
880 @code{scm_array_handle_release}.
882 The variables pointed to by @var{lenp} and @var{incp} are filled with
883 the number of elements of the vector and the increment between elements,
884 respectively. Note that the increment can well be negative.
886 The following example shows the typical way to use this function. It
887 creates a list of all elements of @code{vec} (in reverse order).
890 scm_t_array_handle handle;
896 elt = scm_vector_elements (vec, &handle, &len, &inc);
898 for (i = 0; i < len; i++, elt += inc)
899 list = scm_cons (*elt, list);
900 scm_array_handle_release (&handle);
905 @deftypefn {C Function} {SCM *} scm_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
906 Like @code{scm_vector_elements} but the pointer can be used to modify
909 The following example shows the typical way to use this function. It
910 fills a vector with @code{#t}.
913 scm_t_array_handle handle;
918 elt = scm_vector_elements (vec, &handle, &len, &inc);
919 for (i = 0; i < len; i++, elt += inc)
921 scm_array_handle_release (&handle);
926 @node Uniform Numeric Vectors
927 @subsection Uniform Numeric Vectors
929 A uniform numeric vector is a vector whose elements are all of a single
930 numeric type. Guile offers uniform numeric vectors for signed and
931 unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
932 floating point values, and complex floating-point numbers of these two
935 Strings could be regarded as uniform vectors of characters,
936 @xref{Strings}. Likewise, bit vectors could be regarded as uniform
937 vectors of bits, @xref{Bit Vectors}. Both are sufficiently different
938 from uniform numeric vectors that the procedures described here do not
939 apply to these two data types. However, both strings and bit vectors
940 are generalized vectors, @xref{Generalized Vectors}, and arrays,
943 Uniform numeric vectors are the special case of one dimensional uniform
946 Uniform numeric vectors can be useful since they consume less memory
947 than the non-uniform, general vectors. Also, since the types they can
948 store correspond directly to C types, it is easier to work with them
949 efficiently on a low level. Consider image processing as an example,
950 where you want to apply a filter to some image. While you could store
951 the pixels of an image in a general vector and write a general
952 convolution function, things are much more efficient with uniform
953 vectors: the convolution function knows that all pixels are unsigned
954 8-bit values (say), and can use a very tight inner loop.
956 That is, when it is written in C. Functions for efficiently working
957 with uniform numeric vectors from C are listed at the end of this
960 Procedures similar to the vector procedures (@pxref{Vectors}) are
961 provided for handling these uniform vectors, but they are distinct
962 datatypes and the two cannot be inter-mixed. If you want to work
963 primarily with uniform numeric vectors, but want to offer support for
964 general vectors as a convenience, you can use one of the
965 @code{scm_any_to_*} functions. They will coerce lists and vectors to
966 the given type of uniform vector. Alternatively, you can write two
967 versions of your code: one that is fast and works only with uniform
968 numeric vectors, and one that works with any kind of vector but is
971 One set of the procedures listed below is a generic one: it works with
972 all types of uniform numeric vectors. In addition to that, there is a
973 set of procedures for each type that only works with that type. Unless
974 you really need to the generality of the first set, it is best to use
975 the more specific functions. They might not be that much faster, but
976 their use can serve as a kind of declaration and makes it easier to
979 The generic set of procedures uses @code{uniform} in its names, the
980 specific ones use the tag from the following table.
984 unsigned 8-bit integers
987 signed 8-bit integers
990 unsigned 16-bit integers
993 signed 16-bit integers
996 unsigned 32-bit integers
999 signed 32-bit integers
1002 unsigned 64-bit integers
1005 signed 64-bit integers
1008 the C type @code{float}
1011 the C type @code{double}
1014 complex numbers in rectangular form with the real and imaginary part
1015 being a @code{float}
1018 complex numbers in rectangular form with the real and imaginary part
1019 being a @code{double}
1023 The external representation (ie.@: read syntax) for these vectors is
1024 similar to normal Scheme vectors, but with an additional tag from the
1025 tabel above indiciating the vector's type. For example,
1032 Note that the read syntax for floating-point here conflicts with
1033 @code{#f} for false. In Standard Scheme one can write @code{(1 #f3)}
1034 for a three element list @code{(1 #f 3)}, but for Guile @code{(1 #f3)}
1035 is invalid. @code{(1 #f 3)} is almost certainly what one should write
1036 anyway to make the intention clear, so this is rarely a problem.
1038 @deffn {Scheme Procedure} uniform-vector? obj
1039 @deffnx {Scheme Procedure} u8vector? obj
1040 @deffnx {Scheme Procedure} s8vector? obj
1041 @deffnx {Scheme Procedure} u16vector? obj
1042 @deffnx {Scheme Procedure} s16vector? obj
1043 @deffnx {Scheme Procedure} u32vector? obj
1044 @deffnx {Scheme Procedure} s32vector? obj
1045 @deffnx {Scheme Procedure} u64vector? obj
1046 @deffnx {Scheme Procedure} s64vector? obj
1047 @deffnx {Scheme Procedure} f32vector? obj
1048 @deffnx {Scheme Procedure} f64vector? obj
1049 @deffnx {Scheme Procedure} c32vector? obj
1050 @deffnx {Scheme Procedure} c64vector? obj
1051 @deffnx {C Function} scm_uniform_vector_p obj
1052 @deffnx {C Function} scm_u8vector_p obj
1053 @deffnx {C Function} scm_s8vector_p obj
1054 @deffnx {C Function} scm_u16vector_p obj
1055 @deffnx {C Function} scm_s16vector_p obj
1056 @deffnx {C Function} scm_u32vector_p obj
1057 @deffnx {C Function} scm_s32vector_p obj
1058 @deffnx {C Function} scm_u64vector_p obj
1059 @deffnx {C Function} scm_s64vector_p obj
1060 @deffnx {C Function} scm_f32vector_p obj
1061 @deffnx {C Function} scm_f64vector_p obj
1062 @deffnx {C Function} scm_c32vector_p obj
1063 @deffnx {C Function} scm_c64vector_p obj
1064 Return @code{#t} if @var{obj} is a homogeneous numeric vector of the
1068 @deffn {Scheme Procedure} make-u8vector n [value]
1069 @deffnx {Scheme Procedure} make-s8vector n [value]
1070 @deffnx {Scheme Procedure} make-u16vector n [value]
1071 @deffnx {Scheme Procedure} make-s16vector n [value]
1072 @deffnx {Scheme Procedure} make-u32vector n [value]
1073 @deffnx {Scheme Procedure} make-s32vector n [value]
1074 @deffnx {Scheme Procedure} make-u64vector n [value]
1075 @deffnx {Scheme Procedure} make-s64vector n [value]
1076 @deffnx {Scheme Procedure} make-f32vector n [value]
1077 @deffnx {Scheme Procedure} make-f64vector n [value]
1078 @deffnx {Scheme Procedure} make-c32vector n [value]
1079 @deffnx {Scheme Procedure} make-c64vector n [value]
1080 @deffnx {C Function} scm_make_u8vector n [value]
1081 @deffnx {C Function} scm_make_s8vector n [value]
1082 @deffnx {C Function} scm_make_u16vector n [value]
1083 @deffnx {C Function} scm_make_s16vector n [value]
1084 @deffnx {C Function} scm_make_u32vector n [value]
1085 @deffnx {C Function} scm_make_s32vector n [value]
1086 @deffnx {C Function} scm_make_u64vector n [value]
1087 @deffnx {C Function} scm_make_s64vector n [value]
1088 @deffnx {C Function} scm_make_f32vector n [value]
1089 @deffnx {C Function} scm_make_f64vector n [value]
1090 @deffnx {C Function} scm_make_c32vector n [value]
1091 @deffnx {C Function} scm_make_c64vector n [value]
1092 Return a newly allocated homogeneous numeric vector holding @var{n}
1093 elements of the indicated type. If @var{value} is given, the vector
1094 is initialized with that value, otherwise the contents are
1098 @deffn {Scheme Procedure} u8vector value @dots{}
1099 @deffnx {Scheme Procedure} s8vector value @dots{}
1100 @deffnx {Scheme Procedure} u16vector value @dots{}
1101 @deffnx {Scheme Procedure} s16vector value @dots{}
1102 @deffnx {Scheme Procedure} u32vector value @dots{}
1103 @deffnx {Scheme Procedure} s32vector value @dots{}
1104 @deffnx {Scheme Procedure} u64vector value @dots{}
1105 @deffnx {Scheme Procedure} s64vector value @dots{}
1106 @deffnx {Scheme Procedure} f32vector value @dots{}
1107 @deffnx {Scheme Procedure} f64vector value @dots{}
1108 @deffnx {Scheme Procedure} c32vector value @dots{}
1109 @deffnx {Scheme Procedure} c64vector value @dots{}
1110 @deffnx {C Function} scm_u8vector values
1111 @deffnx {C Function} scm_s8vector values
1112 @deffnx {C Function} scm_u16vector values
1113 @deffnx {C Function} scm_s16vector values
1114 @deffnx {C Function} scm_u32vector values
1115 @deffnx {C Function} scm_s32vector values
1116 @deffnx {C Function} scm_u64vector values
1117 @deffnx {C Function} scm_s64vector values
1118 @deffnx {C Function} scm_f32vector values
1119 @deffnx {C Function} scm_f64vector values
1120 @deffnx {C Function} scm_c32vector values
1121 @deffnx {C Function} scm_c64vector values
1122 Return a newly allocated homogeneous numeric vector of the indicated
1123 type, holding the given parameter @var{value}s. The vector length is
1124 the number of parameters given.
1127 @deffn {Scheme Procedure} uniform-vector-length vec
1128 @deffnx {Scheme Procedure} u8vector-length vec
1129 @deffnx {Scheme Procedure} s8vector-length vec
1130 @deffnx {Scheme Procedure} u16vector-length vec
1131 @deffnx {Scheme Procedure} s16vector-length vec
1132 @deffnx {Scheme Procedure} u32vector-length vec
1133 @deffnx {Scheme Procedure} s32vector-length vec
1134 @deffnx {Scheme Procedure} u64vector-length vec
1135 @deffnx {Scheme Procedure} s64vector-length vec
1136 @deffnx {Scheme Procedure} f32vector-length vec
1137 @deffnx {Scheme Procedure} f64vector-length vec
1138 @deffnx {Scheme Procedure} c32vector-length vec
1139 @deffnx {Scheme Procedure} c64vector-length vec
1140 @deffnx {C Function} scm_uniform_vector_length vec
1141 @deffnx {C Function} scm_u8vector_length vec
1142 @deffnx {C Function} scm_s8vector_length vec
1143 @deffnx {C Function} scm_u16vector_length vec
1144 @deffnx {C Function} scm_s16vector_length vec
1145 @deffnx {C Function} scm_u32vector_length vec
1146 @deffnx {C Function} scm_s32vector_length vec
1147 @deffnx {C Function} scm_u64vector_length vec
1148 @deffnx {C Function} scm_s64vector_length vec
1149 @deffnx {C Function} scm_f32vector_length vec
1150 @deffnx {C Function} scm_f64vector_length vec
1151 @deffnx {C Function} scm_c32vector_length vec
1152 @deffnx {C Function} scm_c64vector_length vec
1153 Return the number of elements in @var{vec}.
1156 @deffn {Scheme Procedure} uniform-vector-ref vec i
1157 @deffnx {Scheme Procedure} u8vector-ref vec i
1158 @deffnx {Scheme Procedure} s8vector-ref vec i
1159 @deffnx {Scheme Procedure} u16vector-ref vec i
1160 @deffnx {Scheme Procedure} s16vector-ref vec i
1161 @deffnx {Scheme Procedure} u32vector-ref vec i
1162 @deffnx {Scheme Procedure} s32vector-ref vec i
1163 @deffnx {Scheme Procedure} u64vector-ref vec i
1164 @deffnx {Scheme Procedure} s64vector-ref vec i
1165 @deffnx {Scheme Procedure} f32vector-ref vec i
1166 @deffnx {Scheme Procedure} f64vector-ref vec i
1167 @deffnx {Scheme Procedure} c32vector-ref vec i
1168 @deffnx {Scheme Procedure} c64vector-ref vec i
1169 @deffnx {C Function} scm_uniform_vector_ref vec i
1170 @deffnx {C Function} scm_u8vector_ref vec i
1171 @deffnx {C Function} scm_s8vector_ref vec i
1172 @deffnx {C Function} scm_u16vector_ref vec i
1173 @deffnx {C Function} scm_s16vector_ref vec i
1174 @deffnx {C Function} scm_u32vector_ref vec i
1175 @deffnx {C Function} scm_s32vector_ref vec i
1176 @deffnx {C Function} scm_u64vector_ref vec i
1177 @deffnx {C Function} scm_s64vector_ref vec i
1178 @deffnx {C Function} scm_f32vector_ref vec i
1179 @deffnx {C Function} scm_f64vector_ref vec i
1180 @deffnx {C Function} scm_c32vector_ref vec i
1181 @deffnx {C Function} scm_c64vector_ref vec i
1182 Return the element at index @var{i} in @var{vec}. The first element
1183 in @var{vec} is index 0.
1186 @deffn {Scheme Procedure} uniform-vector-set! vec i value
1187 @deffnx {Scheme Procedure} u8vector-set! vec i value
1188 @deffnx {Scheme Procedure} s8vector-set! vec i value
1189 @deffnx {Scheme Procedure} u16vector-set! vec i value
1190 @deffnx {Scheme Procedure} s16vector-set! vec i value
1191 @deffnx {Scheme Procedure} u32vector-set! vec i value
1192 @deffnx {Scheme Procedure} s32vector-set! vec i value
1193 @deffnx {Scheme Procedure} u64vector-set! vec i value
1194 @deffnx {Scheme Procedure} s64vector-set! vec i value
1195 @deffnx {Scheme Procedure} f32vector-set! vec i value
1196 @deffnx {Scheme Procedure} f64vector-set! vec i value
1197 @deffnx {Scheme Procedure} c32vector-set! vec i value
1198 @deffnx {Scheme Procedure} c64vector-set! vec i value
1199 @deffnx {C Function} scm_uniform_vector_set_x vec i value
1200 @deffnx {C Function} scm_u8vector_set_x vec i value
1201 @deffnx {C Function} scm_s8vector_set_x vec i value
1202 @deffnx {C Function} scm_u16vector_set_x vec i value
1203 @deffnx {C Function} scm_s16vector_set_x vec i value
1204 @deffnx {C Function} scm_u32vector_set_x vec i value
1205 @deffnx {C Function} scm_s32vector_set_x vec i value
1206 @deffnx {C Function} scm_u64vector_set_x vec i value
1207 @deffnx {C Function} scm_s64vector_set_x vec i value
1208 @deffnx {C Function} scm_f32vector_set_x vec i value
1209 @deffnx {C Function} scm_f64vector_set_x vec i value
1210 @deffnx {C Function} scm_c32vector_set_x vec i value
1211 @deffnx {C Function} scm_c64vector_set_x vec i value
1212 Set the element at index @var{i} in @var{vec} to @var{value}. The
1213 first element in @var{vec} is index 0. The return value is
1217 @deffn {Scheme Procedure} uniform-vector->list vec
1218 @deffnx {Scheme Procedure} u8vector->list vec
1219 @deffnx {Scheme Procedure} s8vector->list vec
1220 @deffnx {Scheme Procedure} u16vector->list vec
1221 @deffnx {Scheme Procedure} s16vector->list vec
1222 @deffnx {Scheme Procedure} u32vector->list vec
1223 @deffnx {Scheme Procedure} s32vector->list vec
1224 @deffnx {Scheme Procedure} u64vector->list vec
1225 @deffnx {Scheme Procedure} s64vector->list vec
1226 @deffnx {Scheme Procedure} f32vector->list vec
1227 @deffnx {Scheme Procedure} f64vector->list vec
1228 @deffnx {Scheme Procedure} c32vector->list vec
1229 @deffnx {Scheme Procedure} c64vector->list vec
1230 @deffnx {C Function} scm_uniform_vector_to_list vec
1231 @deffnx {C Function} scm_u8vector_to_list vec
1232 @deffnx {C Function} scm_s8vector_to_list vec
1233 @deffnx {C Function} scm_u16vector_to_list vec
1234 @deffnx {C Function} scm_s16vector_to_list vec
1235 @deffnx {C Function} scm_u32vector_to_list vec
1236 @deffnx {C Function} scm_s32vector_to_list vec
1237 @deffnx {C Function} scm_u64vector_to_list vec
1238 @deffnx {C Function} scm_s64vector_to_list vec
1239 @deffnx {C Function} scm_f32vector_to_list vec
1240 @deffnx {C Function} scm_f64vector_to_list vec
1241 @deffnx {C Function} scm_c32vector_to_list vec
1242 @deffnx {C Function} scm_c64vector_to_list vec
1243 Return a newly allocated list holding all elements of @var{vec}.
1246 @deffn {Scheme Procedure} list->u8vector lst
1247 @deffnx {Scheme Procedure} list->s8vector lst
1248 @deffnx {Scheme Procedure} list->u16vector lst
1249 @deffnx {Scheme Procedure} list->s16vector lst
1250 @deffnx {Scheme Procedure} list->u32vector lst
1251 @deffnx {Scheme Procedure} list->s32vector lst
1252 @deffnx {Scheme Procedure} list->u64vector lst
1253 @deffnx {Scheme Procedure} list->s64vector lst
1254 @deffnx {Scheme Procedure} list->f32vector lst
1255 @deffnx {Scheme Procedure} list->f64vector lst
1256 @deffnx {Scheme Procedure} list->c32vector lst
1257 @deffnx {Scheme Procedure} list->c64vector lst
1258 @deffnx {C Function} scm_list_to_u8vector lst
1259 @deffnx {C Function} scm_list_to_s8vector lst
1260 @deffnx {C Function} scm_list_to_u16vector lst
1261 @deffnx {C Function} scm_list_to_s16vector lst
1262 @deffnx {C Function} scm_list_to_u32vector lst
1263 @deffnx {C Function} scm_list_to_s32vector lst
1264 @deffnx {C Function} scm_list_to_u64vector lst
1265 @deffnx {C Function} scm_list_to_s64vector lst
1266 @deffnx {C Function} scm_list_to_f32vector lst
1267 @deffnx {C Function} scm_list_to_f64vector lst
1268 @deffnx {C Function} scm_list_to_c32vector lst
1269 @deffnx {C Function} scm_list_to_c64vector lst
1270 Return a newly allocated homogeneous numeric vector of the indicated type,
1271 initialized with the elements of the list @var{lst}.
1274 @deffn {Scheme Procedure} any->u8vector obj
1275 @deffnx {Scheme Procedure} any->s8vector obj
1276 @deffnx {Scheme Procedure} any->u16vector obj
1277 @deffnx {Scheme Procedure} any->s16vector obj
1278 @deffnx {Scheme Procedure} any->u32vector obj
1279 @deffnx {Scheme Procedure} any->s32vector obj
1280 @deffnx {Scheme Procedure} any->u64vector obj
1281 @deffnx {Scheme Procedure} any->s64vector obj
1282 @deffnx {Scheme Procedure} any->f32vector obj
1283 @deffnx {Scheme Procedure} any->f64vector obj
1284 @deffnx {Scheme Procedure} any->c32vector obj
1285 @deffnx {Scheme Procedure} any->c64vector obj
1286 @deffnx {C Function} scm_any_to_u8vector obj
1287 @deffnx {C Function} scm_any_to_s8vector obj
1288 @deffnx {C Function} scm_any_to_u16vector obj
1289 @deffnx {C Function} scm_any_to_s16vector obj
1290 @deffnx {C Function} scm_any_to_u32vector obj
1291 @deffnx {C Function} scm_any_to_s32vector obj
1292 @deffnx {C Function} scm_any_to_u64vector obj
1293 @deffnx {C Function} scm_any_to_s64vector obj
1294 @deffnx {C Function} scm_any_to_f32vector obj
1295 @deffnx {C Function} scm_any_to_f64vector obj
1296 @deffnx {C Function} scm_any_to_c32vector obj
1297 @deffnx {C Function} scm_any_to_c64vector obj
1298 Return a (maybe newly allocated) uniform numeric vector of the indicated
1299 type, initialized with the elements of @var{obj}, which must be a list,
1300 a vector, or a uniform vector. When @var{obj} is already a suitable
1301 uniform numeric vector, it is returned unchanged.
1304 @deftypefn {C Function} int scm_is_uniform_vector (SCM uvec)
1305 Return non-zero when @var{uvec} is a uniform numeric vector, zero
1309 @deftypefn {C Function} SCM scm_take_u8vector (const scm_t_uint8 *data, size_t len)
1310 @deftypefnx {C Function} SCM scm_take_s8vector (const scm_t_int8 *data, size_t len)
1311 @deftypefnx {C Function} SCM scm_take_u16vector (const scm_t_uint16 *data, size_t len)
1312 @deftypefnx {C Function} SCM scm_take_s168vector (const scm_t_int16 *data, size_t len)
1313 @deftypefnx {C Function} SCM scm_take_u32vector (const scm_t_uint32 *data, size_t len)
1314 @deftypefnx {C Function} SCM scm_take_s328vector (const scm_t_int32 *data, size_t len)
1315 @deftypefnx {C Function} SCM scm_take_u64vector (const scm_t_uint64 *data, size_t len)
1316 @deftypefnx {C Function} SCM scm_take_s64vector (const scm_t_int64 *data, size_t len)
1317 @deftypefnx {C Function} SCM scm_take_f32vector (const float *data, size_t len)
1318 @deftypefnx {C Function} SCM scm_take_f64vector (const double *data, size_t len)
1319 @deftypefnx {C Function} SCM scm_take_c32vector (const float *data, size_t len)
1320 @deftypefnx {C Function} SCM scm_take_c64vector (const double *data, size_t len)
1321 Return a new uniform numeric vector of the indicated type and length
1322 that uses the memory pointed to by @var{data} to store its elements.
1323 This memory will eventually be freed with @code{free}. The argument
1324 @var{len} specifies the number of elements in @var{data}, not its size
1327 The @code{c32} and @code{c64} variants take a pointer to a C array of
1328 @code{float}s or @code{double}s. The real parts of the complex numbers
1329 are at even indices in that array, the corresponding imaginary parts are
1330 at the following odd index.
1333 @deftypefn {C Function} size_t scm_c_uniform_vector_length (SCM uvec)
1334 Return the number of elements of @var{uvec} as a @code{size_t}.
1337 @deftypefn {C Function} {const void *} scm_uniform_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1338 @deftypefnx {C Function} {const scm_t_uint8 *} scm_u8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1339 @deftypefnx {C Function} {const scm_t_int8 *} scm_s8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1340 @deftypefnx {C Function} {const scm_t_uint16 *} scm_u16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1341 @deftypefnx {C Function} {const scm_t_int16 *} scm_s16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1342 @deftypefnx {C Function} {const scm_t_uint32 *} scm_u32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1343 @deftypefnx {C Function} {const scm_t_int32 *} scm_s32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1344 @deftypefnx {C Function} {const scm_t_uint64 *} scm_u64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1345 @deftypefnx {C Function} {const scm_t_int64 *} scm_s64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1346 @deftypefnx {C Function} {const float *} scm_f23vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1347 @deftypefnx {C Function} {const double *} scm_f64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1348 @deftypefnx {C Function} {const float *} scm_c32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1349 @deftypefnx {C Function} {const double *} scm_c64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1350 Like @code{scm_vector_elements} (which see), but returns a pointer to
1351 the elements of a uniform numeric vector of the indicated kind.
1354 @deftypefn {C Function} {void *} scm_uniform_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1355 @deftypefnx {C Function} {scm_t_uint8 *} scm_u8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1356 @deftypefnx {C Function} {scm_t_int8 *} scm_s8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1357 @deftypefnx {C Function} {scm_t_uint16 *} scm_u16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1358 @deftypefnx {C Function} {scm_t_int16 *} scm_s16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1359 @deftypefnx {C Function} {scm_t_uint32 *} scm_u32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1360 @deftypefnx {C Function} {scm_t_int32 *} scm_s32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1361 @deftypefnx {C Function} {scm_t_uint64 *} scm_u64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1362 @deftypefnx {C Function} {scm_t_int64 *} scm_s64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1363 @deftypefnx {C Function} {float *} scm_f23vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1364 @deftypefnx {C Function} {double *} scm_f64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1365 @deftypefnx {C Function} {float *} scm_c32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1366 @deftypefnx {C Function} {double *} scm_c64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1367 Like @code{scm_vector_writable_elements} (which see), but returns a
1368 pointer to the elements of a uniform numeric vector of the indicated kind.
1372 @subsection Bit Vectors
1375 Bit vectors are zero-origin, one-dimensional arrays of booleans. They
1376 are displayed as a sequence of @code{0}s and @code{1}s prefixed by
1380 (make-bitvector 8 #f) @result{}
1384 Bit vectors are are also generalized vectors, @xref{Generalized
1385 Vectors}, and can thus be used with the array procedures, @xref{Arrays}.
1386 Bit vectors are the special case of one dimensional bit arrays.
1388 @deffn {Scheme Procedure} bitvector? obj
1389 @deffnx {C Function} scm_bitvector_p (obj)
1390 Return @code{#t} when @var{obj} is a bitvector, else
1394 @deftypefn {C Function} int scm_is_bitvector (SCM obj)
1395 Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
1398 @deffn {Scheme Procedure} make-bitvector len [fill]
1399 @deffnx {C Function} scm_make_bitvector (len, fill)
1400 Create a new bitvector of length @var{len} and
1401 optionally initialize all elements to @var{fill}.
1404 @deftypefn {C Function} SCM scm_c_make_bitvector (size_t len, SCM fill)
1405 Like @code{scm_make_bitvector}, but the length is given as a
1409 @deffn {Scheme Procedure} bitvector . bits
1410 @deffnx {C Function} scm_bitvector (bits)
1411 Create a new bitvector with the arguments as elements.
1414 @deffn {Scheme Procedure} bitvector-length vec
1415 @deffnx {C Function} scm_bitvector_length (vec)
1416 Return the length of the bitvector @var{vec}.
1419 @deftypefn {C Function} size_t scm_c_bitvector_length (SCM vec)
1420 Like @code{scm_bitvector_length}, but the length is returned as a
1424 @deffn {Scheme Procedure} bitvector-ref vec idx
1425 @deffnx {C Function} scm_bitvector_ref (vec, idx)
1426 Return the element at index @var{idx} of the bitvector
1430 @deftypefn {C Function} SCM scm_c_bitvector_ref (SCM obj, size_t idx)
1431 Return the element at index @var{idx} of the bitvector
1435 @deffn {Scheme Procedure} bitvector-set! vec idx val
1436 @deffnx {C Function} scm_bitvector_set_x (vec, idx, val)
1437 Set the element at index @var{idx} of the bitvector
1438 @var{vec} when @var{val} is true, else clear it.
1441 @deftypefn {C Function} SCM scm_c_bitvector_set_x (SCM obj, size_t idx, SCM val)
1442 Set the element at index @var{idx} of the bitvector
1443 @var{vec} when @var{val} is true, else clear it.
1446 @deffn {Scheme Procedure} bitvector-fill! vec val
1447 @deffnx {C Function} scm_bitvector_fill_x (vec, val)
1448 Set all elements of the bitvector
1449 @var{vec} when @var{val} is true, else clear them.
1452 @deffn {Scheme Procedure} list->bitvector list
1453 @deffnx {C Function} scm_list_to_bitvector (list)
1454 Return a new bitvector initialized with the elements
1458 @deffn {Scheme Procedure} bitvector->list vec
1459 @deffnx {C Function} scm_bitvector_to_list (vec)
1460 Return a new list initialized with the elements
1461 of the bitvector @var{vec}.
1464 @deffn {Scheme Procedure} bit-count bool bitvector
1465 @deffnx {C Function} scm_bit_count (bool, bitvector)
1466 Return a count of how many entries in @var{bitvector} are equal to
1467 @var{bool}. For example,
1470 (bit-count #f #*000111000) @result{} 6
1474 @deffn {Scheme Procedure} bit-position bool bitvector start
1475 @deffnx {C Function} scm_bit_position (bool, bitvector, start)
1476 Return the index of the first occurrance of @var{bool} in
1477 @var{bitvector}, starting from @var{start}. If there is no @var{bool}
1478 entry between @var{start} and the end of @var{bitvector}, then return
1479 @code{#f}. For example,
1482 (bit-position #t #*000101 0) @result{} 3
1483 (bit-position #f #*0001111 3) @result{} #f
1487 @deffn {Scheme Procedure} bit-invert! bitvector
1488 @deffnx {C Function} scm_bit_invert_x (bitvector)
1489 Modify @var{bitvector} by replacing each element with its negation.
1492 @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1493 @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1494 Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1495 selecting the entries to change. The return value is unspecified.
1497 If @var{uvec} is a bit vector, then those entries where it has
1498 @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1499 @var{uvec} and @var{bitvector} must be the same length. When
1500 @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1501 @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1505 (define bv #*01000010)
1506 (bit-set*! bv #*10010001 #t)
1508 @result{} #*11010011
1511 If @var{uvec} is a uniform vector of unsigned long integers, then
1512 they're indexes into @var{bitvector} which are set to @var{bool}.
1515 (define bv #*01000010)
1516 (bit-set*! bv #u(5 2 7) #t)
1518 @result{} #*01100111
1522 @deffn {Scheme Procedure} bit-count* bitvector uvec bool
1523 @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1524 Return a count of how many entries in @var{bitvector} are equal to
1525 @var{bool}, with @var{uvec} selecting the entries to consider.
1527 @var{uvec} is interpreted in the same way as for @code{bit-set*!}
1528 above. Namely, if @var{uvec} is a bit vector then entries which have
1529 @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1530 is a uniform vector of unsigned long integers then it's the indexes in
1531 @var{bitvector} to consider.
1536 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1537 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1541 @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)
1542 Like @code{scm_vector_elements} (which see), but for bitvectors. The
1543 variable pointed to by @var{offp} is set to the value returned by
1544 @code{scm_array_handle_bit_elements_offset}. See
1545 @code{scm_array_handle_bit_elements} for how to use the returned pointer
1549 @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)
1550 Like @code{scm_bitvector_elements}, but the pointer is good for reading
1554 @node Generalized Vectors
1555 @subsection Generalized Vectors
1557 Guile has a number of data types that are generally vector-like:
1558 strings, uniform numeric vectors, bitvectors, and of course ordinary
1559 vectors of arbitrary Scheme values. These types are disjoint: a
1560 Scheme value belongs to at most one of the four types listed above.
1562 If you want to gloss over this distinction and want to treat all four
1563 types with common code, you can use the procedures in this section.
1564 They work with the @emph{generalized vector} type, which is the union
1565 of the four vector-like types.
1567 @deffn {Scheme Procedure} generalized-vector? obj
1568 @deffnx {C Function} scm_generalized_vector_p (obj)
1569 Return @code{#t} if @var{obj} is a vector, string,
1570 bitvector, or uniform numeric vector.
1573 @deffn {Scheme Procedure} generalized-vector-length v
1574 @deffnx {C Function} scm_generalized_vector_length (v)
1575 Return the length of the generalized vector @var{v}.
1578 @deffn {Scheme Procedure} generalized-vector-ref v idx
1579 @deffnx {C Function} scm_generalized_vector_ref (v, idx)
1580 Return the element at index @var{idx} of the
1581 generalized vector @var{v}.
1584 @deffn {Scheme Procedure} generalized-vector-set! v idx val
1585 @deffnx {C Function} scm_generalized_vector_set_x (v, idx, val)
1586 Set the element at index @var{idx} of the
1587 generalized vector @var{v} to @var{val}.
1590 @deffn {Scheme Procedure} generalized-vector->list v
1591 @deffnx {C Function} scm_generalized_vector_to_list (v)
1592 Return a new list whose elements are the elements of the
1593 generalized vector @var{v}.
1596 @deftypefn {C Function} int scm_is_generalized_vector (SCM obj)
1597 Return @code{1} if @var{obj} is a vector, string,
1598 bitvector, or uniform numeric vector; else return @code{0}.
1601 @deftypefn {C Function} size_t scm_c_generalized_vector_length (SCM v)
1602 Return the length of the generalized vector @var{v}.
1605 @deftypefn {C Function} SCM scm_c_generalized_vector_ref (SCM v, size_t idx)
1606 Return the element at index @var{idx} of the generalized vector @var{v}.
1609 @deftypefn {C Function} void scm_c_generalized_vector_set_x (SCM v, size_t idx, SCM val)
1610 Set the element at index @var{idx} of the generalized vector @var{v}
1614 @deftypefn {C Function} void scm_generalized_vector_get_handle (SCM v, scm_t_array_handle *handle)
1615 Like @code{scm_array_get_handle} but an error is signalled when @var{v}
1616 is not of rank one. You can use @code{scm_array_handle_ref} and
1617 @code{scm_array_handle_set} to read and write the elements of @var{v},
1618 or you can use functions like @code{scm_array_handle_<foo>_elements} to
1619 deal with specific types of vectors.
1626 @dfn{Arrays} are a collection of cells organized into an arbitrary
1627 number of dimensions. Each cell can be accessed in constant time by
1628 supplying an index for each dimension.
1630 In the current implementation, an array uses a generalized vector for
1631 the actual storage of its elements. Any kind of generalized vector
1632 will do, so you can have arrays of uniform numeric values, arrays of
1633 characters, arrays of bits, and of course, arrays of arbitrary Scheme
1634 values. For example, arrays with an underlying @code{c64vector} might
1635 be nice for digital signal processing, while arrays made from a
1636 @code{u8vector} might be used to hold gray-scale images.
1638 The number of dimensions of an array is called its @dfn{rank}. Thus,
1639 a matrix is an array of rank 2, while a vector has rank 1. When
1640 accessing an array element, you have to specify one exact integer for
1641 each dimension. These integers are called the @dfn{indices} of the
1642 element. An array specifies the allowed range of indices for each
1643 dimension via an inclusive lower and upper bound. These bounds can
1644 well be negative, but the upper bound must be greater than or equal to
1645 the lower bound minus one. When all lower bounds of an array are
1646 zero, it is called a @dfn{zero-origin} array.
1648 Arrays can be of rank 0, which could be interpreted as a scalar.
1649 Thus, a zero-rank array can store exactly one object and the list of
1650 indices of this element is the empty list.
1652 Arrays contain zero elements when one of their dimensions has a zero
1653 length. These empty arrays maintain information about their shape: a
1654 matrix with zero columns and 3 rows is different from a matrix with 3
1655 columns and zero rows, which again is different from a vector of
1658 Generalized vectors, such as strings, uniform numeric vectors, bit
1659 vectors and ordinary vectors, are the special case of one dimensional
1664 * Array Procedures::
1666 * Accessing Arrays from C::
1670 @subsubsection Array Syntax
1672 An array is displayed as @code{#} followed by its rank, followed by a
1673 tag that describes the underlying vector, optionally followed by
1674 information about its shape, and finally followed by the cells,
1675 organized into dimensions using parentheses.
1677 In more words, the array tag is of the form
1680 #<rank><vectag><@@lower><:len><@@lower><:len>...
1683 where @code{<rank>} is a positive integer in decimal giving the rank of
1684 the array. It is omitted when the rank is 1 and the array is non-shared
1685 and has zero-origin (see below). For shared arrays and for a non-zero
1686 origin, the rank is always printed even when it is 1 to dinstinguish
1687 them from ordinary vectors.
1689 The @code{<vectag>} part is the tag for a uniform numeric vector, like
1690 @code{u8}, @code{s16}, etc, @code{b} for bitvectors, or @code{a} for
1691 strings. It is empty for ordinary vectors.
1693 The @code{<@@lower>} part is a @samp{@@} character followed by a signed
1694 integer in decimal giving the lower bound of a dimension. There is one
1695 @code{<@@lower>} for each dimension. When all lower bounds are zero,
1696 all @code{<@@lower>} parts are omitted.
1698 The @code{<:len>} part is a @samp{:} character followed by an unsigned
1699 integer in decimal giving the length of a dimension. Like for the lower
1700 bounds, there is one @code{<:len>} for each dimension, and the
1701 @code{<:len>} part always follows the @code{<@@lower>} part for a
1702 dimension. Lengths are only then printed when they can't be deduced
1703 from the nested lists of elements of the array literal, which can happen
1704 when at least one length is zero.
1706 As a special case, an array of rank 0 is printed as
1707 @code{#0<vectag>(<scalar>)}, where @code{<scalar>} is the result of
1708 printing the single element of the array.
1714 is an ordinary array of rank 1 with lower bound 0 in dimension 0.
1715 (I.e., a regular vector.)
1718 is an ordinary array of rank 1 with lower bound 2 in dimension 0.
1720 @item #2((1 2 3) (4 5 6))
1721 is a non-uniform array of rank 2; a 3@cross{}3 matrix with index ranges 0..2
1725 is a uniform u8 array of rank 1.
1727 @item #2u32@@2@@3((1 2) (2 3))
1728 is a uniform u8 array of rank 2 with index ranges 2..3 and 3..4.
1731 is a two-dimensional array with index ranges 0..-1 and 0..-1, i.e. both
1732 dimensions have length zero.
1735 is a two-dimensional array with index ranges 0..-1 and 0..1, i.e. the
1736 first dimension has length zero, but the second has length 2.
1739 is a rank-zero array with contents 12.
1743 @node Array Procedures
1744 @subsubsection Array Procedures
1746 When an array is created, the range of each dimension must be
1747 specified, e.g., to create a 2@cross{}3 array with a zero-based index:
1750 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1753 The range of each dimension can also be given explicitly, e.g., another
1754 way to create the same array:
1757 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1760 The following procedures can be used with arrays (or vectors). An
1761 argument shown as @var{idx}@dots{} means one parameter for each
1762 dimension in the array. A @var{idxlist} argument means a list of such
1763 values, one for each dimension.
1766 @deffn {Scheme Procedure} array? obj
1767 @deffnx {C Function} scm_array_p (obj, unused)
1768 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1771 The second argument to scm_array_p is there for historical reasons,
1772 but it is not used. You should always pass @code{SCM_UNDEFINED} as
1776 @deffn {Scheme Procedure} typed-array? obj type
1777 @deffnx {C Function} scm_typed_array_p (obj, type)
1778 Return @code{#t} if the @var{obj} is an array of type @var{type}, and
1782 @deftypefn {C Function} int scm_is_array (SCM obj)
1783 Return @code{1} if the @var{obj} is an array and @code{0} if not.
1786 @deftypefn {C Function} int scm_is_typed_array (SCM obj, SCM type)
1787 Return @code{0} if the @var{obj} is an array of type @var{type}, and
1791 @deffn {Scheme Procedure} make-array fill bound @dots{}
1792 @deffnx {C Function} scm_make_array (fill, bounds)
1793 Equivalent to @code{(make-typed-array #t @var{fill} @var{bound} ...)}.
1796 @deffn {Scheme Procedure} make-typed-array type fill bound @dots{}
1797 @deffnx {C Function} scm_make_typed_array (type, fill, bounds)
1798 Create and return an array that has as many dimensions as there are
1799 @var{bound}s and (maybe) fill it with @var{fill}.
1801 The underlaying storage vector is created according to @var{type},
1802 which must be a symbol whose name is the `vectag' of the array as
1803 explained above, or @code{#t} for ordinary, non-specialized arrays.
1805 For example, using the symbol @code{f64} for @var{type} will create an
1806 array that uses a @code{f64vector} for storing its elements, and
1807 @code{a} will use a string.
1809 When @var{fill} is not the special @emph{unspecified} value, the new
1810 array is filled with @var{fill}. Otherwise, the initial contents of
1811 the array is unspecified. The special @emph{unspecified} value is
1812 stored in the variable @code{*unspecified*} so that for example
1813 @code{(make-typed-array 'u32 *unspecified* 4)} creates a uninitialized
1814 @code{u32} vector of length 4.
1816 Each @var{bound} may be a positive non-zero integer @var{N}, in which
1817 case the index for that dimension can range from 0 through @var{N-1}; or
1818 an explicit index range specifier in the form @code{(LOWER UPPER)},
1819 where both @var{lower} and @var{upper} are integers, possibly less than
1820 zero, and possibly the same number (however, @var{lower} cannot be
1821 greater than @var{upper}).
1824 @deffn {Scheme Procedure} list->array dimspec list
1825 Equivalent to @code{(list->typed-array #t @var{dimspec}
1829 @deffn {Scheme Procedure} list->typed-array type dimspec list
1830 @deffnx {C Function} scm_list_to_typed_array (type, dimspec, list)
1831 Return an array of the type indicated by @var{type} with elements the
1832 same as those of @var{list}.
1834 The argument @var{dimspec} determines the number of dimensions of the
1835 array and their lower bounds. When @var{dimspec} is an exact integer,
1836 it gives the number of dimensions directly and all lower bounds are
1837 zero. When it is a list of exact integers, then each element is the
1838 lower index bound of a dimension, and there will be as many dimensions
1839 as elements in the list.
1842 @deffn {Scheme Procedure} array-type array
1843 Return the type of @var{array}. This is the `vectag' used for
1844 printing @var{array} (or @code{#t} for ordinary arrays) and can be
1845 used with @code{make-typed-array} to create an array of the same kind
1849 @deffn {Scheme Procedure} array-ref array idx @dots{}
1850 Return the element at @code{(idx @dots{})} in @var{array}.
1853 (define a (make-array 999 '(1 2) '(3 4)))
1854 (array-ref a 2 4) @result{} 999
1858 @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
1859 @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
1860 Return @code{#t} if the given index would be acceptable to
1864 (define a (make-array #f '(1 2) '(3 4)))
1865 (array-in-bounds? a 2 3) @result{} #f
1866 (array-in-bounds? a 0 0) @result{} #f
1870 @deffn {Scheme Procedure} array-set! array obj idx @dots{}
1871 @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
1872 Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
1873 The return value is unspecified.
1876 (define a (make-array #f '(0 1) '(0 1)))
1877 (array-set! a #t 1 1)
1878 a @result{} #2((#f #f) (#f #t))
1882 @deffn {Scheme Procedure} enclose-array array dim1 @dots{}
1883 @deffnx {C Function} scm_enclose_array (array, dimlist)
1884 @var{dim1}, @var{dim2} @dots{} should be nonnegative integers less than
1885 the rank of @var{array}. @code{enclose-array} returns an array
1886 resembling an array of shared arrays. The dimensions of each shared
1887 array are the same as the @var{dim}th dimensions of the original array,
1888 the dimensions of the outer array are the same as those of the original
1889 array that did not match a @var{dim}.
1891 An enclosed array is not a general Scheme array. Its elements may not
1892 be set using @code{array-set!}. Two references to the same element of
1893 an enclosed array will be @code{equal?} but will not in general be
1894 @code{eq?}. The value returned by @code{array-prototype} when given an
1895 enclosed array is unspecified.
1900 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1)
1902 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1904 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0)
1906 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1910 @deffn {Scheme Procedure} array-shape array
1911 @deffnx {Scheme Procedure} array-dimensions array
1912 @deffnx {C Function} scm_array_dimensions (array)
1913 Return a list of the bounds for each dimenson of @var{array}.
1915 @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
1916 dimension. @code{array-dimensions} instead returns just
1917 @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
1918 suitable as input to @code{make-array}.
1923 (define a (make-array 'foo '(-1 3) 5))
1924 (array-shape a) @result{} ((-1 3) (0 4))
1925 (array-dimensions a) @result{} ((-1 3) 5)
1929 @deffn {Scheme Procedure} array-rank obj
1930 @deffnx {C Function} scm_array_rank (obj)
1931 Return the rank of @var{array}.
1934 @deftypefn {C Function} scm_c_array_rank (SCM array)
1935 Return the rank of @var{array} as a @code{size_t}.
1938 @deffn {Scheme Procedure} array->list array
1939 @deffnx {C Function} scm_array_to_list (array)
1940 Return a list consisting of all the elements, in order, of
1944 @c FIXME: Describe how the order affects the copying (it matters for
1945 @c shared arrays with the same underlying root vector, presumably).
1947 @deffn {Scheme Procedure} array-copy! src dst
1948 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1949 @deffnx {C Function} scm_array_copy_x (src, dst)
1950 Copy every element from vector or array @var{src} to the corresponding
1951 element of @var{dst}. @var{dst} must have the same rank as @var{src},
1952 and be at least as large in each dimension. The return value is
1956 @deffn {Scheme Procedure} array-fill! array fill
1957 @deffnx {C Function} scm_array_fill_x (array, fill)
1958 Store @var{fill} in every element of @var{array}. The value returned
1962 @c begin (texi-doc-string "guile" "array-equal?")
1963 @deffn {Scheme Procedure} array-equal? array1 array2 @dots{}
1964 Return @code{#t} if all arguments are arrays with the same shape, the
1965 same type, and have corresponding elements which are either
1966 @code{equal?} or @code{array-equal?}. This function differs from
1967 @code{equal?} in that a one dimensional shared array may be
1968 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
1971 @deffn {Scheme Procedure} array-contents array [strict]
1972 @deffnx {C Function} scm_array_contents (array, strict)
1973 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1974 without changing their order (last subscript changing fastest), then
1975 @code{array-contents} returns that shared array, otherwise it returns
1976 @code{#f}. All arrays made by @code{make-array} and
1977 @code{make-generalized-array} may be unrolled, some arrays made by
1978 @code{make-shared-array} may not be.
1980 If the optional argument @var{strict} is provided, a shared array will
1981 be returned only if its elements are stored internally contiguous in
1985 @c FIXME: array-map! accepts no source arrays at all, and in that
1986 @c case makes calls "(proc)". Is that meant to be a documented
1989 @c FIXME: array-for-each doesn't say what happens if the sources have
1990 @c different index ranges. The code currently iterates over the
1991 @c indices of the first and expects the others to cover those. That
1992 @c at least vaguely matches array-map!, but is is meant to be a
1993 @c documented feature?
1995 @deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN
1996 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1997 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1998 Set each element of the @var{dst} array to values obtained from calls
1999 to @var{proc}. The value returned is unspecified.
2001 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
2002 where each @var{elem} is from the corresponding @var{src} array, at
2003 the @var{dst} index. @code{array-map-in-order!} makes the calls in
2004 row-major order, @code{array-map!} makes them in an unspecified order.
2006 The @var{src} arrays must have the same number of dimensions as
2007 @var{dst}, and must have a range for each dimension which covers the
2008 range in @var{dst}. This ensures all @var{dst} indices are valid in
2012 @deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN
2013 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
2014 Apply @var{proc} to each tuple of elements of @var{src1} @dots{}
2015 @var{srcN}, in row-major order. The value returned is unspecified.
2018 @deffn {Scheme Procedure} array-index-map! dst proc
2019 @deffnx {C Function} scm_array_index_map_x (dst, proc)
2020 Set each element of the @var{dst} array to values returned by calls to
2021 @var{proc}. The value returned is unspecified.
2023 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
2024 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
2025 each dimension. The order in which the calls are made is unspecified.
2027 For example, to create a @m{4\times4, 4x4} matrix representing a
2031 \advance\leftskip by 2\lispnarrowing {
2049 (define a (make-array #f 4 4))
2050 (array-index-map! a (lambda (i j)
2051 (modulo (+ i j) 4)))
2055 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
2056 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
2057 Attempt to read all elements of @var{ura}, in lexicographic order, as
2058 binary objects from @var{port-or-fdes}.
2059 If an end of file is encountered,
2060 the objects up to that point are put into @var{ura}
2061 (starting at the beginning) and the remainder of the array is
2064 The optional arguments @var{start} and @var{end} allow
2065 a specified region of a vector (or linearized array) to be read,
2066 leaving the remainder of the vector unchanged.
2068 @code{uniform-array-read!} returns the number of objects read.
2069 @var{port-or-fdes} may be omitted, in which case it defaults to the value
2070 returned by @code{(current-input-port)}.
2073 @deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]]
2074 @deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end)
2075 Writes all elements of @var{ura} as binary objects to
2078 The optional arguments @var{start}
2080 a specified region of a vector (or linearized array) to be written.
2082 The number of objects actually written is returned.
2083 @var{port-or-fdes} may be
2084 omitted, in which case it defaults to the value returned by
2085 @code{(current-output-port)}.
2089 @subsubsection Shared Arrays
2091 @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
2092 @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
2093 Return a new array which shares the storage of @var{oldarray}.
2094 Changes made through either affect the same underlying storage. The
2095 @var{bound@dots{}} arguments are the shape of the new array, the same
2096 as @code{make-array} (@pxref{Array Procedures}).
2098 @var{mapfunc} translates coordinates from the new array to the
2099 @var{oldarray}. It's called as @code{(@var{mapfunc} newidx1 @dots{})}
2100 with one parameter for each dimension of the new array, and should
2101 return a list of indices for @var{oldarray}, one for each dimension of
2104 @var{mapfunc} must be affine linear, meaning that each @var{oldarray}
2105 index must be formed by adding integer multiples (possibly negative)
2106 of some or all of @var{newidx1} etc, plus a possible integer offset.
2107 The multiples and offset must be the same in each call.
2110 One good use for a shared array is to restrict the range of some
2111 dimensions, so as to apply say @code{array-for-each} or
2112 @code{array-fill!} to only part of an array. The plain @code{list}
2113 function can be used for @var{mapfunc} in this case, making no changes
2114 to the index values. For example,
2117 (make-shared-array #2((a b c) (d e f) (g h i)) list 3 2)
2118 @result{} #2((a b) (d e) (g h))
2121 The new array can have fewer dimensions than @var{oldarray}, for
2122 example to take a column from an array.
2125 (make-shared-array #2((a b c) (d e f) (g h i))
2126 (lambda (i) (list i 2))
2131 A diagonal can be taken by using the single new array index for both
2132 row and column in the old array. For example,
2135 (make-shared-array #2((a b c) (d e f) (g h i))
2136 (lambda (i) (list i i))
2141 Dimensions can be increased by for instance considering portions of a
2142 one dimensional array as rows in a two dimensional array.
2143 (@code{array-contents} below can do the opposite, flattening an
2147 (make-shared-array #1(a b c d e f g h i j k l)
2148 (lambda (i j) (list (+ (* i 3) j)))
2150 @result{} #2((a b c) (d e f) (g h i) (j k l))
2153 By negating an index the order that elements appear can be reversed.
2154 The following just reverses the column order,
2157 (make-shared-array #2((a b c) (d e f) (g h i))
2158 (lambda (i j) (list i (- 2 j)))
2160 @result{} #2((c b a) (f e d) (i h g))
2163 A fixed offset on indexes allows for instance a change from a 0 based
2167 (define x #2((a b c) (d e f) (g h i)))
2168 (define y (make-shared-array x
2169 (lambda (i j) (list (1- i) (1- j)))
2171 (array-ref x 0 0) @result{} a
2172 (array-ref y 1 1) @result{} a
2175 A multiple on an index allows every Nth element of an array to be
2176 taken. The following is every third element,
2179 (make-shared-array #1(a b c d e f g h i j k l)
2180 (lambda (i) (* i 3))
2182 @result{} #1(a d g j)
2185 The above examples can be combined to make weird and wonderful
2186 selections from an array, but it's important to note that because
2187 @var{mapfunc} must be affine linear, arbitrary permutations are not
2190 In the current implementation, @var{mapfunc} is not called for every
2191 access to the new array but only on some sample points to establish a
2192 base and stride for new array indices in @var{oldarray} data. A few
2193 sample points are enough because @var{mapfunc} is linear.
2196 @deffn {Scheme Procedure} shared-array-increments array
2197 @deffnx {C Function} scm_shared_array_increments (array)
2198 For each dimension, return the distance between elements in the root vector.
2201 @deffn {Scheme Procedure} shared-array-offset array
2202 @deffnx {C Function} scm_shared_array_offset (array)
2203 Return the root vector index of the first element in the array.
2206 @deffn {Scheme Procedure} shared-array-root array
2207 @deffnx {C Function} scm_shared_array_root (array)
2208 Return the root vector of a shared array.
2211 @deffn {Scheme Procedure} transpose-array array dim1 @dots{}
2212 @deffnx {C Function} scm_transpose_array (array, dimlist)
2213 Return an array sharing contents with @var{array}, but with
2214 dimensions arranged in a different order. There must be one
2215 @var{dim} argument for each dimension of @var{array}.
2216 @var{dim1}, @var{dim2}, @dots{} should be integers between 0
2217 and the rank of the array to be returned. Each integer in that
2218 range must appear at least once in the argument list.
2220 The values of @var{dim1}, @var{dim2}, @dots{} correspond to
2221 dimensions in the array to be returned, and their positions in the
2222 argument list to dimensions of @var{array}. Several @var{dim}s
2223 may have the same value, in which case the returned array will
2224 have smaller rank than @var{array}.
2227 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
2228 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
2229 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
2230 #2((a 4) (b 5) (c 6))
2234 @node Accessing Arrays from C
2235 @subsubsection Accessing Arrays from C
2237 Arrays, especially uniform numeric arrays, are useful to efficiently
2238 represent large amounts of rectangularily organized information, such as
2239 matrices, images, or generally blobs of binary data. It is desirable to
2240 access these blobs in a C like manner so that they can be handed to
2241 external C code such as linear algebra libraries or image processing
2244 While pointers to the elements of an array are in use, the array itself
2245 must be protected so that the pointer remains valid. Such a protected
2246 array is said to be @dfn{reserved}. A reserved array can be read but
2247 modifications to it that would cause the pointer to its elements to
2248 become invalid are prevented. When you attempt such a modification, an
2251 (This is similar to locking the array while it is in use, but without
2252 the danger of a deadlock. In a multi-threaded program, you will need
2253 additional synchronization to avoid modifying reserved arrays.)
2255 You must take care to always unreserve an array after reserving it, also
2256 in the presence of non-local exits. To simplify this, reserving and
2257 unreserving work like a frame (@pxref{Frames}): a call to
2258 @code{scm_array_get_handle} can be thought of as beginning a frame and
2259 @code{scm_array_handle_release} as ending it. When a non-local exit
2260 happens between these two calls, the array is implicitely unreserved.
2262 That is, you need to properly pair reserving and unreserving in your
2263 code, but you don't need to worry about non-local exits.
2265 These calls and other pairs of calls that establish dynamic contexts
2266 need to be properly nested. If you begin a frame prior to reserving an
2267 array, you need to unreserve the array before ending the frame.
2268 Likewise, when reserving two or more arrays in a certain order, you need
2269 to unreserve them in the opposite order.
2271 Once you have reserved an array and have retrieved the pointer to its
2272 elements, you must figure out the layout of the elements in memory.
2273 Guile allows slices to be taken out of arrays without actually making a
2274 copy, such as making an alias for the diagonal of a matrix that can be
2275 treated as a vector. Arrays that result from such an operation are not
2276 stored contiguously in memory and when working with their elements
2277 directly, you need to take this into account.
2279 The layout of array elements in memory can be defined via a
2280 @emph{mapping function} that computes a scalar position from a vector of
2281 indices. The scalar position then is the offset of the element with the
2282 given indices from the start of the storage block of the array.
2284 In Guile, this mapping function is restricted to be @dfn{affine}: all
2285 mapping function of Guile arrays can be written as @code{p = b +
2286 c[0]*i[0] + c[1]*i[1] + ... + c[n-1]*i[n-1]} where @code{i[k]} is the
2287 @nicode{k}th index and @code{n} is the rank of the array. For example,
2288 a matrix of size 3x3 would have @code{b == 0}, @code{c[0] == 3} and
2289 @code{c[1] == 1}. When you transpose this matrix (with
2290 @code{transpose-array}, say), you will get an array whose mapping
2291 function has @code{b == 0}, @code{c[0] == 1} and @code{c[1] == 3}.
2293 The function @code{scm_array_handle_dims} gives you (indirect) access to
2294 the coefficients @code{c[k]}.
2297 Note that there are no functions for accessing the elements of a
2298 character array yet. Once the string implementation of Guile has been
2299 changed to use Unicode, we will provide them.
2301 @deftp {C Type} scm_t_array_handle
2302 This is a structure type that holds all information necessary to manage
2303 the reservation of arrays as explained above. Structures of this type
2304 must be allocated on the stack and must only be accessed by the
2305 functions listed below.
2308 @deftypefn {C Function} void scm_array_get_handle (SCM array, scm_t_array_handle *handle)
2309 Reserve @var{array}, which must be an array, and prepare @var{handle} to
2310 be used with the functions below. You must eventually call
2311 @code{scm_array_handle_release} on @var{handle}, and do this in a
2312 properly nested fashion, as explained above. The structure pointed to
2313 by @var{handle} does not need to be initialized before calling this
2317 @deftypefn {C Function} void scm_array_handle_release (scm_t_array_handle *handle)
2318 End the array reservation represented by @var{handle}. After a call to
2319 this function, @var{handle} might be used for another reservation.
2322 @deftypefn {C Function} size_t scm_array_handle_rank (scm_t_array_handle *handle)
2323 Return the rank of the array represented by @var{handle}.
2326 @deftp {C Type} scm_t_array_dim
2327 This structure type holds information about the layout of one dimension
2328 of an array. It includes the following fields:
2333 The lower and upper bounds (both inclusive) of the permissible index
2334 range for the given dimension. Both values can be negative, but
2335 @var{lbnd} is always less than or equal to @var{ubnd}.
2338 The distance from one element of this dimension to the next. Note, too,
2339 that this can be negative.
2343 @deftypefn {C Function} {const scm_t_array_dim *} scm_array_handle_dims (scm_t_array_handle *handle)
2344 Return a pointer to a C vector of information about the dimensions of
2345 the array represented by @var{handle}. This pointer is valid as long as
2346 the array remains reserved. As explained above, the
2347 @code{scm_t_array_dim} structures returned by this function can be used
2348 calculate the position of an element in the storage block of the array
2351 This position can then be used as an index into the C array pointer
2352 returned by the various @code{scm_array_handle_<foo>_elements}
2353 functions, or with @code{scm_array_handle_ref} and
2354 @code{scm_array_handle_set}.
2356 Here is how one can compute the position @var{pos} of an element given
2357 its indices in the vector @var{indices}:
2360 ssize_t indices[RANK];
2361 scm_t_array_dim *dims;
2366 for (i = 0; i < RANK; i++)
2368 if (indices[i] < dims[i].lbnd || indices[i] > dims[i].ubnd)
2370 pos += (indices[i] - dims[i].lbnd) * dims[i].inc;
2375 @deftypefn {C Function} ssize_t scm_array_handle_pos (scm_t_array_handle *handle, SCM indices)
2376 Compute the position corresponding to @var{indices}, a list of
2377 indices. The position is computed as described above for
2378 @code{scm_array_handle_dims}. The number of the indices and their
2379 range is checked and an approrpiate error is signalled for invalid
2383 @deftypefn {C Function} SCM scm_array_handle_ref (scm_t_array_handle *handle, ssize_t pos)
2384 Return the element at position @var{pos} in the storage block of the
2385 array represented by @var{handle}. Any kind of array is acceptable. No
2386 range checking is done on @var{pos}.
2389 @deftypefn {C Function} void scm_array_handle_set (scm_t_array_handle *handle, ssize_t pos, SCM val)
2390 Set the element at position @var{pos} in the storage block of the array
2391 represented by @var{handle} to @var{val}. Any kind of array is
2392 acceptable. No range checking is done on @var{pos}. An error is
2393 signalled when the array can not store @var{val}.
2396 @deftypefn {C Function} {const SCM *} scm_array_handle_elements (scm_t_array_handle *handle)
2397 Return a pointer to the elements of a ordinary array of general Scheme
2398 values (i.e., a non-uniform array) for reading. This pointer is valid
2399 as long as the array remains reserved.
2402 @deftypefn {C Function} {SCM *} scm_array_handle_writable_elements (scm_t_array_handle *handle)
2403 Like @code{scm_array_handle_elements}, but the pointer is good for
2404 reading and writing.
2407 @deftypefn {C Function} {const void *} scm_array_handle_uniform_elements (scm_t_array_handle *handle)
2408 Return a pointer to the elements of a uniform numeric array for reading.
2409 This pointer is valid as long as the array remains reserved. The size
2410 of each element is given by @code{scm_array_handle_uniform_element_size}.
2413 @deftypefn {C Function} {void *} scm_array_handle_uniform_writable_elements (scm_t_array_handle *handle)
2414 Like @code{scm_array_handle_uniform_elements}, but the pointer is good
2415 reading and writing.
2418 @deftypefn {C Function} size_t scm_array_handle_uniform_element_size (scm_t_array_handle *handle)
2419 Return the size of one element of the uniform numeric array represented
2423 @deftypefn {C Function} {const scm_t_uint8 *} scm_array_handle_u8_elements (scm_t_array_handle *handle)
2424 @deftypefnx {C Function} {const scm_t_int8 *} scm_array_handle_s8_elements (scm_t_array_handle *handle)
2425 @deftypefnx {C Function} {const scm_t_uint16 *} scm_array_handle_u16_elements (scm_t_array_handle *handle)
2426 @deftypefnx {C Function} {const scm_t_int16 *} scm_array_handle_s16_elements (scm_t_array_handle *handle)
2427 @deftypefnx {C Function} {const scm_t_uint32 *} scm_array_handle_u32_elements (scm_t_array_handle *handle)
2428 @deftypefnx {C Function} {const scm_t_int32 *} scm_array_handle_s32_elements (scm_t_array_handle *handle)
2429 @deftypefnx {C Function} {const scm_t_uint64 *} scm_array_handle_u64_elements (scm_t_array_handle *handle)
2430 @deftypefnx {C Function} {const scm_t_int64 *} scm_array_handle_s64_elements (scm_t_array_handle *handle)
2431 @deftypefnx {C Function} {const float *} scm_array_handle_f32_elements (scm_t_array_handle *handle)
2432 @deftypefnx {C Function} {const double *} scm_array_handle_f64_elements (scm_t_array_handle *handle)
2433 @deftypefnx {C Function} {const float *} scm_array_handle_c32_elements (scm_t_array_handle *handle)
2434 @deftypefnx {C Function} {const double *} scm_array_handle_c64_elements (scm_t_array_handle *handle)
2435 Return a pointer to the elements of a uniform numeric array of the
2436 indicated kind for reading. This pointer is valid as long as the array
2439 The pointers for @code{c32} and @code{c64} uniform numeric arrays point
2440 to pairs of floating point numbers. The even index holds the real part,
2441 the odd index the imaginary part of the complex number.
2444 @deftypefn {C Function} {scm_t_uint8 *} scm_array_handle_u8_writable_elements (scm_t_array_handle *handle)
2445 @deftypefnx {C Function} {scm_t_int8 *} scm_array_handle_s8_writable_elements (scm_t_array_handle *handle)
2446 @deftypefnx {C Function} {scm_t_uint16 *} scm_array_handle_u16_writable_elements (scm_t_array_handle *handle)
2447 @deftypefnx {C Function} {scm_t_int16 *} scm_array_handle_s16_writable_elements (scm_t_array_handle *handle)
2448 @deftypefnx {C Function} {scm_t_uint32 *} scm_array_handle_u32_writable_elements (scm_t_array_handle *handle)
2449 @deftypefnx {C Function} {scm_t_int32 *} scm_array_handle_s32_writable_elements (scm_t_array_handle *handle)
2450 @deftypefnx {C Function} {scm_t_uint64 *} scm_array_handle_u64_writable_elements (scm_t_array_handle *handle)
2451 @deftypefnx {C Function} {scm_t_int64 *} scm_array_handle_s64_writable_elements (scm_t_array_handle *handle)
2452 @deftypefnx {C Function} {float *} scm_array_handle_f32_writable_elements (scm_t_array_handle *handle)
2453 @deftypefnx {C Function} {double *} scm_array_handle_f64_writable_elements (scm_t_array_handle *handle)
2454 @deftypefnx {C Function} {float *} scm_array_handle_c32_writable_elements (scm_t_array_handle *handle)
2455 @deftypefnx {C Function} {double *} scm_array_handle_c64_writable_elements (scm_t_array_handle *handle)
2456 Like @code{scm_array_handle_<kind>_elements}, but the pointer is good
2457 for reading and writing.
2460 @deftypefn {C Function} {const scm_t_uint32 *} scm_array_handle_bit_elements (scm_t_array_handle *handle)
2461 Return a pointer to the words that store the bits of the represented
2462 array, which must be a bit array.
2464 Unlike other arrays, bit arrays have an additional offset that must be
2465 figured into index calculations. That offset is returned by
2466 @code{scm_array_handle_bit_elements_offset}.
2468 To find a certain bit you first need to calculate its position as
2469 explained above for @code{scm_array_handle_dims} and then add the
2470 offset. This gives the absolute position of the bit, which is always a
2471 non-negative integer.
2473 Each word of the bit array storage block contains exactly 32 bits, with
2474 the least significant bit in that word having the lowest absolute
2475 position number. The next word contains the next 32 bits.
2477 Thus, the following code can be used to access a bit whose position
2478 according to @code{scm_array_handle_dims} is given in @var{pos}:
2482 scm_t_array_handle handle;
2486 size_t word_pos, mask;
2488 scm_array_get_handle (&bit_array, &handle);
2489 bits = scm_array_handle_bit_elements (&handle);
2492 abs_pos = pos + scm_array_handle_bit_elements_offset (&handle);
2493 word_pos = abs_pos / 32;
2494 mask = 1L << (abs_pos % 32);
2496 if (bits[word_pos] & mask)
2499 scm_array_handle_release (&handle);
2504 @deftypefn {C Function} {scm_t_uint32 *} scm_array_handle_bit_writable_elements (scm_t_array_handle *handle)
2505 Like @code{scm_array_handle_bit_elements} but the pointer is good for
2506 reading and writing. You must take care not to modify bits outside of
2507 the allowed index range of the array, even for contiguous arrays.
2513 A @dfn{record type} is a first class object representing a user-defined
2514 data type. A @dfn{record} is an instance of a record type.
2516 @deffn {Scheme Procedure} record? obj
2517 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
2520 Note that @code{record?} may be true of any Scheme value; there is no
2521 promise that records are disjoint with other Scheme types.
2524 @deffn {Scheme Procedure} make-record-type type-name field-names
2525 Return a @dfn{record-type descriptor}, a value representing a new data
2526 type disjoint from all others. The @var{type-name} argument must be a
2527 string, but is only used for debugging purposes (such as the printed
2528 representation of a record of the new type). The @var{field-names}
2529 argument is a list of symbols naming the @dfn{fields} of a record of the
2530 new type. It is an error if the list contains any duplicates. It is
2531 unspecified how record-type descriptors are represented.
2534 @deffn {Scheme Procedure} record-constructor rtd [field-names]
2535 Return a procedure for constructing new members of the type represented
2536 by @var{rtd}. The returned procedure accepts exactly as many arguments
2537 as there are symbols in the given list, @var{field-names}; these are
2538 used, in order, as the initial values of those fields in a new record,
2539 which is returned by the constructor procedure. The values of any
2540 fields not named in that list are unspecified. The @var{field-names}
2541 argument defaults to the list of field names in the call to
2542 @code{make-record-type} that created the type represented by @var{rtd};
2543 if the @var{field-names} argument is provided, it is an error if it
2544 contains any duplicates or any symbols not in the default list.
2547 @deffn {Scheme Procedure} record-predicate rtd
2548 Return a procedure for testing membership in the type represented by
2549 @var{rtd}. The returned procedure accepts exactly one argument and
2550 returns a true value if the argument is a member of the indicated record
2551 type; it returns a false value otherwise.
2554 @deffn {Scheme Procedure} record-accessor rtd field-name
2555 Return a procedure for reading the value of a particular field of a
2556 member of the type represented by @var{rtd}. The returned procedure
2557 accepts exactly one argument which must be a record of the appropriate
2558 type; it returns the current value of the field named by the symbol
2559 @var{field-name} in that record. The symbol @var{field-name} must be a
2560 member of the list of field-names in the call to @code{make-record-type}
2561 that created the type represented by @var{rtd}.
2564 @deffn {Scheme Procedure} record-modifier rtd field-name
2565 Return a procedure for writing the value of a particular field of a
2566 member of the type represented by @var{rtd}. The returned procedure
2567 accepts exactly two arguments: first, a record of the appropriate type,
2568 and second, an arbitrary Scheme value; it modifies the field named by
2569 the symbol @var{field-name} in that record to contain the given value.
2570 The returned value of the modifier procedure is unspecified. The symbol
2571 @var{field-name} must be a member of the list of field-names in the call
2572 to @code{make-record-type} that created the type represented by
2576 @deffn {Scheme Procedure} record-type-descriptor record
2577 Return a record-type descriptor representing the type of the given
2578 record. That is, for example, if the returned descriptor were passed to
2579 @code{record-predicate}, the resulting predicate would return a true
2580 value when passed the given record. Note that it is not necessarily the
2581 case that the returned descriptor is the one that was passed to
2582 @code{record-constructor} in the call that created the constructor
2583 procedure that created the given record.
2586 @deffn {Scheme Procedure} record-type-name rtd
2587 Return the type-name associated with the type represented by rtd. The
2588 returned value is @code{eqv?} to the @var{type-name} argument given in
2589 the call to @code{make-record-type} that created the type represented by
2593 @deffn {Scheme Procedure} record-type-fields rtd
2594 Return a list of the symbols naming the fields in members of the type
2595 represented by @var{rtd}. The returned value is @code{equal?} to the
2596 field-names argument given in the call to @code{make-record-type} that
2597 created the type represented by @var{rtd}.
2602 @subsection Structures
2605 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
2608 A @dfn{structure type} is a first class user-defined data type. A
2609 @dfn{structure} is an instance of a structure type. A structure type is
2612 Structures are less abstract and more general than traditional records.
2613 In fact, in Guile Scheme, records are implemented using structures.
2616 * Structure Concepts:: The structure of Structures
2617 * Structure Layout:: Defining the layout of structure types
2618 * Structure Basics:: make-, -ref and -set! procedures for structs
2619 * Vtables:: Accessing type-specific data
2622 @node Structure Concepts
2623 @subsubsection Structure Concepts
2625 A structure object consists of a handle, structure data, and a vtable.
2626 The handle is a Scheme value which points to both the vtable and the
2627 structure's data. Structure data is a dynamically allocated region of
2628 memory, private to the structure, divided up into typed fields. A
2629 vtable is another structure used to hold type-specific data. Multiple
2630 structures can share a common vtable.
2632 Three concepts are key to understanding structures.
2635 @item @dfn{layout specifications}
2637 Layout specifications determine how memory allocated to structures is
2638 divided up into fields. Programmers must write a layout specification
2639 whenever a new type of structure is defined.
2641 @item @dfn{structural accessors}
2643 Structure access is by field number. There is only one set of
2644 accessors common to all structure objects.
2648 Vtables, themselves structures, are first class representations of
2649 disjoint sub-types of structures in general. In most cases, when a
2650 new structure is created, programmers must specify a vtable for the
2651 new structure. Each vtable has a field describing the layout of its
2652 instances. Vtables can have additional, user-defined fields as well.
2657 @node Structure Layout
2658 @subsubsection Structure Layout
2660 When a structure is created, a region of memory is allocated to hold its
2661 state. The @dfn{layout} of the structure's type determines how that
2662 memory is divided into fields.
2664 Each field has a specified type. There are only three types allowed, each
2665 corresponding to a one letter code. The allowed types are:
2668 @item 'u' -- unprotected
2670 The field holds binary data that is not GC protected.
2672 @item 'p' -- protected
2674 The field holds a Scheme value and is GC protected.
2678 The field holds a Scheme value and is GC protected. When a structure is
2679 created with this type of field, the field is initialized to refer to
2680 the structure's own handle. This kind of field is mainly useful when
2681 mixing Scheme and C code in which the C code may need to compute a
2682 structure's handle given only the address of its malloc'd data.
2686 Each field also has an associated access protection. There are only
2687 three kinds of protection, each corresponding to a one letter code.
2688 The allowed protections are:
2691 @item 'w' -- writable
2693 The field can be read and written.
2695 @item 'r' -- readable
2697 The field can be read, but not written.
2701 The field can be neither read nor written. This kind
2702 of protection is for fields useful only to built-in routines.
2705 A layout specification is described by stringing together pairs
2706 of letters: one to specify a field type and one to specify a field
2707 protection. For example, a traditional cons pair type object could
2711 ; cons pairs have two writable fields of Scheme data
2715 A pair object in which the first field is held constant could be:
2721 Binary fields, (fields of type "u"), hold one @dfn{word} each. The
2722 size of a word is a machine dependent value defined to be equal to the
2723 value of the C expression: @code{sizeof (long)}.
2725 The last field of a structure layout may specify a tail array.
2726 A tail array is indicated by capitalizing the field's protection
2727 code ('W', 'R' or 'O'). A tail-array field is replaced by
2728 a read-only binary data field containing an array size. The array
2729 size is determined at the time the structure is created. It is followed
2730 by a corresponding number of fields of the type specified for the
2731 tail array. For example, a conventional Scheme vector can be
2735 ; A vector is an arbitrary number of writable fields holding Scheme
2740 In the above example, field 0 contains the size of the vector and
2741 fields beginning at 1 contain the vector elements.
2743 A kind of tagged vector (a constant tag followed by conventional
2744 vector elements) might be:
2751 Structure layouts are represented by specially interned symbols whose
2752 name is a string of type and protection codes. To create a new
2753 structure layout, use this procedure:
2755 @deffn {Scheme Procedure} make-struct-layout fields
2756 @deffnx {C Function} scm_make_struct_layout (fields)
2757 Return a new structure layout object.
2759 @var{fields} must be a string made up of pairs of characters
2760 strung together. The first character of each pair describes a field
2761 type, the second a field protection. Allowed types are 'p' for
2762 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
2763 a field that points to the structure itself. Allowed protections
2764 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
2765 fields. The last field protection specification may be capitalized to
2766 indicate that the field is a tail-array.
2771 @node Structure Basics
2772 @subsubsection Structure Basics
2774 This section describes the basic procedures for creating and accessing
2777 @deffn {Scheme Procedure} make-struct vtable tail_array_size . init
2778 @deffnx {C Function} scm_make_struct (vtable, tail_array_size, init)
2779 Create a new structure.
2781 @var{type} must be a vtable structure (@pxref{Vtables}).
2783 @var{tail-elts} must be a non-negative integer. If the layout
2784 specification indicated by @var{type} includes a tail-array,
2785 this is the number of elements allocated to that array.
2787 The @var{init1}, @dots{} are optional arguments describing how
2788 successive fields of the structure should be initialized. Only fields
2789 with protection 'r' or 'w' can be initialized, except for fields of
2790 type 's', which are automatically initialized to point to the new
2791 structure itself; fields with protection 'o' can not be initialized by
2794 If fewer optional arguments than initializable fields are supplied,
2795 fields of type 'p' get default value #f while fields of type 'u' are
2798 Structs are currently the basic representation for record-like data
2799 structures in Guile. The plan is to eventually replace them with a
2800 new representation which will at the same time be easier to use and
2803 For more information, see the documentation for @code{make-vtable-vtable}.
2806 @deffn {Scheme Procedure} struct? x
2807 @deffnx {C Function} scm_struct_p (x)
2808 Return @code{#t} iff @var{x} is a structure object, else
2813 @deffn {Scheme Procedure} struct-ref handle pos
2814 @deffnx {Scheme Procedure} struct-set! struct n value
2815 @deffnx {C Function} scm_struct_ref (handle, pos)
2816 @deffnx {C Function} scm_struct_set_x (struct, n, value)
2817 Access (or modify) the @var{n}th field of @var{struct}.
2819 If the field is of type 'p', then it can be set to an arbitrary value.
2821 If the field is of type 'u', then it can only be set to a non-negative
2822 integer value small enough to fit in one machine word.
2828 @subsubsection Vtables
2830 Vtables are structures that are used to represent structure types. Each
2831 vtable contains a layout specification in field
2832 @code{vtable-index-layout} -- instances of the type are laid out
2833 according to that specification. Vtables contain additional fields
2834 which are used only internally to libguile. The variable
2835 @code{vtable-offset-user} is bound to a field number. Vtable fields
2836 at that position or greater are user definable.
2838 @deffn {Scheme Procedure} struct-vtable handle
2839 @deffnx {C Function} scm_struct_vtable (handle)
2840 Return the vtable structure that describes the type of @var{struct}.
2843 @deffn {Scheme Procedure} struct-vtable? x
2844 @deffnx {C Function} scm_struct_vtable_p (x)
2845 Return @code{#t} iff @var{x} is a vtable structure.
2848 If you have a vtable structure, @code{V}, you can create an instance of
2849 the type it describes by using @code{(make-struct V ...)}. But where
2850 does @code{V} itself come from? One possibility is that @code{V} is an
2851 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
2852 created by using @code{(make-struct V' ...)}. Another possibility is
2853 that @code{V} is an instance of the type it itself describes. Vtable
2854 structures of the second sort are created by this procedure:
2856 @deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init
2857 @deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init)
2858 Return a new, self-describing vtable structure.
2860 @var{user-fields} is a string describing user defined fields of the
2861 vtable beginning at index @code{vtable-offset-user}
2862 (see @code{make-struct-layout}).
2864 @var{tail-size} specifies the size of the tail-array (if any) of
2867 @var{init1}, @dots{} are the optional initializers for the fields of
2870 Vtables have one initializable system field---the struct printer.
2871 This field comes before the user fields in the initializers passed
2872 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
2873 a third optional argument to @code{make-vtable-vtable} and a fourth to
2874 @code{make-struct} when creating vtables:
2876 If the value is a procedure, it will be called instead of the standard
2877 printer whenever a struct described by this vtable is printed.
2878 The procedure will be called with arguments STRUCT and PORT.
2880 The structure of a struct is described by a vtable, so the vtable is
2881 in essence the type of the struct. The vtable is itself a struct with
2882 a vtable. This could go on forever if it weren't for the
2883 vtable-vtables which are self-describing vtables, and thus terminate
2886 There are several potential ways of using structs, but the standard
2887 one is to use three kinds of structs, together building up a type
2888 sub-system: one vtable-vtable working as the root and one or several
2889 "types", each with a set of "instances". (The vtable-vtable should be
2890 compared to the class <class> which is the class of itself.)
2893 (define ball-root (make-vtable-vtable "pr" 0))
2895 (define (make-ball-type ball-color)
2896 (make-struct ball-root 0
2897 (make-struct-layout "pw")
2899 (format port "#<a ~A ball owned by ~A>"
2903 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
2904 (define (owner ball) (struct-ref ball 0))
2906 (define red (make-ball-type 'red))
2907 (define green (make-ball-type 'green))
2909 (define (make-ball type owner) (make-struct type 0 owner))
2911 (define ball (make-ball green 'Nisse))
2912 ball @result{} #<a green ball owned by Nisse>
2916 @deffn {Scheme Procedure} struct-vtable-name vtable
2917 @deffnx {C Function} scm_struct_vtable_name (vtable)
2918 Return the name of the vtable @var{vtable}.
2921 @deffn {Scheme Procedure} set-struct-vtable-name! vtable name
2922 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
2923 Set the name of the vtable @var{vtable} to @var{name}.
2926 @deffn {Scheme Procedure} struct-vtable-tag handle
2927 @deffnx {C Function} scm_struct_vtable_tag (handle)
2928 Return the vtable tag of the structure @var{handle}.
2932 @node Dictionary Types
2933 @subsection Dictionary Types
2935 A @dfn{dictionary} object is a data structure used to index
2936 information in a user-defined way. In standard Scheme, the main
2937 aggregate data types are lists and vectors. Lists are not really
2938 indexed at all, and vectors are indexed only by number
2939 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
2940 to index your data on some other type; for example, in a library
2941 catalog you might want to look up a book by the name of its
2942 author. Dictionaries are used to help you organize information in
2945 An @dfn{association list} (or @dfn{alist} for short) is a list of
2946 key-value pairs. Each pair represents a single quantity or
2947 object; the @code{car} of the pair is a key which is used to
2948 identify the object, and the @code{cdr} is the object's value.
2950 A @dfn{hash table} also permits you to index objects with
2951 arbitrary keys, but in a way that makes looking up any one object
2952 extremely fast. A well-designed hash system makes hash table
2953 lookups almost as fast as conventional array or vector references.
2955 Alists are popular among Lisp programmers because they use only
2956 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
2957 and the equality primitives). No changes to the language core are
2958 necessary. Therefore, with Scheme's built-in list manipulation
2959 facilities, it is very convenient to handle data stored in an
2960 association list. Also, alists are highly portable and can be
2961 easily implemented on even the most minimal Lisp systems.
2963 However, alists are inefficient, especially for storing large
2964 quantities of data. Because we want Guile to be useful for large
2965 software systems as well as small ones, Guile provides a rich set
2966 of tools for using either association lists or hash tables.
2968 @node Association Lists
2969 @subsection Association Lists
2970 @tpindex Association Lists
2972 @cindex association List
2976 An association list is a conventional data structure that is often used
2977 to implement simple key-value databases. It consists of a list of
2978 entries in which each entry is a pair. The @dfn{key} of each entry is
2979 the @code{car} of the pair and the @dfn{value} of each entry is the
2983 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
2991 Association lists are also known, for short, as @dfn{alists}.
2993 The structure of an association list is just one example of the infinite
2994 number of possible structures that can be built using pairs and lists.
2995 As such, the keys and values in an association list can be manipulated
2996 using the general list structure procedures @code{cons}, @code{car},
2997 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
2998 because association lists are so useful, Guile also provides specific
2999 procedures for manipulating them.
3002 * Alist Key Equality::
3003 * Adding or Setting Alist Entries::
3004 * Retrieving Alist Entries::
3005 * Removing Alist Entries::
3006 * Sloppy Alist Functions::
3010 @node Alist Key Equality
3011 @subsubsection Alist Key Equality
3013 All of Guile's dedicated association list procedures, apart from
3014 @code{acons}, come in three flavours, depending on the level of equality
3015 that is required to decide whether an existing key in the association
3016 list is the same as the key that the procedure call uses to identify the
3021 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
3025 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
3029 Procedures with @dfn{assoc} in their name use @code{equal?} to
3030 determine key equality.
3033 @code{acons} is an exception because it is used to build association
3034 lists which do not require their entries' keys to be unique.
3036 @node Adding or Setting Alist Entries
3037 @subsubsection Adding or Setting Alist Entries
3039 @code{acons} adds a new entry to an association list and returns the
3040 combined association list. The combined alist is formed by consing the
3041 new entry onto the head of the alist specified in the @code{acons}
3042 procedure call. So the specified alist is not modified, but its
3043 contents become shared with the tail of the combined alist that
3044 @code{acons} returns.
3046 In the most common usage of @code{acons}, a variable holding the
3047 original association list is updated with the combined alist:
3050 (set! address-list (acons name address address-list))
3053 In such cases, it doesn't matter that the old and new values of
3054 @code{address-list} share some of their contents, since the old value is
3055 usually no longer independently accessible.
3057 Note that @code{acons} adds the specified new entry regardless of
3058 whether the alist may already contain entries with keys that are, in
3059 some sense, the same as that of the new entry. Thus @code{acons} is
3060 ideal for building alists where there is no concept of key uniqueness.
3063 (set! task-list (acons 3 "pay gas bill" '()))
3066 ((3 . "pay gas bill"))
3068 (set! task-list (acons 3 "tidy bedroom" task-list))
3071 ((3 . "tidy bedroom") (3 . "pay gas bill"))
3074 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
3075 or replace an entry in an association list where there @emph{is} a
3076 concept of key uniqueness. If the specified association list already
3077 contains an entry whose key is the same as that specified in the
3078 procedure call, the existing entry is replaced by the new one.
3079 Otherwise, the new entry is consed onto the head of the old association
3080 list to create the combined alist. In all cases, these procedures
3081 return the combined alist.
3083 @code{assq-set!} and friends @emph{may} destructively modify the
3084 structure of the old association list in such a way that an existing
3085 variable is correctly updated without having to @code{set!} it to the
3091 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
3093 (assoc-set! address-list "james" "1a London Road")
3095 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3099 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3105 (assoc-set! address-list "bob" "11 Newington Avenue")
3107 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3108 ("james" . "1a London Road"))
3112 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3115 The only safe way to update an association list variable when adding or
3116 replacing an entry like this is to @code{set!} the variable to the
3121 (assoc-set! address-list "bob" "11 Newington Avenue"))
3124 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3125 ("james" . "1a London Road"))
3128 Because of this slight inconvenience, you may find it more convenient to
3129 use hash tables to store dictionary data. If your application will not
3130 be modifying the contents of an alist very often, this may not make much
3133 If you need to keep the old value of an association list in a form
3134 independent from the list that results from modification by
3135 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
3136 use @code{list-copy} to copy the old association list before modifying
3139 @deffn {Scheme Procedure} acons key value alist
3140 @deffnx {C Function} scm_acons (key, value, alist)
3141 Add a new key-value pair to @var{alist}. A new pair is
3142 created whose car is @var{key} and whose cdr is @var{value}, and the
3143 pair is consed onto @var{alist}, and the new list is returned. This
3144 function is @emph{not} destructive; @var{alist} is not modified.
3147 @deffn {Scheme Procedure} assq-set! alist key val
3148 @deffnx {Scheme Procedure} assv-set! alist key value
3149 @deffnx {Scheme Procedure} assoc-set! alist key value
3150 @deffnx {C Function} scm_assq_set_x (alist, key, val)
3151 @deffnx {C Function} scm_assv_set_x (alist, key, val)
3152 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
3153 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
3154 @var{alist} entry for @var{key} and associate it with the new
3155 @var{value}. If @var{alist} does not contain an entry for @var{key},
3156 add a new one. Return the (possibly new) alist.
3158 These functions do not attempt to verify the structure of @var{alist},
3159 and so may cause unusual results if passed an object that is not an
3163 @node Retrieving Alist Entries
3164 @subsubsection Retrieving Alist Entries
3169 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
3170 arguments and return the entry for that key if an entry exists, or
3171 @code{#f} if there is no entry for that key. Note that, in the cases
3172 where an entry exists, these procedures return the complete entry, that
3173 is @code{(KEY . VALUE)}, not just the value.
3175 @deffn {Scheme Procedure} assq key alist
3176 @deffnx {Scheme Procedure} assv key alist
3177 @deffnx {Scheme Procedure} assoc key alist
3178 @deffnx {C Function} scm_assq (key, alist)
3179 @deffnx {C Function} scm_assv (key, alist)
3180 @deffnx {C Function} scm_assoc (key, alist)
3181 Fetch the entry in @var{alist} that is associated with @var{key}. To
3182 decide whether the argument @var{key} matches a particular entry in
3183 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
3184 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
3185 cannot be found in @var{alist} (according to whichever equality
3186 predicate is in use), then return @code{#f}. These functions
3187 return the entire alist entry found (i.e. both the key and the value).
3190 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
3191 hand, take an alist and a key and return @emph{just the value} for that
3192 key, if an entry exists. If there is no entry for the specified key,
3193 these procedures return @code{#f}.
3195 This creates an ambiguity: if the return value is @code{#f}, it means
3196 either that there is no entry with the specified key, or that there
3197 @emph{is} an entry for the specified key, with value @code{#f}.
3198 Consequently, @code{assq-ref} and friends should only be used where it
3199 is known that an entry exists, or where the ambiguity doesn't matter
3200 for some other reason.
3202 @deffn {Scheme Procedure} assq-ref alist key
3203 @deffnx {Scheme Procedure} assv-ref alist key
3204 @deffnx {Scheme Procedure} assoc-ref alist key
3205 @deffnx {C Function} scm_assq_ref (alist, key)
3206 @deffnx {C Function} scm_assv_ref (alist, key)
3207 @deffnx {C Function} scm_assoc_ref (alist, key)
3208 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
3209 value associated with @var{key} in @var{alist} is returned. These
3210 functions are equivalent to
3213 (let ((ent (@var{associator} @var{key} @var{alist})))
3214 (and ent (cdr ent)))
3217 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
3220 @node Removing Alist Entries
3221 @subsubsection Removing Alist Entries
3223 To remove the element from an association list whose key matches a
3224 specified key, use @code{assq-remove!}, @code{assv-remove!} or
3225 @code{assoc-remove!} (depending, as usual, on the level of equality
3226 required between the key that you specify and the keys in the
3229 As with @code{assq-set!} and friends, the specified alist may or may not
3230 be modified destructively, and the only safe way to update a variable
3231 containing the alist is to @code{set!} it to the value that
3232 @code{assq-remove!} and friends return.
3237 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3238 ("james" . "1a London Road"))
3240 (set! address-list (assoc-remove! address-list "mary"))
3243 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
3246 Note that, when @code{assq/v/oc-remove!} is used to modify an
3247 association list that has been constructed only using the corresponding
3248 @code{assq/v/oc-set!}, there can be at most one matching entry in the
3249 alist, so the question of multiple entries being removed in one go does
3250 not arise. If @code{assq/v/oc-remove!} is applied to an association
3251 list that has been constructed using @code{acons}, or an
3252 @code{assq/v/oc-set!} with a different level of equality, or any mixture
3253 of these, it removes only the first matching entry from the alist, even
3254 if the alist might contain further matching entries. For example:
3257 (define address-list '())
3258 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
3259 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
3262 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
3264 (set! address-list (assoc-remove! address-list "mary"))
3267 (("mary" . "11 Elm Street"))
3270 In this example, the two instances of the string "mary" are not the same
3271 when compared using @code{eq?}, so the two @code{assq-set!} calls add
3272 two distinct entries to @code{address-list}. When compared using
3273 @code{equal?}, both "mary"s in @code{address-list} are the same as the
3274 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
3275 after removing the first matching entry that it finds, and so one of the
3276 "mary" entries is left in place.
3278 @deffn {Scheme Procedure} assq-remove! alist key
3279 @deffnx {Scheme Procedure} assv-remove! alist key
3280 @deffnx {Scheme Procedure} assoc-remove! alist key
3281 @deffnx {C Function} scm_assq_remove_x (alist, key)
3282 @deffnx {C Function} scm_assv_remove_x (alist, key)
3283 @deffnx {C Function} scm_assoc_remove_x (alist, key)
3284 Delete the first entry in @var{alist} associated with @var{key}, and return
3285 the resulting alist.
3288 @node Sloppy Alist Functions
3289 @subsubsection Sloppy Alist Functions
3291 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
3292 like the corresponding non-@code{sloppy-} procedures, except that they
3293 return @code{#f} when the specified association list is not well-formed,
3294 where the non-@code{sloppy-} versions would signal an error.
3296 Specifically, there are two conditions for which the non-@code{sloppy-}
3297 procedures signal an error, which the @code{sloppy-} procedures handle
3298 instead by returning @code{#f}. Firstly, if the specified alist as a
3299 whole is not a proper list:
3302 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3304 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
3305 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 2) ("key" . "door") . "open sesame")
3307 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3313 Secondly, if one of the entries in the specified alist is not a pair:
3316 (assoc 2 '((1 . 1) 2 (3 . 9)))
3318 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
3319 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 1) 2 (3 . 9))
3321 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
3326 Unless you are explicitly working with badly formed association lists,
3327 it is much safer to use the non-@code{sloppy-} procedures, because they
3328 help to highlight coding and data errors that the @code{sloppy-}
3329 versions would silently cover up.
3331 @deffn {Scheme Procedure} sloppy-assq key alist
3332 @deffnx {C Function} scm_sloppy_assq (key, alist)
3333 Behaves like @code{assq} but does not do any error checking.
3334 Recommended only for use in Guile internals.
3337 @deffn {Scheme Procedure} sloppy-assv key alist
3338 @deffnx {C Function} scm_sloppy_assv (key, alist)
3339 Behaves like @code{assv} but does not do any error checking.
3340 Recommended only for use in Guile internals.
3343 @deffn {Scheme Procedure} sloppy-assoc key alist
3344 @deffnx {C Function} scm_sloppy_assoc (key, alist)
3345 Behaves like @code{assoc} but does not do any error checking.
3346 Recommended only for use in Guile internals.
3350 @subsubsection Alist Example
3352 Here is a longer example of how alists may be used in practice.
3355 (define capitals '(("New York" . "Albany")
3356 ("Oregon" . "Salem")
3357 ("Florida" . "Miami")))
3359 ;; What's the capital of Oregon?
3360 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
3361 (assoc-ref capitals "Oregon") @result{} "Salem"
3363 ;; We left out South Dakota.
3365 (assoc-set! capitals "South Dakota" "Pierre"))
3367 @result{} (("South Dakota" . "Pierre")
3368 ("New York" . "Albany")
3369 ("Oregon" . "Salem")
3370 ("Florida" . "Miami"))
3372 ;; And we got Florida wrong.
3374 (assoc-set! capitals "Florida" "Tallahassee"))
3376 @result{} (("South Dakota" . "Pierre")
3377 ("New York" . "Albany")
3378 ("Oregon" . "Salem")
3379 ("Florida" . "Tallahassee"))
3381 ;; After Oregon secedes, we can remove it.
3383 (assoc-remove! capitals "Oregon"))
3385 @result{} (("South Dakota" . "Pierre")
3386 ("New York" . "Albany")
3387 ("Florida" . "Tallahassee"))
3391 @subsection Hash Tables
3392 @tpindex Hash Tables
3394 @c FIXME::martin: Review me!
3396 Hash tables are dictionaries which offer similar functionality as
3397 association lists: They provide a mapping from keys to values. The
3398 difference is that association lists need time linear in the size of
3399 elements when searching for entries, whereas hash tables can normally
3400 search in constant time. The drawback is that hash tables require a
3401 little bit more memory, and that you can not use the normal list
3402 procedures (@pxref{Lists}) for working with them.
3405 * Hash Table Examples:: Demonstration of hash table usage.
3406 * Hash Table Reference:: Hash table procedure descriptions.
3410 @node Hash Table Examples
3411 @subsubsection Hash Table Examples
3413 @c FIXME::martin: Review me!
3415 For demonstration purposes, this section gives a few usage examples of
3416 some hash table procedures, together with some explanation what they do.
3418 First we start by creating a new hash table with 31 slots, and
3419 populate it with two key/value pairs.
3422 (define h (make-hash-table 31))
3424 (hashq-create-handle! h 'foo "bar")
3428 (hashq-create-handle! h 'braz "zonk")
3432 (hashq-create-handle! h 'frob #f)
3437 You can get the value for a given key with the procedure
3438 @code{hashq-ref}, but the problem with this procedure is that you
3439 cannot reliably determine whether a key does exists in the table. The
3440 reason is that the procedure returns @code{#f} if the key is not in
3441 the table, but it will return the same value if the key is in the
3442 table and just happens to have the value @code{#f}, as you can see in
3443 the following examples.
3454 (hashq-ref h 'not-there)
3459 Better is to use the procedure @code{hashq-get-handle}, which makes a
3460 distinction between the two cases. Just like @code{assq}, this
3461 procedure returns a key/value-pair on success, and @code{#f} if the
3465 (hashq-get-handle h 'foo)
3469 (hashq-get-handle h 'not-there)
3474 There is no procedure for calculating the number of key/value-pairs in
3475 a hash table, but @code{hash-fold} can be used for doing exactly that.
3478 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
3483 @node Hash Table Reference
3484 @subsubsection Hash Table Reference
3486 @c FIXME: Describe in broad terms what happens for resizing, and what
3487 @c the initial size means for this.
3489 Like the association list functions, the hash table functions come in
3490 several varieties, according to the equality test used for the keys.
3491 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
3492 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
3493 the @code{hashx-} functions use an application supplied test.
3495 A single @code{make-hash-table} creates a hash table suitable for use
3496 with any set of functions, but it's imperative that just one set is
3497 then used consistently, or results will be unpredictable.
3500 Hash tables are implemented as a vector indexed by a hash value formed
3501 from the key, with an association list of key/value pairs for each
3502 bucket in case distinct keys hash together. Direct access to the
3503 pairs in those lists is provided by the @code{-handle-} functions.
3505 When the number of table entries goes above a threshold the vector is
3506 increased and the entries rehashed, to prevent the bucket lists
3507 becoming too long and slowing down accesses. When the number of
3508 entries goes below a threshold the vector is decreased to save space.
3511 For the @code{hashx-} ``extended'' routines, an application supplies a
3512 @var{hash} function producing an integer index like @code{hashq} etc
3513 below, and an @var{assoc} alist search function like @code{assq} etc
3514 (@pxref{Retrieving Alist Entries}). Here's an example of such
3515 functions implementing case-insensitive hashing of string keys,
3518 (use-modules (srfi srfi-1)
3521 (define (my-hash str size)
3522 (remainder (string-hash-ci str) size))
3523 (define (my-assoc str alist)
3524 (find (lambda (pair) (string-ci=? str (car pair))) alist))
3526 (define my-table (make-hash-table))
3527 (hashx-set! my-hash my-assoc my-table "foo" 123)
3529 (hashx-ref my-hash my-assoc my-table "FOO")
3533 In a @code{hashx-} @var{hash} function the aim is to spread keys
3534 across the vector, so bucket lists don't become long. But the actual
3535 values are arbitrary as long as they're in the range 0 to
3536 @math{@var{size}-1}. Helpful functions for forming a hash value, in
3537 addition to @code{hashq} etc below, include @code{symbol-hash}
3538 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
3539 (@pxref{String Comparison}), and @code{char-set-hash}
3540 (@pxref{Character Set Predicates/Comparison}).
3542 Note that currently, unfortunately, there's no @code{hashx-remove!}
3543 function, which rather limits the usefulness of the @code{hashx-}
3547 @deffn {Scheme Procedure} make-hash-table [size]
3548 Create a new hash table, with an optional minimum vector @var{size}.
3550 When @var{size} is given, the table vector will still grow and shrink
3551 automatically, as described above, but with @var{size} as a minimum.
3552 If an application knows roughly how many entries the table will hold
3553 then it can use @var{size} to avoid rehashing when initial entries are
3557 @deffn {Scheme Procedure} hash-table? obj
3558 @deffnx {C Function} scm_hash_table_p (obj)
3559 Return @code{#t} if @var{obj} is a hash table.
3562 @deffn {Scheme Procedure} hash-clear! table
3563 @deffnx {C Function} scm_hash_clear_x (table)
3564 Remove all items from TABLE (without triggering a resize).
3567 @deffn {Scheme Procedure} hash-ref table key [dflt]
3568 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
3569 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
3570 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
3571 @deffnx {C Function} scm_hash_ref (table, key, dflt)
3572 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
3573 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
3574 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
3575 Lookup @var{key} in the given hash @var{table}, and return the
3576 associated value. If @var{key} is not found, return @var{dflt}, or
3577 @code{#f} if @var{dflt} is not given.
3580 @deffn {Scheme Procedure} hash-set! table key val
3581 @deffnx {Scheme Procedure} hashq-set! table key val
3582 @deffnx {Scheme Procedure} hashv-set! table key val
3583 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
3584 @deffnx {C Function} scm_hash_set_x (table, key, val)
3585 @deffnx {C Function} scm_hashq_set_x (table, key, val)
3586 @deffnx {C Function} scm_hashv_set_x (table, key, val)
3587 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
3588 Associate @var{val} with @var{key} in the given hash @var{table}. If
3589 @var{key} is already present then it's associated value is changed.
3590 If it's not present then a new entry is created.
3593 @deffn {Scheme Procedure} hash-remove! table key
3594 @deffnx {Scheme Procedure} hashq-remove! table key
3595 @deffnx {Scheme Procedure} hashv-remove! table key
3596 @deffnx {C Function} scm_hash_remove_x (table, key)
3597 @deffnx {C Function} scm_hashq_remove_x (table, key)
3598 @deffnx {C Function} scm_hashv_remove_x (table, key)
3599 Remove any association for @var{key} in the given hash @var{table}.
3600 If @var{key} is not in @var{table} then nothing is done.
3603 @deffn {Scheme Procedure} hash key size
3604 @deffnx {Scheme Procedure} hashq key size
3605 @deffnx {Scheme Procedure} hashv key size
3606 @deffnx {C Function} scm_hash (key, size)
3607 @deffnx {C Function} scm_hashq (key, size)
3608 @deffnx {C Function} scm_hashv (key, size)
3609 Return a hash value for @var{key}. This is a number in the range
3610 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
3611 table of the given @var{size}.
3613 Note that @code{hashq} and @code{hashv} may use internal addresses of
3614 objects, so if an object is garbage collected and re-created it can
3615 have a different hash value, even when the two are notionally
3616 @code{eq?}. For instance with symbols,
3619 (hashq 'something 123) @result{} 19
3621 (hashq 'something 123) @result{} 62
3624 In normal use this is not a problem, since an object entered into a
3625 hash table won't be garbage collected until removed. It's only if
3626 hashing calculations are somehow separated from normal references that
3627 its lifetime needs to be considered.
3630 @deffn {Scheme Procedure} hash-get-handle table key
3631 @deffnx {Scheme Procedure} hashq-get-handle table key
3632 @deffnx {Scheme Procedure} hashv-get-handle table key
3633 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
3634 @deffnx {C Function} scm_hash_get_handle (table, key)
3635 @deffnx {C Function} scm_hashq_get_handle (table, key)
3636 @deffnx {C Function} scm_hashv_get_handle (table, key)
3637 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
3638 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3639 given hash @var{table}, or @code{#f} if @var{key} is not in
3643 @deffn {Scheme Procedure} hash-create-handle! table key init
3644 @deffnx {Scheme Procedure} hashq-create-handle! table key init
3645 @deffnx {Scheme Procedure} hashv-create-handle! table key init
3646 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
3647 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
3648 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
3649 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
3650 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
3651 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3652 given hash @var{table}. If @var{key} is not in @var{table} then
3653 create an entry for it with @var{init} as the value, and return that
3657 @deffn {Scheme Procedure} hash-map->list proc table
3658 @deffnx {Scheme Procedure} hash-for-each proc table
3659 @deffnx {C Function} scm_hash_map_to_list (proc, table)
3660 @deffnx {C Function} scm_hash_for_each (proc, table)
3661 Apply @var{proc} to the entries in the given hash @var{table}. Each
3662 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
3663 returns a list of the results from these calls, @code{hash-for-each}
3664 discards the results and returns an unspecified value.
3666 Calls are made over the table entries in an unspecified order, and for
3667 @code{hash-map->list} the order of the values in the returned list is
3668 unspecified. Results will be unpredictable if @var{table} is modified
3671 For example the following returns a new alist comprising all the
3672 entries from @code{mytable}, in no particular order.
3675 (hash-map->list cons mytable)
3679 @deffn {Scheme Procedure} hash-for-each-handle proc table
3680 @deffnx {C Function} scm_hash_for_each_handle (proc, table)
3681 Apply @var{proc} to the entries in the given hash @var{table}. Each
3682 call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
3683 @code{(@var{key} . @var{value})} pair. Return an unspecified value.
3685 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
3686 the argument list of @var{proc}.
3689 @deffn {Scheme Procedure} hash-fold proc init table
3690 @deffnx {C Function} scm_hash_fold (proc, init, table)
3691 Accumulate a result by applying @var{proc} to the elements of the
3692 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
3693 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
3694 from the @var{table} and @var{prior-result} is the return from the
3695 previous @var{proc} call. For the first call, @var{prior-result} is
3696 the given @var{init} value.
3698 Calls are made over the table entries in an unspecified order.
3699 Results will be unpredictable if @var{table} is modified while
3700 @code{hash-fold} is running.
3702 For example, the following returns a count of how many keys in
3703 @code{mytable} are strings.
3706 (hash-fold (lambda (key value prior)
3707 (if (string? key) (1+ prior) prior))
3714 @c TeX-master: "guile.texi"