(Uniform Arrays): Added a FIXME warning
[bpt/guile.git] / doc / ref / scheme-compound.texi
CommitLineData
2da09c3f
MV
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
4c731ece
NJ
7@page
8@node Compound Data Types
9@chapter Compound Data Types
10
11This chapter describes Guile's compound data types. By @dfn{compound}
12we mean that the primary purpose of these data types is to act as
13containers for other kinds of data (including other compound objects).
14For instance, a (non-uniform) vector with length 5 is a container that
15can hold five arbitrary Scheme objects.
16
17The various kinds of container object differ from each other in how
18their memory is allocated, how they are indexed, and how particular
19values 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* Records::
26* Structures::
27* Arrays:: Arrays of values.
28* Association Lists and Hash Tables:: Dictionary data types.
29@end menu
30
31
32@node Pairs
33@section Pairs
34@tpindex Pairs
35
4c731ece
NJ
36Pairs are used to combine two Scheme objects into one compound object.
37Hence the name: A pair stores a pair of objects.
38
39The data type @dfn{pair} is extremely important in Scheme, just like in
40any other Lisp dialect. The reason is that pairs are not only used to
41make two values available as one object, but that pairs are used for
42constructing lists of values. Because lists are so important in Scheme,
43they are described in a section of their own (@pxref{Lists}).
44
45Pairs can literally get entered in source code or at the REPL, in the
46so-called @dfn{dotted list} syntax. This syntax consists of an opening
47parentheses, the first element of the pair, a dot, the second element
48and a closing parentheses. The following example shows how a pair
49consisting of the two numbers 1 and 2, and a pair containing the symbols
50@code{foo} and @code{bar} can be entered. It is very important to write
51the whitespace before and after the dot, because otherwise the Scheme
85a9b4ed 52parser would not be able to figure out where to split the tokens.
4c731ece
NJ
53
54@lisp
55(1 . 2)
56(foo . bar)
57@end lisp
58
59But beware, if you want to try out these examples, you have to
60@dfn{quote} the expressions. More information about quotation is
61available in the section (REFFIXME). The correct way to try these
62examples is as follows.
63
64@lisp
65'(1 . 2)
66@result{}
67(1 . 2)
68'(foo . bar)
69@result{}
70(foo . bar)
71@end lisp
72
73A new pair is made by calling the procedure @code{cons} with two
74arguments. Then the argument values are stored into a newly allocated
75pair, and the pair is returned. The name @code{cons} stands for
76"construct". Use the procedure @code{pair?} to test whether a
77given Scheme object is a pair or not.
78
79@rnindex cons
80@deffn {Scheme Procedure} cons x y
81@deffnx {C Function} scm_cons (x, y)
82Return a newly allocated pair whose car is @var{x} and whose
83cdr is @var{y}. The pair is guaranteed to be different (in the
84sense of @code{eq?}) from every previously existing object.
85@end deffn
86
87@rnindex pair?
88@deffn {Scheme Procedure} pair? x
89@deffnx {C Function} scm_pair_p (x)
90Return @code{#t} if @var{x} is a pair; otherwise return
91@code{#f}.
92@end deffn
93
94The two parts of a pair are traditionally called @dfn{car} and
95@dfn{cdr}. They can be retrieved with procedures of the same name
96(@code{car} and @code{cdr}), and can be modified with the procedures
97@code{set-car!} and @code{set-cdr!}. Since a very common operation in
98Scheme programs is to access the car of a pair, or the car of the cdr of
99a pair, etc., the procedures called @code{caar}, @code{cadr} and so on
100are also predefined.
101
102@rnindex car
103@rnindex cdr
104@deffn {Scheme Procedure} car pair
105@deffnx {Scheme Procedure} cdr pair
106Return the car or the cdr of @var{pair}, respectively.
107@end deffn
108
109@deffn {Scheme Procedure} caar pair
110@deffnx {Scheme Procedure} cadr pair @dots{}
111@deffnx {Scheme Procedure} cdddar pair
112@deffnx {Scheme Procedure} cddddr pair
113These procedures are compositions of @code{car} and @code{cdr}, where
114for example @code{caddr} could be defined by
115
116@lisp
117(define caddr (lambda (x) (car (cdr (cdr x)))))
118@end lisp
119@end deffn
120
121@rnindex set-car!
122@deffn {Scheme Procedure} set-car! pair value
123@deffnx {C Function} scm_set_car_x (pair, value)
124Stores @var{value} in the car field of @var{pair}. The value returned
125by @code{set-car!} is unspecified.
126@end deffn
127
128@rnindex set-cdr!
129@deffn {Scheme Procedure} set-cdr! pair value
130@deffnx {C Function} scm_set_cdr_x (pair, value)
131Stores @var{value} in the cdr field of @var{pair}. The value returned
132by @code{set-cdr!} is unspecified.
133@end deffn
134
135
136@node Lists
137@section Lists
138@tpindex Lists
139
4c731ece
NJ
140A very important data type in Scheme---as well as in all other Lisp
141dialects---is the data type @dfn{list}.@footnote{Strictly speaking,
142Scheme does not have a real datatype @dfn{list}. Lists are made up of
143@dfn{chained pairs}, and only exist by definition---a list is a chain
144of pairs which looks like a list.}
145
146This is the short definition of what a list is:
147
148@itemize @bullet
149@item
150Either the empty list @code{()},
151
152@item
153or a pair which has a list in its cdr.
154@end itemize
155
156@c FIXME::martin: Describe the pair chaining in more detail.
157
158@c FIXME::martin: What is a proper, what an improper list?
159@c What is a circular list?
160
161@c FIXME::martin: Maybe steal some graphics from the Elisp reference
162@c manual?
163
164@menu
165* List Syntax:: Writing literal lists.
166* List Predicates:: Testing lists.
167* List Constructors:: Creating new lists.
168* List Selection:: Selecting from lists, getting their length.
169* Append/Reverse:: Appending and reversing lists.
170* List Modification:: Modifying existing lists.
171* List Searching:: Searching for list elements
172* List Mapping:: Applying procedures to lists.
173@end menu
174
175@node List Syntax
176@subsection List Read Syntax
177
4c731ece
NJ
178The syntax for lists is an opening parentheses, then all the elements of
179the list (separated by whitespace) and finally a closing
180parentheses.@footnote{Note that there is no separation character between
181the list elements, like a comma or a semicolon.}.
182
183@lisp
184(1 2 3) ; @r{a list of the numbers 1, 2 and 3}
185("foo" bar 3.1415) ; @r{a string, a symbol and a real number}
186() ; @r{the empty list}
187@end lisp
188
189The last example needs a bit more explanation. A list with no elements,
190called the @dfn{empty list}, is special in some ways. It is used for
191terminating lists by storing it into the cdr of the last pair that makes
192up a list. An example will clear that up:
193
194@lisp
195(car '(1))
196@result{}
1971
198(cdr '(1))
199@result{}
200()
201@end lisp
202
203This example also shows that lists have to be quoted (REFFIXME) when
204written, because they would otherwise be mistakingly taken as procedure
205applications (@pxref{Simple Invocation}).
206
207
208@node List Predicates
209@subsection List Predicates
210
4c731ece
NJ
211Often it is useful to test whether a given Scheme object is a list or
212not. List-processing procedures could use this information to test
213whether their input is valid, or they could do different things
214depending on the datatype of their arguments.
215
216@rnindex list?
217@deffn {Scheme Procedure} list? x
218@deffnx {C Function} scm_list_p (x)
219Return @code{#t} iff @var{x} is a proper list, else @code{#f}.
220@end deffn
221
222The predicate @code{null?} is often used in list-processing code to
223tell whether a given list has run out of elements. That is, a loop
224somehow deals with the elements of a list until the list satisfies
225@code{null?}. Then, the algorithm terminates.
226
227@rnindex null?
228@deffn {Scheme Procedure} null? x
229@deffnx {C Function} scm_null_p (x)
230Return @code{#t} iff @var{x} is the empty list, else @code{#f}.
231@end deffn
232
233@node List Constructors
234@subsection List Constructors
235
236This section describes the procedures for constructing new lists.
237@code{list} simply returns a list where the elements are the arguments,
238@code{cons*} is similar, but the last argument is stored in the cdr of
239the last pair of the list.
240
51787257
KR
241@c C Function scm_list(rest) used to be documented here, but it's a
242@c no-op since it does nothing but return the list the caller must
243@c have already created.
244@c
245@deffn {Scheme Procedure} list elem1 @dots{} elemN
246@deffnx {C Function} scm_list_1 (elem1)
247@deffnx {C Function} scm_list_2 (elem1, elem2)
248@deffnx {C Function} scm_list_3 (elem1, elem2, elem3)
249@deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4)
250@deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5)
251@deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED})
4c731ece 252@rnindex list
51787257
KR
253Return a new list containing elements @var{elem1} to @var{elemN}.
254
255@code{scm_list_n} takes a variable number of arguments, terminated by
256the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is
257not included in the list. None of @var{elem1} to @var{elemN} can
258themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will
259terminate at that point.
4c731ece
NJ
260@end deffn
261
603707f4
KR
262@c C Function scm_cons_star(arg1,rest) used to be documented here,
263@c but it's not really a useful interface, since it expects the
264@c caller to have already consed up all but the first argument
265@c already.
266@c
4c731ece 267@deffn {Scheme Procedure} cons* arg1 arg2 @dots{}
4c731ece
NJ
268Like @code{list}, but the last arg provides the tail of the
269constructed list, returning @code{(cons @var{arg1} (cons
270@var{arg2} (cons @dots{} @var{argn})))}. Requires at least one
271argument. If given one argument, that argument is returned as
272result. This function is called @code{list*} in some other
273Schemes and in Common LISP.
274@end deffn
275
276@deffn {Scheme Procedure} list-copy lst
277@deffnx {C Function} scm_list_copy (lst)
278Return a (newly-created) copy of @var{lst}.
279@end deffn
280
281@deffn {Scheme Procedure} make-list n [init]
282Create a list containing of @var{n} elements, where each element is
283initialized to @var{init}. @var{init} defaults to the empty list
284@code{()} if not given.
285@end deffn
286
287Note that @code{list-copy} only makes a copy of the pairs which make up
288the spine of the lists. The list elements are not copied, which means
85a9b4ed 289that modifying the elements of the new list also modifies the elements
4c731ece
NJ
290of the old list. On the other hand, applying procedures like
291@code{set-cdr!} or @code{delv!} to the new list will not alter the old
292list. If you also need to copy the list elements (making a deep copy),
293use the procedure @code{copy-tree} (@pxref{Copying}).
294
295@node List Selection
296@subsection List Selection
297
4c731ece
NJ
298These procedures are used to get some information about a list, or to
299retrieve one or more elements of a list.
300
301@rnindex length
302@deffn {Scheme Procedure} length lst
303@deffnx {C Function} scm_length (lst)
304Return the number of elements in list @var{lst}.
305@end deffn
306
307@deffn {Scheme Procedure} last-pair lst
308@deffnx {C Function} scm_last_pair (lst)
309Return a pointer to the last pair in @var{lst}, signalling an error if
310@var{lst} is circular.
311@end deffn
312
313@rnindex list-ref
314@deffn {Scheme Procedure} list-ref list k
315@deffnx {C Function} scm_list_ref (list, k)
316Return the @var{k}th element from @var{list}.
317@end deffn
318
319@rnindex list-tail
320@deffn {Scheme Procedure} list-tail lst k
321@deffnx {Scheme Procedure} list-cdr-ref lst k
322@deffnx {C Function} scm_list_tail (lst, k)
323Return the "tail" of @var{lst} beginning with its @var{k}th element.
324The first element of the list is considered to be element 0.
325
326@code{list-tail} and @code{list-cdr-ref} are identical. It may help to
327think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list,
328or returning the results of cdring @var{k} times down @var{lst}.
329@end deffn
330
331@deffn {Scheme Procedure} list-head lst k
332@deffnx {C Function} scm_list_head (lst, k)
333Copy the first @var{k} elements from @var{lst} into a new list, and
334return it.
335@end deffn
336
337@node Append/Reverse
338@subsection Append and Reverse
339
4c731ece
NJ
340@code{append} and @code{append!} are used to concatenate two or more
341lists in order to form a new list. @code{reverse} and @code{reverse!}
342return lists with the same elements as their arguments, but in reverse
343order. The procedure variants with an @code{!} directly modify the
344pairs which form the list, whereas the other procedures create new
345pairs. This is why you should be careful when using the side-effecting
346variants.
347
348@rnindex append
697039a9
KR
349@deffn {Scheme Procedure} append lst1 @dots{} lstN
350@deffnx {Scheme Procedure} append! lst1 @dots{} lstN
351@deffnx {C Function} scm_append (lstlst)
352@deffnx {C Function} scm_append_x (lstlst)
353Return a list comprising all the elements of lists @var{lst1} to
354@var{lstN}.
355
4c731ece
NJ
356@lisp
357(append '(x) '(y)) @result{} (x y)
358(append '(a) '(b c d)) @result{} (a b c d)
359(append '(a (b)) '((c))) @result{} (a (b) (c))
360@end lisp
697039a9
KR
361
362The last argument @var{lstN} may actually be any object; an improper
363list results if the last argument is not a proper list.
364
4c731ece
NJ
365@lisp
366(append '(a b) '(c . d)) @result{} (a b c . d)
367(append '() 'a) @result{} a
368@end lisp
4c731ece 369
697039a9
KR
370@code{append} doesn't modify the given lists, but the return may share
371structure with the final @var{lstN}. @code{append!} modifies the
372given lists to form its return.
373
374For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list
375of the list operands @var{lst1} @dots{} @var{lstN}. That @var{lstlst}
376itself is not modified or used in the return.
4c731ece
NJ
377@end deffn
378
379@rnindex reverse
380@deffn {Scheme Procedure} reverse lst
c537e01b 381@deffnx {Scheme Procedure} reverse! lst [newtail]
4c731ece 382@deffnx {C Function} scm_reverse (lst)
c537e01b
KR
383@deffnx {C Function} scm_reverse_x (lst, newtail)
384Return a list comprising the elements of @var{lst}, in reverse order.
385
386@code{reverse} constructs a new list, @code{reverse!} modifies
387@var{lst} in constructing its return.
4c731ece 388
c537e01b
KR
389For @code{reverse!}, the optional @var{newtail} is appended to to the
390result. @var{newtail} isn't reversed, it simply becomes the list
391tail. For @code{scm_reverse_x}, the @var{newtail} parameter is
392mandatory, but can be @code{SCM_EOL} if no further tail is required.
4c731ece
NJ
393@end deffn
394
395@node List Modification
396@subsection List Modification
397
398The following procedures modify an existing list, either by changing
399elements of the list, or by changing the list structure itself.
400
401@deffn {Scheme Procedure} list-set! list k val
402@deffnx {C Function} scm_list_set_x (list, k, val)
403Set the @var{k}th element of @var{list} to @var{val}.
404@end deffn
405
406@deffn {Scheme Procedure} list-cdr-set! list k val
407@deffnx {C Function} scm_list_cdr_set_x (list, k, val)
408Set the @var{k}th cdr of @var{list} to @var{val}.
409@end deffn
410
411@deffn {Scheme Procedure} delq item lst
412@deffnx {C Function} scm_delq (item, lst)
413Return a newly-created copy of @var{lst} with elements
414@code{eq?} to @var{item} removed. This procedure mirrors
415@code{memq}: @code{delq} compares elements of @var{lst} against
416@var{item} with @code{eq?}.
417@end deffn
418
419@deffn {Scheme Procedure} delv item lst
420@deffnx {C Function} scm_delv (item, lst)
421Return a newly-created copy of @var{lst} with elements
422@code{eqv?} to @var{item} removed. This procedure mirrors
423@code{memv}: @code{delv} compares elements of @var{lst} against
424@var{item} with @code{eqv?}.
425@end deffn
426
427@deffn {Scheme Procedure} delete item lst
428@deffnx {C Function} scm_delete (item, lst)
429Return a newly-created copy of @var{lst} with elements
430@code{equal?} to @var{item} removed. This procedure mirrors
431@code{member}: @code{delete} compares elements of @var{lst}
432against @var{item} with @code{equal?}.
433@end deffn
434
435@deffn {Scheme Procedure} delq! item lst
436@deffnx {Scheme Procedure} delv! item lst
437@deffnx {Scheme Procedure} delete! item lst
438@deffnx {C Function} scm_delq_x (item, lst)
439@deffnx {C Function} scm_delv_x (item, lst)
440@deffnx {C Function} scm_delete_x (item, lst)
441These procedures are destructive versions of @code{delq}, @code{delv}
442and @code{delete}: they modify the pointers in the existing @var{lst}
443rather than creating a new list. Caveat evaluator: Like other
444destructive list functions, these functions cannot modify the binding of
445@var{lst}, and so cannot be used to delete the first element of
446@var{lst} destructively.
447@end deffn
448
449@deffn {Scheme Procedure} delq1! item lst
450@deffnx {C Function} scm_delq1_x (item, lst)
451Like @code{delq!}, but only deletes the first occurrence of
452@var{item} from @var{lst}. Tests for equality using
453@code{eq?}. See also @code{delv1!} and @code{delete1!}.
454@end deffn
455
456@deffn {Scheme Procedure} delv1! item lst
457@deffnx {C Function} scm_delv1_x (item, lst)
458Like @code{delv!}, but only deletes the first occurrence of
459@var{item} from @var{lst}. Tests for equality using
460@code{eqv?}. See also @code{delq1!} and @code{delete1!}.
461@end deffn
462
463@deffn {Scheme Procedure} delete1! item lst
464@deffnx {C Function} scm_delete1_x (item, lst)
465Like @code{delete!}, but only deletes the first occurrence of
466@var{item} from @var{lst}. Tests for equality using
467@code{equal?}. See also @code{delq1!} and @code{delv1!}.
468@end deffn
469
60e25dc4
KR
470@deffn {Scheme Procedure} filter pred lst
471@deffnx {Scheme Procedure} filter! pred lst
472Return a list containing all elements from @var{lst} which satisfy the
473predicate @var{pred}. The elements in the result list have the same
474order as in @var{lst}. The order in which @var{pred} is applied to
475the list elements is not specified.
476
477@code{filter!} is allowed, but not required to modify the structure of
478@end deffn
479
4c731ece
NJ
480@node List Searching
481@subsection List Searching
482
4c731ece
NJ
483The following procedures search lists for particular elements. They use
484different comparison predicates for comparing list elements with the
485object to be searched. When they fail, they return @code{#f}, otherwise
486they return the sublist whose car is equal to the search object, where
487equality depends on the equality predicate used.
488
489@rnindex memq
490@deffn {Scheme Procedure} memq x lst
491@deffnx {C Function} scm_memq (x, lst)
492Return the first sublist of @var{lst} whose car is @code{eq?}
493to @var{x} where the sublists of @var{lst} are the non-empty
494lists returned by @code{(list-tail @var{lst} @var{k})} for
495@var{k} less than the length of @var{lst}. If @var{x} does not
496occur in @var{lst}, then @code{#f} (not the empty list) is
497returned.
498@end deffn
499
500@rnindex memv
501@deffn {Scheme Procedure} memv x lst
502@deffnx {C Function} scm_memv (x, lst)
503Return the first sublist of @var{lst} whose car is @code{eqv?}
504to @var{x} where the sublists of @var{lst} are the non-empty
505lists returned by @code{(list-tail @var{lst} @var{k})} for
506@var{k} less than the length of @var{lst}. If @var{x} does not
507occur in @var{lst}, then @code{#f} (not the empty list) is
508returned.
509@end deffn
510
511@rnindex member
512@deffn {Scheme Procedure} member x lst
513@deffnx {C Function} scm_member (x, lst)
514Return the first sublist of @var{lst} whose car is
515@code{equal?} to @var{x} where the sublists of @var{lst} are
516the non-empty lists returned by @code{(list-tail @var{lst}
517@var{k})} for @var{k} less than the length of @var{lst}. If
518@var{x} does not occur in @var{lst}, then @code{#f} (not the
519empty list) is returned.
520@end deffn
521
4c731ece
NJ
522
523@node List Mapping
524@subsection List Mapping
525
4c731ece
NJ
526List processing is very convenient in Scheme because the process of
527iterating over the elements of a list can be highly abstracted. The
528procedures in this section are the most basic iterating procedures for
529lists. They take a procedure and one or more lists as arguments, and
530apply the procedure to each element of the list. They differ in their
531return value.
532
533@rnindex map
534@c begin (texi-doc-string "guile" "map")
535@deffn {Scheme Procedure} map proc arg1 arg2 @dots{}
536@deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{}
537@deffnx {C Function} scm_map (proc, arg1, args)
538Apply @var{proc} to each element of the list @var{arg1} (if only two
539arguments are given), or to the corresponding elements of the argument
540lists (if more than two arguments are given). The result(s) of the
541procedure applications are saved and returned in a list. For
542@code{map}, the order of procedure applications is not specified,
543@code{map-in-order} applies the procedure from left to right to the list
544elements.
545@end deffn
546
547@rnindex for-each
548@c begin (texi-doc-string "guile" "for-each")
549@deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{}
550Like @code{map}, but the procedure is always applied from left to right,
551and the result(s) of the procedure applications are thrown away. The
552return value is not specified.
553@end deffn
554
555
556@node Vectors
557@section Vectors
558@tpindex Vectors
559
4c731ece
NJ
560Vectors are sequences of Scheme objects. Unlike lists, the length of a
561vector, once the vector is created, cannot be changed. The advantage of
562vectors over lists is that the time required to access one element of a vector
563given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number,
564is constant, whereas lists have an access time linear to the position of the
565accessed element in the list.
566
567Vectors can contain any kind of Scheme object; it is even possible to have
568different types of objects in the same vector. For vectors containing
569vectors, you may wish to use arrays, instead. Note, too, that some array
570procedures operate happily on vectors (@pxref{Arrays}).
571
0624ce33
NJ
572@menu
573* Vector Syntax:: Read syntax for vectors.
574* Vector Creation:: Dynamic vector creation and validation.
575* Vector Accessors:: Accessing and modifying vector contents.
576@end menu
577
578
579@node Vector Syntax
580@subsection Read Syntax for Vectors
4c731ece
NJ
581
582Vectors can literally be entered in source code, just like strings,
583characters or some of the other data types. The read syntax for vectors
584is as follows: A sharp sign (@code{#}), followed by an opening
585parentheses, all elements of the vector in their respective read syntax,
586and finally a closing parentheses. The following are examples of the
587read syntax for vectors; where the first vector only contains numbers
588and the second three different object types: a string, a symbol and a
589number in hexadecimal notation.
590
591@lisp
592#(1 2 3)
593#("Hello" foo #xdeadbeef)
594@end lisp
595
42ad901d
DH
596Like lists, vectors have to be quoted (REFFIXME):
597
598@lisp
599'#(a b c) @result{} #(a b c)
600@end lisp
4c731ece 601
0624ce33
NJ
602@node Vector Creation
603@subsection Dynamic Vector Creation and Validation
4c731ece 604
0624ce33
NJ
605Instead of creating a vector implicitly by using the read syntax just
606described, you can create a vector dynamically by calling one of the
607@code{vector} and @code{list->vector} primitives with the list of Scheme
608values that you want to place into a vector. The size of the vector
609thus created is determined implicitly by the number of arguments given.
4c731ece
NJ
610
611@rnindex vector
612@rnindex list->vector
613@deffn {Scheme Procedure} vector . l
614@deffnx {Scheme Procedure} list->vector l
615@deffnx {C Function} scm_vector (l)
616Return a newly allocated vector composed of the
617given arguments. Analogous to @code{list}.
618
619@lisp
620(vector 'a 'b 'c) @result{} #(a b c)
621@end lisp
622@end deffn
623
0624ce33
NJ
624(As an aside, an interesting implementation detail is that the Guile
625reader reads the @code{#(@dots{})} syntax by reading everything but the
626initial @code{#} as a @emph{list}, and then passing the list that
627results to @code{list->vector}. Notice how neatly this fits with the
628similarity between the read (and print) syntaxes for lists and vectors.)
629
630The inverse operation is @code{vector->list}:
631
4c731ece
NJ
632@rnindex vector->list
633@deffn {Scheme Procedure} vector->list v
634@deffnx {C Function} scm_vector_to_list (v)
635Return a newly allocated list composed of the elements of @var{v}.
636
637@lisp
638(vector->list '#(dah dah didah)) @result{} (dah dah didah)
639(list->vector '(dididit dah)) @result{} #(dididit dah)
640@end lisp
641@end deffn
642
0624ce33
NJ
643To allocate a vector with an explicitly specified size, use
644@code{make-vector}. With this primitive you can also specify an initial
645value for the vector elements (the same value for all elements, that
646is):
647
648@rnindex make-vector
649@deffn {Scheme Procedure} make-vector k [fill]
650@deffnx {C Function} scm_make_vector (k, fill)
651Return a newly allocated vector of @var{k} elements. If a
652second argument is given, then each position is initialized to
653@var{fill}. Otherwise the initial contents of each position is
654unspecified.
655@end deffn
656
657To check whether an arbitrary Scheme value @emph{is} a vector, use the
658@code{vector?} primitive:
659
660@rnindex vector?
661@deffn {Scheme Procedure} vector? obj
662@deffnx {C Function} scm_vector_p (obj)
663Return @code{#t} if @var{obj} is a vector, otherwise return
664@code{#f}.
665@end deffn
666
667
668@node Vector Accessors
669@subsection Accessing and Modifying Vector Contents
4c731ece 670
0624ce33
NJ
671@code{vector-length} and @code{vector-ref} return information about a
672given vector, respectively its size and the elements that are contained
673in the vector.
4c731ece 674
0624ce33
NJ
675@rnindex vector-length
676@deffn {Scheme Procedure} vector-length vector
677@deffnx {C Function} scm_vector_length vector
678Return the number of elements in @var{vector} as an exact integer.
679@end deffn
680
681@rnindex vector-ref
682@deffn {Scheme Procedure} vector-ref vector k
683@deffnx {C Function} scm_vector_ref vector k
684Return the contents of position @var{k} of @var{vector}.
685@var{k} must be a valid index of @var{vector}.
686@lisp
687(vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8
688(vector-ref '#(1 1 2 3 5 8 13 21)
689 (let ((i (round (* 2 (acos -1)))))
690 (if (inexact? i)
691 (inexact->exact i)
692 i))) @result{} 13
693@end lisp
694@end deffn
695
696A vector created by one of the dynamic vector constructor procedures
697(@pxref{Vector Creation}) can be modified using the following
698procedures.
699
700@emph{NOTE:} According to R5RS, it is an error to use any of these
701procedures on a literally read vector, because such vectors should be
702considered as constants. Currently, however, Guile does not detect this
4c731ece
NJ
703error.
704
705@rnindex vector-set!
706@deffn {Scheme Procedure} vector-set! vector k obj
0624ce33 707@deffnx {C Function} scm_vector_set_x vector k obj
4c731ece
NJ
708Store @var{obj} in position @var{k} of @var{vector}.
709@var{k} must be a valid index of @var{vector}.
710The value returned by @samp{vector-set!} is unspecified.
711@lisp
712(let ((vec (vector 0 '(2 2 2 2) "Anna")))
713 (vector-set! vec 1 '("Sue" "Sue"))
714 vec) @result{} #(0 ("Sue" "Sue") "Anna")
715@end lisp
716@end deffn
717
718@rnindex vector-fill!
719@deffn {Scheme Procedure} vector-fill! v fill
720@deffnx {C Function} scm_vector_fill_x (v, fill)
721Store @var{fill} in every position of @var{vector}. The value
722returned by @code{vector-fill!} is unspecified.
723@end deffn
724
725@deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2
726@deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2)
727Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
728to @var{vec2} starting at position @var{start2}. @var{start1} and
729@var{start2} are inclusive indices; @var{end1} is exclusive.
730
731@code{vector-move-left!} copies elements in leftmost order.
732Therefore, in the case where @var{vec1} and @var{vec2} refer to the
733same vector, @code{vector-move-left!} is usually appropriate when
734@var{start1} is greater than @var{start2}.
735@end deffn
736
737@deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2
738@deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2)
739Copy elements from @var{vec1}, positions @var{start1} to @var{end1},
740to @var{vec2} starting at position @var{start2}. @var{start1} and
741@var{start2} are inclusive indices; @var{end1} is exclusive.
742
743@code{vector-move-right!} copies elements in rightmost order.
744Therefore, in the case where @var{vec1} and @var{vec2} refer to the
745same vector, @code{vector-move-right!} is usually appropriate when
746@var{start1} is less than @var{start2}.
747@end deffn
748
4c731ece
NJ
749
750@node Records
751@section Records
752
753A @dfn{record type} is a first class object representing a user-defined
754data type. A @dfn{record} is an instance of a record type.
755
756@deffn {Scheme Procedure} record? obj
757Return @code{#t} if @var{obj} is a record of any type and @code{#f}
758otherwise.
759
760Note that @code{record?} may be true of any Scheme value; there is no
761promise that records are disjoint with other Scheme types.
762@end deffn
763
764@deffn {Scheme Procedure} make-record-type type-name field-names
765Return a @dfn{record-type descriptor}, a value representing a new data
766type disjoint from all others. The @var{type-name} argument must be a
767string, but is only used for debugging purposes (such as the printed
768representation of a record of the new type). The @var{field-names}
769argument is a list of symbols naming the @dfn{fields} of a record of the
770new type. It is an error if the list contains any duplicates. It is
771unspecified how record-type descriptors are represented.
772@end deffn
773
774@deffn {Scheme Procedure} record-constructor rtd [field-names]
775Return a procedure for constructing new members of the type represented
776by @var{rtd}. The returned procedure accepts exactly as many arguments
777as there are symbols in the given list, @var{field-names}; these are
778used, in order, as the initial values of those fields in a new record,
779which is returned by the constructor procedure. The values of any
780fields not named in that list are unspecified. The @var{field-names}
781argument defaults to the list of field names in the call to
782@code{make-record-type} that created the type represented by @var{rtd};
783if the @var{field-names} argument is provided, it is an error if it
784contains any duplicates or any symbols not in the default list.
785@end deffn
786
787@deffn {Scheme Procedure} record-predicate rtd
788Return a procedure for testing membership in the type represented by
789@var{rtd}. The returned procedure accepts exactly one argument and
790returns a true value if the argument is a member of the indicated record
791type; it returns a false value otherwise.
792@end deffn
793
794@deffn {Scheme Procedure} record-accessor rtd field-name
795Return a procedure for reading the value of a particular field of a
796member of the type represented by @var{rtd}. The returned procedure
797accepts exactly one argument which must be a record of the appropriate
798type; it returns the current value of the field named by the symbol
799@var{field-name} in that record. The symbol @var{field-name} must be a
800member of the list of field-names in the call to @code{make-record-type}
801that created the type represented by @var{rtd}.
802@end deffn
803
804@deffn {Scheme Procedure} record-modifier rtd field-name
805Return a procedure for writing the value of a particular field of a
806member of the type represented by @var{rtd}. The returned procedure
807accepts exactly two arguments: first, a record of the appropriate type,
808and second, an arbitrary Scheme value; it modifies the field named by
809the symbol @var{field-name} in that record to contain the given value.
810The returned value of the modifier procedure is unspecified. The symbol
811@var{field-name} must be a member of the list of field-names in the call
812to @code{make-record-type} that created the type represented by
813@var{rtd}.
814@end deffn
815
816@deffn {Scheme Procedure} record-type-descriptor record
817Return a record-type descriptor representing the type of the given
818record. That is, for example, if the returned descriptor were passed to
819@code{record-predicate}, the resulting predicate would return a true
820value when passed the given record. Note that it is not necessarily the
821case that the returned descriptor is the one that was passed to
822@code{record-constructor} in the call that created the constructor
823procedure that created the given record.
824@end deffn
825
826@deffn {Scheme Procedure} record-type-name rtd
827Return the type-name associated with the type represented by rtd. The
828returned value is @code{eqv?} to the @var{type-name} argument given in
829the call to @code{make-record-type} that created the type represented by
830@var{rtd}.
831@end deffn
832
833@deffn {Scheme Procedure} record-type-fields rtd
834Return a list of the symbols naming the fields in members of the type
835represented by @var{rtd}. The returned value is @code{equal?} to the
836field-names argument given in the call to @code{make-record-type} that
837created the type represented by @var{rtd}.
838@end deffn
839
840
841@node Structures
842@section Structures
843@tpindex Structures
844
845[FIXME: this is pasted in from Tom Lord's original guile.texi and should
846be reviewed]
847
848A @dfn{structure type} is a first class user-defined data type. A
849@dfn{structure} is an instance of a structure type. A structure type is
850itself a structure.
851
852Structures are less abstract and more general than traditional records.
853In fact, in Guile Scheme, records are implemented using structures.
854
855@menu
856* Structure Concepts:: The structure of Structures
857* Structure Layout:: Defining the layout of structure types
858* Structure Basics:: make-, -ref and -set! procedures for structs
859* Vtables:: Accessing type-specific data
860@end menu
861
862@node Structure Concepts
863@subsection Structure Concepts
864
865A structure object consists of a handle, structure data, and a vtable.
866The handle is a Scheme value which points to both the vtable and the
867structure's data. Structure data is a dynamically allocated region of
868memory, private to the structure, divided up into typed fields. A
869vtable is another structure used to hold type-specific data. Multiple
870structures can share a common vtable.
871
872Three concepts are key to understanding structures.
873
874@itemize @bullet{}
875@item @dfn{layout specifications}
876
877Layout specifications determine how memory allocated to structures is
878divided up into fields. Programmers must write a layout specification
879whenever a new type of structure is defined.
880
881@item @dfn{structural accessors}
882
883Structure access is by field number. There is only one set of
884accessors common to all structure objects.
885
886@item @dfn{vtables}
887
888Vtables, themselves structures, are first class representations of
889disjoint sub-types of structures in general. In most cases, when a
85a9b4ed 890new structure is created, programmers must specify a vtable for the
4c731ece
NJ
891new structure. Each vtable has a field describing the layout of its
892instances. Vtables can have additional, user-defined fields as well.
893@end itemize
894
895
896
897@node Structure Layout
898@subsection Structure Layout
899
900When a structure is created, a region of memory is allocated to hold its
901state. The @dfn{layout} of the structure's type determines how that
902memory is divided into fields.
903
904Each field has a specified type. There are only three types allowed, each
905corresponding to a one letter code. The allowed types are:
906
907@itemize @bullet{}
908@item 'u' -- unprotected
909
910The field holds binary data that is not GC protected.
911
912@item 'p' -- protected
913
914The field holds a Scheme value and is GC protected.
915
916@item 's' -- self
917
918The field holds a Scheme value and is GC protected. When a structure is
919created with this type of field, the field is initialized to refer to
920the structure's own handle. This kind of field is mainly useful when
921mixing Scheme and C code in which the C code may need to compute a
801892e7 922structure's handle given only the address of its malloc'd data.
4c731ece
NJ
923@end itemize
924
925
926Each field also has an associated access protection. There are only
927three kinds of protection, each corresponding to a one letter code.
928The allowed protections are:
929
930@itemize @bullet{}
931@item 'w' -- writable
932
933The field can be read and written.
934
935@item 'r' -- readable
936
937The field can be read, but not written.
938
939@item 'o' -- opaque
940
941The field can be neither read nor written. This kind
942of protection is for fields useful only to built-in routines.
943@end itemize
944
945A layout specification is described by stringing together pairs
946of letters: one to specify a field type and one to specify a field
947protection. For example, a traditional cons pair type object could
948be described as:
949
950@example
951; cons pairs have two writable fields of Scheme data
952"pwpw"
953@end example
954
955A pair object in which the first field is held constant could be:
956
957@example
958"prpw"
959@end example
960
961Binary fields, (fields of type "u"), hold one @dfn{word} each. The
962size of a word is a machine dependent value defined to be equal to the
963value of the C expression: @code{sizeof (long)}.
964
965The last field of a structure layout may specify a tail array.
966A tail array is indicated by capitalizing the field's protection
967code ('W', 'R' or 'O'). A tail-array field is replaced by
968a read-only binary data field containing an array size. The array
969size is determined at the time the structure is created. It is followed
970by a corresponding number of fields of the type specified for the
971tail array. For example, a conventional Scheme vector can be
972described as:
973
974@example
975; A vector is an arbitrary number of writable fields holding Scheme
976; values:
977"pW"
978@end example
979
980In the above example, field 0 contains the size of the vector and
981fields beginning at 1 contain the vector elements.
982
85a9b4ed 983A kind of tagged vector (a constant tag followed by conventional
4c731ece
NJ
984vector elements) might be:
985
986@example
987"prpW"
988@end example
989
990
991Structure layouts are represented by specially interned symbols whose
992name is a string of type and protection codes. To create a new
993structure layout, use this procedure:
994
995@deffn {Scheme Procedure} make-struct-layout fields
996@deffnx {C Function} scm_make_struct_layout (fields)
997Return a new structure layout object.
998
999@var{fields} must be a string made up of pairs of characters
1000strung together. The first character of each pair describes a field
1001type, the second a field protection. Allowed types are 'p' for
1002GC-protected Scheme data, 'u' for unprotected binary data, and 's' for
1003a field that points to the structure itself. Allowed protections
1004are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque
1005fields. The last field protection specification may be capitalized to
1006indicate that the field is a tail-array.
1007@end deffn
1008
1009
1010
1011@node Structure Basics
1012@subsection Structure Basics
1013
1014This section describes the basic procedures for creating and accessing
1015structures.
1016
1017@deffn {Scheme Procedure} make-struct vtable tail_array_size . init
1018@deffnx {C Function} scm_make_struct (vtable, tail_array_size, init)
1019Create a new structure.
1020
1021@var{type} must be a vtable structure (@pxref{Vtables}).
1022
1023@var{tail-elts} must be a non-negative integer. If the layout
1024specification indicated by @var{type} includes a tail-array,
1025this is the number of elements allocated to that array.
1026
1027The @var{init1}, @dots{} are optional arguments describing how
1028successive fields of the structure should be initialized. Only fields
1029with protection 'r' or 'w' can be initialized, except for fields of
1030type 's', which are automatically initialized to point to the new
1031structure itself; fields with protection 'o' can not be initialized by
1032Scheme programs.
1033
1034If fewer optional arguments than initializable fields are supplied,
1035fields of type 'p' get default value #f while fields of type 'u' are
1036initialized to 0.
1037
1038Structs are currently the basic representation for record-like data
1039structures in Guile. The plan is to eventually replace them with a
1040new representation which will at the same time be easier to use and
1041more powerful.
1042
1043For more information, see the documentation for @code{make-vtable-vtable}.
1044@end deffn
1045
1046@deffn {Scheme Procedure} struct? x
1047@deffnx {C Function} scm_struct_p (x)
1048Return @code{#t} iff @var{x} is a structure object, else
1049@code{#f}.
1050@end deffn
1051
1052
1053@deffn {Scheme Procedure} struct-ref handle pos
1054@deffnx {Scheme Procedure} struct-set! struct n value
1055@deffnx {C Function} scm_struct_ref (handle, pos)
1056@deffnx {C Function} scm_struct_set_x (struct, n, value)
1057Access (or modify) the @var{n}th field of @var{struct}.
1058
1059If the field is of type 'p', then it can be set to an arbitrary value.
1060
1061If the field is of type 'u', then it can only be set to a non-negative
1062integer value small enough to fit in one machine word.
1063@end deffn
1064
1065
1066
1067@node Vtables
1068@subsection Vtables
1069
1070Vtables are structures that are used to represent structure types. Each
1071vtable contains a layout specification in field
1072@code{vtable-index-layout} -- instances of the type are laid out
1073according to that specification. Vtables contain additional fields
1074which are used only internally to libguile. The variable
1075@code{vtable-offset-user} is bound to a field number. Vtable fields
1076at that position or greater are user definable.
1077
1078@deffn {Scheme Procedure} struct-vtable handle
1079@deffnx {C Function} scm_struct_vtable (handle)
1080Return the vtable structure that describes the type of @var{struct}.
1081@end deffn
1082
1083@deffn {Scheme Procedure} struct-vtable? x
1084@deffnx {C Function} scm_struct_vtable_p (x)
1085Return @code{#t} iff @var{x} is a vtable structure.
1086@end deffn
1087
1088If you have a vtable structure, @code{V}, you can create an instance of
1089the type it describes by using @code{(make-struct V ...)}. But where
1090does @code{V} itself come from? One possibility is that @code{V} is an
1091instance of a user-defined vtable type, @code{V'}, so that @code{V} is
1092created by using @code{(make-struct V' ...)}. Another possibility is
1093that @code{V} is an instance of the type it itself describes. Vtable
1094structures of the second sort are created by this procedure:
1095
1096@deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init
1097@deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init)
1098Return a new, self-describing vtable structure.
1099
1100@var{user-fields} is a string describing user defined fields of the
1101vtable beginning at index @code{vtable-offset-user}
1102(see @code{make-struct-layout}).
1103
1104@var{tail-size} specifies the size of the tail-array (if any) of
1105this vtable.
1106
1107@var{init1}, @dots{} are the optional initializers for the fields of
1108the vtable.
1109
1110Vtables have one initializable system field---the struct printer.
1111This field comes before the user fields in the initializers passed
1112to @code{make-vtable-vtable} and @code{make-struct}, and thus works as
1113a third optional argument to @code{make-vtable-vtable} and a fourth to
1114@code{make-struct} when creating vtables:
1115
1116If the value is a procedure, it will be called instead of the standard
1117printer whenever a struct described by this vtable is printed.
1118The procedure will be called with arguments STRUCT and PORT.
1119
1120The structure of a struct is described by a vtable, so the vtable is
1121in essence the type of the struct. The vtable is itself a struct with
1122a vtable. This could go on forever if it weren't for the
1123vtable-vtables which are self-describing vtables, and thus terminate
1124the chain.
1125
1126There are several potential ways of using structs, but the standard
1127one is to use three kinds of structs, together building up a type
1128sub-system: one vtable-vtable working as the root and one or several
1129"types", each with a set of "instances". (The vtable-vtable should be
1130compared to the class <class> which is the class of itself.)
1131
1132@lisp
1133(define ball-root (make-vtable-vtable "pr" 0))
1134
1135(define (make-ball-type ball-color)
1136 (make-struct ball-root 0
1137 (make-struct-layout "pw")
1138 (lambda (ball port)
1139 (format port "#<a ~A ball owned by ~A>"
1140 (color ball)
1141 (owner ball)))
1142 ball-color))
1143(define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user))
1144(define (owner ball) (struct-ref ball 0))
1145
1146(define red (make-ball-type 'red))
1147(define green (make-ball-type 'green))
1148
1149(define (make-ball type owner) (make-struct type 0 owner))
1150
1151(define ball (make-ball green 'Nisse))
1152ball @result{} #<a green ball owned by Nisse>
1153@end lisp
1154@end deffn
1155
1156@deffn {Scheme Procedure} struct-vtable-name vtable
1157@deffnx {C Function} scm_struct_vtable_name (vtable)
1158Return the name of the vtable @var{vtable}.
1159@end deffn
1160
1161@deffn {Scheme Procedure} set-struct-vtable-name! vtable name
1162@deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name)
1163Set the name of the vtable @var{vtable} to @var{name}.
1164@end deffn
1165
1166@deffn {Scheme Procedure} struct-vtable-tag handle
1167@deffnx {C Function} scm_struct_vtable_tag (handle)
1168Return the vtable tag of the structure @var{handle}.
1169@end deffn
1170
1171
1172@node Arrays
1173@section Arrays
1174@tpindex Arrays
1175
1176@menu
1177* Conventional Arrays:: Arrays with arbitrary data.
1178* Array Mapping:: Applying a procedure to the contents of an array.
1179* Uniform Arrays:: Arrays with data of a single type.
1180* Bit Vectors:: Vectors of bits.
1181@end menu
1182
1183@node Conventional Arrays
1184@subsection Conventional Arrays
1185
1186@dfn{Conventional arrays} are a collection of cells organized into an
1187arbitrary number of dimensions. Each cell can hold any kind of Scheme
1188value and can be accessed in constant time by supplying an index for
1189each dimension. This contrasts with uniform arrays, which use memory
1190more efficiently but can hold data of only a single type, and lists
1191where inserting and deleting cells is more efficient, but more time
1192is usually required to access a particular cell.
1193
1194A conventional array is displayed as @code{#} followed by the @dfn{rank}
1195(number of dimensions) followed by the cells, organized into dimensions
1196using parentheses. The nesting depth of the parentheses is equal to
1197the rank.
1198
1199When an array is created, the number of dimensions and range of each
1200dimension must be specified, e.g., to create a 2x3 array with a
1201zero-based index:
1202
1203@example
1204(make-array 'ho 2 3) @result{}
1205#2((ho ho ho) (ho ho ho))
1206@end example
1207
1208The range of each dimension can also be given explicitly, e.g., another
1209way to create the same array:
1210
1211@example
1212(make-array 'ho '(0 1) '(0 2)) @result{}
1213#2((ho ho ho) (ho ho ho))
1214@end example
1215
1216A conventional array with one dimension based at zero is identical to
1217a vector:
1218
1219@example
1220(make-array 'ho 3) @result{}
1221#(ho ho ho)
1222@end example
1223
1224The following procedures can be used with conventional arrays (or vectors).
1225
1226@deffn {Scheme Procedure} array? v [prot]
1227@deffnx {C Function} scm_array_p (v, prot)
1228Return @code{#t} if the @var{obj} is an array, and @code{#f} if
1229not. The @var{prototype} argument is used with uniform arrays
1230and is described elsewhere.
1231@end deffn
1232
1233@deffn {Scheme Procedure} make-array initial-value bound1 bound2 @dots{}
1234Create and return an array that has as many dimensions as there are
1235@var{bound}s and fill it with @var{initial-value}. Each @var{bound}
1236may be a positive non-zero integer @var{N}, in which case the index for
1237that dimension can range from 0 through @var{N-1}; or an explicit index
1238range specifier in the form @code{(LOWER UPPER)}, where both @var{lower}
1239and @var{upper} are integers, possibly less than zero, and possibly the
1240same number (however, @var{lower} cannot be greater than @var{upper}).
1241@end deffn
1242
1243@c array-ref's type is `compiled-closure'. There's some weird stuff
1244@c going on in array.c, too. Let's call it a primitive. -twp
1245
1246@deffn {Scheme Procedure} uniform-vector-ref v args
1247@deffnx {Scheme Procedure} array-ref v . args
1248@deffnx {C Function} scm_uniform_vector_ref (v, args)
1249Return the element at the @code{(index1, index2)} element in
1250@var{array}.
1251@end deffn
1252
1253@deffn {Scheme Procedure} array-in-bounds? v . args
1254@deffnx {C Function} scm_array_in_bounds_p (v, args)
1255Return @code{#t} if its arguments would be acceptable to
1256@code{array-ref}.
1257@end deffn
1258
1259@c fixme: why do these sigs differ? -ttn 2001/07/19 01:14:12
1260@deffn {Scheme Procedure} array-set! v obj . args
1261@deffnx {Scheme Procedure} uniform-array-set1! v obj args
1262@deffnx {C Function} scm_array_set_x (v, obj, args)
1263Set the element at the @code{(index1, index2)} element in @var{array} to
1264@var{new-value}. The value returned by array-set! is unspecified.
1265@end deffn
1266
1267@deffn {Scheme Procedure} make-shared-array oldra mapfunc . dims
1268@deffnx {C Function} scm_make_shared_array (oldra, mapfunc, dims)
1269@code{make-shared-array} can be used to create shared subarrays of other
1270arrays. The @var{mapper} is a function that translates coordinates in
1271the new array into coordinates in the old array. A @var{mapper} must be
1272linear, and its range must stay within the bounds of the old array, but
1273it can be otherwise arbitrary. A simple example:
1274@lisp
1275(define fred (make-array #f 8 8))
1276(define freds-diagonal
1277 (make-shared-array fred (lambda (i) (list i i)) 8))
1278(array-set! freds-diagonal 'foo 3)
1279(array-ref fred 3 3) @result{} foo
1280(define freds-center
1281 (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2))
1282(array-ref freds-center 0 0) @result{} foo
1283@end lisp
1284@end deffn
1285
1286@deffn {Scheme Procedure} shared-array-increments ra
1287@deffnx {C Function} scm_shared_array_increments (ra)
1288For each dimension, return the distance between elements in the root vector.
1289@end deffn
1290
1291@deffn {Scheme Procedure} shared-array-offset ra
1292@deffnx {C Function} scm_shared_array_offset (ra)
1293Return the root vector index of the first element in the array.
1294@end deffn
1295
1296@deffn {Scheme Procedure} shared-array-root ra
1297@deffnx {C Function} scm_shared_array_root (ra)
1298Return the root vector of a shared array.
1299@end deffn
1300
1301@deffn {Scheme Procedure} transpose-array ra . args
1302@deffnx {C Function} scm_transpose_array (ra, args)
1303Return an array sharing contents with @var{array}, but with
1304dimensions arranged in a different order. There must be one
1305@var{dim} argument for each dimension of @var{array}.
1306@var{dim0}, @var{dim1}, @dots{} should be integers between 0
1307and the rank of the array to be returned. Each integer in that
1308range must appear at least once in the argument list.
1309
1310The values of @var{dim0}, @var{dim1}, @dots{} correspond to
1311dimensions in the array to be returned, their positions in the
1312argument list to dimensions of @var{array}. Several @var{dim}s
1313may have the same value, in which case the returned array will
1314have smaller rank than @var{array}.
1315
1316@lisp
1317(transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d))
1318(transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d)
1319(transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{}
1320 #2((a 4) (b 5) (c 6))
1321@end lisp
1322@end deffn
1323
1324@deffn {Scheme Procedure} enclose-array ra . axes
1325@deffnx {C Function} scm_enclose_array (ra, axes)
1326@var{dim0}, @var{dim1} @dots{} should be nonnegative integers less than
1327the rank of @var{array}. @var{enclose-array} returns an array
1328resembling an array of shared arrays. The dimensions of each shared
1329array are the same as the @var{dim}th dimensions of the original array,
1330the dimensions of the outer array are the same as those of the original
1331array that did not match a @var{dim}.
1332
1333An enclosed array is not a general Scheme array. Its elements may not
1334be set using @code{array-set!}. Two references to the same element of
1335an enclosed array will be @code{equal?} but will not in general be
1336@code{eq?}. The value returned by @var{array-prototype} when given an
1337enclosed array is unspecified.
1338
1339examples:
1340@lisp
1341(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) @result{}
1342 #<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))>
1343
1344(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) @result{}
1345 #<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))>
1346@end lisp
1347@end deffn
1348
1349@deffn {Scheme Procedure} array-shape array
1350Return a list of inclusive bounds of integers.
1351@example
1352(array-shape (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) (0 4))
1353@end example
1354@end deffn
1355
1356@deffn {Scheme Procedure} array-dimensions ra
1357@deffnx {C Function} scm_array_dimensions (ra)
1358@code{Array-dimensions} is similar to @code{array-shape} but replaces
1359elements with a @code{0} minimum with one greater than the maximum. So:
1360@lisp
1361(array-dimensions (make-array 'foo '(-1 3) 5)) @result{} ((-1 3) 5)
1362@end lisp
1363@end deffn
1364
1365@deffn {Scheme Procedure} array-rank ra
1366@deffnx {C Function} scm_array_rank (ra)
1367Return the number of dimensions of @var{obj}. If @var{obj} is
1368not an array, @code{0} is returned.
1369@end deffn
1370
1371@deffn {Scheme Procedure} array->list v
21b83aab 1372@deffnx {C Function} scm_array_to_list (v)
4c731ece
NJ
1373Return a list consisting of all the elements, in order, of
1374@var{array}.
1375@end deffn
1376
1377@deffn {Scheme Procedure} array-copy! src dst
1378@deffnx {Scheme Procedure} array-copy-in-order! src dst
1379@deffnx {C Function} scm_array_copy_x (src, dst)
1380Copy every element from vector or array @var{source} to the
1381corresponding element of @var{destination}. @var{destination} must have
1382the same rank as @var{source}, and be at least as large in each
1383dimension. The order is unspecified.
1384@end deffn
1385
1386@deffn {Scheme Procedure} array-fill! ra fill
1387@deffnx {C Function} scm_array_fill_x (ra, fill)
1388Store @var{fill} in every element of @var{array}. The value returned
1389is unspecified.
1390@end deffn
1391
1392@c begin (texi-doc-string "guile" "array-equal?")
1393@deffn {Scheme Procedure} array-equal? ra0 ra1
1394Return @code{#t} iff all arguments are arrays with the same shape, the
1395same type, and have corresponding elements which are either
1396@code{equal?} or @code{array-equal?}. This function differs from
1397@code{equal?} in that a one dimensional shared array may be
1398@var{array-equal?} but not @var{equal?} to a vector or uniform vector.
1399@end deffn
1400
1401@deffn {Scheme Procedure} array-contents array [strict]
1402@deffnx {C Function} scm_array_contents (array, strict)
1403If @var{array} may be @dfn{unrolled} into a one dimensional shared array
1404without changing their order (last subscript changing fastest), then
1405@code{array-contents} returns that shared array, otherwise it returns
1406@code{#f}. All arrays made by @var{make-array} and
1407@var{make-uniform-array} may be unrolled, some arrays made by
1408@var{make-shared-array} may not be.
1409
1410If the optional argument @var{strict} is provided, a shared array will
1411be returned only if its elements are stored internally contiguous in
1412memory.
1413@end deffn
1414
1415@node Array Mapping
1416@subsection Array Mapping
1417
d23496c0
KR
1418@c FIXME: array-map! accepts no source arrays at all, and in that
1419@c case makes calls "(proc)". Is that meant to be a documented
1420@c feature?
1421@c
1422@c FIXME: array-for-each doesn't say what happens if the sources have
1423@c different index ranges. The code currently iterates over the
1424@c indices of the first and expects the others to cover those. That
1425@c at least vaguely matches array-map!, but is is meant to be a
1426@c documented feature?
1427
1428@deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN
1429@deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN
1430@deffnx {C Function} scm_array_map_x (dst, proc, srclist)
1431Set each element of the @var{dst} array to values obtained from calls
1432to @var{proc}. The value returned is unspecified.
1433
1434Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})},
1435where each @var{elem} is from the corresponding @var{src} array, at
1436the @var{dst} index. @code{array-map-in-order!} makes the calls in
1437row-major order, @code{array-map!} makes them in an unspecified order.
1438
1439The @var{src} arrays must have the same number of dimensions as
1440@var{dst}, and must have a range for each dimension which covers the
1441range in @var{dst}. This ensures all @var{dst} indices are valid in
1442each @var{src}.
1443@end deffn
1444
1445@deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN
1446@deffnx {C Function} scm_array_for_each (proc, src1, srclist)
1447Apply @var{proc} to each tuple of elements of @var{src1} @dots{}
1448@var{srcN}, in row-major order. The value returned is unspecified.
1449@end deffn
1450
1451@deffn {Scheme Procedure} array-index-map! dst proc
1452@deffnx {C Function} scm_array_index_map_x (dst, proc)
1453Set each element of the @var{dst} array to values returned by calls to
1454@var{proc}. The value returned is unspecified.
1455
1456Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where
1457@var{i1}@dots{}@var{iN} is the destination index, one parameter for
1458each dimension. The order in which the calls are made is unspecified.
1459
1460For example, to create a @m{4\times4, 4x4} matrix representing a
1461cyclic group,
1462
1463@tex
1464\advance\leftskip by 2\lispnarrowing {
1465$\left(\matrix{%
14660 & 1 & 2 & 3 \cr
14671 & 2 & 3 & 0 \cr
14682 & 3 & 0 & 1 \cr
14693 & 0 & 1 & 2 \cr
1470}\right)$} \par
1471@end tex
1472@ifnottex
1473@example
1474 / 0 1 2 3 \
1475 | 1 2 3 0 |
1476 | 2 3 0 1 |
1477 \ 3 0 1 2 /
1478@end example
1479@end ifnottex
1480
1481@example
1482(define a (make-array #f 4 4))
1483(array-index-map! a (lambda (i j)
1484 (modulo (+ i j) 4)))
1485@end example
4c731ece
NJ
1486@end deffn
1487
1488@node Uniform Arrays
1489@subsection Uniform Arrays
1490@tpindex Uniform Arrays
1491
1492@noindent
1493@dfn{Uniform arrays} have elements all of the
1494same type and occupy less storage than conventional
1495arrays. Uniform arrays with a single zero-based dimension
1496are also known as @dfn{uniform vectors}. The procedures in
1497this section can also be used on conventional arrays, vectors,
1498bit-vectors and strings.
1499
1500@noindent
1501When creating a uniform array, the type of data to be stored
1502is indicated with a @var{prototype} argument. The following table
1503lists the types available and example prototypes:
1504
1505@example
1506prototype type printing character
1507
1508#t boolean (bit-vector) b
1509#\a char (string) a
1510#\nul byte (integer) y
1511's short (integer) h
15121 unsigned long (integer) u
1513-1 signed long (integer) e
1514'l signed long long (integer) l
15151.0 float (single precision) s
15161/3 double (double precision float) i
328df3e3
MD
1517[FIXME: This (1/3) no longer works due to the
1518 new support for rational numbers.]
4c731ece
NJ
15190+i complex (double precision) c
1520() conventional vector
1521@end example
1522
1523@noindent
1524Unshared uniform arrays of characters with a single zero-based dimension
1525are identical to strings:
1526
1527@example
1528(make-uniform-array #\a 3) @result{}
1529"aaa"
1530@end example
1531
1532@noindent
1533Unshared uniform arrays of booleans with a single zero-based dimension
1534are identical to @ref{Bit Vectors, bit-vectors}.
1535
1536@example
1537(make-uniform-array #t 3) @result{}
1538#*111
1539@end example
1540
1541@noindent
1542Other uniform vectors are written in a form similar to that of vectors,
1543except that a single character from the above table is put between
1544@code{#} and @code{(}. For example, a uniform vector of signed
1545long integers is displayed in the form @code{'#e(3 5 9)}.
1546
1547@deffn {Scheme Procedure} array? v [prot]
1548Return @code{#t} if the @var{obj} is an array, and @code{#f} if not.
1549
1550The @var{prototype} argument is used with uniform arrays and is described
1551elsewhere.
1552@end deffn
1553
1554@deffn {Scheme Procedure} make-uniform-array prototype bound1 bound2 @dots{}
1555Create and return a uniform array of type corresponding to
1556@var{prototype} that has as many dimensions as there are @var{bound}s
1557and fill it with @var{prototype}.
1558@end deffn
1559
1560@deffn {Scheme Procedure} array-prototype ra
1561@deffnx {C Function} scm_array_prototype (ra)
1562Return an object that would produce an array of the same type
1563as @var{array}, if used as the @var{prototype} for
1564@code{make-uniform-array}.
1565@end deffn
1566
1567@deffn {Scheme Procedure} list->uniform-array ndim prot lst
1568@deffnx {Scheme Procedure} list->uniform-vector prot lst
1569@deffnx {C Function} scm_list_to_uniform_array (ndim, prot, lst)
1570Return a uniform array of the type indicated by prototype
1571@var{prot} with elements the same as those of @var{lst}.
1572Elements must be of the appropriate type, no coercions are
1573done.
1574@end deffn
1575
1576@deffn {Scheme Procedure} uniform-vector-fill! uve fill
1577Store @var{fill} in every element of @var{uve}. The value returned is
1578unspecified.
1579@end deffn
1580
1581@deffn {Scheme Procedure} uniform-vector-length v
1582@deffnx {C Function} scm_uniform_vector_length (v)
1583Return the number of elements in @var{uve}.
1584@end deffn
1585
1586@deffn {Scheme Procedure} dimensions->uniform-array dims prot [fill]
1587@deffnx {Scheme Procedure} make-uniform-vector length prototype [fill]
1588@deffnx {C Function} scm_dimensions_to_uniform_array (dims, prot, fill)
1589Create and return a uniform array or vector of type
1590corresponding to @var{prototype} with dimensions @var{dims} or
1591length @var{length}. If @var{fill} is supplied, it's used to
1592fill the array, otherwise @var{prototype} is used.
1593@end deffn
1594
1595@c Another compiled-closure. -twp
1596
1597@deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]]
1598@deffnx {Scheme Procedure} uniform-vector-read! uve [port-or-fdes] [start] [end]
1599@deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end)
1600Attempt to read all elements of @var{ura}, in lexicographic order, as
1601binary objects from @var{port-or-fdes}.
1602If an end of file is encountered,
1603the objects up to that point are put into @var{ura}
1604(starting at the beginning) and the remainder of the array is
1605unchanged.
1606
1607The optional arguments @var{start} and @var{end} allow
1608a specified region of a vector (or linearized array) to be read,
1609leaving the remainder of the vector unchanged.
1610
1611@code{uniform-array-read!} returns the number of objects read.
1612@var{port-or-fdes} may be omitted, in which case it defaults to the value
1613returned by @code{(current-input-port)}.
1614@end deffn
1615
1616@deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]]
1617@deffnx {Scheme Procedure} uniform-vector-write uve [port-or-fdes] [start] [end]
1618@deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end)
1619Writes all elements of @var{ura} as binary objects to
1620@var{port-or-fdes}.
1621
1622The optional arguments @var{start}
1623and @var{end} allow
1624a specified region of a vector (or linearized array) to be written.
1625
1626The number of objects actually written is returned.
1627@var{port-or-fdes} may be
1628omitted, in which case it defaults to the value returned by
1629@code{(current-output-port)}.
1630@end deffn
1631
1632@node Bit Vectors
1633@subsection Bit Vectors
1634
1635@noindent
1636Bit vectors are a specific type of uniform array: an array of booleans
1637with a single zero-based index.
1638
1639@noindent
1640They are displayed as a sequence of @code{0}s and
1641@code{1}s prefixed by @code{#*}, e.g.,
1642
1643@example
1644(make-uniform-vector 8 #t #f) @result{}
1645#*00000000
4c731ece
NJ
1646@end example
1647
84bde77f
KR
1648@deffn {Scheme Procedure} bit-count bool bitvector
1649@deffnx {C Function} scm_bit_count (bool, bitvector)
1650Return a count of how many entries in @var{bitvector} are equal to
1651@var{bool}. For example,
1652
1653@example
1654(bit-count #f #*000111000) @result{} 6
1655@end example
4c731ece
NJ
1656@end deffn
1657
84bde77f
KR
1658@deffn {Scheme Procedure} bit-position bool bitvector start
1659@deffnx {C Function} scm_bit_position (bool, bitvector, start)
1660Return the index of the first occurrance of @var{bool} in
1661@var{bitvector}, starting from @var{start}. If there is no @var{bool}
1662entry between @var{start} and the end of @var{bitvector}, then return
1663@code{#f}. For example,
1664
1665@example
1666(bit-position #t #*000101 0) @result{} 3
1667(bit-position #f #*0001111 3) @result{} #f
1668@end example
4c731ece
NJ
1669@end deffn
1670
84bde77f
KR
1671@deffn {Scheme Procedure} bit-invert! bitvector
1672@deffnx {C Function} scm_bit_invert_x (bitvector)
1673Modify @var{bitvector} by replacing each element with its negation.
4c731ece
NJ
1674@end deffn
1675
84bde77f
KR
1676@deffn {Scheme Procedure} bit-set*! bitvector uvec bool
1677@deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool)
1678Set entries of @var{bitvector} to @var{bool}, with @var{uvec}
1679selecting the entries to change.
1680
1681If @var{uvec} is a bit vector, then those entries where it has
1682@code{#t} are the ones in @var{bitvector} which are set to @var{bool}.
1683When @var{bool} is @code{#t} it's like @var{uvec} is OR'ed into
1684@var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an
1685ANDNOT.
1686
1687@example
1688(define bv #*01000010)
1689(bit-set*! bv #*10010001 #t)
1690bv
1691@result{} #*11010011
1692@end example
4c731ece 1693
84bde77f
KR
1694If @var{uvec} is a uniform vector of unsigned long integers, then
1695they're indexes into @var{bitvector} which are set to @var{bool}.
1696
1697@example
1698(define bv #*01000010)
1699(bit-set*! bv #u(5 2 7) #t)
1700bv
1701@result{} #*01100111
1702@end example
4c731ece
NJ
1703@end deffn
1704
84bde77f
KR
1705@deffn {Scheme Procedure} bit-count* bitvector uvec bool
1706@deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool)
1707Return a count of how many entries in @var{bitvector} are equal to
1708@var{bool}, with @var{uvec} selecting the entries to consider.
1709
1710@var{uvec} is interpreted in the same way as for @code{bit-set*!}
1711above. Namely, if @var{uvec} is a bit vector then entries which have
1712@code{#t} there are considered in @var{bitvector}. Or if @var{uvec}
1713is a uniform vector of unsigned long integers then it's the indexes in
1714@var{bitvector} to consider.
1715
1716For example,
1717
1718@example
1719(bit-count* #*01110111 #*11001101 #t) @result{} 3
1720(bit-count* #*01110111 #u(7 0 4) #f) @result{} 2
1721@end example
4c731ece
NJ
1722@end deffn
1723
1724
1725@node Association Lists and Hash Tables
1726@section Association Lists and Hash Tables
1727
1728This chapter discusses dictionary objects: data structures that are
1729useful for organizing and indexing large bodies of information.
1730
1731@menu
1732* Dictionary Types:: About dictionary types; what they're good for.
1733* Association Lists:: List-based dictionaries.
1734* Hash Tables:: Table-based dictionaries.
1735@end menu
1736
1737@node Dictionary Types
1738@subsection Dictionary Types
1739
1740A @dfn{dictionary} object is a data structure used to index
1741information in a user-defined way. In standard Scheme, the main
1742aggregate data types are lists and vectors. Lists are not really
1743indexed at all, and vectors are indexed only by number
1744(e.g. @code{(vector-ref foo 5)}). Often you will find it useful
1745to index your data on some other type; for example, in a library
1746catalog you might want to look up a book by the name of its
1747author. Dictionaries are used to help you organize information in
1748such a way.
1749
1750An @dfn{association list} (or @dfn{alist} for short) is a list of
1751key-value pairs. Each pair represents a single quantity or
1752object; the @code{car} of the pair is a key which is used to
1753identify the object, and the @code{cdr} is the object's value.
1754
1755A @dfn{hash table} also permits you to index objects with
1756arbitrary keys, but in a way that makes looking up any one object
1757extremely fast. A well-designed hash system makes hash table
1758lookups almost as fast as conventional array or vector references.
1759
1760Alists are popular among Lisp programmers because they use only
1761the language's primitive operations (lists, @dfn{car}, @dfn{cdr}
1762and the equality primitives). No changes to the language core are
1763necessary. Therefore, with Scheme's built-in list manipulation
1764facilities, it is very convenient to handle data stored in an
1765association list. Also, alists are highly portable and can be
1766easily implemented on even the most minimal Lisp systems.
1767
1768However, alists are inefficient, especially for storing large
1769quantities of data. Because we want Guile to be useful for large
1770software systems as well as small ones, Guile provides a rich set
1771of tools for using either association lists or hash tables.
1772
1773@node Association Lists
1774@subsection Association Lists
1775@tpindex Association Lists
1776@tpindex Alist
1777
1778@cindex Association List
1779@cindex Alist
1780@cindex Database
1781
1782An association list is a conventional data structure that is often used
1783to implement simple key-value databases. It consists of a list of
1784entries in which each entry is a pair. The @dfn{key} of each entry is
1785the @code{car} of the pair and the @dfn{value} of each entry is the
1786@code{cdr}.
1787
1788@example
1789ASSOCIATION LIST ::= '( (KEY1 . VALUE1)
1790 (KEY2 . VALUE2)
1791 (KEY3 . VALUE3)
1792 @dots{}
1793 )
1794@end example
1795
1796@noindent
1797Association lists are also known, for short, as @dfn{alists}.
1798
1799The structure of an association list is just one example of the infinite
1800number of possible structures that can be built using pairs and lists.
1801As such, the keys and values in an association list can be manipulated
1802using the general list structure procedures @code{cons}, @code{car},
1803@code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However,
1804because association lists are so useful, Guile also provides specific
1805procedures for manipulating them.
1806
1807@menu
801892e7
NJ
1808* Alist Key Equality::
1809* Adding or Setting Alist Entries::
1810* Retrieving Alist Entries::
1811* Removing Alist Entries::
1812* Sloppy Alist Functions::
1813* Alist Example::
4c731ece
NJ
1814@end menu
1815
1816@node Alist Key Equality
1817@subsubsection Alist Key Equality
1818
1819All of Guile's dedicated association list procedures, apart from
801892e7 1820@code{acons}, come in three flavours, depending on the level of equality
4c731ece
NJ
1821that is required to decide whether an existing key in the association
1822list is the same as the key that the procedure call uses to identify the
1823required entry.
1824
1825@itemize @bullet
1826@item
1827Procedures with @dfn{assq} in their name use @code{eq?} to determine key
1828equality.
1829
1830@item
1831Procedures with @dfn{assv} in their name use @code{eqv?} to determine
1832key equality.
1833
1834@item
1835Procedures with @dfn{assoc} in their name use @code{equal?} to
1836determine key equality.
1837@end itemize
1838
1839@code{acons} is an exception because it is used to build association
1840lists which do not require their entries' keys to be unique.
1841
1842@node Adding or Setting Alist Entries
1843@subsubsection Adding or Setting Alist Entries
1844
1845@code{acons} adds a new entry to an association list and returns the
1846combined association list. The combined alist is formed by consing the
1847new entry onto the head of the alist specified in the @code{acons}
1848procedure call. So the specified alist is not modified, but its
1849contents become shared with the tail of the combined alist that
1850@code{acons} returns.
1851
1852In the most common usage of @code{acons}, a variable holding the
1853original association list is updated with the combined alist:
1854
1855@example
1856(set! address-list (acons name address address-list))
1857@end example
1858
1859In such cases, it doesn't matter that the old and new values of
1860@code{address-list} share some of their contents, since the old value is
1861usually no longer independently accessible.
1862
1863Note that @code{acons} adds the specified new entry regardless of
1864whether the alist may already contain entries with keys that are, in
1865some sense, the same as that of the new entry. Thus @code{acons} is
1866ideal for building alists where there is no concept of key uniqueness.
1867
1868@example
1869(set! task-list (acons 3 "pay gas bill" '()))
1870task-list
1871@result{}
1872((3 . "pay gas bill"))
1873
1874(set! task-list (acons 3 "tidy bedroom" task-list))
1875task-list
1876@result{}
1877((3 . "tidy bedroom") (3 . "pay gas bill"))
1878@end example
1879
1880@code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add
1881or replace an entry in an association list where there @emph{is} a
1882concept of key uniqueness. If the specified association list already
1883contains an entry whose key is the same as that specified in the
1884procedure call, the existing entry is replaced by the new one.
1885Otherwise, the new entry is consed onto the head of the old association
1886list to create the combined alist. In all cases, these procedures
1887return the combined alist.
1888
1889@code{assq-set!} and friends @emph{may} destructively modify the
1890structure of the old association list in such a way that an existing
1891variable is correctly updated without having to @code{set!} it to the
1892value returned:
1893
1894@example
1895address-list
1896@result{}
1897(("mary" . "34 Elm Road") ("james" . "16 Bow Street"))
1898
1899(assoc-set! address-list "james" "1a London Road")
1900@result{}
1901(("mary" . "34 Elm Road") ("james" . "1a London Road"))
1902
1903address-list
1904@result{}
1905(("mary" . "34 Elm Road") ("james" . "1a London Road"))
1906@end example
1907
1908Or they may not:
1909
1910@example
1911(assoc-set! address-list "bob" "11 Newington Avenue")
1912@result{}
1913(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1914 ("james" . "1a London Road"))
1915
1916address-list
1917@result{}
1918(("mary" . "34 Elm Road") ("james" . "1a London Road"))
1919@end example
1920
1921The only safe way to update an association list variable when adding or
1922replacing an entry like this is to @code{set!} the variable to the
1923returned value:
1924
1925@example
1926(set! address-list
1927 (assoc-set! address-list "bob" "11 Newington Avenue"))
1928address-list
1929@result{}
1930(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
1931 ("james" . "1a London Road"))
1932@end example
1933
1934Because of this slight inconvenience, you may find it more convenient to
1935use hash tables to store dictionary data. If your application will not
1936be modifying the contents of an alist very often, this may not make much
1937difference to you.
1938
1939If you need to keep the old value of an association list in a form
1940independent from the list that results from modification by
1941@code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!},
1942use @code{list-copy} to copy the old association list before modifying
1943it.
1944
1945@deffn {Scheme Procedure} acons key value alist
1946@deffnx {C Function} scm_acons (key, value, alist)
1947Add a new key-value pair to @var{alist}. A new pair is
1948created whose car is @var{key} and whose cdr is @var{value}, and the
1949pair is consed onto @var{alist}, and the new list is returned. This
1950function is @emph{not} destructive; @var{alist} is not modified.
1951@end deffn
1952
1953@deffn {Scheme Procedure} assq-set! alist key val
1954@deffnx {Scheme Procedure} assv-set! alist key value
1955@deffnx {Scheme Procedure} assoc-set! alist key value
1956@deffnx {C Function} scm_assq_set_x (alist, key, val)
1957@deffnx {C Function} scm_assv_set_x (alist, key, val)
1958@deffnx {C Function} scm_assoc_set_x (alist, key, val)
801892e7 1959Reassociate @var{key} in @var{alist} with @var{value}: find any existing
4c731ece
NJ
1960@var{alist} entry for @var{key} and associate it with the new
1961@var{value}. If @var{alist} does not contain an entry for @var{key},
1962add a new one. Return the (possibly new) alist.
1963
1964These functions do not attempt to verify the structure of @var{alist},
1965and so may cause unusual results if passed an object that is not an
1966association list.
1967@end deffn
1968
1969@node Retrieving Alist Entries
1970@subsubsection Retrieving Alist Entries
1971@rnindex assq
1972@rnindex assv
1973@rnindex assoc
1974
1975@code{assq}, @code{assv} and @code{assoc} take an alist and a key as
1976arguments and return the entry for that key if an entry exists, or
1977@code{#f} if there is no entry for that key. Note that, in the cases
1978where an entry exists, these procedures return the complete entry, that
1979is @code{(KEY . VALUE)}, not just the value.
1980
1981@deffn {Scheme Procedure} assq key alist
1982@deffnx {Scheme Procedure} assv key alist
1983@deffnx {Scheme Procedure} assoc key alist
1984@deffnx {C Function} scm_assq (key, alist)
1985@deffnx {C Function} scm_assv (key, alist)
1986@deffnx {C Function} scm_assoc (key, alist)
1987Fetch the entry in @var{alist} that is associated with @var{key}. To
1988decide whether the argument @var{key} matches a particular entry in
1989@var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv}
1990uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key}
1991cannot be found in @var{alist} (according to whichever equality
1992predicate is in use), then return @code{#f}. These functions
1993return the entire alist entry found (i.e. both the key and the value).
1994@end deffn
1995
1996@code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other
1997hand, take an alist and a key and return @emph{just the value} for that
1998key, if an entry exists. If there is no entry for the specified key,
1999these procedures return @code{#f}.
2000
2001This creates an ambiguity: if the return value is @code{#f}, it means
2002either that there is no entry with the specified key, or that there
2003@emph{is} an entry for the specified key, with value @code{#f}.
2004Consequently, @code{assq-ref} and friends should only be used where it
2005is known that an entry exists, or where the ambiguity doesn't matter
2006for some other reason.
2007
2008@deffn {Scheme Procedure} assq-ref alist key
2009@deffnx {Scheme Procedure} assv-ref alist key
2010@deffnx {Scheme Procedure} assoc-ref alist key
2011@deffnx {C Function} scm_assq_ref (alist, key)
2012@deffnx {C Function} scm_assv_ref (alist, key)
2013@deffnx {C Function} scm_assoc_ref (alist, key)
2014Like @code{assq}, @code{assv} and @code{assoc}, except that only the
2015value associated with @var{key} in @var{alist} is returned. These
2016functions are equivalent to
2017
2018@lisp
2019(let ((ent (@var{associator} @var{key} @var{alist})))
2020 (and ent (cdr ent)))
2021@end lisp
2022
2023where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}.
2024@end deffn
2025
2026@node Removing Alist Entries
2027@subsubsection Removing Alist Entries
2028
2029To remove the element from an association list whose key matches a
2030specified key, use @code{assq-remove!}, @code{assv-remove!} or
2031@code{assoc-remove!} (depending, as usual, on the level of equality
2032required between the key that you specify and the keys in the
2033association list).
2034
2035As with @code{assq-set!} and friends, the specified alist may or may not
2036be modified destructively, and the only safe way to update a variable
2037containing the alist is to @code{set!} it to the value that
2038@code{assq-remove!} and friends return.
2039
2040@example
2041address-list
2042@result{}
2043(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road")
2044 ("james" . "1a London Road"))
2045
2046(set! address-list (assoc-remove! address-list "mary"))
2047address-list
2048@result{}
2049(("bob" . "11 Newington Avenue") ("james" . "1a London Road"))
2050@end example
2051
2052Note that, when @code{assq/v/oc-remove!} is used to modify an
2053association list that has been constructed only using the corresponding
2054@code{assq/v/oc-set!}, there can be at most one matching entry in the
2055alist, so the question of multiple entries being removed in one go does
2056not arise. If @code{assq/v/oc-remove!} is applied to an association
2057list that has been constructed using @code{acons}, or an
2058@code{assq/v/oc-set!} with a different level of equality, or any mixture
2059of these, it removes only the first matching entry from the alist, even
2060if the alist might contain further matching entries. For example:
2061
2062@example
2063(define address-list '())
2064(set! address-list (assq-set! address-list "mary" "11 Elm Street"))
2065(set! address-list (assq-set! address-list "mary" "57 Pine Drive"))
2066address-list
2067@result{}
2068(("mary" . "57 Pine Drive") ("mary" . "11 Elm Street"))
2069
2070(set! address-list (assoc-remove! address-list "mary"))
2071address-list
2072@result{}
2073(("mary" . "11 Elm Street"))
2074@end example
2075
2076In this example, the two instances of the string "mary" are not the same
2077when compared using @code{eq?}, so the two @code{assq-set!} calls add
2078two distinct entries to @code{address-list}. When compared using
2079@code{equal?}, both "mary"s in @code{address-list} are the same as the
2080"mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops
2081after removing the first matching entry that it finds, and so one of the
2082"mary" entries is left in place.
2083
2084@deffn {Scheme Procedure} assq-remove! alist key
2085@deffnx {Scheme Procedure} assv-remove! alist key
2086@deffnx {Scheme Procedure} assoc-remove! alist key
2087@deffnx {C Function} scm_assq_remove_x (alist, key)
2088@deffnx {C Function} scm_assv_remove_x (alist, key)
2089@deffnx {C Function} scm_assoc_remove_x (alist, key)
2090Delete the first entry in @var{alist} associated with @var{key}, and return
2091the resulting alist.
2092@end deffn
2093
2094@node Sloppy Alist Functions
2095@subsubsection Sloppy Alist Functions
2096
2097@code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave
2098like the corresponding non-@code{sloppy-} procedures, except that they
2099return @code{#f} when the specified association list is not well-formed,
2100where the non-@code{sloppy-} versions would signal an error.
2101
2102Specifically, there are two conditions for which the non-@code{sloppy-}
2103procedures signal an error, which the @code{sloppy-} procedures handle
2104instead by returning @code{#f}. Firstly, if the specified alist as a
2105whole is not a proper list:
2106
2107@example
2108(assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2109@result{}
2110ERROR: In procedure assoc in expression (assoc "mary" (quote #)):
2111ERROR: Wrong type argument in position 2 (expecting NULLP): "open sesame"
2112ABORT: (wrong-type-arg)
2113
2114(sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame"))
2115@result{}
2116#f
2117@end example
2118
2119@noindent
2120Secondly, if one of the entries in the specified alist is not a pair:
2121
2122@example
2123(assoc 2 '((1 . 1) 2 (3 . 9)))
2124@result{}
2125ERROR: In procedure assoc in expression (assoc 2 (quote #)):
2126ERROR: Wrong type argument in position 2 (expecting CONSP): 2
2127ABORT: (wrong-type-arg)
2128
2129(sloppy-assoc 2 '((1 . 1) 2 (3 . 9)))
2130@result{}
2131#f
2132@end example
2133
2134Unless you are explicitly working with badly formed association lists,
2135it is much safer to use the non-@code{sloppy-} procedures, because they
2136help to highlight coding and data errors that the @code{sloppy-}
2137versions would silently cover up.
2138
2139@deffn {Scheme Procedure} sloppy-assq key alist
2140@deffnx {C Function} scm_sloppy_assq (key, alist)
2141Behaves like @code{assq} but does not do any error checking.
2142Recommended only for use in Guile internals.
2143@end deffn
2144
2145@deffn {Scheme Procedure} sloppy-assv key alist
2146@deffnx {C Function} scm_sloppy_assv (key, alist)
2147Behaves like @code{assv} but does not do any error checking.
2148Recommended only for use in Guile internals.
2149@end deffn
2150
2151@deffn {Scheme Procedure} sloppy-assoc key alist
2152@deffnx {C Function} scm_sloppy_assoc (key, alist)
2153Behaves like @code{assoc} but does not do any error checking.
2154Recommended only for use in Guile internals.
2155@end deffn
2156
2157@node Alist Example
2158@subsubsection Alist Example
2159
2160Here is a longer example of how alists may be used in practice.
2161
2162@lisp
2163(define capitals '(("New York" . "Albany")
2164 ("Oregon" . "Salem")
2165 ("Florida" . "Miami")))
2166
2167;; What's the capital of Oregon?
2168(assoc "Oregon" capitals) @result{} ("Oregon" . "Salem")
2169(assoc-ref capitals "Oregon") @result{} "Salem"
2170
2171;; We left out South Dakota.
2172(set! capitals
5ad5a7b6 2173 (assoc-set! capitals "South Dakota" "Pierre"))
4c731ece 2174capitals
5ad5a7b6 2175@result{} (("South Dakota" . "Pierre")
4c731ece
NJ
2176 ("New York" . "Albany")
2177 ("Oregon" . "Salem")
2178 ("Florida" . "Miami"))
2179
2180;; And we got Florida wrong.
2181(set! capitals
2182 (assoc-set! capitals "Florida" "Tallahassee"))
2183capitals
5ad5a7b6 2184@result{} (("South Dakota" . "Pierre")
4c731ece
NJ
2185 ("New York" . "Albany")
2186 ("Oregon" . "Salem")
2187 ("Florida" . "Tallahassee"))
2188
2189;; After Oregon secedes, we can remove it.
2190(set! capitals
2191 (assoc-remove! capitals "Oregon"))
2192capitals
5ad5a7b6 2193@result{} (("South Dakota" . "Pierre")
4c731ece
NJ
2194 ("New York" . "Albany")
2195 ("Florida" . "Tallahassee"))
2196@end lisp
2197
2198@node Hash Tables
2199@subsection Hash Tables
2200@tpindex Hash Tables
2201
2202@c FIXME::martin: Review me!
2203
2204Hash tables are dictionaries which offer similar functionality as
2205association lists: They provide a mapping from keys to values. The
2206difference is that association lists need time linear in the size of
2207elements when searching for entries, whereas hash tables can normally
2208search in constant time. The drawback is that hash tables require a
2209little bit more memory, and that you can not use the normal list
2210procedures (@pxref{Lists}) for working with them.
2211
2212@menu
2213* Hash Table Examples:: Demonstration of hash table usage.
2214* Hash Table Reference:: Hash table procedure descriptions.
2215@end menu
2216
2217
2218@node Hash Table Examples
2219@subsubsection Hash Table Examples
2220
2221@c FIXME::martin: Review me!
2222
2223For demonstration purposes, this section gives a few usage examples of
2224some hash table procedures, together with some explanation what they do.
2225
2226First we start by creating a new hash table with 31 slots, and
2227populate it with two key/value pairs.
2228
2229@lisp
2230(define h (make-hash-table 31))
2231
2232(hashq-create-handle! h 'foo "bar")
2233@result{}
2234(foo . "bar")
2235
2236(hashq-create-handle! h 'braz "zonk")
2237@result{}
2238(braz . "zonk")
2239
2240(hashq-create-handle! h 'frob #f)
2241@result{}
2242(frob . #f)
2243@end lisp
2244
2245You can get the value for a given key with the procedure
2246@code{hashq-ref}, but the problem with this procedure is that you
2247cannot reliably determine whether a key does exists in the table. The
2248reason is that the procedure returns @code{#f} if the key is not in
2249the table, but it will return the same value if the key is in the
2250table and just happens to have the value @code{#f}, as you can see in
2251the following examples.
2252
2253@lisp
2254(hashq-ref h 'foo)
2255@result{}
2256"bar"
2257
2258(hashq-ref h 'frob)
2259@result{}
2260#f
2261
2262(hashq-ref h 'not-there)
2263@result{}
2264#f
2265@end lisp
2266
2267Better is to use the procedure @code{hashq-get-handle}, which makes a
2268distinction between the two cases. Just like @code{assq}, this
2269procedure returns a key/value-pair on success, and @code{#f} if the
2270key is not found.
2271
2272@lisp
2273(hashq-get-handle h 'foo)
2274@result{}
2275(foo . "bar")
2276
2277(hashq-get-handle h 'not-there)
2278@result{}
2279#f
2280@end lisp
2281
2282There is no procedure for calculating the number of key/value-pairs in
2283a hash table, but @code{hash-fold} can be used for doing exactly that.
2284
2285@lisp
2286(hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
2287@result{}
22883
2289@end lisp
2290
2291@node Hash Table Reference
2292@subsubsection Hash Table Reference
2293
ac5fa6d1
KR
2294@c FIXME: Describe in broad terms what happens for resizing, and what
2295@c the initial size means for this.
2296
2297Like the association list functions, the hash table functions come in
2298several varieties, according to the equality test used for the keys.
2299Plain @code{hash-} functions use @code{equal?}, @code{hashq-}
2300functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and
3adbc48c 2301the @code{hashx-} functions use an application supplied test.
ac5fa6d1
KR
2302
2303A single @code{make-hash-table} creates a hash table suitable for use
2304with any set of functions, but it's imperative that just one set is
2305then used consistently, or results will be unpredictable.
2306
2307@sp 1
ea2b9c2f 2308Hash tables are implemented as a vector indexed by a hash value formed
ac5fa6d1
KR
2309from the key, with an association list of key/value pairs for each
2310bucket in case distinct keys hash together. Direct access to the
2311pairs in those lists is provided by the @code{-handle-} functions.
2312
ea2b9c2f
KR
2313When the number of table entries goes above a threshold the vector is
2314increased and the entries rehashed, to prevent the bucket lists
2315becoming too long and slowing down accesses. When the number of
2316entries goes below a threshold the vector is decreased to save space.
2317
2318@sp 1
ac5fa6d1 2319For the @code{hashx-} ``extended'' routines, an application supplies a
3adbc48c
KR
2320@var{hash} function producing an integer index like @code{hashq} etc
2321below, and an @var{assoc} alist search function like @code{assq} etc
2322(@pxref{Retrieving Alist Entries}). Here's an example of such
2323functions implementing case-insensitive hashing of string keys,
2324
2325@example
2326(use-modules (srfi srfi-1)
2327 (srfi srfi-13))
ea2b9c2f 2328
3adbc48c
KR
2329(define (my-hash str size)
2330 (remainder (string-hash-ci str) size))
2331(define (my-assoc str alist)
2332 (find (lambda (pair) (string-ci=? str (car pair))) alist))
2333
2334(define my-table (make-hash-table))
2335(hashx-set! my-hash my-assoc my-table "foo" 123)
2336
2337(hashx-ref my-hash my-assoc my-table "FOO")
2338@result{} 123
2339@end example
2340
2341In a @code{hashx-} @var{hash} function the aim is to spread keys
ea2b9c2f
KR
2342across the vector, so bucket lists don't become long. But the actual
2343values are arbitrary as long as they're in the range 0 to
2344@math{@var{size}-1}. Helpful functions for forming a hash value, in
3adbc48c
KR
2345addition to @code{hashq} etc below, include @code{symbol-hash}
2346(@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci}
2347(@pxref{SRFI-13 Comparison}), and @code{char-set-hash} (@pxref{SRFI-14
2348Predicates/Comparison}).
ac5fa6d1 2349
ea2b9c2f
KR
2350Note that currently, unfortunately, there's no @code{hashx-remove!}
2351function, which rather limits the usefulness of the @code{hashx-}
2352routines.
2353
ac5fa6d1
KR
2354@sp 1
2355@deffn {Scheme Procedure} make-hash-table [size]
ea2b9c2f 2356Create a new hash table, with an optional minimum vector @var{size}.
ac5fa6d1 2357
ea2b9c2f
KR
2358When @var{size} is given, the table vector will still grow and shrink
2359automatically, as described above, but with @var{size} as a minimum.
2360If an application knows roughly how many entries the table will hold
2361then it can use @var{size} to avoid rehashing when initial entries are
2362added.
4c731ece
NJ
2363@end deffn
2364
2365@deffn {Scheme Procedure} hash-ref table key [dflt]
ac5fa6d1
KR
2366@deffnx {Scheme Procedure} hashq-ref table key [dflt]
2367@deffnx {Scheme Procedure} hashv-ref table key [dflt]
2368@deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt]
4c731ece 2369@deffnx {C Function} scm_hash_ref (table, key, dflt)
ac5fa6d1
KR
2370@deffnx {C Function} scm_hashq_ref (table, key, dflt)
2371@deffnx {C Function} scm_hashv_ref (table, key, dflt)
2372@deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt)
2373Lookup @var{key} in the given hash @var{table}, and return the
2374associated value. If @var{key} is not found, return @var{dflt}, or
2375@code{#f} if @var{dflt} is not given. (For the C functions,
2376@var{dflt} must be given.)
4c731ece
NJ
2377@end deffn
2378
2379@deffn {Scheme Procedure} hash-set! table key val
ac5fa6d1
KR
2380@deffnx {Scheme Procedure} hashq-set! table key val
2381@deffnx {Scheme Procedure} hashv-set! table key val
2382@deffnx {Scheme Procedure} hashx-set! hash assoc table key val
4c731ece 2383@deffnx {C Function} scm_hash_set_x (table, key, val)
ac5fa6d1
KR
2384@deffnx {C Function} scm_hashq_set_x (table, key, val)
2385@deffnx {C Function} scm_hashv_set_x (table, key, val)
2386@deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val)
2387Associate @var{val} with @var{key} in the given hash @var{table}. If
2388@var{key} is already present then it's associated value is changed.
2389If it's not present then a new entry is created.
4c731ece
NJ
2390@end deffn
2391
2392@deffn {Scheme Procedure} hash-remove! table key
ac5fa6d1
KR
2393@deffnx {Scheme Procedure} hashq-remove! table key
2394@deffnx {Scheme Procedure} hashv-remove! table key
4c731ece 2395@deffnx {C Function} scm_hash_remove_x (table, key)
ac5fa6d1
KR
2396@deffnx {C Function} scm_hashq_remove_x (table, key)
2397@deffnx {C Function} scm_hashv_remove_x (table, key)
2398Remove any association for @var{key} in the given hash @var{table}.
2399If @var{key} is not in @var{table} then nothing is done.
4c731ece
NJ
2400@end deffn
2401
2402@deffn {Scheme Procedure} hash key size
ac5fa6d1
KR
2403@deffnx {Scheme Procedure} hashq key size
2404@deffnx {Scheme Procedure} hashv key size
4c731ece 2405@deffnx {C Function} scm_hash (key, size)
ac5fa6d1
KR
2406@deffnx {C Function} scm_hashq (key, size)
2407@deffnx {C Function} scm_hashv (key, size)
2408Return a hash value for @var{key}. This is a number in the range
2409@math{0} to @math{@var{size}-1}, which is suitable for use in a hash
2410table of the given @var{size}.
4c731ece 2411
ac5fa6d1
KR
2412Note that @code{hashq} and @code{hashv} may use internal addresses of
2413objects, so if an object is garbage collected and re-created it can
2414have a different hash value, even when the two are notionally
2415@code{eq?}. For instance with symbols,
4c731ece 2416
ac5fa6d1
KR
2417@example
2418(hashq 'something 123) @result{} 19
2419(gc)
2420(hashq 'something 123) @result{} 62
2421@end example
4c731ece 2422
ac5fa6d1
KR
2423In normal use this is not a problem, since an object entered into a
2424hash table won't be garbage collected until removed. It's only if
2425hashing calculations are somehow separated from normal references that
2426its lifetime needs to be considered.
4c731ece
NJ
2427@end deffn
2428
2429@deffn {Scheme Procedure} hash-get-handle table key
ac5fa6d1
KR
2430@deffnx {Scheme Procedure} hashq-get-handle table key
2431@deffnx {Scheme Procedure} hashv-get-handle table key
2432@deffnx {Scheme Procedure} hashx-get-handle hash assoc table key
4c731ece 2433@deffnx {C Function} scm_hash_get_handle (table, key)
ac5fa6d1
KR
2434@deffnx {C Function} scm_hashq_get_handle (table, key)
2435@deffnx {C Function} scm_hashv_get_handle (table, key)
4c731ece 2436@deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key)
ac5fa6d1
KR
2437Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2438given hash @var{table}, or @code{#f} if @var{key} is not in
2439@var{table}.
4c731ece
NJ
2440@end deffn
2441
ac5fa6d1
KR
2442@deffn {Scheme Procedure} hash-create-handle! table key init
2443@deffnx {Scheme Procedure} hashq-create-handle! table key init
2444@deffnx {Scheme Procedure} hashv-create-handle! table key init
2445@deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init
2446@deffnx {C Function} scm_hash_create_handle_x (table, key, init)
4c731ece 2447@deffnx {C Function} scm_hashq_create_handle_x (table, key, init)
4c731ece 2448@deffnx {C Function} scm_hashv_create_handle_x (table, key, init)
ac5fa6d1
KR
2449@deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init)
2450Return the @code{(@var{key} . @var{value})} pair for @var{key} in the
2451given hash @var{table}. If @var{key} is not in @var{table} then
2452create an entry for it with @var{init} as the value, and return that
2453pair.
4c731ece
NJ
2454@end deffn
2455
ac5fa6d1
KR
2456@deffn {Scheme Procedure} hash-map proc table
2457@deffnx {Scheme Procedure} hash-for-each proc table
2458@deffnx {C Function} scm_hash_map (proc, table)
2459@deffnx {C Function} scm_hash_for_each (proc, table)
2460Apply @var{proc} to the entries in the given hash @var{table}. Each
2461call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map}
2462returns a list of the results from these calls, @code{hash-for-each}
3adbc48c 2463discards the results and returns an unspecified value.
4c731ece 2464
ac5fa6d1
KR
2465Calls are made over the table entries in an unspecified order, and for
2466@code{hash-map} the order of the values in the returned list is
2467unspecified. Results will be unpredictable if @var{table} is modified
2468while iterating.
2469
2470For example the following returns a new alist comprising all the
2471entries from @code{mytable}, in no particular order.
2472
2473@example
2474(hash-map cons mytable)
2475@end example
4c731ece
NJ
2476@end deffn
2477
2478@deffn {Scheme Procedure} hash-fold proc init table
2479@deffnx {C Function} scm_hash_fold (proc, init, table)
ac5fa6d1
KR
2480Accumulate a result by applying @var{proc} to the elements of the
2481given hash @var{table}. Each call is @code{(@var{proc} @var{key}
2482@var{value} @var{prior-result})}, where @var{key} and @var{value} are
2483from the @var{table} and @var{prior-result} is the return from the
2484previous @var{proc} call. For the first call, @var{prior-result} is
2485the given @var{init} value.
2486
2487Calls are made over the table entries in an unspecified order.
2488Results will be unpredictable if @var{table} is modified while
2489@code{hash-fold} is running.
2490
2491For example, the following returns a count of how many keys in
2492@code{mytable} are strings.
2493
2494@example
2495(hash-fold (lambda (key value prior)
2496 (if (string? key) (1+ prior) prior))
2497 0 mytable)
2498@end example
4c731ece
NJ
2499@end deffn
2500
2501
2502@c Local Variables:
2503@c TeX-master: "guile.texi"
2504@c End: