One more incremental step towards the new array API.
[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).
847
848 @deftypefn {C Function} int scm_is_simple_vector (SCM obj)
849 Return non-zero if @var{obj} is a simple vector, else return zero. A
850 simple vector is a vector that can be used with the @code{SCM_SIMPLE_*}
851 macros below.
852
853 The following functions are guaranteed to return simple vectors:
854 @code{scm_make_vector}, @code{scm_c_make_vector}, @code{scm_vector},
855 @code{scm_list_to_vector}.
856 @end deftypefn
857
858 @deftypefn {C Macro} size_t SCM_SIMPLE_VECTOR_LENGTH (SCM vec)
859 Evaluates to the length of the simple vector @var{vec}. No type
860 checking is done.
861 @end deftypefn
862
863 @deftypefn {C Macro} SCM SCM_SIMPLE_VECTOR_REF (SCM vec, size_t idx)
864 Evaluates to the element at position @var{idx} in the simple vector
865 @var{vec}. No type or range checking is done.
866 @end deftypefn
867
868 @deftypefn {C Macro} void SCM_SIMPLE_VECTOR_SET_X (SCM vec, size_t idx, SCM val)
869 Sets the element at position @var{idx} in the simple vector
870 @var{vec} to @var{val}. No type or range checking is done.
871 @end deftypefn
872
873 @deftypefn {C Function} const SCM *scm_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
874 Acquire a handle for the vector @var{vec} and return a pointer to the
875 elements of it. This pointer can only be used to read the elements of
876 @var{vec}. When @var{vec} is not a vector, an error is signaled.
877
878 The variables pointed to by @var{lenp} and @var{incp} are filled with
879 the number of elements of the vector and the increment between elements,
880 respectively. Note that the increment can well be negative.
881
882 The following example shows the typical way to use this function. It
883 creates a list of all elements of @code{vec} (in reverse order).
884
885 @example
886 scm_t_array_handle handle;
887 size_t i, len;
888 ssize_t inc;
889 const SCM *elt;
890 SCM list;
891
892 elt = scm_vector_elements (vec, &handle, &len, &inc);
893 list = SCM_EOL;
894 for (i = 0; i < len; i++, elt += inc)
895 list = scm_cons (*elt, list);
896 @end example
897
898 @end deftypefn
899
900 @deftypefn {C Function} SCM *scm_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
901 Like @code{scm_vector_elements} but the pointer can be used to modify
902 the vector.
903
904 The following example shows the typical way to use this function. It
905 fills a vector with @code{#t}.
906
907 @example
908 scm_t_array_handle handle;
909 size_t i, len;
910 ssize_t inc;
911 SCM *elt;
912
913 elt = scm_vector_elements (vec, &handle, &len, &inc);
914 for (i = 0; i < len; i++, elt += inc)
915 *elt = SCM_BOOL_T;
916 @end example
917
918 @end deftypefn
919
920 @node Uniform Numeric Vectors
921 @subsection Uniform Numeric Vectors
922
923 A uniform numeric vector is a vector whose elements are all of a single
924 numeric type. Guile offers uniform numeric vectors for signed and
925 unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
926 floating point values, and complex floating-point numbers of these two
927 sizes.
928
929 Strings could be regarded as uniform vectors of characters,
930 @xref{Strings}. Likewise, bit vectors could be regarded as uniform
931 vectors of bits, @xref{Bit Vectors}. Both are sufficiently different
932 from uniform numeric vectors that the procedures described here do not
933 apply to these two data types. However, both strings and bit vectors
934 are generalized vectors, @xref{Generalized Vectors}, and arrays,
935 @xref{Arrays}.
936
937 Uniform numeric vectors are the special case of one dimensional uniform
938 numeric arrays.
939
940 Uniform numeric vectors can be useful since they consume less memory
941 than the non-uniform, general vectors. Also, since the types they can
942 store correspond directly to C types, it is easier to work with them
943 efficiently on a low level. Consider image processing as an example,
944 where you want to apply a filter to some image. While you could store
945 the pixels of an image in a general vector and write a general
946 convolution function, things are much more efficient with uniform
947 vectors: the convolution function knows that all pixels are unsigned
948 8-bit values (say), and can use a very tight inner loop.
949
950 That is, when it is written in C. Functions for efficiently working
951 with uniform numeric vectors from C are listed at the end of this
952 section.
953
954 Procedures similar to the vector procedures (@pxref{Vectors}) are
955 provided for handling these uniform vectors, but they are distinct
956 datatypes and the two cannot be inter-mixed. If you want to work
957 primarily with uniform numeric vectors, but want to offer support for
958 general vectors as a convenience, you can use one of the
959 @code{scm_any_to_*} functions. They will coerce lists and vectors to
960 the given type of uniform vector. Alternatively, you can write two
961 versions of your code: one that is fast and works only with uniform
962 numeric vectors, and one that works with any kind of vector but is
963 slower.
964
965 One set of the procedures listed below is a generic one: it works with
966 all types of uniform numeric vectors. In addition to that, there is a
967 set of procedures for each type that only works with that type. Unless
968 you really need to the generality of the first set, it is best to use
969 the more specific functions. They might not be that much faster, but
970 their use can serve as a kind of declaration and makes it easier to
971 optimize later on.
972
973 The generic set of procedures uses @code{uniform} in its names, the
974 specific ones use the tag from the following table.
975
976 @table @nicode
977 @item u8
978 unsigned 8-bit integers
979
980 @item s8
981 signed 8-bit integers
982
983 @item u16
984 unsigned 16-bit integers
985
986 @item s16
987 signed 16-bit integers
988
989 @item u32
990 unsigned 32-bit integers
991
992 @item s32
993 signed 32-bit integers
994
995 @item u64
996 unsigned 64-bit integers
997
998 @item s64
999 signed 64-bit integers
1000
1001 @item f32
1002 the C type @code{float}
1003
1004 @item f64
1005 the C type @code{double}
1006
1007 @item c32
1008 complex numbers in rectangular form with the real and imaginary part
1009 being a @code{float}
1010
1011 @item c64
1012 complex numbers in rectangular form with the real and imaginary part
1013 being a @code{double}
1014
1015 @end table
1016
1017 The external representation (ie.@: read syntax) for these vectors is
1018 similar to normal Scheme vectors, but with an additional tag from the
1019 tabel above indiciating the vector's type. For example,
1020
1021 @lisp
1022 #u16(1 2 3)
1023 #f64(3.1415 2.71)
1024 @end lisp
1025
1026 Note that the read syntax for floating-point here conflicts with
1027 @code{#f} for false. In Standard Scheme one can write @code{(1 #f3)}
1028 for a three element list @code{(1 #f 3)}, but for Guile @code{(1 #f3)}
1029 is invalid. @code{(1 #f 3)} is almost certainly what one should write
1030 anyway to make the intention clear, so this is rarely a problem.
1031
1032 @deffn {Scheme Procedure} uniform-vector? obj
1033 @deffnx {Scheme Procedure} u8vector? obj
1034 @deffnx {Scheme Procedure} s8vector? obj
1035 @deffnx {Scheme Procedure} u16vector? obj
1036 @deffnx {Scheme Procedure} s16vector? obj
1037 @deffnx {Scheme Procedure} u32vector? obj
1038 @deffnx {Scheme Procedure} s32vector? obj
1039 @deffnx {Scheme Procedure} u64vector? obj
1040 @deffnx {Scheme Procedure} s64vector? obj
1041 @deffnx {Scheme Procedure} f32vector? obj
1042 @deffnx {Scheme Procedure} f64vector? obj
1043 @deffnx {Scheme Procedure} c32vector? obj
1044 @deffnx {Scheme Procedure} c64vector? obj
1045 @deffnx {C Function} scm_uniform_vector_p obj
1046 @deffnx {C Function} scm_u8vector_p obj
1047 @deffnx {C Function} scm_s8vector_p obj
1048 @deffnx {C Function} scm_u16vector_p obj
1049 @deffnx {C Function} scm_s16vector_p obj
1050 @deffnx {C Function} scm_u32vector_p obj
1051 @deffnx {C Function} scm_s32vector_p obj
1052 @deffnx {C Function} scm_u64vector_p obj
1053 @deffnx {C Function} scm_s64vector_p obj
1054 @deffnx {C Function} scm_f32vector_p obj
1055 @deffnx {C Function} scm_f64vector_p obj
1056 @deffnx {C Function} scm_c32vector_p obj
1057 @deffnx {C Function} scm_c64vector_p obj
1058 Return @code{#t} if @var{obj} is a homogeneous numeric vector of the
1059 indicated type.
1060 @end deffn
1061
1062 @deffn {Scheme Procedure} make-u8vector n [value]
1063 @deffnx {Scheme Procedure} make-s8vector n [value]
1064 @deffnx {Scheme Procedure} make-u16vector n [value]
1065 @deffnx {Scheme Procedure} make-s16vector n [value]
1066 @deffnx {Scheme Procedure} make-u32vector n [value]
1067 @deffnx {Scheme Procedure} make-s32vector n [value]
1068 @deffnx {Scheme Procedure} make-u64vector n [value]
1069 @deffnx {Scheme Procedure} make-s64vector n [value]
1070 @deffnx {Scheme Procedure} make-f32vector n [value]
1071 @deffnx {Scheme Procedure} make-f64vector n [value]
1072 @deffnx {Scheme Procedure} make-c32vector n [value]
1073 @deffnx {Scheme Procedure} make-c64vector n [value]
1074 @deffnx {C Function} scm_make_u8vector n [value]
1075 @deffnx {C Function} scm_make_s8vector n [value]
1076 @deffnx {C Function} scm_make_u16vector n [value]
1077 @deffnx {C Function} scm_make_s16vector n [value]
1078 @deffnx {C Function} scm_make_u32vector n [value]
1079 @deffnx {C Function} scm_make_s32vector n [value]
1080 @deffnx {C Function} scm_make_u64vector n [value]
1081 @deffnx {C Function} scm_make_s64vector n [value]
1082 @deffnx {C Function} scm_make_f32vector n [value]
1083 @deffnx {C Function} scm_make_f64vector n [value]
1084 @deffnx {C Function} scm_make_c32vector n [value]
1085 @deffnx {C Function} scm_make_c64vector n [value]
1086 Return a newly allocated homogeneous numeric vector holding @var{n}
1087 elements of the indicated type. If @var{value} is given, the vector
1088 is initialized with that value, otherwise the contents are
1089 unspecified.
1090 @end deffn
1091
1092 @deffn {Scheme Procedure} u8vector value @dots{}
1093 @deffnx {Scheme Procedure} s8vector value @dots{}
1094 @deffnx {Scheme Procedure} u16vector value @dots{}
1095 @deffnx {Scheme Procedure} s16vector value @dots{}
1096 @deffnx {Scheme Procedure} u32vector value @dots{}
1097 @deffnx {Scheme Procedure} s32vector value @dots{}
1098 @deffnx {Scheme Procedure} u64vector value @dots{}
1099 @deffnx {Scheme Procedure} s64vector value @dots{}
1100 @deffnx {Scheme Procedure} f32vector value @dots{}
1101 @deffnx {Scheme Procedure} f64vector value @dots{}
1102 @deffnx {Scheme Procedure} c32vector value @dots{}
1103 @deffnx {Scheme Procedure} c64vector value @dots{}
1104 @deffnx {C Function} scm_u8vector values
1105 @deffnx {C Function} scm_s8vector values
1106 @deffnx {C Function} scm_u16vector values
1107 @deffnx {C Function} scm_s16vector values
1108 @deffnx {C Function} scm_u32vector values
1109 @deffnx {C Function} scm_s32vector values
1110 @deffnx {C Function} scm_u64vector values
1111 @deffnx {C Function} scm_s64vector values
1112 @deffnx {C Function} scm_f32vector values
1113 @deffnx {C Function} scm_f64vector values
1114 @deffnx {C Function} scm_c32vector values
1115 @deffnx {C Function} scm_c64vector values
1116 Return a newly allocated homogeneous numeric vector of the indicated
1117 type, holding the given parameter @var{value}s. The vector length is
1118 the number of parameters given.
1119 @end deffn
1120
1121 @deffn {Scheme Procedure} uniform-vector-length vec
1122 @deffnx {Scheme Procedure} u8vector-length vec
1123 @deffnx {Scheme Procedure} s8vector-length vec
1124 @deffnx {Scheme Procedure} u16vector-length vec
1125 @deffnx {Scheme Procedure} s16vector-length vec
1126 @deffnx {Scheme Procedure} u32vector-length vec
1127 @deffnx {Scheme Procedure} s32vector-length vec
1128 @deffnx {Scheme Procedure} u64vector-length vec
1129 @deffnx {Scheme Procedure} s64vector-length vec
1130 @deffnx {Scheme Procedure} f32vector-length vec
1131 @deffnx {Scheme Procedure} f64vector-length vec
1132 @deffnx {Scheme Procedure} c32vector-length vec
1133 @deffnx {Scheme Procedure} c64vector-length vec
1134 @deffnx {C Function} scm_uniform_vector_length vec
1135 @deffnx {C Function} scm_u8vector_length vec
1136 @deffnx {C Function} scm_s8vector_length vec
1137 @deffnx {C Function} scm_u16vector_length vec
1138 @deffnx {C Function} scm_s16vector_length vec
1139 @deffnx {C Function} scm_u32vector_length vec
1140 @deffnx {C Function} scm_s32vector_length vec
1141 @deffnx {C Function} scm_u64vector_length vec
1142 @deffnx {C Function} scm_s64vector_length vec
1143 @deffnx {C Function} scm_f32vector_length vec
1144 @deffnx {C Function} scm_f64vector_length vec
1145 @deffnx {C Function} scm_c32vector_length vec
1146 @deffnx {C Function} scm_c64vector_length vec
1147 Return the number of elements in @var{vec}.
1148 @end deffn
1149
1150 @deffn {Scheme Procedure} uniform-vector-ref vec i
1151 @deffnx {Scheme Procedure} u8vector-ref vec i
1152 @deffnx {Scheme Procedure} s8vector-ref vec i
1153 @deffnx {Scheme Procedure} u16vector-ref vec i
1154 @deffnx {Scheme Procedure} s16vector-ref vec i
1155 @deffnx {Scheme Procedure} u32vector-ref vec i
1156 @deffnx {Scheme Procedure} s32vector-ref vec i
1157 @deffnx {Scheme Procedure} u64vector-ref vec i
1158 @deffnx {Scheme Procedure} s64vector-ref vec i
1159 @deffnx {Scheme Procedure} f32vector-ref vec i
1160 @deffnx {Scheme Procedure} f64vector-ref vec i
1161 @deffnx {Scheme Procedure} c32vector-ref vec i
1162 @deffnx {Scheme Procedure} c64vector-ref vec i
1163 @deffnx {C Function} scm_uniform_vector_ref vec i
1164 @deffnx {C Function} scm_u8vector_ref vec i
1165 @deffnx {C Function} scm_s8vector_ref vec i
1166 @deffnx {C Function} scm_u16vector_ref vec i
1167 @deffnx {C Function} scm_s16vector_ref vec i
1168 @deffnx {C Function} scm_u32vector_ref vec i
1169 @deffnx {C Function} scm_s32vector_ref vec i
1170 @deffnx {C Function} scm_u64vector_ref vec i
1171 @deffnx {C Function} scm_s64vector_ref vec i
1172 @deffnx {C Function} scm_f32vector_ref vec i
1173 @deffnx {C Function} scm_f64vector_ref vec i
1174 @deffnx {C Function} scm_c32vector_ref vec i
1175 @deffnx {C Function} scm_c64vector_ref vec i
1176 Return the element at index @var{i} in @var{vec}. The first element
1177 in @var{vec} is index 0.
1178 @end deffn
1179
1180 @deffn {Scheme Procedure} uniform-vector-set! vec i value
1181 @deffnx {Scheme Procedure} u8vector-set! vec i value
1182 @deffnx {Scheme Procedure} s8vector-set! vec i value
1183 @deffnx {Scheme Procedure} u16vector-set! vec i value
1184 @deffnx {Scheme Procedure} s16vector-set! vec i value
1185 @deffnx {Scheme Procedure} u32vector-set! vec i value
1186 @deffnx {Scheme Procedure} s32vector-set! vec i value
1187 @deffnx {Scheme Procedure} u64vector-set! vec i value
1188 @deffnx {Scheme Procedure} s64vector-set! vec i value
1189 @deffnx {Scheme Procedure} f32vector-set! vec i value
1190 @deffnx {Scheme Procedure} f64vector-set! vec i value
1191 @deffnx {Scheme Procedure} c32vector-set! vec i value
1192 @deffnx {Scheme Procedure} c64vector-set! vec i value
1193 @deffnx {C Function} scm_uniform_vector_set_x vec i value
1194 @deffnx {C Function} scm_u8vector_set_x vec i value
1195 @deffnx {C Function} scm_s8vector_set_x vec i value
1196 @deffnx {C Function} scm_u16vector_set_x vec i value
1197 @deffnx {C Function} scm_s16vector_set_x vec i value
1198 @deffnx {C Function} scm_u32vector_set_x vec i value
1199 @deffnx {C Function} scm_s32vector_set_x vec i value
1200 @deffnx {C Function} scm_u64vector_set_x vec i value
1201 @deffnx {C Function} scm_s64vector_set_x vec i value
1202 @deffnx {C Function} scm_f32vector_set_x vec i value
1203 @deffnx {C Function} scm_f64vector_set_x vec i value
1204 @deffnx {C Function} scm_c32vector_set_x vec i value
1205 @deffnx {C Function} scm_c64vector_set_x vec i value
1206 Set the element at index @var{i} in @var{vec} to @var{value}. The
1207 first element in @var{vec} is index 0. The return value is
1208 unspecified.
1209 @end deffn
1210
1211 @deffn {Scheme Procedure} uniform-vector->list vec
1212 @deffnx {Scheme Procedure} u8vector->list vec
1213 @deffnx {Scheme Procedure} s8vector->list vec
1214 @deffnx {Scheme Procedure} u16vector->list vec
1215 @deffnx {Scheme Procedure} s16vector->list vec
1216 @deffnx {Scheme Procedure} u32vector->list vec
1217 @deffnx {Scheme Procedure} s32vector->list vec
1218 @deffnx {Scheme Procedure} u64vector->list vec
1219 @deffnx {Scheme Procedure} s64vector->list vec
1220 @deffnx {Scheme Procedure} f32vector->list vec
1221 @deffnx {Scheme Procedure} f64vector->list vec
1222 @deffnx {Scheme Procedure} c32vector->list vec
1223 @deffnx {Scheme Procedure} c64vector->list vec
1224 @deffnx {C Function} scm_uniform_vector_to_list vec
1225 @deffnx {C Function} scm_u8vector_to_list vec
1226 @deffnx {C Function} scm_s8vector_to_list vec
1227 @deffnx {C Function} scm_u16vector_to_list vec
1228 @deffnx {C Function} scm_s16vector_to_list vec
1229 @deffnx {C Function} scm_u32vector_to_list vec
1230 @deffnx {C Function} scm_s32vector_to_list vec
1231 @deffnx {C Function} scm_u64vector_to_list vec
1232 @deffnx {C Function} scm_s64vector_to_list vec
1233 @deffnx {C Function} scm_f32vector_to_list vec
1234 @deffnx {C Function} scm_f64vector_to_list vec
1235 @deffnx {C Function} scm_c32vector_to_list vec
1236 @deffnx {C Function} scm_c64vector_to_list vec
1237 Return a newly allocated list holding all elements of @var{vec}.
1238 @end deffn
1239
1240 @deffn {Scheme Procedure} list->u8vector lst
1241 @deffnx {Scheme Procedure} list->s8vector lst
1242 @deffnx {Scheme Procedure} list->u16vector lst
1243 @deffnx {Scheme Procedure} list->s16vector lst
1244 @deffnx {Scheme Procedure} list->u32vector lst
1245 @deffnx {Scheme Procedure} list->s32vector lst
1246 @deffnx {Scheme Procedure} list->u64vector lst
1247 @deffnx {Scheme Procedure} list->s64vector lst
1248 @deffnx {Scheme Procedure} list->f32vector lst
1249 @deffnx {Scheme Procedure} list->f64vector lst
1250 @deffnx {Scheme Procedure} list->c32vector lst
1251 @deffnx {Scheme Procedure} list->c64vector lst
1252 @deffnx {C Function} scm_list_to_u8vector lst
1253 @deffnx {C Function} scm_list_to_s8vector lst
1254 @deffnx {C Function} scm_list_to_u16vector lst
1255 @deffnx {C Function} scm_list_to_s16vector lst
1256 @deffnx {C Function} scm_list_to_u32vector lst
1257 @deffnx {C Function} scm_list_to_s32vector lst
1258 @deffnx {C Function} scm_list_to_u64vector lst
1259 @deffnx {C Function} scm_list_to_s64vector lst
1260 @deffnx {C Function} scm_list_to_f32vector lst
1261 @deffnx {C Function} scm_list_to_f64vector lst
1262 @deffnx {C Function} scm_list_to_c32vector lst
1263 @deffnx {C Function} scm_list_to_c64vector lst
1264 Return a newly allocated homogeneous numeric vector of the indicated type,
1265 initialized with the elements of the list @var{lst}.
1266 @end deffn
1267
1268 @deffn {Scheme Procedure} any->u8vector obj
1269 @deffnx {Scheme Procedure} any->s8vector obj
1270 @deffnx {Scheme Procedure} any->u16vector obj
1271 @deffnx {Scheme Procedure} any->s16vector obj
1272 @deffnx {Scheme Procedure} any->u32vector obj
1273 @deffnx {Scheme Procedure} any->s32vector obj
1274 @deffnx {Scheme Procedure} any->u64vector obj
1275 @deffnx {Scheme Procedure} any->s64vector obj
1276 @deffnx {Scheme Procedure} any->f32vector obj
1277 @deffnx {Scheme Procedure} any->f64vector obj
1278 @deffnx {Scheme Procedure} any->c32vector obj
1279 @deffnx {Scheme Procedure} any->c64vector obj
1280 @deffnx {C Function} scm_any_to_u8vector obj
1281 @deffnx {C Function} scm_any_to_s8vector obj
1282 @deffnx {C Function} scm_any_to_u16vector obj
1283 @deffnx {C Function} scm_any_to_s16vector obj
1284 @deffnx {C Function} scm_any_to_u32vector obj
1285 @deffnx {C Function} scm_any_to_s32vector obj
1286 @deffnx {C Function} scm_any_to_u64vector obj
1287 @deffnx {C Function} scm_any_to_s64vector obj
1288 @deffnx {C Function} scm_any_to_f32vector obj
1289 @deffnx {C Function} scm_any_to_f64vector obj
1290 @deffnx {C Function} scm_any_to_c32vector obj
1291 @deffnx {C Function} scm_any_to_c64vector obj
1292 Return a newly allocated homogeneous numeric vector of the indicated
1293 type, initialized with the elements of @var{obj}, which must be a list,
1294 a vector, or a uniform vector.
1295 @end deffn
1296
1297 @deftypefn {C Function} int scm_is_uniform_vector (SCM uvec)
1298 Return @code{1} when @var{uvec} is a uniform vector, @code{0} otherwise.
1299 @end deftypefn
1300
1301 @deftypefn {C Function} SCM scm_take_u8vector (const scm_t_uint8 *data, size_t len)
1302 @deftypefnx {C Function} SCM scm_take_s8vector (const scm_t_int8 *data, size_t len)
1303 @deftypefnx {C Function} SCM scm_take_u16vector (const scm_t_uint16 *data, size_t len)
1304 @deftypefnx {C Function} SCM scm_take_s168vector (const scm_t_int16 *data, size_t len)
1305 @deftypefnx {C Function} SCM scm_take_u32vector (const scm_t_uint32 *data, size_t len)
1306 @deftypefnx {C Function} SCM scm_take_s328vector (const scm_t_int32 *data, size_t len)
1307 @deftypefnx {C Function} SCM scm_take_u64vector (const scm_t_uint64 *data, size_t len)
1308 @deftypefnx {C Function} SCM scm_take_s64vector (const scm_t_int64 *data, size_t len)
1309 @deftypefnx {C Function} SCM scm_take_f32vector (const float *data, size_t len)
1310 @deftypefnx {C Function} SCM scm_take_f64vector (const double *data, size_t len)
1311 @deftypefnx {C Function} SCM scm_take_c32vector (const float *data, size_t len)
1312 @deftypefnx {C Function} SCM scm_take_c64vector (const double *data, size_t len)
1313 Return a new uniform vector of the indicated type and length that uses
1314 the memory pointed to by @var{data} to store its elements. This memory
1315 will eventually be freed with @code{free}. The argument @var{len}
1316 specifies the number of elements in @var{data}, not its size in bytes.
1317
1318 The @code{c32} and @code{c64} variants take a pointer to a C array of
1319 @code{float}s or @code{double}s. The real parts of the complex numbers
1320 are at even indices in that array, the corresponding imaginary parts are
1321 at the following odd index.
1322 @end deftypefn
1323
1324 @deftypefn {C Function} size_t scm_c_uniform_vector_length (SCM uvec)
1325 Return the number of elements of @var{uvec} as a @code{size_t}.
1326 @end deftypefn
1327
1328 @deftypefn {C Function} size_t scm_c_uniform_vector_element_size (SCM uvec)
1329 Return the number of bytes of one element of @var{uvec}.
1330 @end deftypefn
1331
1332 @deftypefn {C Function} size_t scm_c_uniform_vector_size (SCM uvec)
1333 Return the number of bytes used by all elements of @var{uvec}. This is
1334 just @code{scm_c_uniform_vector_length (@var{uvec}) *
1335 scm_c_uniform_vector_element_size (@var{uvec})}.
1336 @end deftypefn
1337
1338
1339 @node Bit Vectors
1340 @subsection Bit Vectors
1341
1342 @noindent
1343 Bit vectors are zero-origin, one-dimensional arrays of booleans. They
1344 are displayed as a sequence of @code{0}s and @code{1}s prefixed by
1345 @code{#*}, e.g.,
1346
1347 @example
1348 (make-bitvector 8 #f) @result{}
1349 #*00000000
1350 @end example
1351
1352 Bit vectors are are also generalized vectors, @xref{Generalized
1353 Vectors}, and can thus be used with the array procedures, @xref{Arrays}.
1354 Bit vectors are the special case of one dimensional bit arrays.
1355
1356 @deffn {Scheme Procedure} bitvector? obj
1357 @deffnx {C Function} scm_bitvector_p (obj)
1358 Return @code{#t} when @var{obj} is a bitvector, else
1359 return @code{#f}.
1360 @end deffn
1361
1362 @deftypefn {C Function} int scm_is_bitvector (SCM obj)
1363 Return @code{1} when @var{obj} is a bitvector, else return @code{0}.
1364 @end deftypefn
1365
1366 @deffn {Scheme Procedure} make-bitvector len [fill]
1367 @deffnx {C Function} scm_make_bitvector (len, fill)
1368 Create a new bitvector of length @var{len} and
1369 optionally initialize all elements to @var{fill}.
1370 @end deffn
1371
1372 @deftypefn {C Function} SCM scm_c_make_bitvector (size_t len, SCM fill)
1373 Like @code{scm_make_bitvector}, but the length is given as a
1374 @code{size_t}.
1375 @end deftypefn
1376
1377 @deffn {Scheme Procedure} bitvector . bits
1378 @deffnx {C Function} scm_bitvector (bits)
1379 Create a new bitvector with the arguments as elements.
1380 @end deffn
1381
1382 @deffn {Scheme Procedure} bitvector-length vec
1383 @deffnx {C Function} scm_bitvector_length (vec)
1384 Return the length of the bitvector @var{vec}.
1385 @end deffn
1386
1387 @deftypefn {C Function} size_t scm_c_bitvector_length (SCM vec)
1388 Like @code{scm_bitvector_length}, but the length is returned as a
1389 @code{size_t}.
1390 @end deftypefn
1391
1392 @deffn {Scheme Procedure} bitvector-ref vec idx
1393 @deffnx {C Function} scm_bitvector_ref (vec, idx)
1394 Return the element at index @var{idx} of the bitvector
1395 @var{vec}.
1396 @end deffn
1397
1398 @deftypefn {C Function} SCM scm_c_bitvector_ref (SCM obj, size_t idx)
1399 Return the element at index @var{idx} of the bitvector
1400 @var{vec}.
1401 @end deftypefn
1402
1403 @deffn {Scheme Procedure} bitvector-set! vec idx val
1404 @deffnx {C Function} scm_bitvector_set_x (vec, idx, val)
1405 Set the element at index @var{idx} of the bitvector
1406 @var{vec} when @var{val} is true, else clear it.
1407 @end deffn
1408
1409 @deftypefn {C Function} SCM scm_c_bitvector_set_x (SCM obj, size_t idx, SCM val)
1410 Set the element at index @var{idx} of the bitvector
1411 @var{vec} when @var{val} is true, else clear it.
1412 @end deftypefn
1413
1414 @deffn {Scheme Procedure} bitvector-fill! vec val
1415 @deffnx {C Function} scm_bitvector_fill_x (vec, val)
1416 Set all elements of the bitvector
1417 @var{vec} when @var{val} is true, else clear them.
1418 @end deffn
1419
1420 @deffn {Scheme Procedure} list->bitvector list
1421 @deffnx {C Function} scm_list_to_bitvector (list)
1422 Return a new bitvector initialized with the elements
1423 of @var{list}.
1424 @end deffn
1425
1426 @deffn {Scheme Procedure} bitvector->list vec
1427 @deffnx {C Function} scm_bitvector_to_list (vec)
1428 Return a new list initialized with the elements
1429 of the bitvector @var{vec}.
1430 @end deffn
1431
1432 @deffn {Scheme Procedure} bit-count bool bitvector
1433 @deffnx {C Function} scm_bit_count (bool, bitvector)
1434 Return a count of how many entries in @var{bitvector} are equal to
1435 @var{bool}. For example,
1436
1437 @example
1438 (bit-count #f #*000111000) @result{} 6
1439 @end example
1440 @end deffn
1441
1442 @deffn {Scheme Procedure} bit-position bool bitvector start
1443 @deffnx {C Function} scm_bit_position (bool, bitvector, start)
1444 Return the index of the first occurrance of @var{bool} in
1445 @var{bitvector}, starting from @var{start}. If there is no @var{bool}
1446 entry between @var{start} and the end of @var{bitvector}, then return
1447 @code{#f}. For example,
1448
1449 @example
1450 (bit-position #t #*000101 0) @result{} 3
1451 (bit-position #f #*0001111 3) @result{} #f
1452 @end example
1453 @end deffn
1454
1455 @deffn {Scheme Procedure} bit-invert! bitvector
1456 @deffnx {C Function} scm_bit_invert_x (bitvector)
1457 Modify @var{bitvector} by replacing each element with its negation.
1458 @end deffn
1459
1460 @deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1461 @deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1462 Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1463 selecting the entries to change. The return value is unspecified.
1464
1465 If @var{uvec} is a bit vector, then those entries where it has
1466 @code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1467 @var{uvec} and @var{bitvector} must be the same length. When
1468 @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1469 @var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1470 ANDNOT.
1471
1472 @example
1473 (define bv #*01000010)
1474 (bit-set*! bv #*10010001 #t)
1475 bv
1476 @result{} #*11010011
1477 @end example
1478
1479 If @var{uvec} is a uniform vector of unsigned long integers, then
1480 they're indexes into @var{bitvector} which are set to @var{bool}.
1481
1482 @example
1483 (define bv #*01000010)
1484 (bit-set*! bv #u(5 2 7) #t)
1485 bv
1486 @result{} #*01100111
1487 @end example
1488 @end deffn
1489
1490 @deffn {Scheme Procedure} bit-count* bitvector uvec bool
1491 @deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1492 Return a count of how many entries in @var{bitvector} are equal to
1493 @var{bool}, with @var{uvec} selecting the entries to consider.
1494
1495 @var{uvec} is interpreted in the same way as for @code{bit-set*!}
1496 above. Namely, if @var{uvec} is a bit vector then entries which have
1497 @code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1498 is a uniform vector of unsigned long integers then it's the indexes in
1499 @var{bitvector} to consider.
1500
1501 For example,
1502
1503 @example
1504 (bit-count* #*01110111 #*11001101 #t) @result{} 3
1505 (bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1506 @end example
1507 @end deffn
1508
1509
1510 @node Generalized Vectors
1511 @subsection Generalized Vectors
1512
1513 Guile has a number of data types that are generally vector-like:
1514 strings, uniform numeric vectors, bitvectors, and of course ordinary
1515 vectors of arbitrary Scheme values. These types are disjoint: a
1516 Scheme value belongs to at most one of the four types listed above.
1517
1518 If you want to gloss over this distinction and want to treat all four
1519 types with common code, you can use the procedures in this section.
1520 They work with the @emph{generalized vector} type, which is the union
1521 of the four vector-like types.
1522
1523 @deffn {Scheme Procedure} generalized-vector? obj
1524 @deffnx {C Function} scm_generalized_vector_p (obj)
1525 Return @code{#t} if @var{obj} is a vector, string,
1526 bitvector, or uniform numeric vector.
1527 @end deffn
1528
1529 @deffn {Scheme Procedure} generalized-vector-length v
1530 @deffnx {C Function} scm_generalized_vector_length (v)
1531 Return the length of the generalized vector @var{v}.
1532 @end deffn
1533
1534 @deffn {Scheme Procedure} generalized-vector-ref v idx
1535 @deffnx {C Function} scm_generalized_vector_ref (v, idx)
1536 Return the element at index @var{idx} of the
1537 generalized vector @var{v}.
1538 @end deffn
1539
1540 @deffn {Scheme Procedure} generalized-vector-set! v idx val
1541 @deffnx {C Function} scm_generalized_vector_set_x (v, idx, val)
1542 Set the element at index @var{idx} of the
1543 generalized vector @var{v} to @var{val}.
1544 @end deffn
1545
1546 @deffn {Scheme Procedure} generalized-vector->list v
1547 @deffnx {C Function} scm_generalized_vector_to_list (v)
1548 Return a new list whose elements are the elements of the
1549 generalized vector @var{v}.
1550 @end deffn
1551
1552 @deftypefn {C Function} int scm_is_generalized_vector (SCM obj)
1553 Return @code{1} if @var{obj} is a vector, string,
1554 bitvector, or uniform numeric vector; else return @code{0}.
1555 @end deftypefn
1556
1557 @deftypefn {C Function} size_t scm_c_generalized_vector_length (SCM v)
1558 Return the length of the generalized vector @var{v}.
1559 @end deftypefn
1560
1561 @deftypefn {C Function} SCM scm_c_generalized_vector_ref (SCM v, size_t idx)
1562 Return the element at index @var{idx} of the generalized vector @var{v}.
1563 @end deftypefn
1564
1565 @deftypefn {C Function} void scm_c_generalized_vector_set_x (SCM v, size_t idx, SCM val)
1566 Set the element at index @var{idx} of the generalized vector @var{v}
1567 to @var{val}.
1568 @end deftypefn
1569
1570 @node Arrays
1571 @subsection Arrays
1572 @tpindex Arrays
1573
1574 @dfn{Arrays} are a collection of cells organized into an arbitrary
1575 number of dimensions. Each cell can be accessed in constant time by
1576 supplying an index for each dimension.
1577
1578 In the current implementation, an array uses a generalized vector for
1579 the actual storage of its elements. Any kind of generalized vector
1580 will do, so you can have arrays of uniform numeric values, arrays of
1581 characters, arrays of bits, and of course, arrays of arbitrary Scheme
1582 values. For example, arrays with an underlying @code{c64vector} might
1583 be nice for digital signal processing, while arrays made from a
1584 @code{u8vector} might be used to hold gray-scale images.
1585
1586 The number of dimensions of an array is called its @dfn{rank}. Thus, a
1587 matrix is an array of rank 2, while a vector has rank 1. When accessing
1588 an array element, you have to specify one exact integer for each
1589 dimension. These integers are called the @dfn{indices} of the element.
1590 An array specifies the allowed range of indices for each dimension via
1591 an inclusive lower and upper bound. These bounds can well be negative,
1592 but the upper bound must be greater than or equal to the lower bound.
1593 When all lower bounds of an array are zero, it is called a
1594 @dfn{zero-origin} array.
1595
1596 For example, ordinary vectors are the special case of one dimensional,
1597 ordinary arrays and strings are one dimensional character arrays.
1598
1599 @menu
1600 * Array Syntax::
1601 * Array Procedures::
1602 * Accessing Arrays from C::
1603 @end menu
1604
1605 @node Array Syntax
1606 @subsubsection Array Syntax
1607
1608 An array is displayed as @code{#} followed by its rank, followed by a
1609 tag that describes the underlying vector, optionally followed by the
1610 lower bounds, and finally followed by the cells, organized into
1611 dimensions using parentheses.
1612
1613 In more words, the array tag is of the form
1614
1615 @example
1616 #<rank><vectag><@@lower><@@lower>...
1617 @end example
1618
1619 where @code{<rank>} is a positive integer in decimal giving the rank of
1620 the array. It is omitted when the rank is 1 and the array is non-shared
1621 and has zero-origin (see below). For shared arrays and for a non-zero
1622 origin, the rank is always printed even when it is 1 to dinstinguish
1623 them from ordinary vectors.
1624
1625 The @code{<vectag>} part is the tag for a uniform numeric vector, like
1626 @code{u8}, @code{s16}, etc, @code{b} for bitvectors, or @code{a} for
1627 strings. It is empty for ordinary vectors.
1628
1629 The @code{<@@lower>} part is a @samp{@@} sign followed by an integer in
1630 decimal giving the lower bound of a dimension. There is one
1631 @code{<@@lower>} for each dimension. When all lower bounds are zero,
1632 all @code{<@@lower>} parts are omitted.
1633
1634 Thus,
1635
1636 @table @code
1637 @item #(1 2 3)
1638 is an ordinary array of rank 1 with lower bound 0 in dimension 0.
1639 (I.e., a regular vector.)
1640
1641 @item #@@2(1 2 3)
1642 is an ordinary array of rank 1 with lower bound 2 in dimension 0.
1643
1644 @item #2((1 2 3) (4 5 6))
1645 is a non-uniform array of rank 2; a 3@cross{}3 matrix with index ranges 0..2
1646 and 0..2.
1647
1648 @item #u32(0 1 2)
1649 is a uniform u8 array of rank 1.
1650
1651 @item #2u32@@2@@3((1 2) (2 3))
1652 is a uniform u8 array of rank 2 with index ranges 2..3 and 3..4.
1653
1654 @end table
1655
1656 @node Array Procedures
1657 @subsubsection Array Procedures
1658
1659 When an array is created, the range of each dimension must be
1660 specified, e.g., to create a 2@cross{}3 array with a zero-based index:
1661
1662 @example
1663 (make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho))
1664 @end example
1665
1666 The range of each dimension can also be given explicitly, e.g., another
1667 way to create the same array:
1668
1669 @example
1670 (make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho))
1671 @end example
1672
1673 The following procedures can be used with arrays (or vectors). An
1674 argument shown as @var{idx}@dots{} means one parameter for each
1675 dimension in the array. A @var{idxlist} argument means a list of such
1676 values, one for each dimension.
1677
1678
1679 @deffn {Scheme Procedure} array? obj
1680 @deffnx {C Function} scm_array_p (obj, unused)
1681 Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1682 not.
1683
1684 The second argument to scm_array_p is there for historical reasons,
1685 but it is not used. You should always pass @code{SCM_UNDEFINED} as
1686 its value.
1687 @end deffn
1688
1689 @deffn {Scheme Procedure} typed-array? obj type
1690 @deffnx {C Function} scm_typed_array_p (obj, type)
1691 Return @code{#t} if the @var{obj} is an array of type @var{type}, and
1692 @code{#f} if not.
1693 @end deffn
1694
1695 @deftypefn {C Function} int scm_is_array (SCM obj)
1696 Return @code{1} if the @var{obj} is an array and @code{0} if not.
1697 @end deftypefn
1698
1699 @deftypefn {C Function} int scm_is_typed_array (SCM obj, SCM type)
1700 Return @code{0} if the @var{obj} is an array of type @var{type}, and
1701 @code{1} if not.
1702 @end deftypefn
1703
1704 @deffn {Scheme Procedure} make-array fill bound @dots{}
1705 @deffnx {C Function} scm_make_array (fill, bounds)
1706 Equivalent to @code{(make-typed-array #t @var{fill} @var{bound} ...)}.
1707 @end deffn
1708
1709 @deffn {Scheme Procedure} make-typed-array type fill bound @dots{}
1710 @deffnx {C Function} scm_make_typed_array (type, fill, bounds)
1711 Create and return an array that has as many dimensions as there are
1712 @var{bound}s and (maybe) fill it with @var{fill}.
1713
1714 The underlaying storage vector is created according to @var{type},
1715 which must be a symbol whose name is the `vectag' of the array as
1716 explained above, or @code{#t} for ordinary, non-specialized arrays.
1717
1718 For example, using the symbol @code{f64} for @var{type} will create an
1719 array that uses a @code{f64vector} for storing its elements, and
1720 @code{a} will use a string.
1721
1722 Ordinary arrays (signified by a @var{type} of @code{#t}) are filled
1723 with @var{fill}. Other types of arrays are only then filled with
1724 @var{fill} when @var{fill} is non-@nicode{#f}.
1725
1726 Each @var{bound} may be a positive non-zero integer @var{N}, in which
1727 case the index for that dimension can range from 0 through @var{N-1}; or
1728 an explicit index range specifier in the form @code{(LOWER UPPER)},
1729 where both @var{lower} and @var{upper} are integers, possibly less than
1730 zero, and possibly the same number (however, @var{lower} cannot be
1731 greater than @var{upper}).
1732 @end deffn
1733
1734 @deffn {Scheme Procedure} list->array dimspec list
1735 Equivalent to @code{(list->typed-array #t @var{dimspec}
1736 @var{list})}.
1737 @end deffn
1738
1739 @deffn {Scheme Procedure} list->typed-array type dimspec list
1740 @deffnx {C Function} scm_list_to_typed_array (type, dimspec, list)
1741 Return an array of the type indicated by @var{type} with elements the
1742 same as those of @var{list}.
1743
1744 The argument @var{dimspec} determines the number of dimensions of the
1745 array and their lower bounds. When @var{dimspec} is an exact integer,
1746 it gives the number of dimensions directly and all lower bounds are
1747 zero. When it is a list of exact integers, then each element is the
1748 lower index bound of a dimension, and there will be as many dimensions
1749 as elements in the list.
1750 @end deffn
1751
1752 @deffn {Scheme Procedure} array-type array
1753 Return the type of @var{array}. This is the `vectag' used for
1754 printing @var{array} (or @code{#t} for ordinary arrays) and can be
1755 used with @code{make-typed-array} to create an array of the same kind
1756 as @var{array}.
1757 @end deffn
1758
1759 @deffn {Scheme Procedure} array-ref array idx @dots{}
1760 Return the element at @code{(idx @dots{})} in @var{array}.
1761
1762 @example
1763 (define a (make-array 999 '(1 2) '(3 4)))
1764 (array-ref a 2 4) @result{} 999
1765 @end example
1766 @end deffn
1767
1768 @deffn {Scheme Procedure} array-in-bounds? array idx @dots{}
1769 @deffnx {C Function} scm_array_in_bounds_p (array, idxlist)
1770 Return @code{#t} if the given index would be acceptable to
1771 @code{array-ref}.
1772
1773 @example
1774 (define a (make-array #f '(1 2) '(3 4)))
1775 (array-in-bounds? a 2 3) @result{} #f
1776 (array-in-bounds? a 0 0) @result{} #f
1777 @end example
1778 @end deffn
1779
1780 @deffn {Scheme Procedure} array-set! array obj idx @dots{}
1781 @deffnx {C Function} scm_array_set_x (array, obj, idxlist)
1782 Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}.
1783 The return value is unspecified.
1784
1785 @example
1786 (define a (make-array #f '(0 1) '(0 1)))
1787 (array-set! a #t 1 1)
1788 a @result{} #2((#f #f) (#f #t))
1789 @end example
1790 @end deffn
1791
1792 @deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{}
1793 @deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist)
1794 @code{make-shared-array} can be used to create shared subarrays of other
1795 arrays. The @var{mapper} is a function that translates coordinates in
1796 the new array into coordinates in the old array. A @var{mapper} must be
1797 affine, and its range must stay within the bounds of the old array, but
1798 it can be otherwise arbitrary. A simple example:
1799
1800 @lisp
1801 (define fred (make-array #f 8 8))
1802 (define freds-diagonal
1803 (make-shared-array fred (lambda (i) (list i i)) 8))
1804 (array-set! freds-diagonal 'foo 3)
1805 (array-ref fred 3 3) @result{} foo
1806 (define freds-center
1807 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
1808 (array-ref freds-center 0 0) @result{} foo
1809 @end lisp
1810 @end deffn
1811
1812 @deffn {Scheme Procedure} shared-array-increments array
1813 @deffnx {C Function} scm_shared_array_increments (array)
1814 For each dimension, return the distance between elements in the root vector.
1815 @end deffn
1816
1817 @deffn {Scheme Procedure} shared-array-offset array
1818 @deffnx {C Function} scm_shared_array_offset (array)
1819 Return the root vector index of the first element in the array.
1820 @end deffn
1821
1822 @deffn {Scheme Procedure} shared-array-root array
1823 @deffnx {C Function} scm_shared_array_root (array)
1824 Return the root vector of a shared array.
1825 @end deffn
1826
1827 @deffn {Scheme Procedure} transpose-array array dim1 @dots{}
1828 @deffnx {C Function} scm_transpose_array (array, dimlist)
1829 Return an array sharing contents with @var{array}, but with
1830 dimensions arranged in a different order. There must be one
1831 @var{dim} argument for each dimension of @var{array}.
1832 @var{dim1}, @var{dim2}, @dots{} should be integers between 0
1833 and the rank of the array to be returned. Each integer in that
1834 range must appear at least once in the argument list.
1835
1836 The values of @var{dim1}, @var{dim2}, @dots{} correspond to
1837 dimensions in the array to be returned, and their positions in the
1838 argument list to dimensions of @var{array}. Several @var{dim}s
1839 may have the same value, in which case the returned array will
1840 have smaller rank than @var{array}.
1841
1842 @lisp
1843 (transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1844 (transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1845 (transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1846 #2((a 4) (b 5) (c 6))
1847 @end lisp
1848 @end deffn
1849
1850 @deffn {Scheme Procedure} enclose-array array dim1 @dots{}
1851 @deffnx {C Function} scm_enclose_array (array, dimlist)
1852 @var{dim1}, @var{dim2} @dots{} should be nonnegative integers less than
1853 the rank of @var{array}. @code{enclose-array} returns an array
1854 resembling an array of shared arrays. The dimensions of each shared
1855 array are the same as the @var{dim}th dimensions of the original array,
1856 the dimensions of the outer array are the same as those of the original
1857 array that did not match a @var{dim}.
1858
1859 An enclosed array is not a general Scheme array. Its elements may not
1860 be set using @code{array-set!}. Two references to the same element of
1861 an enclosed array will be @code{equal?} but will not in general be
1862 @code{eq?}. The value returned by @code{array-prototype} when given an
1863 enclosed array is unspecified.
1864
1865 For example,
1866
1867 @lisp
1868 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1)
1869 @result{}
1870 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1871
1872 (enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0)
1873 @result{}
1874 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1875 @end lisp
1876 @end deffn
1877
1878 @deffn {Scheme Procedure} array-shape array
1879 @deffnx {Scheme Procedure} array-dimensions array
1880 @deffnx {C Function} scm_array_dimensions (array)
1881 Return a list of the bounds for each dimenson of @var{array}.
1882
1883 @code{array-shape} gives @code{(@var{lower} @var{upper})} for each
1884 dimension. @code{array-dimensions} instead returns just
1885 @math{@var{upper}+1} for dimensions with a 0 lower bound. Both are
1886 suitable as input to @code{make-array}.
1887
1888 For example,
1889
1890 @example
1891 (define a (make-array 'foo '(-1 3) 5))
1892 (array-shape a) @result{} ((-1 3) (0 4))
1893 (array-dimensions a) @result{} ((-1 3) 5)
1894 @end example
1895 @end deffn
1896
1897 @deffn {Scheme Procedure} array-rank obj
1898 @deffnx {C Function} scm_array_rank (obj)
1899 Return the number of dimensions of an array @var{obj}, or if @var{obj}
1900 is not an array then return 0.
1901 @end deffn
1902
1903 @deffn {Scheme Procedure} array->list array
1904 @deffnx {C Function} scm_array_to_list (array)
1905 Return a list consisting of all the elements, in order, of
1906 @var{array}.
1907 @end deffn
1908
1909 @c FIXME: Describe how the order affects the copying (it matters for
1910 @c shared arrays with the same underlying root vector, presumably).
1911 @c
1912 @deffn {Scheme Procedure} array-copy! src dst
1913 @deffnx {Scheme Procedure} array-copy-in-order! src dst
1914 @deffnx {C Function} scm_array_copy_x (src, dst)
1915 Copy every element from vector or array @var{src} to the corresponding
1916 element of @var{dst}. @var{dst} must have the same rank as @var{src},
1917 and be at least as large in each dimension. The return value is
1918 unspecified.
1919 @end deffn
1920
1921 @deffn {Scheme Procedure} array-fill! array fill
1922 @deffnx {C Function} scm_array_fill_x (array, fill)
1923 Store @var{fill} in every element of @var{array}. The value returned
1924 is unspecified.
1925 @end deffn
1926
1927 @c begin (texi-doc-string "guile" "array-equal?")
1928 @deffn {Scheme Procedure} array-equal? array1 array2 @dots{}
1929 Return @code{#t} if all arguments are arrays with the same shape, the
1930 same type, and have corresponding elements which are either
1931 @code{equal?} or @code{array-equal?}. This function differs from
1932 @code{equal?} in that a one dimensional shared array may be
1933 @var{array-equal?} but not @var{equal?} to a vector or uniform vector.
1934 @end deffn
1935
1936 @deffn {Scheme Procedure} array-contents array [strict]
1937 @deffnx {C Function} scm_array_contents (array, strict)
1938 If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1939 without changing their order (last subscript changing fastest), then
1940 @code{array-contents} returns that shared array, otherwise it returns
1941 @code{#f}. All arrays made by @code{make-array} and
1942 @code{make-generalized-array} may be unrolled, some arrays made by
1943 @code{make-shared-array} may not be.
1944
1945 If the optional argument @var{strict} is provided, a shared array will
1946 be returned only if its elements are stored internally contiguous in
1947 memory.
1948 @end deffn
1949
1950 @c FIXME: array-map! accepts no source arrays at all, and in that
1951 @c case makes calls "(proc)". Is that meant to be a documented
1952 @c feature?
1953 @c
1954 @c FIXME: array-for-each doesn't say what happens if the sources have
1955 @c different index ranges. The code currently iterates over the
1956 @c indices of the first and expects the others to cover those. That
1957 @c at least vaguely matches array-map!, but is is meant to be a
1958 @c documented feature?
1959
1960 @deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN
1961 @deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1962 @deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1963 Set each element of the @var{dst} array to values obtained from calls
1964 to @var{proc}. The value returned is unspecified.
1965
1966 Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1967 where each @var{elem} is from the corresponding @var{src} array, at
1968 the @var{dst} index. @code{array-map-in-order!} makes the calls in
1969 row-major order, @code{array-map!} makes them in an unspecified order.
1970
1971 The @var{src} arrays must have the same number of dimensions as
1972 @var{dst}, and must have a range for each dimension which covers the
1973 range in @var{dst}. This ensures all @var{dst} indices are valid in
1974 each @var{src}.
1975 @end deffn
1976
1977 @deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN
1978 @deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1979 Apply @var{proc} to each tuple of elements of @var{src1} @dots{}
1980 @var{srcN}, in row-major order. The value returned is unspecified.
1981 @end deffn
1982
1983 @deffn {Scheme Procedure} array-index-map! dst proc
1984 @deffnx {C Function} scm_array_index_map_x (dst, proc)
1985 Set each element of the @var{dst} array to values returned by calls to
1986 @var{proc}. The value returned is unspecified.
1987
1988 Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1989 @var{i1}@dots{}@var{iN} is the destination index, one parameter for
1990 each dimension. The order in which the calls are made is unspecified.
1991
1992 For example, to create a @m{4\times4, 4x4} matrix representing a
1993 cyclic group,
1994
1995 @tex
1996 \advance\leftskip by 2\lispnarrowing {
1997 $\left(\matrix{%
1998 0 & 1 & 2 & 3 \cr
1999 1 & 2 & 3 & 0 \cr
2000 2 & 3 & 0 & 1 \cr
2001 3 & 0 & 1 & 2 \cr
2002 }\right)$} \par
2003 @end tex
2004 @ifnottex
2005 @example
2006 / 0 1 2 3 \
2007 | 1 2 3 0 |
2008 | 2 3 0 1 |
2009 \ 3 0 1 2 /
2010 @end example
2011 @end ifnottex
2012
2013 @example
2014 (define a (make-array #f 4 4))
2015 (array-index-map! a (lambda (i j)
2016 (modulo (+ i j) 4)))
2017 @end example
2018 @end deffn
2019
2020 @deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
2021 @deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
2022 Attempt to read all elements of @var{ura}, in lexicographic order, as
2023 binary objects from @var{port-or-fdes}.
2024 If an end of file is encountered,
2025 the objects up to that point are put into @var{ura}
2026 (starting at the beginning) and the remainder of the array is
2027 unchanged.
2028
2029 The optional arguments @var{start} and @var{end} allow
2030 a specified region of a vector (or linearized array) to be read,
2031 leaving the remainder of the vector unchanged.
2032
2033 @code{uniform-array-read!} returns the number of objects read.
2034 @var{port-or-fdes} may be omitted, in which case it defaults to the value
2035 returned by @code{(current-input-port)}.
2036 @end deffn
2037
2038 @deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]]
2039 @deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end)
2040 Writes all elements of @var{ura} as binary objects to
2041 @var{port-or-fdes}.
2042
2043 The optional arguments @var{start}
2044 and @var{end} allow
2045 a specified region of a vector (or linearized array) to be written.
2046
2047 The number of objects actually written is returned.
2048 @var{port-or-fdes} may be
2049 omitted, in which case it defaults to the value returned by
2050 @code{(current-output-port)}.
2051 @end deffn
2052
2053 @node Accessing Arrays from C
2054 @subsubsection Accessing Arrays from C
2055
2056 Arrays, especially uniform numeric arrays, are useful to efficiently
2057 represent large amounts of rectangularily organized information, such as
2058 matrices, images, or generally blobs of binary data. It is desirable to
2059 access these blobs in a C like manner so that they can be handed to
2060 external code such as linear algebra libraries or image processing
2061 routines.
2062
2063 While pointers to the elements of an array are in use, the array itself
2064 must be protected so that the pointer remains valid. Such a protected
2065 array is said to be @dfn{reserved}. A reserved array can be read but it
2066 can not be modified. When you try to modify it, an error is signalled.
2067
2068 (This is similar to locking the array while it is in use, but without
2069 the danger of a deadlock. In a multi-threaded program, you will need
2070 additional synchronization to avoid modifying reserved arrays.)
2071
2072 You must take care to always unreserve an array after reserving it, also
2073 in the presence of non-local exits. To simplify this, reserving and
2074 unreserving work like a frame (@pxref{Frames}): a call to
2075 @code{scm_array_get_handle} can be thought of as beginning a frame and
2076 @code{scm_array_handle_release} as ending it. When a non-local exit
2077 happens between these two calls, the array is implicitely unreserved.
2078
2079 That is, you need to properly pair reserving and unreserving in your
2080 code, but you don't need to worry about non-local exits.
2081
2082 These calls and other pairs of calls that establish dynamic contexts
2083 need to be properly nested. If you begin a frame prior to reserving an
2084 array, you need to unreserve the array before ending the frame.
2085 Likewise, when reserving two or more arrays in a certain order, you need
2086 to unreserve them in the opposite order.
2087
2088 Once you have reserved an array and have retrieved the pointer to its
2089 elements, you must figure out the layout of the elements in memory.
2090 Guile allows slices to be taken out of arrays without actually making a
2091 copy, such as making an alias for the diagonal of a matrix. Arrays that
2092 result from such an operation are not stored contiguously in memory and
2093 when working with them, you need to take this into account.
2094
2095
2096 @node Records
2097 @subsection Records
2098
2099 A @dfn{record type} is a first class object representing a user-defined
2100 data type. A @dfn{record} is an instance of a record type.
2101
2102 @deffn {Scheme Procedure} record? obj
2103 Return @code{#t} if @var{obj} is a record of any type and @code{#f}
2104 otherwise.
2105
2106 Note that @code{record?} may be true of any Scheme value; there is no
2107 promise that records are disjoint with other Scheme types.
2108 @end deffn
2109
2110 @deffn {Scheme Procedure} make-record-type type-name field-names
2111 Return a @dfn{record-type descriptor}, a value representing a new data
2112 type disjoint from all others. The @var{type-name} argument must be a
2113 string, but is only used for debugging purposes (such as the printed
2114 representation of a record of the new type). The @var{field-names}
2115 argument is a list of symbols naming the @dfn{fields} of a record of the
2116 new type. It is an error if the list contains any duplicates. It is
2117 unspecified how record-type descriptors are represented.
2118 @end deffn
2119
2120 @deffn {Scheme Procedure} record-constructor rtd [field-names]
2121 Return a procedure for constructing new members of the type represented
2122 by @var{rtd}. The returned procedure accepts exactly as many arguments
2123 as there are symbols in the given list, @var{field-names}; these are
2124 used, in order, as the initial values of those fields in a new record,
2125 which is returned by the constructor procedure. The values of any
2126 fields not named in that list are unspecified. The @var{field-names}
2127 argument defaults to the list of field names in the call to
2128 @code{make-record-type} that created the type represented by @var{rtd};
2129 if the @var{field-names} argument is provided, it is an error if it
2130 contains any duplicates or any symbols not in the default list.
2131 @end deffn
2132
2133 @deffn {Scheme Procedure} record-predicate rtd
2134 Return a procedure for testing membership in the type represented by
2135 @var{rtd}. The returned procedure accepts exactly one argument and
2136 returns a true value if the argument is a member of the indicated record
2137 type; it returns a false value otherwise.
2138 @end deffn
2139
2140 @deffn {Scheme Procedure} record-accessor rtd field-name
2141 Return a procedure for reading the value of a particular field of a
2142 member of the type represented by @var{rtd}. The returned procedure
2143 accepts exactly one argument which must be a record of the appropriate
2144 type; it returns the current value of the field named by the symbol
2145 @var{field-name} in that record. The symbol @var{field-name} must be a
2146 member of the list of field-names in the call to @code{make-record-type}
2147 that created the type represented by @var{rtd}.
2148 @end deffn
2149
2150 @deffn {Scheme Procedure} record-modifier rtd field-name
2151 Return a procedure for writing the value of a particular field of a
2152 member of the type represented by @var{rtd}. The returned procedure
2153 accepts exactly two arguments: first, a record of the appropriate type,
2154 and second, an arbitrary Scheme value; it modifies the field named by
2155 the symbol @var{field-name} in that record to contain the given value.
2156 The returned value of the modifier procedure is unspecified. The symbol
2157 @var{field-name} must be a member of the list of field-names in the call
2158 to @code{make-record-type} that created the type represented by
2159 @var{rtd}.
2160 @end deffn
2161
2162 @deffn {Scheme Procedure} record-type-descriptor record
2163 Return a record-type descriptor representing the type of the given
2164 record. That is, for example, if the returned descriptor were passed to
2165 @code{record-predicate}, the resulting predicate would return a true
2166 value when passed the given record. Note that it is not necessarily the
2167 case that the returned descriptor is the one that was passed to
2168 @code{record-constructor} in the call that created the constructor
2169 procedure that created the given record.
2170 @end deffn
2171
2172 @deffn {Scheme Procedure} record-type-name rtd
2173 Return the type-name associated with the type represented by rtd. The
2174 returned value is @code{eqv?} to the @var{type-name} argument given in
2175 the call to @code{make-record-type} that created the type represented by
2176 @var{rtd}.
2177 @end deffn
2178
2179 @deffn {Scheme Procedure} record-type-fields rtd
2180 Return a list of the symbols naming the fields in members of the type
2181 represented by @var{rtd}. The returned value is @code{equal?} to the
2182 field-names argument given in the call to @code{make-record-type} that
2183 created the type represented by @var{rtd}.
2184 @end deffn
2185
2186
2187 @node Structures
2188 @subsection Structures
2189 @tpindex Structures
2190
2191 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
2192 be reviewed]
2193
2194 A @dfn{structure type} is a first class user-defined data type. A
2195 @dfn{structure} is an instance of a structure type. A structure type is
2196 itself a structure.
2197
2198 Structures are less abstract and more general than traditional records.
2199 In fact, in Guile Scheme, records are implemented using structures.
2200
2201 @menu
2202 * Structure Concepts:: The structure of Structures
2203 * Structure Layout:: Defining the layout of structure types
2204 * Structure Basics:: make-, -ref and -set! procedures for structs
2205 * Vtables:: Accessing type-specific data
2206 @end menu
2207
2208 @node Structure Concepts
2209 @subsubsection Structure Concepts
2210
2211 A structure object consists of a handle, structure data, and a vtable.
2212 The handle is a Scheme value which points to both the vtable and the
2213 structure's data. Structure data is a dynamically allocated region of
2214 memory, private to the structure, divided up into typed fields. A
2215 vtable is another structure used to hold type-specific data. Multiple
2216 structures can share a common vtable.
2217
2218 Three concepts are key to understanding structures.
2219
2220 @itemize @bullet{}
2221 @item @dfn{layout specifications}
2222
2223 Layout specifications determine how memory allocated to structures is
2224 divided up into fields. Programmers must write a layout specification
2225 whenever a new type of structure is defined.
2226
2227 @item @dfn{structural accessors}
2228
2229 Structure access is by field number. There is only one set of
2230 accessors common to all structure objects.
2231
2232 @item @dfn{vtables}
2233
2234 Vtables, themselves structures, are first class representations of
2235 disjoint sub-types of structures in general. In most cases, when a
2236 new structure is created, programmers must specify a vtable for the
2237 new structure. Each vtable has a field describing the layout of its
2238 instances. Vtables can have additional, user-defined fields as well.
2239 @end itemize
2240
2241
2242
2243 @node Structure Layout
2244 @subsubsection Structure Layout
2245
2246 When a structure is created, a region of memory is allocated to hold its
2247 state. The @dfn{layout} of the structure's type determines how that
2248 memory is divided into fields.
2249
2250 Each field has a specified type. There are only three types allowed, each
2251 corresponding to a one letter code. The allowed types are:
2252
2253 @itemize @bullet{}
2254 @item 'u' -- unprotected
2255
2256 The field holds binary data that is not GC protected.
2257
2258 @item 'p' -- protected
2259
2260 The field holds a Scheme value and is GC protected.
2261
2262 @item 's' -- self
2263
2264 The field holds a Scheme value and is GC protected. When a structure is
2265 created with this type of field, the field is initialized to refer to
2266 the structure's own handle. This kind of field is mainly useful when
2267 mixing Scheme and C code in which the C code may need to compute a
2268 structure's handle given only the address of its malloc'd data.
2269 @end itemize
2270
2271
2272 Each field also has an associated access protection. There are only
2273 three kinds of protection, each corresponding to a one letter code.
2274 The allowed protections are:
2275
2276 @itemize @bullet{}
2277 @item 'w' -- writable
2278
2279 The field can be read and written.
2280
2281 @item 'r' -- readable
2282
2283 The field can be read, but not written.
2284
2285 @item 'o' -- opaque
2286
2287 The field can be neither read nor written. This kind
2288 of protection is for fields useful only to built-in routines.
2289 @end itemize
2290
2291 A layout specification is described by stringing together pairs
2292 of letters: one to specify a field type and one to specify a field
2293 protection. For example, a traditional cons pair type object could
2294 be described as:
2295
2296 @example
2297 ; cons pairs have two writable fields of Scheme data
2298 "pwpw"
2299 @end example
2300
2301 A pair object in which the first field is held constant could be:
2302
2303 @example
2304 "prpw"
2305 @end example
2306
2307 Binary fields, (fields of type "u"), hold one @dfn{word} each. The
2308 size of a word is a machine dependent value defined to be equal to the
2309 value of the C expression: @code{sizeof (long)}.
2310
2311 The last field of a structure layout may specify a tail array.
2312 A tail array is indicated by capitalizing the field's protection
2313 code ('W', 'R' or 'O'). A tail-array field is replaced by
2314 a read-only binary data field containing an array size. The array
2315 size is determined at the time the structure is created. It is followed
2316 by a corresponding number of fields of the type specified for the
2317 tail array. For example, a conventional Scheme vector can be
2318 described as:
2319
2320 @example
2321 ; A vector is an arbitrary number of writable fields holding Scheme
2322 ; values:
2323 "pW"
2324 @end example
2325
2326 In the above example, field 0 contains the size of the vector and
2327 fields beginning at 1 contain the vector elements.
2328
2329 A kind of tagged vector (a constant tag followed by conventional
2330 vector elements) might be:
2331
2332 @example
2333 "prpW"
2334 @end example
2335
2336
2337 Structure layouts are represented by specially interned symbols whose
2338 name is a string of type and protection codes. To create a new
2339 structure layout, use this procedure:
2340
2341 @deffn {Scheme Procedure} make-struct-layout fields
2342 @deffnx {C Function} scm_make_struct_layout (fields)
2343 Return a new structure layout object.
2344
2345 @var{fields} must be a string made up of pairs of characters
2346 strung together. The first character of each pair describes a field
2347 type, the second a field protection. Allowed types are 'p' for
2348 GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
2349 a field that points to the structure itself. Allowed protections
2350 are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
2351 fields. The last field protection specification may be capitalized to
2352 indicate that the field is a tail-array.
2353 @end deffn
2354
2355
2356
2357 @node Structure Basics
2358 @subsubsection Structure Basics
2359
2360 This section describes the basic procedures for creating and accessing
2361 structures.
2362
2363 @deffn {Scheme Procedure} make-struct vtable tail_array_size . init
2364 @deffnx {C Function} scm_make_struct (vtable, tail_array_size, init)
2365 Create a new structure.
2366
2367 @var{type} must be a vtable structure (@pxref{Vtables}).
2368
2369 @var{tail-elts} must be a non-negative integer. If the layout
2370 specification indicated by @var{type} includes a tail-array,
2371 this is the number of elements allocated to that array.
2372
2373 The @var{init1}, @dots{} are optional arguments describing how
2374 successive fields of the structure should be initialized. Only fields
2375 with protection 'r' or 'w' can be initialized, except for fields of
2376 type 's', which are automatically initialized to point to the new
2377 structure itself; fields with protection 'o' can not be initialized by
2378 Scheme programs.
2379
2380 If fewer optional arguments than initializable fields are supplied,
2381 fields of type 'p' get default value #f while fields of type 'u' are
2382 initialized to 0.
2383
2384 Structs are currently the basic representation for record-like data
2385 structures in Guile. The plan is to eventually replace them with a
2386 new representation which will at the same time be easier to use and
2387 more powerful.
2388
2389 For more information, see the documentation for @code{make-vtable-vtable}.
2390 @end deffn
2391
2392 @deffn {Scheme Procedure} struct? x
2393 @deffnx {C Function} scm_struct_p (x)
2394 Return @code{#t} iff @var{x} is a structure object, else
2395 @code{#f}.
2396 @end deffn
2397
2398
2399 @deffn {Scheme Procedure} struct-ref handle pos
2400 @deffnx {Scheme Procedure} struct-set! struct n value
2401 @deffnx {C Function} scm_struct_ref (handle, pos)
2402 @deffnx {C Function} scm_struct_set_x (struct, n, value)
2403 Access (or modify) the @var{n}th field of @var{struct}.
2404
2405 If the field is of type 'p', then it can be set to an arbitrary value.
2406
2407 If the field is of type 'u', then it can only be set to a non-negative
2408 integer value small enough to fit in one machine word.
2409 @end deffn
2410
2411
2412
2413 @node Vtables
2414 @subsubsection Vtables
2415
2416 Vtables are structures that are used to represent structure types. Each
2417 vtable contains a layout specification in field
2418 @code{vtable-index-layout} -- instances of the type are laid out
2419 according to that specification. Vtables contain additional fields
2420 which are used only internally to libguile. The variable
2421 @code{vtable-offset-user} is bound to a field number. Vtable fields
2422 at that position or greater are user definable.
2423
2424 @deffn {Scheme Procedure} struct-vtable handle
2425 @deffnx {C Function} scm_struct_vtable (handle)
2426 Return the vtable structure that describes the type of @var{struct}.
2427 @end deffn
2428
2429 @deffn {Scheme Procedure} struct-vtable? x
2430 @deffnx {C Function} scm_struct_vtable_p (x)
2431 Return @code{#t} iff @var{x} is a vtable structure.
2432 @end deffn
2433
2434 If you have a vtable structure, @code{V}, you can create an instance of
2435 the type it describes by using @code{(make-struct V ...)}. But where
2436 does @code{V} itself come from? One possibility is that @code{V} is an
2437 instance of a user-defined vtable type, @code{V'}, so that @code{V} is
2438 created by using @code{(make-struct V' ...)}. Another possibility is
2439 that @code{V} is an instance of the type it itself describes. Vtable
2440 structures of the second sort are created by this procedure:
2441
2442 @deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init
2443 @deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init)
2444 Return a new, self-describing vtable structure.
2445
2446 @var{user-fields} is a string describing user defined fields of the
2447 vtable beginning at index @code{vtable-offset-user}
2448 (see @code{make-struct-layout}).
2449
2450 @var{tail-size} specifies the size of the tail-array (if any) of
2451 this vtable.
2452
2453 @var{init1}, @dots{} are the optional initializers for the fields of
2454 the vtable.
2455
2456 Vtables have one initializable system field---the struct printer.
2457 This field comes before the user fields in the initializers passed
2458 to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
2459 a third optional argument to @code{make-vtable-vtable} and a fourth to
2460 @code{make-struct} when creating vtables:
2461
2462 If the value is a procedure, it will be called instead of the standard
2463 printer whenever a struct described by this vtable is printed.
2464 The procedure will be called with arguments STRUCT and PORT.
2465
2466 The structure of a struct is described by a vtable, so the vtable is
2467 in essence the type of the struct. The vtable is itself a struct with
2468 a vtable. This could go on forever if it weren't for the
2469 vtable-vtables which are self-describing vtables, and thus terminate
2470 the chain.
2471
2472 There are several potential ways of using structs, but the standard
2473 one is to use three kinds of structs, together building up a type
2474 sub-system: one vtable-vtable working as the root and one or several
2475 "types", each with a set of "instances". (The vtable-vtable should be
2476 compared to the class <class> which is the class of itself.)
2477
2478 @lisp
2479 (define ball-root (make-vtable-vtable "pr" 0))
2480
2481 (define (make-ball-type ball-color)
2482 (make-struct ball-root 0
2483 (make-struct-layout "pw")
2484 (lambda (ball port)
2485 (format port "#<a ~A ball owned by ~A>"
2486 (color ball)
2487 (owner ball)))
2488 ball-color))
2489 (define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
2490 (define (owner ball) (struct-ref ball 0))
2491
2492 (define red (make-ball-type 'red))
2493 (define green (make-ball-type 'green))
2494
2495 (define (make-ball type owner) (make-struct type 0 owner))
2496
2497 (define ball (make-ball green 'Nisse))
2498 ball @result{} #<a green ball owned by Nisse>
2499 @end lisp
2500 @end deffn
2501
2502 @deffn {Scheme Procedure} struct-vtable-name vtable
2503 @deffnx {C Function} scm_struct_vtable_name (vtable)
2504 Return the name of the vtable @var{vtable}.
2505 @end deffn
2506
2507 @deffn {Scheme Procedure} set-struct-vtable-name! vtable name
2508 @deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
2509 Set the name of the vtable @var{vtable} to @var{name}.
2510 @end deffn
2511
2512 @deffn {Scheme Procedure} struct-vtable-tag handle
2513 @deffnx {C Function} scm_struct_vtable_tag (handle)
2514 Return the vtable tag of the structure @var{handle}.
2515 @end deffn
2516
2517
2518 @node Dictionary Types
2519 @subsection Dictionary Types
2520
2521 A @dfn{dictionary} object is a data structure used to index
2522 information in a user-defined way. In standard Scheme, the main
2523 aggregate data types are lists and vectors. Lists are not really
2524 indexed at all, and vectors are indexed only by number
2525 (e.g. @code{(vector-ref foo 5)}). Often you will find it useful
2526 to index your data on some other type; for example, in a library
2527 catalog you might want to look up a book by the name of its
2528 author. Dictionaries are used to help you organize information in
2529 such a way.
2530
2531 An @dfn{association list} (or @dfn{alist} for short) is a list of
2532 key-value pairs. Each pair represents a single quantity or
2533 object; the @code{car} of the pair is a key which is used to
2534 identify the object, and the @code{cdr} is the object's value.
2535
2536 A @dfn{hash table} also permits you to index objects with
2537 arbitrary keys, but in a way that makes looking up any one object
2538 extremely fast. A well-designed hash system makes hash table
2539 lookups almost as fast as conventional array or vector references.
2540
2541 Alists are popular among Lisp programmers because they use only
2542 the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
2543 and the equality primitives). No changes to the language core are
2544 necessary. Therefore, with Scheme's built-in list manipulation
2545 facilities, it is very convenient to handle data stored in an
2546 association list. Also, alists are highly portable and can be
2547 easily implemented on even the most minimal Lisp systems.
2548
2549 However, alists are inefficient, especially for storing large
2550 quantities of data. Because we want Guile to be useful for large
2551 software systems as well as small ones, Guile provides a rich set
2552 of tools for using either association lists or hash tables.
2553
2554 @node Association Lists
2555 @subsection Association Lists
2556 @tpindex Association Lists
2557 @tpindex Alist
2558
2559 @cindex Association List
2560 @cindex Alist
2561 @cindex Database
2562
2563 An association list is a conventional data structure that is often used
2564 to implement simple key-value databases. It consists of a list of
2565 entries in which each entry is a pair. The @dfn{key} of each entry is
2566 the @code{car} of the pair and the @dfn{value} of each entry is the
2567 @code{cdr}.
2568
2569 @example
2570 ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
2571 (KEY2 . VALUE2)
2572 (KEY3 . VALUE3)
2573 @dots{}
2574 )
2575 @end example
2576
2577 @noindent
2578 Association lists are also known, for short, as @dfn{alists}.
2579
2580 The structure of an association list is just one example of the infinite
2581 number of possible structures that can be built using pairs and lists.
2582 As such, the keys and values in an association list can be manipulated
2583 using the general list structure procedures @code{cons}, @code{car},
2584 @code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
2585 because association lists are so useful, Guile also provides specific
2586 procedures for manipulating them.
2587
2588 @menu
2589 * Alist Key Equality::
2590 * Adding or Setting Alist Entries::
2591 * Retrieving Alist Entries::
2592 * Removing Alist Entries::
2593 * Sloppy Alist Functions::
2594 * Alist Example::
2595 @end menu
2596
2597 @node Alist Key Equality
2598 @subsubsection Alist Key Equality
2599
2600 All of Guile's dedicated association list procedures, apart from
2601 @code{acons}, come in three flavours, depending on the level of equality
2602 that is required to decide whether an existing key in the association
2603 list is the same as the key that the procedure call uses to identify the
2604 required entry.
2605
2606 @itemize @bullet
2607 @item
2608 Procedures with @dfn{assq} in their name use @code{eq?} to determine key
2609 equality.
2610
2611 @item
2612 Procedures with @dfn{assv} in their name use @code{eqv?} to determine
2613 key equality.
2614
2615 @item
2616 Procedures with @dfn{assoc} in their name use @code{equal?} to
2617 determine key equality.
2618 @end itemize
2619
2620 @code{acons} is an exception because it is used to build association
2621 lists which do not require their entries' keys to be unique.
2622
2623 @node Adding or Setting Alist Entries
2624 @subsubsection Adding or Setting Alist Entries
2625
2626 @code{acons} adds a new entry to an association list and returns the
2627 combined association list. The combined alist is formed by consing the
2628 new entry onto the head of the alist specified in the @code{acons}
2629 procedure call. So the specified alist is not modified, but its
2630 contents become shared with the tail of the combined alist that
2631 @code{acons} returns.
2632
2633 In the most common usage of @code{acons}, a variable holding the
2634 original association list is updated with the combined alist:
2635
2636 @example
2637 (set! address-list (acons name address address-list))
2638 @end example
2639
2640 In such cases, it doesn't matter that the old and new values of
2641 @code{address-list} share some of their contents, since the old value is
2642 usually no longer independently accessible.
2643
2644 Note that @code{acons} adds the specified new entry regardless of
2645 whether the alist may already contain entries with keys that are, in
2646 some sense, the same as that of the new entry. Thus @code{acons} is
2647 ideal for building alists where there is no concept of key uniqueness.
2648
2649 @example
2650 (set! task-list (acons 3 "pay gas bill" '()))
2651 task-list
2652 @result{}
2653 ((3 . "pay gas bill"))
2654
2655 (set! task-list (acons 3 "tidy bedroom" task-list))
2656 task-list
2657 @result{}
2658 ((3 . "tidy bedroom") (3 . "pay gas bill"))
2659 @end example
2660
2661 @code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
2662 or replace an entry in an association list where there @emph{is} a
2663 concept of key uniqueness. If the specified association list already
2664 contains an entry whose key is the same as that specified in the
2665 procedure call, the existing entry is replaced by the new one.
2666 Otherwise, the new entry is consed onto the head of the old association
2667 list to create the combined alist. In all cases, these procedures
2668 return the combined alist.
2669
2670 @code{assq-set!} and friends @emph{may} destructively modify the
2671 structure of the old association list in such a way that an existing
2672 variable is correctly updated without having to @code{set!} it to the
2673 value returned:
2674
2675 @example
2676 address-list
2677 @result{}
2678 (("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
2679
2680 (assoc-set! address-list "james" "1a London Road")
2681 @result{}
2682 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
2683
2684 address-list
2685 @result{}
2686 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
2687 @end example
2688
2689 Or they may not:
2690
2691 @example
2692 (assoc-set! address-list "bob" "11 Newington Avenue")
2693 @result{}
2694 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
2695 ("james" . "1a London Road"))
2696
2697 address-list
2698 @result{}
2699 (("mary" . "34 Elm Road") ("james" . "1a London Road"))
2700 @end example
2701
2702 The only safe way to update an association list variable when adding or
2703 replacing an entry like this is to @code{set!} the variable to the
2704 returned value:
2705
2706 @example
2707 (set! address-list
2708 (assoc-set! address-list "bob" "11 Newington Avenue"))
2709 address-list
2710 @result{}
2711 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
2712 ("james" . "1a London Road"))
2713 @end example
2714
2715 Because of this slight inconvenience, you may find it more convenient to
2716 use hash tables to store dictionary data. If your application will not
2717 be modifying the contents of an alist very often, this may not make much
2718 difference to you.
2719
2720 If you need to keep the old value of an association list in a form
2721 independent from the list that results from modification by
2722 @code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
2723 use @code{list-copy} to copy the old association list before modifying
2724 it.
2725
2726 @deffn {Scheme Procedure} acons key value alist
2727 @deffnx {C Function} scm_acons (key, value, alist)
2728 Add a new key-value pair to @var{alist}. A new pair is
2729 created whose car is @var{key} and whose cdr is @var{value}, and the
2730 pair is consed onto @var{alist}, and the new list is returned. This
2731 function is @emph{not} destructive; @var{alist} is not modified.
2732 @end deffn
2733
2734 @deffn {Scheme Procedure} assq-set! alist key val
2735 @deffnx {Scheme Procedure} assv-set! alist key value
2736 @deffnx {Scheme Procedure} assoc-set! alist key value
2737 @deffnx {C Function} scm_assq_set_x (alist, key, val)
2738 @deffnx {C Function} scm_assv_set_x (alist, key, val)
2739 @deffnx {C Function} scm_assoc_set_x (alist, key, val)
2740 Reassociate @var{key} in @var{alist} with @var{value}: find any existing
2741 @var{alist} entry for @var{key} and associate it with the new
2742 @var{value}. If @var{alist} does not contain an entry for @var{key},
2743 add a new one. Return the (possibly new) alist.
2744
2745 These functions do not attempt to verify the structure of @var{alist},
2746 and so may cause unusual results if passed an object that is not an
2747 association list.
2748 @end deffn
2749
2750 @node Retrieving Alist Entries
2751 @subsubsection Retrieving Alist Entries
2752 @rnindex assq
2753 @rnindex assv
2754 @rnindex assoc
2755
2756 @code{assq}, @code{assv} and @code{assoc} take an alist and a key as
2757 arguments and return the entry for that key if an entry exists, or
2758 @code{#f} if there is no entry for that key. Note that, in the cases
2759 where an entry exists, these procedures return the complete entry, that
2760 is @code{(KEY . VALUE)}, not just the value.
2761
2762 @deffn {Scheme Procedure} assq key alist
2763 @deffnx {Scheme Procedure} assv key alist
2764 @deffnx {Scheme Procedure} assoc key alist
2765 @deffnx {C Function} scm_assq (key, alist)
2766 @deffnx {C Function} scm_assv (key, alist)
2767 @deffnx {C Function} scm_assoc (key, alist)
2768 Fetch the entry in @var{alist} that is associated with @var{key}. To
2769 decide whether the argument @var{key} matches a particular entry in
2770 @var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
2771 uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
2772 cannot be found in @var{alist} (according to whichever equality
2773 predicate is in use), then return @code{#f}. These functions
2774 return the entire alist entry found (i.e. both the key and the value).
2775 @end deffn
2776
2777 @code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
2778 hand, take an alist and a key and return @emph{just the value} for that
2779 key, if an entry exists. If there is no entry for the specified key,
2780 these procedures return @code{#f}.
2781
2782 This creates an ambiguity: if the return value is @code{#f}, it means
2783 either that there is no entry with the specified key, or that there
2784 @emph{is} an entry for the specified key, with value @code{#f}.
2785 Consequently, @code{assq-ref} and friends should only be used where it
2786 is known that an entry exists, or where the ambiguity doesn't matter
2787 for some other reason.
2788
2789 @deffn {Scheme Procedure} assq-ref alist key
2790 @deffnx {Scheme Procedure} assv-ref alist key
2791 @deffnx {Scheme Procedure} assoc-ref alist key
2792 @deffnx {C Function} scm_assq_ref (alist, key)
2793 @deffnx {C Function} scm_assv_ref (alist, key)
2794 @deffnx {C Function} scm_assoc_ref (alist, key)
2795 Like @code{assq}, @code{assv} and @code{assoc}, except that only the
2796 value associated with @var{key} in @var{alist} is returned. These
2797 functions are equivalent to
2798
2799 @lisp
2800 (let ((ent (@var{associator} @var{key} @var{alist})))
2801 (and ent (cdr ent)))
2802 @end lisp
2803
2804 where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
2805 @end deffn
2806
2807 @node Removing Alist Entries
2808 @subsubsection Removing Alist Entries
2809
2810 To remove the element from an association list whose key matches a
2811 specified key, use @code{assq-remove!}, @code{assv-remove!} or
2812 @code{assoc-remove!} (depending, as usual, on the level of equality
2813 required between the key that you specify and the keys in the
2814 association list).
2815
2816 As with @code{assq-set!} and friends, the specified alist may or may not
2817 be modified destructively, and the only safe way to update a variable
2818 containing the alist is to @code{set!} it to the value that
2819 @code{assq-remove!} and friends return.
2820
2821 @example
2822 address-list
2823 @result{}
2824 (("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
2825 ("james" . "1a London Road"))
2826
2827 (set! address-list (assoc-remove! address-list "mary"))
2828 address-list
2829 @result{}
2830 (("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
2831 @end example
2832
2833 Note that, when @code{assq/v/oc-remove!} is used to modify an
2834 association list that has been constructed only using the corresponding
2835 @code{assq/v/oc-set!}, there can be at most one matching entry in the
2836 alist, so the question of multiple entries being removed in one go does
2837 not arise. If @code{assq/v/oc-remove!} is applied to an association
2838 list that has been constructed using @code{acons}, or an
2839 @code{assq/v/oc-set!} with a different level of equality, or any mixture
2840 of these, it removes only the first matching entry from the alist, even
2841 if the alist might contain further matching entries. For example:
2842
2843 @example
2844 (define address-list '())
2845 (set! address-list (assq-set! address-list "mary" "11 Elm Street"))
2846 (set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
2847 address-list
2848 @result{}
2849 (("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
2850
2851 (set! address-list (assoc-remove! address-list "mary"))
2852 address-list
2853 @result{}
2854 (("mary" . "11 Elm Street"))
2855 @end example
2856
2857 In this example, the two instances of the string "mary" are not the same
2858 when compared using @code{eq?}, so the two @code{assq-set!} calls add
2859 two distinct entries to @code{address-list}. When compared using
2860 @code{equal?}, both "mary"s in @code{address-list} are the same as the
2861 "mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
2862 after removing the first matching entry that it finds, and so one of the
2863 "mary" entries is left in place.
2864
2865 @deffn {Scheme Procedure} assq-remove! alist key
2866 @deffnx {Scheme Procedure} assv-remove! alist key
2867 @deffnx {Scheme Procedure} assoc-remove! alist key
2868 @deffnx {C Function} scm_assq_remove_x (alist, key)
2869 @deffnx {C Function} scm_assv_remove_x (alist, key)
2870 @deffnx {C Function} scm_assoc_remove_x (alist, key)
2871 Delete the first entry in @var{alist} associated with @var{key}, and return
2872 the resulting alist.
2873 @end deffn
2874
2875 @node Sloppy Alist Functions
2876 @subsubsection Sloppy Alist Functions
2877
2878 @code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
2879 like the corresponding non-@code{sloppy-} procedures, except that they
2880 return @code{#f} when the specified association list is not well-formed,
2881 where the non-@code{sloppy-} versions would signal an error.
2882
2883 Specifically, there are two conditions for which the non-@code{sloppy-}
2884 procedures signal an error, which the @code{sloppy-} procedures handle
2885 instead by returning @code{#f}. Firstly, if the specified alist as a
2886 whole is not a proper list:
2887
2888 @example
2889 (assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2890 @result{}
2891 ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
2892 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 2) ("key" . "door") . "open sesame")
2893
2894 (sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2895 @result{}
2896 #f
2897 @end example
2898
2899 @noindent
2900 Secondly, if one of the entries in the specified alist is not a pair:
2901
2902 @example
2903 (assoc 2 '((1 . 1) 2 (3 . 9)))
2904 @result{}
2905 ERROR: In procedure assoc in expression (assoc 2 (quote #)):
2906 ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 1) 2 (3 . 9))
2907
2908 (sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
2909 @result{}
2910 #f
2911 @end example
2912
2913 Unless you are explicitly working with badly formed association lists,
2914 it is much safer to use the non-@code{sloppy-} procedures, because they
2915 help to highlight coding and data errors that the @code{sloppy-}
2916 versions would silently cover up.
2917
2918 @deffn {Scheme Procedure} sloppy-assq key alist
2919 @deffnx {C Function} scm_sloppy_assq (key, alist)
2920 Behaves like @code{assq} but does not do any error checking.
2921 Recommended only for use in Guile internals.
2922 @end deffn
2923
2924 @deffn {Scheme Procedure} sloppy-assv key alist
2925 @deffnx {C Function} scm_sloppy_assv (key, alist)
2926 Behaves like @code{assv} but does not do any error checking.
2927 Recommended only for use in Guile internals.
2928 @end deffn
2929
2930 @deffn {Scheme Procedure} sloppy-assoc key alist
2931 @deffnx {C Function} scm_sloppy_assoc (key, alist)
2932 Behaves like @code{assoc} but does not do any error checking.
2933 Recommended only for use in Guile internals.
2934 @end deffn
2935
2936 @node Alist Example
2937 @subsubsection Alist Example
2938
2939 Here is a longer example of how alists may be used in practice.
2940
2941 @lisp
2942 (define capitals '(("New York" . "Albany")
2943 ("Oregon" . "Salem")
2944 ("Florida" . "Miami")))
2945
2946 ;; What's the capital of Oregon?
2947 (assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
2948 (assoc-ref capitals "Oregon") @result{} "Salem"
2949
2950 ;; We left out South Dakota.
2951 (set! capitals
2952 (assoc-set! capitals "South Dakota" "Pierre"))
2953 capitals
2954 @result{} (("South Dakota" . "Pierre")
2955 ("New York" . "Albany")
2956 ("Oregon" . "Salem")
2957 ("Florida" . "Miami"))
2958
2959 ;; And we got Florida wrong.
2960 (set! capitals
2961 (assoc-set! capitals "Florida" "Tallahassee"))
2962 capitals
2963 @result{} (("South Dakota" . "Pierre")
2964 ("New York" . "Albany")
2965 ("Oregon" . "Salem")
2966 ("Florida" . "Tallahassee"))
2967
2968 ;; After Oregon secedes, we can remove it.
2969 (set! capitals
2970 (assoc-remove! capitals "Oregon"))
2971 capitals
2972 @result{} (("South Dakota" . "Pierre")
2973 ("New York" . "Albany")
2974 ("Florida" . "Tallahassee"))
2975 @end lisp
2976
2977 @node Hash Tables
2978 @subsection Hash Tables
2979 @tpindex Hash Tables
2980
2981 @c FIXME::martin: Review me!
2982
2983 Hash tables are dictionaries which offer similar functionality as
2984 association lists: They provide a mapping from keys to values. The
2985 difference is that association lists need time linear in the size of
2986 elements when searching for entries, whereas hash tables can normally
2987 search in constant time. The drawback is that hash tables require a
2988 little bit more memory, and that you can not use the normal list
2989 procedures (@pxref{Lists}) for working with them.
2990
2991 @menu
2992 * Hash Table Examples:: Demonstration of hash table usage.
2993 * Hash Table Reference:: Hash table procedure descriptions.
2994 @end menu
2995
2996
2997 @node Hash Table Examples
2998 @subsubsection Hash Table Examples
2999
3000 @c FIXME::martin: Review me!
3001
3002 For demonstration purposes, this section gives a few usage examples of
3003 some hash table procedures, together with some explanation what they do.
3004
3005 First we start by creating a new hash table with 31 slots, and
3006 populate it with two key/value pairs.
3007
3008 @lisp
3009 (define h (make-hash-table 31))
3010
3011 (hashq-create-handle! h 'foo "bar")
3012 @result{}
3013 (foo . "bar")
3014
3015 (hashq-create-handle! h 'braz "zonk")
3016 @result{}
3017 (braz . "zonk")
3018
3019 (hashq-create-handle! h 'frob #f)
3020 @result{}
3021 (frob . #f)
3022 @end lisp
3023
3024 You can get the value for a given key with the procedure
3025 @code{hashq-ref}, but the problem with this procedure is that you
3026 cannot reliably determine whether a key does exists in the table. The
3027 reason is that the procedure returns @code{#f} if the key is not in
3028 the table, but it will return the same value if the key is in the
3029 table and just happens to have the value @code{#f}, as you can see in
3030 the following examples.
3031
3032 @lisp
3033 (hashq-ref h 'foo)
3034 @result{}
3035 "bar"
3036
3037 (hashq-ref h 'frob)
3038 @result{}
3039 #f
3040
3041 (hashq-ref h 'not-there)
3042 @result{}
3043 #f
3044 @end lisp
3045
3046 Better is to use the procedure @code{hashq-get-handle}, which makes a
3047 distinction between the two cases. Just like @code{assq}, this
3048 procedure returns a key/value-pair on success, and @code{#f} if the
3049 key is not found.
3050
3051 @lisp
3052 (hashq-get-handle h 'foo)
3053 @result{}
3054 (foo . "bar")
3055
3056 (hashq-get-handle h 'not-there)
3057 @result{}
3058 #f
3059 @end lisp
3060
3061 There is no procedure for calculating the number of key/value-pairs in
3062 a hash table, but @code{hash-fold} can be used for doing exactly that.
3063
3064 @lisp
3065 (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
3066 @result{}
3067 3
3068 @end lisp
3069
3070 @node Hash Table Reference
3071 @subsubsection Hash Table Reference
3072
3073 @c FIXME: Describe in broad terms what happens for resizing, and what
3074 @c the initial size means for this.
3075
3076 Like the association list functions, the hash table functions come in
3077 several varieties, according to the equality test used for the keys.
3078 Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
3079 functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
3080 the @code{hashx-} functions use an application supplied test.
3081
3082 A single @code{make-hash-table} creates a hash table suitable for use
3083 with any set of functions, but it's imperative that just one set is
3084 then used consistently, or results will be unpredictable.
3085
3086 @sp 1
3087 Hash tables are implemented as a vector indexed by a hash value formed
3088 from the key, with an association list of key/value pairs for each
3089 bucket in case distinct keys hash together. Direct access to the
3090 pairs in those lists is provided by the @code{-handle-} functions.
3091
3092 When the number of table entries goes above a threshold the vector is
3093 increased and the entries rehashed, to prevent the bucket lists
3094 becoming too long and slowing down accesses. When the number of
3095 entries goes below a threshold the vector is decreased to save space.
3096
3097 @sp 1
3098 For the @code{hashx-} ``extended'' routines, an application supplies a
3099 @var{hash} function producing an integer index like @code{hashq} etc
3100 below, and an @var{assoc} alist search function like @code{assq} etc
3101 (@pxref{Retrieving Alist Entries}). Here's an example of such
3102 functions implementing case-insensitive hashing of string keys,
3103
3104 @example
3105 (use-modules (srfi srfi-1)
3106 (srfi srfi-13))
3107
3108 (define (my-hash str size)
3109 (remainder (string-hash-ci str) size))
3110 (define (my-assoc str alist)
3111 (find (lambda (pair) (string-ci=? str (car pair))) alist))
3112
3113 (define my-table (make-hash-table))
3114 (hashx-set! my-hash my-assoc my-table "foo" 123)
3115
3116 (hashx-ref my-hash my-assoc my-table "FOO")
3117 @result{} 123
3118 @end example
3119
3120 In a @code{hashx-} @var{hash} function the aim is to spread keys
3121 across the vector, so bucket lists don't become long. But the actual
3122 values are arbitrary as long as they're in the range 0 to
3123 @math{@var{size}-1}. Helpful functions for forming a hash value, in
3124 addition to @code{hashq} etc below, include @code{symbol-hash}
3125 (@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
3126 (@pxref{String Comparison}), and @code{char-set-hash}
3127 (@pxref{Character Set Predicates/Comparison}).
3128
3129 Note that currently, unfortunately, there's no @code{hashx-remove!}
3130 function, which rather limits the usefulness of the @code{hashx-}
3131 routines.
3132
3133 @sp 1
3134 @deffn {Scheme Procedure} make-hash-table [size]
3135 Create a new hash table, with an optional minimum vector @var{size}.
3136
3137 When @var{size} is given, the table vector will still grow and shrink
3138 automatically, as described above, but with @var{size} as a minimum.
3139 If an application knows roughly how many entries the table will hold
3140 then it can use @var{size} to avoid rehashing when initial entries are
3141 added.
3142 @end deffn
3143
3144 @deffn {Scheme Procedure} hash-table? obj
3145 @deffnx {C Function} scm_hash_table_p (obj)
3146 Return @code{#t} if @var{obj} is a hash table.
3147 @end deffn
3148
3149 @deffn {Scheme Procedure} hash-clear! table
3150 @deffnx {C Function} scm_hash_clear_x (table)
3151 Remove all items from TABLE (without triggering a resize).
3152 @end deffn
3153
3154 @deffn {Scheme Procedure} hash-ref table key [dflt]
3155 @deffnx {Scheme Procedure} hashq-ref table key [dflt]
3156 @deffnx {Scheme Procedure} hashv-ref table key [dflt]
3157 @deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
3158 @deffnx {C Function} scm_hash_ref (table, key, dflt)
3159 @deffnx {C Function} scm_hashq_ref (table, key, dflt)
3160 @deffnx {C Function} scm_hashv_ref (table, key, dflt)
3161 @deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
3162 Lookup @var{key} in the given hash @var{table}, and return the
3163 associated value. If @var{key} is not found, return @var{dflt}, or
3164 @code{#f} if @var{dflt} is not given.
3165 @end deffn
3166
3167 @deffn {Scheme Procedure} hash-set! table key val
3168 @deffnx {Scheme Procedure} hashq-set! table key val
3169 @deffnx {Scheme Procedure} hashv-set! table key val
3170 @deffnx {Scheme Procedure} hashx-set! hash assoc table key val
3171 @deffnx {C Function} scm_hash_set_x (table, key, val)
3172 @deffnx {C Function} scm_hashq_set_x (table, key, val)
3173 @deffnx {C Function} scm_hashv_set_x (table, key, val)
3174 @deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
3175 Associate @var{val} with @var{key} in the given hash @var{table}. If
3176 @var{key} is already present then it's associated value is changed.
3177 If it's not present then a new entry is created.
3178 @end deffn
3179
3180 @deffn {Scheme Procedure} hash-remove! table key
3181 @deffnx {Scheme Procedure} hashq-remove! table key
3182 @deffnx {Scheme Procedure} hashv-remove! table key
3183 @deffnx {C Function} scm_hash_remove_x (table, key)
3184 @deffnx {C Function} scm_hashq_remove_x (table, key)
3185 @deffnx {C Function} scm_hashv_remove_x (table, key)
3186 Remove any association for @var{key} in the given hash @var{table}.
3187 If @var{key} is not in @var{table} then nothing is done.
3188 @end deffn
3189
3190 @deffn {Scheme Procedure} hash key size
3191 @deffnx {Scheme Procedure} hashq key size
3192 @deffnx {Scheme Procedure} hashv key size
3193 @deffnx {C Function} scm_hash (key, size)
3194 @deffnx {C Function} scm_hashq (key, size)
3195 @deffnx {C Function} scm_hashv (key, size)
3196 Return a hash value for @var{key}. This is a number in the range
3197 @math{0} to @math{@var{size}-1}, which is suitable for use in a hash
3198 table of the given @var{size}.
3199
3200 Note that @code{hashq} and @code{hashv} may use internal addresses of
3201 objects, so if an object is garbage collected and re-created it can
3202 have a different hash value, even when the two are notionally
3203 @code{eq?}. For instance with symbols,
3204
3205 @example
3206 (hashq 'something 123) @result{} 19
3207 (gc)
3208 (hashq 'something 123) @result{} 62
3209 @end example
3210
3211 In normal use this is not a problem, since an object entered into a
3212 hash table won't be garbage collected until removed. It's only if
3213 hashing calculations are somehow separated from normal references that
3214 its lifetime needs to be considered.
3215 @end deffn
3216
3217 @deffn {Scheme Procedure} hash-get-handle table key
3218 @deffnx {Scheme Procedure} hashq-get-handle table key
3219 @deffnx {Scheme Procedure} hashv-get-handle table key
3220 @deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
3221 @deffnx {C Function} scm_hash_get_handle (table, key)
3222 @deffnx {C Function} scm_hashq_get_handle (table, key)
3223 @deffnx {C Function} scm_hashv_get_handle (table, key)
3224 @deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
3225 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3226 given hash @var{table}, or @code{#f} if @var{key} is not in
3227 @var{table}.
3228 @end deffn
3229
3230 @deffn {Scheme Procedure} hash-create-handle! table key init
3231 @deffnx {Scheme Procedure} hashq-create-handle! table key init
3232 @deffnx {Scheme Procedure} hashv-create-handle! table key init
3233 @deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
3234 @deffnx {C Function} scm_hash_create_handle_x (table, key, init)
3235 @deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
3236 @deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
3237 @deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
3238 Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
3239 given hash @var{table}. If @var{key} is not in @var{table} then
3240 create an entry for it with @var{init} as the value, and return that
3241 pair.
3242 @end deffn
3243
3244 @deffn {Scheme Procedure} hash-map->list proc table
3245 @deffnx {Scheme Procedure} hash-for-each proc table
3246 @deffnx {C Function} scm_hash_map_to_list (proc, table)
3247 @deffnx {C Function} scm_hash_for_each (proc, table)
3248 Apply @var{proc} to the entries in the given hash @var{table}. Each
3249 call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list}
3250 returns a list of the results from these calls, @code{hash-for-each}
3251 discards the results and returns an unspecified value.
3252
3253 Calls are made over the table entries in an unspecified order, and for
3254 @code{hash-map->list} the order of the values in the returned list is
3255 unspecified. Results will be unpredictable if @var{table} is modified
3256 while iterating.
3257
3258 For example the following returns a new alist comprising all the
3259 entries from @code{mytable}, in no particular order.
3260
3261 @example
3262 (hash-map->list cons mytable)
3263 @end example
3264 @end deffn
3265
3266 @deffn {Scheme Procedure} hash-for-each-handle proc table
3267 @deffnx {C Function} scm_hash_for_each_handle (proc, table)
3268 Apply @var{proc} to the entries in the given hash @var{table}. Each
3269 call is @code{(@var{proc} @var{handle})}, where @var{handle} is a
3270 @code{(@var{key} . @var{value})} pair. Return an unspecified value.
3271
3272 @code{hash-for-each-handle} differs from @code{hash-for-each} only in
3273 the argument list of @var{proc}.
3274 @end deffn
3275
3276 @deffn {Scheme Procedure} hash-fold proc init table
3277 @deffnx {C Function} scm_hash_fold (proc, init, table)
3278 Accumulate a result by applying @var{proc} to the elements of the
3279 given hash @var{table}. Each call is @code{(@var{proc} @var{key}
3280 @var{value} @var{prior-result})}, where @var{key} and @var{value} are
3281 from the @var{table} and @var{prior-result} is the return from the
3282 previous @var{proc} call. For the first call, @var{prior-result} is
3283 the given @var{init} value.
3284
3285 Calls are made over the table entries in an unspecified order.
3286 Results will be unpredictable if @var{table} is modified while
3287 @code{hash-fold} is running.
3288
3289 For example, the following returns a count of how many keys in
3290 @code{mytable} are strings.
3291
3292 @example
3293 (hash-fold (lambda (key value prior)
3294 (if (string? key) (1+ prior) prior))
3295 0 mytable)
3296 @end example
3297 @end deffn
3298
3299
3300 @c Local Variables:
3301 @c TeX-master: "guile.texi"
3302 @c End: