(Shared Arrays): Rewrite make-shared-array for clarity, adding examples.
[bpt/guile.git] / doc / ref / api-compound.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node Compound Data Types
9 @section Compound Data Types
10
11 This chapter describes Guile's compound data types. By @dfn{compound}
12 we mean that the primary purpose of these data types is to act as
13 containers for other kinds of data (including other compound objects).
14 For instance, a (non-uniform) vector with length 5 is a container that
15 can hold five arbitrary Scheme objects.
16
17 The various kinds of container object differ from each other in how
18 their memory is allocated, how they are indexed, and how particular
19 values can be looked up within them.
20
21 @menu
22 * Pairs:: Scheme's basic building block.
23 * Lists:: Special list functions supported by Guile.
24 * Vectors:: One-dimensional arrays of Scheme objects.
25 * 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.
29 * Records::
30 * Structures::
31 * Dictionary Types:: About dictionary types in general.
32 * Association Lists:: List-based dictionaries.
33 * Hash Tables:: Table-based dictionaries.
34 @end menu
35
36
37 @node Pairs
38 @subsection Pairs
39 @tpindex Pairs
40
41 Pairs are used to combine two Scheme objects into one compound object.
42 Hence the name: A pair stores a pair of objects.
43
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}).
49
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.
58
59 @lisp
60 (1 . 2)
61 (foo . bar)
62 @end lisp
63
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.
68
69 @lisp
70 '(1 . 2)
71 @result{}
72 (1 . 2)
73 '(foo . bar)
74 @result{}
75 (foo . bar)
76 @end lisp
77
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.
83
84 @rnindex cons
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.
90 @end deffn
91
92 @rnindex pair?
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
96 @code{#f}.
97 @end deffn
98
99 @deftypefn {C Function} int scm_is_pair (SCM x)
100 Return 1 when @var{x} is a pair; otherwise return 0.
101 @end deftypefn
102
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
109 are also predefined.
110
111 @rnindex car
112 @rnindex cdr
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.
118 @end deffn
119
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
178
179 @lisp
180 (define caddr (lambda (x) (car (cdr (cdr x)))))
181 @end lisp
182 @end deffn
183
184 @rnindex set-car!
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.
189 @end deffn
190
191 @rnindex set-cdr!
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.
196 @end deffn
197
198
199 @node Lists
200 @subsection Lists
201 @tpindex Lists
202
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.}
208
209 This is the short definition of what a list is:
210
211 @itemize @bullet
212 @item
213 Either the empty list @code{()},
214
215 @item
216 or a pair which has a list in its cdr.
217 @end itemize
218
219 @c FIXME::martin: Describe the pair chaining in more detail.
220
221 @c FIXME::martin: What is a proper, what an improper list?
222 @c What is a circular list?
223
224 @c FIXME::martin: Maybe steal some graphics from the Elisp reference
225 @c manual?
226
227 @menu
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.
236 @end menu
237
238 @node List Syntax
239 @subsubsection List Read Syntax
240
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.}.
245
246 @lisp
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}
250 @end lisp
251
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:
256
257 @lisp
258 (car '(1))
259 @result{}
260 1
261 (cdr '(1))
262 @result{}
263 ()
264 @end lisp
265
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}).
269
270
271 @node List Predicates
272 @subsubsection List Predicates
273
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.
278
279 @rnindex list?
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}.
283 @end deffn
284
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.
289
290 @rnindex null?
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}.
294 @end deffn
295
296 @deftypefn {C Function} int scm_is_null (SCM x)
297 Return 1 when @var{x} is the empty list; otherwise return 0.
298 @end deftypefn
299
300
301 @node List Constructors
302 @subsubsection List Constructors
303
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.
308
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.
312 @c
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})
320 @rnindex list
321 Return a new list containing elements @var{elem1} to @var{elemN}.
322
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.
328 @end deffn
329
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
333 @c already.
334 @c
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.
342 @end deffn
343
344 @deffn {Scheme Procedure} list-copy lst
345 @deffnx {C Function} scm_list_copy (lst)
346 Return a (newly-created) copy of @var{lst}.
347 @end deffn
348
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.
353 @end deffn
354
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}).
362
363 @node List Selection
364 @subsubsection List Selection
365
366 These procedures are used to get some information about a list, or to
367 retrieve one or more elements of a list.
368
369 @rnindex length
370 @deffn {Scheme Procedure} length lst
371 @deffnx {C Function} scm_length (lst)
372 Return the number of elements in list @var{lst}.
373 @end deffn
374
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.
379 @end deffn
380
381 @rnindex list-ref
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}.
385 @end deffn
386
387 @rnindex list-tail
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.
393
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}.
397 @end deffn
398
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
402 return it.
403 @end deffn
404
405 @node Append/Reverse
406 @subsubsection Append and Reverse
407
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
414 variants.
415
416 @rnindex append
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
422 @var{lstN}.
423
424 @lisp
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))
428 @end lisp
429
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.
432
433 @lisp
434 (append '(a b) '(c . d)) @result{} (a b c . d)
435 (append '() 'a) @result{} a
436 @end lisp
437
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.
441
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.
445 @end deffn
446
447 @rnindex reverse
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.
453
454 @code{reverse} constructs a new list, @code{reverse!} modifies
455 @var{lst} in constructing its return.
456
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.
461 @end deffn
462
463 @node List Modification
464 @subsubsection List Modification
465
466 The following procedures modify an existing list, either by changing
467 elements of the list, or by changing the list structure itself.
468
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}.
472 @end deffn
473
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}.
477 @end deffn
478
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?}.
485 @end deffn
486
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?}.
493 @end deffn
494
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?}.
501 @end deffn
502
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.
515 @end deffn
516
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!}.
522 @end deffn
523
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!}.
529 @end deffn
530
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!}.
536 @end deffn
537
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.
544
545 @code{filter!} is allowed, but not required to modify the structure of
546 @end deffn
547
548 @node List Searching
549 @subsubsection List Searching
550
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.
556
557 @rnindex memq
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
565 returned.
566 @end deffn
567
568 @rnindex memv
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
576 returned.
577 @end deffn
578
579 @rnindex member
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.
588 @end deffn
589
590
591 @node List Mapping
592 @subsubsection List Mapping
593
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
599 return value.
600
601 @rnindex map
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
612 elements.
613 @end deffn
614
615 @rnindex for-each
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.
621 @end deffn
622
623
624 @node Vectors
625 @subsection Vectors
626 @tpindex Vectors
627
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.
634
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
640 (@pxref{Arrays}).
641
642 @menu
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.
647 @end menu
648
649
650 @node Vector Syntax
651 @subsubsection Read Syntax for Vectors
652
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.
661
662 @lisp
663 #(1 2 3)
664 #("Hello" foo #xdeadbeef)
665 @end lisp
666
667 Like lists, vectors have to be quoted:
668
669 @lisp
670 '#(a b c) @result{} #(a b c)
671 @end lisp
672
673 @node Vector Creation
674 @subsubsection Dynamic Vector Creation and Validation
675
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.
681
682 @rnindex vector
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}.
689
690 @lisp
691 (vector 'a 'b 'c) @result{} #(a b c)
692 @end lisp
693 @end deffn
694
695 The inverse operation is @code{vector->list}:
696
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}.
701
702 @lisp
703 (vector->list '#(dah dah didah)) @result{} (dah dah didah)
704 (list->vector '(dididit dah)) @result{} #(dididit dah)
705 @end lisp
706 @end deffn
707
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
711 is):
712
713 @rnindex make-vector
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
719 unspecified.
720 @end deffn
721
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}.
724 @end deftypefn
725
726 To check whether an arbitrary Scheme value @emph{is} a vector, use the
727 @code{vector?} primitive:
728
729 @rnindex vector?
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
733 @code{#f}.
734 @end deffn
735
736 @deftypefn {C Function} int scm_is_vector (SCM obj)
737 Return non-zero when @var{obj} is a vector, otherwise return
738 @code{zero}.
739 @end deftypefn
740
741 @node Vector Accessors
742 @subsubsection Accessing and Modifying Vector Contents
743
744 @code{vector-length} and @code{vector-ref} return information about a
745 given vector, respectively its size and the elements that are contained
746 in the vector.
747
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.
752 @end deffn
753
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}.
756 @end deftypefn
757
758 @rnindex vector-ref
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}.
763 @lisp
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)))))
767 (if (inexact? i)
768 (inexact->exact i)
769 i))) @result{} 13
770 @end lisp
771 @end deffn
772
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
775 @var{vector}.
776 @end deftypefn
777
778 A vector created by one of the dynamic vector constructor procedures
779 (@pxref{Vector Creation}) can be modified using the following
780 procedures.
781
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
785 error.
786
787 @rnindex vector-set!
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.
793 @lisp
794 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
795 (vector-set! vec 1 '("Sue" "Sue"))
796 vec) @result{} #(0 ("Sue" "Sue") "Anna")
797 @end lisp
798 @end deffn
799
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}.
802 @end deftypefn
803
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.
809 @end deffn
810
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.
816
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}.
821 @end deffn
822
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.
828
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}.
833 @end deffn
834
835 @node Vector Accessing from C
836 @subsubsection Vector Accessing from C
837
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.
849
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_*}
853 macros below.
854
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}.
858 @end deftypefn
859
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
862 checking is done.
863 @end deftypefn
864
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.
868 @end deftypefn
869
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.
873 @end deftypefn
874
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}.
881
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.
885
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).
888
889 @example
890 scm_t_array_handle handle;
891 size_t i, len;
892 ssize_t inc;
893 const SCM *elt;
894 SCM list;
895
896 elt = scm_vector_elements (vec, &handle, &len, &inc);
897 list = SCM_EOL;
898 for (i = 0; i < len; i++, elt += inc)
899 list = scm_cons (*elt, list);
900 scm_array_handle_release (&handle);
901 @end example
902
903 @end deftypefn
904
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
907 the vector.
908
909 The following example shows the typical way to use this function. It
910 fills a vector with @code{#t}.
911
912 @example
913 scm_t_array_handle handle;
914 size_t i, len;
915 ssize_t inc;
916 SCM *elt;
917
918 elt = scm_vector_elements (vec, &handle, &len, &inc);
919 for (i = 0; i < len; i++, elt += inc)
920 *elt = SCM_BOOL_T;
921 scm_array_handle_release (&handle);
922 @end example
923
924 @end deftypefn
925
926 @node Uniform Numeric Vectors
927 @subsection Uniform Numeric Vectors
928
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
933 sizes.
934
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,
941 @xref{Arrays}.
942
943 Uniform numeric vectors are the special case of one dimensional uniform
944 numeric arrays.
945
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.
955
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
958 section.
959
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
969 slower.
970
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
977 optimize later on.
978
979 The generic set of procedures uses @code{uniform} in its names, the
980 specific ones use the tag from the following table.
981
982 @table @nicode
983 @item u8
984 unsigned 8-bit integers
985
986 @item s8
987 signed 8-bit integers
988
989 @item u16
990 unsigned 16-bit integers
991
992 @item s16
993 signed 16-bit integers
994
995 @item u32
996 unsigned 32-bit integers
997
998 @item s32
999 signed 32-bit integers
1000
1001 @item u64
1002 unsigned 64-bit integers
1003
1004 @item s64
1005 signed 64-bit integers
1006
1007 @item f32
1008 the C type @code{float}
1009
1010 @item f64
1011 the C type @code{double}
1012
1013 @item c32
1014 complex numbers in rectangular form with the real and imaginary part
1015 being a @code{float}
1016
1017 @item c64
1018 complex numbers in rectangular form with the real and imaginary part
1019 being a @code{double}
1020
1021 @end table
1022
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,
1026
1027 @lisp
1028 #u16(1 2 3)
1029 #f64(3.1415 2.71)
1030 @end lisp
1031
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.
1037
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
1065 indicated type.
1066 @end deffn
1067
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
1095 unspecified.
1096 @end deffn
1097
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.
1125 @end deffn
1126
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}.
1154 @end deffn
1155
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.
1184 @end deffn
1185
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
1214 unspecified.
1215 @end deffn
1216
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}.
1244 @end deffn
1245
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}.
1272 @end deffn
1273
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.
1302 @end deffn
1303
1304 @deftypefn {C Function} int scm_is_uniform_vector (SCM uvec)
1305 Return non-zero when @var{uvec} is a uniform numeric vector, zero
1306 otherwise.
1307 @end deftypefn
1308
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
1325 in bytes.
1326
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.
1331 @end deftypefn
1332
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}.
1335 @end deftypefn
1336
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.
1352 @end deftypefn
1353
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.
1369 @end deftypefn
1370
1371 @node Bit Vectors
1372 @subsection Bit Vectors
1373
1374 @noindent
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
1377 @code{#*}, e.g.,
1378
1379 @example
1380 (make-bitvector 8 #f) @result{}
1381 #*00000000
1382 @end example
1383
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.
1387
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
1391 return @code{#f}.
1392 @end deffn
1393
1394 @deftypefn {C Function} int scm_is_bitvector (SCM obj)
1395 Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
1396 @end deftypefn
1397
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}.
1402 @end deffn
1403
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
1406 @code{size_t}.
1407 @end deftypefn
1408
1409 @deffn {Scheme Procedure} bitvector . bits
1410 @deffnx {C Function} scm_bitvector (bits)
1411 Create a new bitvector with the arguments as elements.
1412 @end deffn
1413
1414 @deffn {Scheme Procedure} bitvector-length vec
1415 @deffnx {C Function} scm_bitvector_length (vec)
1416 Return the length of the bitvector @var{vec}.
1417 @end deffn
1418
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
1421 @code{size_t}.
1422 @end deftypefn
1423
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
1427 @var{vec}.
1428 @end deffn
1429
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
1432 @var{vec}.
1433 @end deftypefn
1434
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.
1439 @end deffn
1440
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.
1444 @end deftypefn
1445
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.
1450 @end deffn
1451
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
1455 of @var{list}.
1456 @end deffn
1457
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}.
1462 @end deffn
1463
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,
1468
1469 @example
1470 (bit-count #f #*000111000) @result{} 6
1471 @end example
1472 @end deffn
1473
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,
1480
1481 @example
1482 (bit-position #t #*000101 0) @result{} 3
1483 (bit-position #f #*0001111 3) @result{} #f
1484 @end example
1485 @end deffn
1486
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.
1490 @end deffn
1491
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.
1496
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
1502 ANDNOT.
1503
1504 @example
1505 (define bv #*01000010)
1506 (bit-set*! bv #*10010001 #t)
1507 bv
1508 @result{} #*11010011
1509 @end example
1510
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}.
1513
1514 @example
1515 (define bv #*01000010)
1516 (bit-set*! bv #u(5 2 7) #t)
1517 bv
1518 @result{} #*01100111
1519 @end example
1520 @end deffn
1521
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.
1526
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.
1532
1533 For example,
1534
1535 @example
1536 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1537 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1538 @end example
1539 @end deffn
1540
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
1546 and the offset.
1547 @end deftypefn
1548
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
1551 and writing.
1552 @end deftypefn
1553
1554 @node Generalized Vectors
1555 @subsection Generalized Vectors
1556
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.
1561
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.
1566
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.
1571 @end deffn
1572
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}.
1576 @end deffn
1577
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}.
1582 @end deffn
1583
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}.
1588 @end deffn
1589
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}.
1594 @end deffn
1595
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}.
1599 @end deftypefn
1600
1601 @deftypefn {C Function} size_t scm_c_generalized_vector_length (SCM v)
1602 Return the length of the generalized vector @var{v}.
1603 @end deftypefn
1604
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}.
1607 @end deftypefn
1608
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}
1611 to @var{val}.
1612 @end deftypefn
1613
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.
1620 @end deftypefn
1621
1622 @node Arrays
1623 @subsection Arrays
1624 @tpindex Arrays
1625
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.
1629
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.
1637
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.
1647
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.
1651
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
1656 length zero.
1657
1658 Generalized vectors, such as strings, uniform numeric vectors, bit
1659 vectors and ordinary vectors, are the special case of one dimensional
1660 arrays.
1661
1662 @menu
1663 * Array Syntax::
1664 * Array Procedures::
1665 * Shared Arrays::
1666 * Accessing Arrays from C::
1667 @end menu
1668
1669 @node Array Syntax
1670 @subsubsection Array Syntax
1671
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.
1676
1677 In more words, the array tag is of the form
1678
1679 @example
1680 #<rank><vectag><@@lower><:len><@@lower><:len>...
1681 @end example
1682
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.
1688
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.
1692
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.
1697
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.
1705
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.
1709
1710 Thus,
1711
1712 @table @code
1713 @item #(1 2 3)
1714 is an ordinary array of rank 1 with lower bound 0 in dimension 0.
1715 (I.e., a regular vector.)
1716
1717 @item #@@2(1 2 3)
1718 is an ordinary array of rank 1 with lower bound 2 in dimension 0.
1719
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
1722 and 0..2.
1723
1724 @item #u32(0 1 2)
1725 is a uniform u8 array of rank 1.
1726
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.
1729
1730 @item #2()
1731 is a two-dimensional array with index ranges 0..-1 and 0..-1, i.e. both
1732 dimensions have length zero.
1733
1734 @item #2:0:2()
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.
1737
1738 @item #0(12)
1739 is a rank-zero array with contents 12.
1740
1741 @end table
1742
1743 @node Array Procedures
1744 @subsubsection Array Procedures
1745
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:
1748
1749 @example
1750 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1751 @end example
1752
1753 The range of each dimension can also be given explicitly, e.g., another
1754 way to create the same array:
1755
1756 @example
1757 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1758 @end example
1759
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.
1764
1765
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
1769 not.
1770
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
1773 its value.
1774 @end deffn
1775
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
1779 @code{#f} if not.
1780 @end deffn
1781
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.
1784 @end deftypefn
1785
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
1788 @code{1} if not.
1789 @end deftypefn
1790
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} ...)}.
1794 @end deffn
1795
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}.
1800
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.
1804
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.
1808
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.
1815
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}).
1822 @end deffn
1823
1824 @deffn {Scheme Procedure} list->array dimspec list
1825 Equivalent to @code{(list->typed-array #t @var{dimspec}
1826 @var{list})}.
1827 @end deffn
1828
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}.
1833
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.
1840 @end deffn
1841
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
1846 as @var{array}.
1847 @end deffn
1848
1849 @deffn {Scheme Procedure} array-ref array idx @dots{}
1850 Return the element at @code{(idx @dots{})} in @var{array}.
1851
1852 @example
1853 (define a (make-array 999 '(1 2) '(3 4)))
1854 (array-ref a 2 4) @result{} 999
1855 @end example
1856 @end deffn
1857
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
1861 @code{array-ref}.
1862
1863 @example
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
1867 @end example
1868 @end deffn
1869
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.
1874
1875 @example
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))
1879 @end example
1880 @end deffn
1881
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}.
1890
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.
1896
1897 For example,
1898
1899 @lisp
1900 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1)
1901 @result{}
1902 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1903
1904 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0)
1905 @result{}
1906 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1907 @end lisp
1908 @end deffn
1909
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}.
1914
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}.
1919
1920 For example,
1921
1922 @example
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)
1926 @end example
1927 @end deffn
1928
1929 @deffn {Scheme Procedure} array-rank obj
1930 @deffnx {C Function} scm_array_rank (obj)
1931 Return the rank of @var{array}.
1932 @end deffn
1933
1934 @deftypefn {C Function} scm_c_array_rank (SCM array)
1935 Return the rank of @var{array} as a @code{size_t}.
1936 @end deftypefn
1937
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
1941 @var{array}.
1942 @end deffn
1943
1944 @c FIXME: Describe how the order affects the copying (it matters for
1945 @c shared arrays with the same underlying root vector, presumably).
1946 @c
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
1953 unspecified.
1954 @end deffn
1955
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
1959 is unspecified.
1960 @end deffn
1961
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.
1969 @end deffn
1970
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.
1979
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
1982 memory.
1983 @end deffn
1984
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
1987 @c feature?
1988 @c
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?
1994
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.
2000
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.
2005
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
2009 each @var{src}.
2010 @end deffn
2011
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.
2016 @end deffn
2017
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.
2022
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.
2026
2027 For example, to create a @m{4\times4, 4x4} matrix representing a
2028 cyclic group,
2029
2030 @tex
2031 \advance\leftskip by 2\lispnarrowing {
2032 $\left(\matrix{%
2033 0 & 1 & 2 & 3 \cr
2034 1 & 2 & 3 & 0 \cr
2035 2 & 3 & 0 & 1 \cr
2036 3 & 0 & 1 & 2 \cr
2037 }\right)$} \par
2038 @end tex
2039 @ifnottex
2040 @example
2041 / 0 1 2 3 \
2042 | 1 2 3 0 |
2043 | 2 3 0 1 |
2044 \ 3 0 1 2 /
2045 @end example
2046 @end ifnottex
2047
2048 @example
2049 (define a (make-array #f 4 4))
2050 (array-index-map! a (lambda (i j)
2051 (modulo (+ i j) 4)))
2052 @end example
2053 @end deffn
2054
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
2062 unchanged.
2063
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.
2067
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)}.
2071 @end deffn
2072
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
2076 @var{port-or-fdes}.
2077
2078 The optional arguments @var{start}
2079 and @var{end} allow
2080 a specified region of a vector (or linearized array) to be written.
2081
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)}.
2086 @end deffn
2087
2088 @node Shared Arrays
2089 @subsubsection Shared Arrays
2090
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}).
2097
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
2102 @var{oldarray}.
2103
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.
2108
2109 @sp 1
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,
2115
2116 @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))
2119 @end example
2120
2121 The new array can have fewer dimensions than @var{oldarray}, for
2122 example to take a column from an array.
2123
2124 @example
2125 (make-shared-array #2((a b c) (d e f) (g h i))
2126 (lambda (i) (list i 2))
2127 '(0 2))
2128 @result{} #1(c f i)
2129 @end example
2130
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,
2133
2134 @example
2135 (make-shared-array #2((a b c) (d e f) (g h i))
2136 (lambda (i) (list i i))
2137 '(0 2))
2138 @result{} #1(a e i)
2139 @end example
2140
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
2144 array.)
2145
2146 @example
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)))
2149 4 3)
2150 @result{} #2((a b c) (d e f) (g h i) (j k l))
2151 @end example
2152
2153 By negating an index the order that elements appear can be reversed.
2154 The following just reverses the column order,
2155
2156 @example
2157 (make-shared-array #2((a b c) (d e f) (g h i))
2158 (lambda (i j) (list i (- 2 j)))
2159 3 3)
2160 @result{} #2((c b a) (f e d) (i h g))
2161 @end example
2162
2163 A fixed offset on indexes allows for instance a change from a 0 based
2164 to a 1 based array,
2165
2166 @example
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)))
2170 '(1 3) '(1 3)))
2171 (array-ref x 0 0) @result{} a
2172 (array-ref y 1 1) @result{} a
2173 @end example
2174
2175 A multiple on an index allows every Nth element of an array to be
2176 taken. The following is every third element,
2177
2178 @example
2179 (make-shared-array #1(a b c d e f g h i j k l)
2180 (lambda (i) (* i 3))
2181 4)
2182 @result{} #1(a d g j)
2183 @end example
2184
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
2188 possible.
2189
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.
2194 @end deffn
2195
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.
2199 @end deffn
2200
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.
2204 @end deffn
2205
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.
2209 @end deffn
2210
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.
2219
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}.
2225
2226 @lisp
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))
2231 @end lisp
2232 @end deffn
2233
2234 @node Accessing Arrays from C
2235 @subsubsection Accessing Arrays from C
2236
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
2242 routines.
2243
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
2249 error is signalled.
2250
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.)
2254
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.
2261
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.
2264
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.
2270
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.
2278
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.
2283
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}.
2292
2293 The function @code{scm_array_handle_dims} gives you (indirect) access to
2294 the coefficients @code{c[k]}.
2295
2296 @c XXX
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.
2300
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.
2306 @end deftp
2307
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
2314 function.
2315 @end deftypefn
2316
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.
2320 @end deftypefn
2321
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}.
2324 @end deftypefn
2325
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:
2329
2330 @table @code
2331 @item ssize_t lbnd
2332 @itemx ssize_t ubnd
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}.
2336
2337 @item ssize_t inc
2338 The distance from one element of this dimension to the next. Note, too,
2339 that this can be negative.
2340 @end table
2341 @end deftp
2342
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
2349 from its indices.
2350
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}.
2355
2356 Here is how one can compute the position @var{pos} of an element given
2357 its indices in the vector @var{indices}:
2358
2359 @example
2360 ssize_t indices[RANK];
2361 scm_t_array_dim *dims;
2362 ssize_t pos;
2363 size_t i;
2364
2365 pos = 0;
2366 for (i = 0; i < RANK; i++)
2367 @{
2368 if (indices[i] < dims[i].lbnd || indices[i] > dims[i].ubnd)
2369 out_of_range ();
2370 pos += (indices[i] - dims[i].lbnd) * dims[i].inc;
2371 @}
2372 @end example
2373 @end deftypefn
2374
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
2380 indices.
2381 @end deftypefn
2382
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}.
2387 @end deftypefn
2388
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}.
2394 @end deftypefn
2395
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.
2400 @end deftypefn
2401
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.
2405 @end deftypefn
2406
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}.
2411 @end deftypefn
2412
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.
2416 @end deftypefn
2417
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
2420 by @var{handle}.
2421 @end deftypefn
2422
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
2437 remains reserved.
2438
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.
2442 @end deftypefn
2443
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.
2458 @end deftypefn
2459
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.
2463
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}.
2467
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.
2472
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.
2476
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}:
2479
2480 @example
2481 SCM bit_array;
2482 scm_t_array_handle handle;
2483 scm_t_uint32 *bits;
2484 ssize_t pos;
2485 size_t abs_pos;
2486 size_t word_pos, mask;
2487
2488 scm_array_get_handle (&bit_array, &handle);
2489 bits = scm_array_handle_bit_elements (&handle);
2490
2491 pos = ...
2492 abs_pos = pos + scm_array_handle_bit_elements_offset (&handle);
2493 word_pos = abs_pos / 32;
2494 mask = 1L << (abs_pos % 32);
2495
2496 if (bits[word_pos] & mask)
2497 /* bit is set. */
2498
2499 scm_array_handle_release (&handle);
2500 @end example
2501
2502 @end deftypefn
2503
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.
2508 @end deftypefn
2509
2510 @node Records
2511 @subsection Records
2512
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.
2515
2516 @deffn {Scheme Procedure} record? obj
2517 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
2518 otherwise.
2519
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.
2522 @end deffn
2523
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.
2532 @end deffn
2533
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.
2545 @end deffn
2546
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.
2552 @end deffn
2553
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}.
2562 @end deffn
2563
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
2573 @var{rtd}.
2574 @end deffn
2575
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.
2584 @end deffn
2585
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
2590 @var{rtd}.
2591 @end deffn
2592
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}.
2598 @end deffn
2599
2600
2601 @node Structures
2602 @subsection Structures
2603 @tpindex Structures
2604
2605 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
2606 be reviewed]
2607
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
2610 itself a structure.
2611
2612 Structures are less abstract and more general than traditional records.
2613 In fact, in Guile Scheme, records are implemented using structures.
2614
2615 @menu
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
2620 @end menu
2621
2622 @node Structure Concepts
2623 @subsubsection Structure Concepts
2624
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.
2631
2632 Three concepts are key to understanding structures.
2633
2634 @itemize @bullet{}
2635 @item @dfn{layout specifications}
2636
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.
2640
2641 @item @dfn{structural accessors}
2642
2643 Structure access is by field number. There is only one set of
2644 accessors common to all structure objects.
2645
2646 @item @dfn{vtables}
2647
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.
2653 @end itemize
2654
2655
2656
2657 @node Structure Layout
2658 @subsubsection Structure Layout
2659
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.
2663
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:
2666
2667 @itemize @bullet{}
2668 @item 'u' -- unprotected
2669
2670 The field holds binary data that is not GC protected.
2671
2672 @item 'p' -- protected
2673
2674 The field holds a Scheme value and is GC protected.
2675
2676 @item 's' -- self
2677
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.
2683 @end itemize
2684
2685
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:
2689
2690 @itemize @bullet{}
2691 @item 'w' -- writable
2692
2693 The field can be read and written.
2694
2695 @item 'r' -- readable
2696
2697 The field can be read, but not written.
2698
2699 @item 'o' -- opaque
2700
2701 The field can be neither read nor written. This kind
2702 of protection is for fields useful only to built-in routines.
2703 @end itemize
2704
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
2708 be described as:
2709
2710 @example
2711 ; cons pairs have two writable fields of Scheme data
2712 "pwpw"
2713 @end example
2714
2715 A pair object in which the first field is held constant could be:
2716
2717 @example
2718 "prpw"
2719 @end example
2720
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)}.
2724
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
2732 described as:
2733
2734 @example
2735 ; A vector is an arbitrary number of writable fields holding Scheme
2736 ; values:
2737 "pW"
2738 @end example
2739
2740 In the above example, field 0 contains the size of the vector and
2741 fields beginning at 1 contain the vector elements.
2742
2743 A kind of tagged vector (a constant tag followed by conventional
2744 vector elements) might be:
2745
2746 @example
2747 "prpW"
2748 @end example
2749
2750
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:
2754
2755 @deffn {Scheme Procedure} make-struct-layout fields
2756 @deffnx {C Function} scm_make_struct_layout (fields)
2757 Return a new structure layout object.
2758
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.
2767 @end deffn
2768
2769
2770
2771 @node Structure Basics
2772 @subsubsection Structure Basics
2773
2774 This section describes the basic procedures for creating and accessing
2775 structures.
2776
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.
2780
2781 @var{type} must be a vtable structure (@pxref{Vtables}).
2782
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.
2786
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
2792 Scheme programs.
2793
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
2796 initialized to 0.
2797
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
2801 more powerful.
2802
2803 For more information, see the documentation for @code{make-vtable-vtable}.
2804 @end deffn
2805
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
2809 @code{#f}.
2810 @end deffn
2811
2812
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}.
2818
2819 If the field is of type 'p', then it can be set to an arbitrary value.
2820
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.
2823 @end deffn
2824
2825
2826
2827 @node Vtables
2828 @subsubsection Vtables
2829
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.
2837
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}.
2841 @end deffn
2842
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.
2846 @end deffn
2847
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:
2855
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.
2859
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}).
2863
2864 @var{tail-size} specifies the size of the tail-array (if any) of
2865 this vtable.
2866
2867 @var{init1}, @dots{} are the optional initializers for the fields of
2868 the vtable.
2869
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:
2875
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.
2879
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
2884 the chain.
2885
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.)
2891
2892 @lisp
2893 (define ball-root (make-vtable-vtable "pr" 0))
2894
2895 (define (make-ball-type ball-color)
2896 (make-struct ball-root 0
2897 (make-struct-layout "pw")
2898 (lambda (ball port)
2899 (format port "#<a ~A ball owned by ~A>"
2900 (color ball)
2901 (owner ball)))
2902 ball-color))
2903 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
2904 (define (owner ball) (struct-ref ball 0))
2905
2906 (define red (make-ball-type 'red))
2907 (define green (make-ball-type 'green))
2908
2909 (define (make-ball type owner) (make-struct type 0 owner))
2910
2911 (define ball (make-ball green 'Nisse))
2912 ball @result{} #<a green ball owned by Nisse>
2913 @end lisp
2914 @end deffn
2915
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}.
2919 @end deffn
2920
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}.
2924 @end deffn
2925
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}.
2929 @end deffn
2930
2931
2932 @node Dictionary Types
2933 @subsection Dictionary Types
2934
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
2943 such a way.
2944
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.
2949
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.
2954
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.
2962
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.
2967
2968 @node Association Lists
2969 @subsection Association Lists
2970 @tpindex Association Lists
2971 @tpindex Alist
2972 @cindex association List
2973 @cindex alist
2974 @cindex aatabase
2975
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
2980 @code{cdr}.
2981
2982 @example
2983 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
2984 (KEY2 . VALUE2)
2985 (KEY3 . VALUE3)
2986 @dots{}
2987 )
2988 @end example
2989
2990 @noindent
2991 Association lists are also known, for short, as @dfn{alists}.
2992
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.
3000
3001 @menu
3002 * Alist Key Equality::
3003 * Adding or Setting Alist Entries::
3004 * Retrieving Alist Entries::
3005 * Removing Alist Entries::
3006 * Sloppy Alist Functions::
3007 * Alist Example::
3008 @end menu
3009
3010 @node Alist Key Equality
3011 @subsubsection Alist Key Equality
3012
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
3017 required entry.
3018
3019 @itemize @bullet
3020 @item
3021 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
3022 equality.
3023
3024 @item
3025 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
3026 key equality.
3027
3028 @item
3029 Procedures with @dfn{assoc} in their name use @code{equal?} to
3030 determine key equality.
3031 @end itemize
3032
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.
3035
3036 @node Adding or Setting Alist Entries
3037 @subsubsection Adding or Setting Alist Entries
3038
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.
3045
3046 In the most common usage of @code{acons}, a variable holding the
3047 original association list is updated with the combined alist:
3048
3049 @example
3050 (set! address-list (acons name address address-list))
3051 @end example
3052
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.
3056
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.
3061
3062 @example
3063 (set! task-list (acons 3 "pay gas bill" '()))
3064 task-list
3065 @result{}
3066 ((3 . "pay gas bill"))
3067
3068 (set! task-list (acons 3 "tidy bedroom" task-list))
3069 task-list
3070 @result{}
3071 ((3 . "tidy bedroom") (3 . "pay gas bill"))
3072 @end example
3073
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.
3082
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
3086 value returned:
3087
3088 @example
3089 address-list
3090 @result{}
3091 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
3092
3093 (assoc-set! address-list "james" "1a London Road")
3094 @result{}
3095 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3096
3097 address-list
3098 @result{}
3099 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3100 @end example
3101
3102 Or they may not:
3103
3104 @example
3105 (assoc-set! address-list "bob" "11 Newington Avenue")
3106 @result{}
3107 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3108 ("james" . "1a London Road"))
3109
3110 address-list
3111 @result{}
3112 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
3113 @end example
3114
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
3117 returned value:
3118
3119 @example
3120 (set! address-list
3121 (assoc-set! address-list "bob" "11 Newington Avenue"))
3122 address-list
3123 @result{}
3124 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3125 ("james" . "1a London Road"))
3126 @end example
3127
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
3131 difference to you.
3132
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
3137 it.
3138
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.
3145 @end deffn
3146
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.
3157
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
3160 association list.
3161 @end deffn
3162
3163 @node Retrieving Alist Entries
3164 @subsubsection Retrieving Alist Entries
3165 @rnindex assq
3166 @rnindex assv
3167 @rnindex assoc
3168
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.
3174
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).
3188 @end deffn
3189
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}.
3194
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.
3201
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
3211
3212 @lisp
3213 (let ((ent (@var{associator} @var{key} @var{alist})))
3214 (and ent (cdr ent)))
3215 @end lisp
3216
3217 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
3218 @end deffn
3219
3220 @node Removing Alist Entries
3221 @subsubsection Removing Alist Entries
3222
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
3227 association list).
3228
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.
3233
3234 @example
3235 address-list
3236 @result{}
3237 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
3238 ("james" . "1a London Road"))
3239
3240 (set! address-list (assoc-remove! address-list "mary"))
3241 address-list
3242 @result{}
3243 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
3244 @end example
3245
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:
3255
3256 @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"))
3260 address-list
3261 @result{}
3262 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
3263
3264 (set! address-list (assoc-remove! address-list "mary"))
3265 address-list
3266 @result{}
3267 (("mary" . "11 Elm Street"))
3268 @end example
3269
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.
3277
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.
3286 @end deffn
3287
3288 @node Sloppy Alist Functions
3289 @subsubsection Sloppy Alist Functions
3290
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.
3295
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:
3300
3301 @example
3302 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3303 @result{}
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")
3306
3307 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
3308 @result{}
3309 #f
3310 @end example
3311
3312 @noindent
3313 Secondly, if one of the entries in the specified alist is not a pair:
3314
3315 @example
3316 (assoc 2 '((1 . 1) 2 (3 . 9)))
3317 @result{}
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))
3320
3321 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
3322 @result{}
3323 #f
3324 @end example
3325
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.
3330
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.
3335 @end deffn
3336
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.
3341 @end deffn
3342
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.
3347 @end deffn
3348
3349 @node Alist Example
3350 @subsubsection Alist Example
3351
3352 Here is a longer example of how alists may be used in practice.
3353
3354 @lisp
3355 (define capitals '(("New York" . "Albany")
3356 ("Oregon" . "Salem")
3357 ("Florida" . "Miami")))
3358
3359 ;; What's the capital of Oregon?
3360 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
3361 (assoc-ref capitals "Oregon") @result{} "Salem"
3362
3363 ;; We left out South Dakota.
3364 (set! capitals
3365 (assoc-set! capitals "South Dakota" "Pierre"))
3366 capitals
3367 @result{} (("South Dakota" . "Pierre")
3368 ("New York" . "Albany")
3369 ("Oregon" . "Salem")
3370 ("Florida" . "Miami"))
3371
3372 ;; And we got Florida wrong.
3373 (set! capitals
3374 (assoc-set! capitals "Florida" "Tallahassee"))
3375 capitals
3376 @result{} (("South Dakota" . "Pierre")
3377 ("New York" . "Albany")
3378 ("Oregon" . "Salem")
3379 ("Florida" . "Tallahassee"))
3380
3381 ;; After Oregon secedes, we can remove it.
3382 (set! capitals
3383 (assoc-remove! capitals "Oregon"))
3384 capitals
3385 @result{} (("South Dakota" . "Pierre")
3386 ("New York" . "Albany")
3387 ("Florida" . "Tallahassee"))
3388 @end lisp
3389
3390 @node Hash Tables
3391 @subsection Hash Tables
3392 @tpindex Hash Tables
3393
3394 @c FIXME::martin: Review me!
3395
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.
3403
3404 @menu
3405 * Hash Table Examples:: Demonstration of hash table usage.
3406 * Hash Table Reference:: Hash table procedure descriptions.
3407 @end menu
3408
3409
3410 @node Hash Table Examples
3411 @subsubsection Hash Table Examples
3412
3413 @c FIXME::martin: Review me!
3414
3415 For demonstration purposes, this section gives a few usage examples of
3416 some hash table procedures, together with some explanation what they do.
3417
3418 First we start by creating a new hash table with 31 slots, and
3419 populate it with two key/value pairs.
3420
3421 @lisp
3422 (define h (make-hash-table 31))
3423
3424 (hashq-create-handle! h 'foo "bar")
3425 @result{}
3426 (foo . "bar")
3427
3428 (hashq-create-handle! h 'braz "zonk")
3429 @result{}
3430 (braz . "zonk")
3431
3432 (hashq-create-handle! h 'frob #f)
3433 @result{}
3434 (frob . #f)
3435 @end lisp
3436
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.
3444
3445 @lisp
3446 (hashq-ref h 'foo)
3447 @result{}
3448 "bar"
3449
3450 (hashq-ref h 'frob)
3451 @result{}
3452 #f
3453
3454 (hashq-ref h 'not-there)
3455 @result{}
3456 #f
3457 @end lisp
3458
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
3462 key is not found.
3463
3464 @lisp
3465 (hashq-get-handle h 'foo)
3466 @result{}
3467 (foo . "bar")
3468
3469 (hashq-get-handle h 'not-there)
3470 @result{}
3471 #f
3472 @end lisp
3473
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.
3476
3477 @lisp
3478 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
3479 @result{}
3480 3
3481 @end lisp
3482
3483 @node Hash Table Reference
3484 @subsubsection Hash Table Reference
3485
3486 @c FIXME: Describe in broad terms what happens for resizing, and what
3487 @c the initial size means for this.
3488
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.
3494
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.
3498
3499 @sp 1
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.
3504
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.
3509
3510 @sp 1
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,
3516
3517 @example
3518 (use-modules (srfi srfi-1)
3519 (srfi srfi-13))
3520
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))
3525
3526 (define my-table (make-hash-table))
3527 (hashx-set! my-hash my-assoc my-table "foo" 123)
3528
3529 (hashx-ref my-hash my-assoc my-table "FOO")
3530 @result{} 123
3531 @end example
3532
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}).
3541
3542 Note that currently, unfortunately, there's no @code{hashx-remove!}
3543 function, which rather limits the usefulness of the @code{hashx-}
3544 routines.
3545
3546 @sp 1
3547 @deffn {Scheme Procedure} make-hash-table [size]
3548 Create a new hash table, with an optional minimum vector @var{size}.
3549
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
3554 added.
3555 @end deffn
3556
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.
3560 @end deffn
3561
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).
3565 @end deffn
3566
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.
3578 @end deffn
3579
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.
3591 @end deffn
3592
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.
3601 @end deffn
3602
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}.
3612
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,
3617
3618 @example
3619 (hashq 'something 123) @result{} 19
3620 (gc)
3621 (hashq 'something 123) @result{} 62
3622 @end example
3623
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.
3628 @end deffn
3629
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
3640 @var{table}.
3641 @end deffn
3642
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
3654 pair.
3655 @end deffn
3656
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.
3665
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
3669 while iterating.
3670
3671 For example the following returns a new alist comprising all the
3672 entries from @code{mytable}, in no particular order.
3673
3674 @example
3675 (hash-map->list cons mytable)
3676 @end example
3677 @end deffn
3678
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.
3684
3685 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
3686 the argument list of @var{proc}.
3687 @end deffn
3688
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.
3697
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.
3701
3702 For example, the following returns a count of how many keys in
3703 @code{mytable} are strings.
3704
3705 @example
3706 (hash-fold (lambda (key value prior)
3707 (if (string? key) (1+ prior) prior))
3708 0 mytable)
3709 @end example
3710 @end deffn
3711
3712
3713 @c Local Variables:
3714 @c TeX-master: "guile.texi"
3715 @c End: