Fix dangling references to files that have been removed.
[bpt/guile.git] / doc / ref / srfi-modules.texi
CommitLineData
2da09c3f
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
9a18d8d4 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007
2da09c3f
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
a0e07ba4
NJ
7@page
8@node SRFI Support
3229f68b 9@section SRFI Support Modules
8742c48b 10@cindex SRFI
a0e07ba4
NJ
11
12SRFI is an acronym for Scheme Request For Implementation. The SRFI
13documents define a lot of syntactic and procedure extensions to standard
14Scheme as defined in R5RS.
15
16Guile has support for a number of SRFIs. This chapter gives an overview
17over the available SRFIs and some usage hints. For complete
18documentation, design rationales and further examples, we advise you to
19get the relevant SRFI documents from the SRFI home page
20@url{http://srfi.schemers.org}.
21
22@menu
23* About SRFI Usage:: What to know about Guile's SRFI support.
24* SRFI-0:: cond-expand
25* SRFI-1:: List library.
26* SRFI-2:: and-let*.
27* SRFI-4:: Homogeneous numeric vector datatypes.
28* SRFI-6:: Basic String Ports.
29* SRFI-8:: receive.
30* SRFI-9:: define-record-type.
31* SRFI-10:: Hash-Comma Reader Extension.
32* SRFI-11:: let-values and let-values*.
33* SRFI-13:: String library.
34* SRFI-14:: Character-set library.
35* SRFI-16:: case-lambda
36* SRFI-17:: Generalized set!
bfc9c8e0 37* SRFI-19:: Time/Date library.
1de8c1ae 38* SRFI-26:: Specializing parameters
8638c417 39* SRFI-31:: A special form `rec' for recursive evaluation
f50ca8da
LC
40* SRFI-34:: Exception handling.
41* SRFI-35:: Conditions.
d4c38221 42* SRFI-37:: args-fold program argument processor
eeadfda1 43* SRFI-39:: Parameter objects
4ea9becb 44* SRFI-55:: Requiring Features.
8503beb8 45* SRFI-60:: Integers as bits.
43ed3b69 46* SRFI-61:: A more general `cond' clause
1317062f 47* SRFI-69:: Basic hash tables.
a0e07ba4
NJ
48@end menu
49
50
51@node About SRFI Usage
3229f68b 52@subsection About SRFI Usage
a0e07ba4
NJ
53
54@c FIXME::martin: Review me!
55
56SRFI support in Guile is currently implemented partly in the core
57library, and partly as add-on modules. That means that some SRFIs are
58automatically available when the interpreter is started, whereas the
59other SRFIs require you to use the appropriate support module
12991fed 60explicitly.
a0e07ba4
NJ
61
62There are several reasons for this inconsistency. First, the feature
63checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
64available immediately, because it must be there when the user wants to
65check for the Scheme implementation, that is, before she can know that
66it is safe to use @code{use-modules} to load SRFI support modules. The
67second reason is that some features defined in SRFIs had been
68implemented in Guile before the developers started to add SRFI
69implementations as modules (for example SRFI-6 (@pxref{SRFI-6})). In
70the future, it is possible that SRFIs in the core library might be
71factored out into separate modules, requiring explicit module loading
72when they are needed. So you should be prepared to have to use
73@code{use-modules} someday in the future to access SRFI-6 bindings. If
74you want, you can do that already. We have included the module
75@code{(srfi srfi-6)} in the distribution, which currently does nothing,
76but ensures that you can write future-safe code.
77
78Generally, support for a specific SRFI is made available by using
79modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
80number of the SRFI needed. Another possibility is to use the command
81line option @code{--use-srfi}, which will load the necessary modules
82automatically (@pxref{Invoking Guile}).
83
84
85@node SRFI-0
3229f68b 86@subsection SRFI-0 - cond-expand
8742c48b 87@cindex SRFI-0
a0e07ba4 88
5eef0f61
KR
89This SRFI lets a portable Scheme program test for the presence of
90certain features, and adapt itself by using different blocks of code,
91or fail if the necessary features are not available. There's no
92module to load, this is in the Guile core.
a0e07ba4 93
5eef0f61
KR
94A program designed only for Guile will generally not need this
95mechanism, such a program can of course directly use the various
96documented parts of Guile.
a0e07ba4 97
5eef0f61
KR
98@deffn syntax cond-expand (feature body@dots{}) @dots{}
99Expand to the @var{body} of the first clause whose @var{feature}
100specification is satisfied. It is an error if no @var{feature} is
a0e07ba4
NJ
101satisfied.
102
5eef0f61
KR
103Features are symbols such as @code{srfi-1}, and a feature
104specification can use @code{and}, @code{or} and @code{not} forms to
105test combinations. The last clause can be an @code{else}, to be used
106if no other passes.
a0e07ba4 107
5eef0f61
KR
108For example, define a private version of @code{alist-cons} if SRFI-1
109is not available.
a0e07ba4 110
5eef0f61
KR
111@example
112(cond-expand (srfi-1
113 )
114 (else
115 (define (alist-cons key val alist)
116 (cons (cons key val) alist))))
117@end example
a0e07ba4 118
5eef0f61
KR
119Or demand a certain set of SRFIs (list operations, string ports,
120@code{receive} and string operations), failing if they're not
121available.
a0e07ba4 122
5eef0f61
KR
123@example
124(cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
125 ))
126@end example
127@end deffn
a0e07ba4 128
f38d22c5
KR
129@noindent
130The Guile core has the following features,
131
132@example
133guile
134r5rs
135srfi-0
136srfi-4
137srfi-6
138srfi-13
139srfi-14
140@end example
141
142Other SRFI feature symbols are defined once their code has been loaded
143with @code{use-modules}, since only then are their bindings available.
a0e07ba4 144
5eef0f61
KR
145The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
146a good way to load SRFIs to satisfy @code{cond-expand} when running a
147portable program.
a0e07ba4 148
5eef0f61
KR
149Testing the @code{guile} feature allows a program to adapt itself to
150the Guile module system, but still run on other Scheme systems. For
151example the following demands SRFI-8 (@code{receive}), but also knows
152how to load it with the Guile mechanism.
a0e07ba4
NJ
153
154@example
5eef0f61
KR
155(cond-expand (srfi-8
156 )
157 (guile
158 (use-modules (srfi srfi-8))))
a0e07ba4
NJ
159@end example
160
5eef0f61
KR
161It should be noted that @code{cond-expand} is separate from the
162@code{*features*} mechanism (@pxref{Feature Tracking}), feature
163symbols in one are unrelated to those in the other.
a0e07ba4
NJ
164
165
166@node SRFI-1
3229f68b 167@subsection SRFI-1 - List library
8742c48b 168@cindex SRFI-1
7c2e18cd 169@cindex list
a0e07ba4
NJ
170
171@c FIXME::martin: Review me!
172
173The list library defined in SRFI-1 contains a lot of useful list
174processing procedures for construction, examining, destructuring and
175manipulating lists and pairs.
176
177Since SRFI-1 also defines some procedures which are already contained
178in R5RS and thus are supported by the Guile core library, some list
179and pair procedures which appear in the SRFI-1 document may not appear
180in this section. So when looking for a particular list/pair
181processing procedure, you should also have a look at the sections
182@ref{Lists} and @ref{Pairs}.
183
184@menu
185* SRFI-1 Constructors:: Constructing new lists.
186* SRFI-1 Predicates:: Testing list for specific properties.
187* SRFI-1 Selectors:: Selecting elements from lists.
188* SRFI-1 Length Append etc:: Length calculation and list appending.
189* SRFI-1 Fold and Map:: Higher-order list processing.
190* SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
85a9b4ed 191* SRFI-1 Searching:: Search for elements.
a0e07ba4
NJ
192* SRFI-1 Deleting:: Delete elements from lists.
193* SRFI-1 Association Lists:: Handle association lists.
194* SRFI-1 Set Operations:: Use lists for representing sets.
195@end menu
196
197@node SRFI-1 Constructors
3229f68b 198@subsubsection Constructors
7c2e18cd 199@cindex list constructor
a0e07ba4
NJ
200
201@c FIXME::martin: Review me!
202
203New lists can be constructed by calling one of the following
204procedures.
205
8f85c0c6 206@deffn {Scheme Procedure} xcons d a
a0e07ba4
NJ
207Like @code{cons}, but with interchanged arguments. Useful mostly when
208passed to higher-order procedures.
209@end deffn
210
8f85c0c6 211@deffn {Scheme Procedure} list-tabulate n init-proc
a0e07ba4
NJ
212Return an @var{n}-element list, where each list element is produced by
213applying the procedure @var{init-proc} to the corresponding list
214index. The order in which @var{init-proc} is applied to the indices
215is not specified.
216@end deffn
217
57066448
KR
218@deffn {Scheme Procedure} list-copy lst
219Return a new list containing the elements of the list @var{lst}.
220
221This function differs from the core @code{list-copy} (@pxref{List
222Constructors}) in accepting improper lists too. And if @var{lst} is
223not a pair at all then it's treated as the final tail of an improper
224list and simply returned.
225@end deffn
226
8f85c0c6 227@deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
a0e07ba4
NJ
228Return a circular list containing the given arguments @var{elt1}
229@var{elt2} @dots{}.
230@end deffn
231
8f85c0c6 232@deffn {Scheme Procedure} iota count [start step]
256853db
KR
233Return a list containing @var{count} numbers, starting from
234@var{start} and adding @var{step} each time. The default @var{start}
235is 0, the default @var{step} is 1. For example,
a0e07ba4 236
256853db
KR
237@example
238(iota 6) @result{} (0 1 2 3 4 5)
239(iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
240@end example
a0e07ba4 241
256853db
KR
242This function takes its name from the corresponding primitive in the
243APL language.
a0e07ba4
NJ
244@end deffn
245
246
247@node SRFI-1 Predicates
3229f68b 248@subsubsection Predicates
7c2e18cd 249@cindex list predicate
a0e07ba4
NJ
250
251@c FIXME::martin: Review me!
252
253The procedures in this section test specific properties of lists.
254
8f85c0c6 255@deffn {Scheme Procedure} proper-list? obj
f18f87aa
KR
256Return @code{#t} if @var{obj} is a proper list, or @code{#f}
257otherwise. This is the same as the core @code{list?} (@pxref{List
258Predicates}).
259
260A proper list is a list which ends with the empty list @code{()} in
261the usual way. The empty list @code{()} itself is a proper list too.
262
263@example
264(proper-list? '(1 2 3)) @result{} #t
265(proper-list? '()) @result{} #t
266@end example
a0e07ba4
NJ
267@end deffn
268
8f85c0c6 269@deffn {Scheme Procedure} circular-list? obj
f18f87aa
KR
270Return @code{#t} if @var{obj} is a circular list, or @code{#f}
271otherwise.
272
273A circular list is a list where at some point the @code{cdr} refers
274back to a previous pair in the list (either the start or some later
275point), so that following the @code{cdr}s takes you around in a
276circle, with no end.
277
278@example
279(define x (list 1 2 3 4))
280(set-cdr! (last-pair x) (cddr x))
281x @result{} (1 2 3 4 3 4 3 4 ...)
282(circular-list? x) @result{} #t
283@end example
a0e07ba4
NJ
284@end deffn
285
8f85c0c6 286@deffn {Scheme Procedure} dotted-list? obj
f18f87aa
KR
287Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
288otherwise.
289
290A dotted list is a list where the @code{cdr} of the last pair is not
291the empty list @code{()}. Any non-pair @var{obj} is also considered a
292dotted list, with length zero.
293
294@example
295(dotted-list? '(1 2 . 3)) @result{} #t
296(dotted-list? 99) @result{} #t
297@end example
a0e07ba4
NJ
298@end deffn
299
f18f87aa
KR
300It will be noted that any Scheme object passes exactly one of the
301above three tests @code{proper-list?}, @code{circular-list?} and
302@code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
303are either @code{proper-list?} or @code{dotted-list?}, and infinite
304lists are @code{circular-list?}.
305
306@sp 1
8f85c0c6 307@deffn {Scheme Procedure} null-list? lst
a0e07ba4
NJ
308Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
309otherwise. If something else than a proper or circular list is passed
85a9b4ed 310as @var{lst}, an error is signalled. This procedure is recommended
a0e07ba4
NJ
311for checking for the end of a list in contexts where dotted lists are
312not allowed.
313@end deffn
314
8f85c0c6 315@deffn {Scheme Procedure} not-pair? obj
a0e07ba4
NJ
316Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
317This is shorthand notation @code{(not (pair? @var{obj}))} and is
318supposed to be used for end-of-list checking in contexts where dotted
319lists are allowed.
320@end deffn
321
8f85c0c6 322@deffn {Scheme Procedure} list= elt= list1 @dots{}
a0e07ba4
NJ
323Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
324List equality is determined by testing whether all lists have the same
325length and the corresponding elements are equal in the sense of the
326equality predicate @var{elt=}. If no or only one list is given,
327@code{#t} is returned.
328@end deffn
329
330
331@node SRFI-1 Selectors
3229f68b 332@subsubsection Selectors
7c2e18cd 333@cindex list selector
a0e07ba4
NJ
334
335@c FIXME::martin: Review me!
336
8f85c0c6
NJ
337@deffn {Scheme Procedure} first pair
338@deffnx {Scheme Procedure} second pair
339@deffnx {Scheme Procedure} third pair
340@deffnx {Scheme Procedure} fourth pair
341@deffnx {Scheme Procedure} fifth pair
342@deffnx {Scheme Procedure} sixth pair
343@deffnx {Scheme Procedure} seventh pair
344@deffnx {Scheme Procedure} eighth pair
345@deffnx {Scheme Procedure} ninth pair
346@deffnx {Scheme Procedure} tenth pair
a0e07ba4
NJ
347These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
348@end deffn
349
8f85c0c6 350@deffn {Scheme Procedure} car+cdr pair
a0e07ba4
NJ
351Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
352@end deffn
353
8f85c0c6
NJ
354@deffn {Scheme Procedure} take lst i
355@deffnx {Scheme Procedure} take! lst i
a0e07ba4
NJ
356Return a list containing the first @var{i} elements of @var{lst}.
357
358@code{take!} may modify the structure of the argument list @var{lst}
359in order to produce the result.
360@end deffn
361
8f85c0c6 362@deffn {Scheme Procedure} drop lst i
a0e07ba4
NJ
363Return a list containing all but the first @var{i} elements of
364@var{lst}.
365@end deffn
366
8f85c0c6 367@deffn {Scheme Procedure} take-right lst i
a0e07ba4 368Return the a list containing the @var{i} last elements of @var{lst}.
64bf8517 369The return shares a common tail with @var{lst}.
a0e07ba4
NJ
370@end deffn
371
8f85c0c6
NJ
372@deffn {Scheme Procedure} drop-right lst i
373@deffnx {Scheme Procedure} drop-right! lst i
a0e07ba4
NJ
374Return the a list containing all but the @var{i} last elements of
375@var{lst}.
376
64bf8517
KR
377@code{drop-right} always returns a new list, even when @var{i} is
378zero. @code{drop-right!} may modify the structure of the argument
379list @var{lst} in order to produce the result.
a0e07ba4
NJ
380@end deffn
381
8f85c0c6
NJ
382@deffn {Scheme Procedure} split-at lst i
383@deffnx {Scheme Procedure} split-at! lst i
a0e07ba4
NJ
384Return two values, a list containing the first @var{i} elements of the
385list @var{lst} and a list containing the remaining elements.
386
387@code{split-at!} may modify the structure of the argument list
388@var{lst} in order to produce the result.
389@end deffn
390
8f85c0c6 391@deffn {Scheme Procedure} last lst
a0e07ba4
NJ
392Return the last element of the non-empty, finite list @var{lst}.
393@end deffn
394
395
396@node SRFI-1 Length Append etc
3229f68b 397@subsubsection Length, Append, Concatenate, etc.
a0e07ba4
NJ
398
399@c FIXME::martin: Review me!
400
8f85c0c6 401@deffn {Scheme Procedure} length+ lst
a0e07ba4
NJ
402Return the length of the argument list @var{lst}. When @var{lst} is a
403circular list, @code{#f} is returned.
404@end deffn
405
8f85c0c6
NJ
406@deffn {Scheme Procedure} concatenate list-of-lists
407@deffnx {Scheme Procedure} concatenate! list-of-lists
a0e07ba4
NJ
408Construct a list by appending all lists in @var{list-of-lists}.
409
410@code{concatenate!} may modify the structure of the given lists in
411order to produce the result.
a3e856f2
KR
412
413@code{concatenate} is the same as @code{(apply append
414@var{list-of-lists})}. It exists because some Scheme implementations
415have a limit on the number of arguments a function takes, which the
416@code{apply} might exceed. In Guile there is no such limit.
a0e07ba4
NJ
417@end deffn
418
8f85c0c6
NJ
419@deffn {Scheme Procedure} append-reverse rev-head tail
420@deffnx {Scheme Procedure} append-reverse! rev-head tail
23f2b9a3
KR
421Reverse @var{rev-head}, append @var{tail} to it, and return the
422result. This is equivalent to @code{(append (reverse @var{rev-head})
423@var{tail})}, but its implementation is more efficient.
424
425@example
426(append-reverse '(1 2 3) '(4 5 6)) @result{} (3 2 1 4 5 6)
427@end example
a0e07ba4
NJ
428
429@code{append-reverse!} may modify @var{rev-head} in order to produce
430the result.
431@end deffn
432
8f85c0c6 433@deffn {Scheme Procedure} zip lst1 lst2 @dots{}
a0e07ba4
NJ
434Return a list as long as the shortest of the argument lists, where
435each element is a list. The first list contains the first elements of
436the argument lists, the second list contains the second elements, and
437so on.
438@end deffn
439
8f85c0c6
NJ
440@deffn {Scheme Procedure} unzip1 lst
441@deffnx {Scheme Procedure} unzip2 lst
442@deffnx {Scheme Procedure} unzip3 lst
443@deffnx {Scheme Procedure} unzip4 lst
444@deffnx {Scheme Procedure} unzip5 lst
a0e07ba4
NJ
445@code{unzip1} takes a list of lists, and returns a list containing the
446first elements of each list, @code{unzip2} returns two lists, the
447first containing the first elements of each lists and the second
448containing the second elements of each lists, and so on.
449@end deffn
450
e508c863
KR
451@deffn {Scheme Procedure} count pred lst1 @dots{} lstN
452Return a count of the number of times @var{pred} returns true when
453called on elements from the given lists.
454
455@var{pred} is called with @var{N} parameters @code{(@var{pred}
456@var{elem1} @dots{} @var{elemN})}, each element being from the
457corresponding @var{lst1} @dots{} @var{lstN}. The first call is with
458the first element of each list, the second with the second element
459from each, and so on.
460
461Counting stops when the end of the shortest list is reached. At least
462one list must be non-circular.
463@end deffn
464
a0e07ba4
NJ
465
466@node SRFI-1 Fold and Map
3229f68b 467@subsubsection Fold, Unfold & Map
7c2e18cd
KR
468@cindex list fold
469@cindex list map
a0e07ba4
NJ
470
471@c FIXME::martin: Review me!
472
1e181a08
KR
473@deffn {Scheme Procedure} fold proc init lst1 @dots{} lstN
474@deffnx {Scheme Procedure} fold-right proc init lst1 @dots{} lstN
475Apply @var{proc} to the elements of @var{lst1} @dots{} @var{lstN} to
476build a result, and return that result.
a0e07ba4 477
1e181a08
KR
478Each @var{proc} call is @code{(@var{proc} @var{elem1} @dots{}
479@var{elemN} @var{previous})}, where @var{elem1} is from @var{lst1},
480through @var{elemN} from @var{lstN}. @var{previous} is the return
481from the previous call to @var{proc}, or the given @var{init} for the
482first call. If any list is empty, just @var{init} is returned.
a0e07ba4 483
1e181a08
KR
484@code{fold} works through the list elements from first to last. The
485following shows a list reversal and the calls it makes,
a0e07ba4 486
1e181a08
KR
487@example
488(fold cons '() '(1 2 3))
a0e07ba4 489
1e181a08
KR
490(cons 1 '())
491(cons 2 '(1))
492(cons 3 '(2 1)
493@result{} (3 2 1)
494@end example
a0e07ba4 495
1e181a08
KR
496@code{fold-right} works through the list elements from last to first,
497ie.@: from the right. So for example the following finds the longest
498string, and the last among equal longest,
499
500@example
501(fold-right (lambda (str prev)
502 (if (> (string-length str) (string-length prev))
503 str
504 prev))
505 ""
506 '("x" "abc" "xyz" "jk"))
507@result{} "xyz"
508@end example
a0e07ba4 509
1e181a08
KR
510If @var{lst1} through @var{lstN} have different lengths, @code{fold}
511stops when the end of the shortest is reached; @code{fold-right}
512commences at the last element of the shortest. Ie.@: elements past
513the length of the shortest are ignored in the other @var{lst}s. At
514least one @var{lst} must be non-circular.
515
516@code{fold} should be preferred over @code{fold-right} if the order of
517processing doesn't matter, or can be arranged either way, since
518@code{fold} is a little more efficient.
519
520The way @code{fold} builds a result from iterating is quite general,
521it can do more than other iterations like say @code{map} or
522@code{filter}. The following for example removes adjacent duplicate
523elements from a list,
524
525@example
526(define (delete-adjacent-duplicates lst)
527 (fold-right (lambda (elem ret)
528 (if (equal? elem (first ret))
529 ret
530 (cons elem ret)))
531 (list (last lst))
532 lst))
533(delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
534@result{} (1 2 3 4 5)
535@end example
536
537Clearly the same sort of thing can be done with a @code{for-each} and
5f708db6
KR
538a variable in which to build the result, but a self-contained
539@var{proc} can be re-used in multiple contexts, where a
540@code{for-each} would have to be written out each time.
a0e07ba4
NJ
541@end deffn
542
1e181a08
KR
543@deffn {Scheme Procedure} pair-fold proc init lst1 @dots{} lstN
544@deffnx {Scheme Procedure} pair-fold-right proc init lst1 @dots{} lstN
545The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
546the pairs of the lists instead of the list elements.
a0e07ba4
NJ
547@end deffn
548
5f708db6
KR
549@deffn {Scheme Procedure} reduce proc default lst
550@deffnx {Scheme Procedure} reduce-right proc default lst
551@code{reduce} is a variant of @code{fold}, where the first call to
552@var{proc} is on two elements from @var{lst}, rather than one element
553and a given initial value.
1e181a08 554
5f708db6
KR
555If @var{lst} is empty, @code{reduce} returns @var{default} (this is
556the only use for @var{default}). If @var{lst} has just one element
557then that's the return value. Otherwise @var{proc} is called on the
558elements of @var{lst}.
1e181a08 559
5f708db6
KR
560Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
561where @var{elem} is from @var{lst} (the second and subsequent elements
562of @var{lst}), and @var{previous} is the return from the previous call
563to @var{proc}. The first element of @var{lst} is the @var{previous}
564for the first call to @var{proc}.
1e181a08 565
5f708db6
KR
566For example, the following adds a list of numbers, the calls made to
567@code{+} are shown. (Of course @code{+} accepts multiple arguments
568and can add a list directly, with @code{apply}.)
1e181a08
KR
569
570@example
5f708db6
KR
571(reduce + 0 '(5 6 7)) @result{} 18
572
573(+ 6 5) @result{} 11
574(+ 7 11) @result{} 18
1e181a08
KR
575@end example
576
5f708db6
KR
577@code{reduce} can be used instead of @code{fold} where the @var{init}
578value is an ``identity'', meaning a value which under @var{proc}
579doesn't change the result, in this case 0 is an identity since
580@code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
1e181a08
KR
581
582@code{reduce-right} is a similar variation on @code{fold-right},
5f708db6
KR
583working from the end (ie.@: the right) of @var{lst}. The last element
584of @var{lst} is the @var{previous} for the first call to @var{proc},
585and the @var{elem} values go from the second last.
1e181a08
KR
586
587@code{reduce} should be preferred over @code{reduce-right} if the
588order of processing doesn't matter, or can be arranged either way,
589since @code{reduce} is a little more efficient.
a0e07ba4
NJ
590@end deffn
591
8f85c0c6 592@deffn {Scheme Procedure} unfold p f g seed [tail-gen]
a0e07ba4
NJ
593@code{unfold} is defined as follows:
594
595@lisp
596(unfold p f g seed) =
597 (if (p seed) (tail-gen seed)
598 (cons (f seed)
599 (unfold p f g (g seed))))
600@end lisp
601
602@table @var
603@item p
604Determines when to stop unfolding.
605
606@item f
607Maps each seed value to the corresponding list element.
608
609@item g
610Maps each seed value to next seed valu.
611
612@item seed
613The state value for the unfold.
614
615@item tail-gen
616Creates the tail of the list; defaults to @code{(lambda (x) '())}.
617@end table
618
619@var{g} produces a series of seed values, which are mapped to list
620elements by @var{f}. These elements are put into a list in
621left-to-right order, and @var{p} tells when to stop unfolding.
622@end deffn
623
8f85c0c6 624@deffn {Scheme Procedure} unfold-right p f g seed [tail]
a0e07ba4
NJ
625Construct a list with the following loop.
626
627@lisp
628(let lp ((seed seed) (lis tail))
629 (if (p seed) lis
630 (lp (g seed)
631 (cons (f seed) lis))))
632@end lisp
633
634@table @var
635@item p
636Determines when to stop unfolding.
637
638@item f
639Maps each seed value to the corresponding list element.
640
641@item g
642Maps each seed value to next seed valu.
643
644@item seed
645The state value for the unfold.
646
647@item tail-gen
648Creates the tail of the list; defaults to @code{(lambda (x) '())}.
649@end table
650
651@end deffn
652
8f85c0c6 653@deffn {Scheme Procedure} map f lst1 lst2 @dots{}
a0e07ba4
NJ
654Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
655return a list containing the results of the procedure applications.
656This procedure is extended with respect to R5RS, because the argument
657lists may have different lengths. The result list will have the same
658length as the shortest argument lists. The order in which @var{f}
659will be applied to the list element(s) is not specified.
660@end deffn
661
8f85c0c6 662@deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
a0e07ba4
NJ
663Apply the procedure @var{f} to each pair of corresponding elements of
664the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
665specified. This procedure is extended with respect to R5RS, because
666the argument lists may have different lengths. The shortest argument
667list determines the number of times @var{f} is called. @var{f} will
85a9b4ed 668be applied to the list elements in left-to-right order.
a0e07ba4
NJ
669
670@end deffn
671
8f85c0c6
NJ
672@deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
673@deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
12991fed 674Equivalent to
a0e07ba4
NJ
675
676@lisp
12991fed 677(apply append (map f clist1 clist2 ...))
a0e07ba4
NJ
678@end lisp
679
12991fed 680and
a0e07ba4
NJ
681
682@lisp
12991fed 683(apply append! (map f clist1 clist2 ...))
a0e07ba4
NJ
684@end lisp
685
686Map @var{f} over the elements of the lists, just as in the @code{map}
687function. However, the results of the applications are appended
688together to make the final result. @code{append-map} uses
689@code{append} to append the results together; @code{append-map!} uses
690@code{append!}.
691
692The dynamic order in which the various applications of @var{f} are
693made is not specified.
694@end deffn
695
8f85c0c6 696@deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
a0e07ba4
NJ
697Linear-update variant of @code{map} -- @code{map!} is allowed, but not
698required, to alter the cons cells of @var{lst1} to construct the
699result list.
700
701The dynamic order in which the various applications of @var{f} are
702made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
703@dots{} must have at least as many elements as @var{lst1}.
704@end deffn
705
8f85c0c6 706@deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
a0e07ba4
NJ
707Like @code{for-each}, but applies the procedure @var{f} to the pairs
708from which the argument lists are constructed, instead of the list
709elements. The return value is not specified.
710@end deffn
711
8f85c0c6 712@deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
a0e07ba4
NJ
713Like @code{map}, but only results from the applications of @var{f}
714which are true are saved in the result list.
715@end deffn
716
717
718@node SRFI-1 Filtering and Partitioning
3229f68b 719@subsubsection Filtering and Partitioning
7c2e18cd
KR
720@cindex list filter
721@cindex list partition
a0e07ba4
NJ
722
723@c FIXME::martin: Review me!
724
725Filtering means to collect all elements from a list which satisfy a
726specific condition. Partitioning a list means to make two groups of
727list elements, one which contains the elements satisfying a condition,
728and the other for the elements which don't.
729
60e25dc4
KR
730The @code{filter} and @code{filter!} functions are implemented in the
731Guile core, @xref{List Modification}.
a0e07ba4 732
8f85c0c6
NJ
733@deffn {Scheme Procedure} partition pred lst
734@deffnx {Scheme Procedure} partition! pred lst
193239f1
KR
735Split @var{lst} into those elements which do and don't satisfy the
736predicate @var{pred}.
a0e07ba4 737
193239f1
KR
738The return is two values (@pxref{Multiple Values}), the first being a
739list of all elements from @var{lst} which satisfy @var{pred}, the
740second a list of those which do not.
741
742The elements in the result lists are in the same order as in @var{lst}
743but the order in which the calls @code{(@var{pred} elem)} are made on
744the list elements is unspecified.
745
746@code{partition} does not change @var{lst}, but one of the returned
747lists may share a tail with it. @code{partition!} may modify
748@var{lst} to construct its return.
a0e07ba4
NJ
749@end deffn
750
8f85c0c6
NJ
751@deffn {Scheme Procedure} remove pred lst
752@deffnx {Scheme Procedure} remove! pred lst
a0e07ba4
NJ
753Return a list containing all elements from @var{lst} which do not
754satisfy the predicate @var{pred}. The elements in the result list
755have the same order as in @var{lst}. The order in which @var{pred} is
756applied to the list elements is not specified.
757
758@code{remove!} is allowed, but not required to modify the structure of
759the input list.
760@end deffn
761
762
763@node SRFI-1 Searching
3229f68b 764@subsubsection Searching
7c2e18cd 765@cindex list search
a0e07ba4
NJ
766
767@c FIXME::martin: Review me!
768
769The procedures for searching elements in lists either accept a
770predicate or a comparison object for determining which elements are to
771be searched.
772
8f85c0c6 773@deffn {Scheme Procedure} find pred lst
a0e07ba4
NJ
774Return the first element of @var{lst} which satisfies the predicate
775@var{pred} and @code{#f} if no such element is found.
776@end deffn
777
8f85c0c6 778@deffn {Scheme Procedure} find-tail pred lst
a0e07ba4
NJ
779Return the first pair of @var{lst} whose @sc{car} satisfies the
780predicate @var{pred} and @code{#f} if no such element is found.
781@end deffn
782
8f85c0c6
NJ
783@deffn {Scheme Procedure} take-while pred lst
784@deffnx {Scheme Procedure} take-while! pred lst
a0e07ba4
NJ
785Return the longest initial prefix of @var{lst} whose elements all
786satisfy the predicate @var{pred}.
787
788@code{take-while!} is allowed, but not required to modify the input
789list while producing the result.
790@end deffn
791
8f85c0c6 792@deffn {Scheme Procedure} drop-while pred lst
a0e07ba4
NJ
793Drop the longest initial prefix of @var{lst} whose elements all
794satisfy the predicate @var{pred}.
795@end deffn
796
8f85c0c6
NJ
797@deffn {Scheme Procedure} span pred lst
798@deffnx {Scheme Procedure} span! pred lst
799@deffnx {Scheme Procedure} break pred lst
800@deffnx {Scheme Procedure} break! pred lst
a0e07ba4
NJ
801@code{span} splits the list @var{lst} into the longest initial prefix
802whose elements all satisfy the predicate @var{pred}, and the remaining
803tail. @code{break} inverts the sense of the predicate.
804
805@code{span!} and @code{break!} are allowed, but not required to modify
806the structure of the input list @var{lst} in order to produce the
807result.
3e73b6f9
KR
808
809Note that the name @code{break} conflicts with the @code{break}
810binding established by @code{while} (@pxref{while do}). Applications
811wanting to use @code{break} from within a @code{while} loop will need
812to make a new define under a different name.
a0e07ba4
NJ
813@end deffn
814
62705beb
KR
815@deffn {Scheme Procedure} any pred lst1 lst2 @dots{} lstN
816Test whether any set of elements from @var{lst1} @dots{} lstN
817satisfies @var{pred}. If so the return value is the return from the
818successful @var{pred} call, or if not the return is @code{#f}.
819
820Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
821@var{elemN})} taking an element from each @var{lst}. The calls are
822made successively for the first, second, etc elements of the lists,
823stopping when @var{pred} returns non-@code{#f}, or when the end of the
824shortest list is reached.
825
826The @var{pred} call on the last set of elements (ie.@: when the end of
827the shortest list has been reached), if that point is reached, is a
828tail call.
829@end deffn
830
831@deffn {Scheme Procedure} every pred lst1 lst2 @dots{} lstN
832Test whether every set of elements from @var{lst1} @dots{} lstN
833satisfies @var{pred}. If so the return value is the return from the
834final @var{pred} call, or if not the return is @code{#f}.
835
836Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
837@var{elemN})} taking an element from each @var{lst}. The calls are
838made successively for the first, second, etc elements of the lists,
839stopping if @var{pred} returns @code{#f}, or when the end of any of
840the lists is reached.
841
842The @var{pred} call on the last set of elements (ie.@: when the end of
843the shortest list has been reached) is a tail call.
844
845If one of @var{lst1} @dots{} @var{lstN} is empty then no calls to
846@var{pred} are made, and the return is @code{#t}.
a0e07ba4
NJ
847@end deffn
848
0166e7f2 849@deffn {Scheme Procedure} list-index pred lst1 @dots{} lstN
d1736abf
KR
850Return the index of the first set of elements, one from each of
851@var{lst1}@dots{}@var{lstN}, which satisfies @var{pred}.
852
853@var{pred} is called as @code{(@var{pred} elem1 @dots{} elemN)}.
854Searching stops when the end of the shortest @var{lst} is reached.
855The return index starts from 0 for the first set of elements. If no
856set of elements pass then the return is @code{#f}.
0166e7f2
KR
857
858@example
859(list-index odd? '(2 4 6 9)) @result{} 3
860(list-index = '(1 2 3) '(3 1 2)) @result{} #f
861@end example
a0e07ba4
NJ
862@end deffn
863
8f85c0c6 864@deffn {Scheme Procedure} member x lst [=]
a0e07ba4 865Return the first sublist of @var{lst} whose @sc{car} is equal to
ca04a5ae 866@var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
ea6ea01b 867
ca04a5ae
KR
868Equality is determined by @code{equal?}, or by the equality predicate
869@var{=} if given. @var{=} is called @code{(= @var{x} elem)},
870ie.@: with the given @var{x} first, so for example to find the first
871element greater than 5,
872
873@example
874(member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
875@end example
876
877This version of @code{member} extends the core @code{member}
878(@pxref{List Searching}) by accepting an equality predicate.
a0e07ba4
NJ
879@end deffn
880
881
882@node SRFI-1 Deleting
3229f68b 883@subsubsection Deleting
7c2e18cd 884@cindex list delete
a0e07ba4 885
8f85c0c6
NJ
886@deffn {Scheme Procedure} delete x lst [=]
887@deffnx {Scheme Procedure} delete! x lst [=]
b6b9376a
KR
888Return a list containing the elements of @var{lst} but with those
889equal to @var{x} deleted. The returned elements will be in the same
890order as they were in @var{lst}.
891
892Equality is determined by the @var{=} predicate, or @code{equal?} if
893not given. An equality call is made just once for each element, but
894the order in which the calls are made on the elements is unspecified.
a0e07ba4 895
243bdb63 896The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
b6b9376a
KR
897is first. This means for instance elements greater than 5 can be
898deleted with @code{(delete 5 lst <)}.
899
900@code{delete} does not modify @var{lst}, but the return might share a
901common tail with @var{lst}. @code{delete!} may modify the structure
902of @var{lst} to construct its return.
ea6ea01b 903
4eb21177
KR
904These functions extend the core @code{delete} and @code{delete!}
905(@pxref{List Modification}) in accepting an equality predicate. See
906also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
907deleting multiple elements from a list.
a0e07ba4
NJ
908@end deffn
909
8f85c0c6
NJ
910@deffn {Scheme Procedure} delete-duplicates lst [=]
911@deffnx {Scheme Procedure} delete-duplicates! lst [=]
b6b9376a
KR
912Return a list containing the elements of @var{lst} but without
913duplicates.
914
915When elements are equal, only the first in @var{lst} is retained.
916Equal elements can be anywhere in @var{lst}, they don't have to be
917adjacent. The returned list will have the retained elements in the
918same order as they were in @var{lst}.
919
920Equality is determined by the @var{=} predicate, or @code{equal?} if
921not given. Calls @code{(= x y)} are made with element @var{x} being
922before @var{y} in @var{lst}. A call is made at most once for each
923combination, but the sequence of the calls across the elements is
924unspecified.
925
926@code{delete-duplicates} does not modify @var{lst}, but the return
927might share a common tail with @var{lst}. @code{delete-duplicates!}
928may modify the structure of @var{lst} to construct its return.
929
930In the worst case, this is an @math{O(N^2)} algorithm because it must
931check each element against all those preceding it. For long lists it
932is more efficient to sort and then compare only adjacent elements.
a0e07ba4
NJ
933@end deffn
934
935
936@node SRFI-1 Association Lists
3229f68b 937@subsubsection Association Lists
7c2e18cd
KR
938@cindex association list
939@cindex alist
a0e07ba4
NJ
940
941@c FIXME::martin: Review me!
942
943Association lists are described in detail in section @ref{Association
944Lists}. The present section only documents the additional procedures
945for dealing with association lists defined by SRFI-1.
946
8f85c0c6 947@deffn {Scheme Procedure} assoc key alist [=]
23f2b9a3
KR
948Return the pair from @var{alist} which matches @var{key}. This
949extends the core @code{assoc} (@pxref{Retrieving Alist Entries}) by
950taking an optional @var{=} comparison procedure.
951
952The default comparison is @code{equal?}. If an @var{=} parameter is
953given it's called @code{(@var{=} @var{key} @var{alistcar})}, ie. the
954given target @var{key} is the first argument, and a @code{car} from
955@var{alist} is second.
ea6ea01b 956
23f2b9a3
KR
957For example a case-insensitive string lookup,
958
959@example
960(assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
961@result{} ("YY" . 2)
962@end example
a0e07ba4
NJ
963@end deffn
964
8f85c0c6 965@deffn {Scheme Procedure} alist-cons key datum alist
5e5999f9
KR
966Cons a new association @var{key} and @var{datum} onto @var{alist} and
967return the result. This is equivalent to
a0e07ba4
NJ
968
969@lisp
970(cons (cons @var{key} @var{datum}) @var{alist})
971@end lisp
972
5e5999f9
KR
973@code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
974core does the same thing.
a0e07ba4
NJ
975@end deffn
976
8f85c0c6 977@deffn {Scheme Procedure} alist-copy alist
a0e07ba4
NJ
978Return a newly allocated copy of @var{alist}, that means that the
979spine of the list as well as the pairs are copied.
980@end deffn
981
8f85c0c6
NJ
982@deffn {Scheme Procedure} alist-delete key alist [=]
983@deffnx {Scheme Procedure} alist-delete! key alist [=]
bd35f1f0
KR
984Return a list containing the elements of @var{alist} but with those
985elements whose keys are equal to @var{key} deleted. The returned
986elements will be in the same order as they were in @var{alist}.
a0e07ba4 987
bd35f1f0
KR
988Equality is determined by the @var{=} predicate, or @code{equal?} if
989not given. The order in which elements are tested is unspecified, but
990each equality call is made @code{(= key alistkey)}, ie. the given
991@var{key} parameter is first and the key from @var{alist} second.
992This means for instance all associations with a key greater than 5 can
993be removed with @code{(alist-delete 5 alist <)}.
994
995@code{alist-delete} does not modify @var{alist}, but the return might
996share a common tail with @var{alist}. @code{alist-delete!} may modify
997the list structure of @var{alist} to construct its return.
a0e07ba4
NJ
998@end deffn
999
1000
1001@node SRFI-1 Set Operations
3229f68b 1002@subsubsection Set Operations on Lists
7c2e18cd 1003@cindex list set operation
a0e07ba4 1004
4eb21177
KR
1005Lists can be used to represent sets of objects. The procedures in
1006this section operate on such lists as sets.
1007
1008Note that lists are not an efficient way to implement large sets. The
9aa0c3dd 1009procedures here typically take time @math{@var{m}@cross{}@var{n}} when
4eb21177
KR
1010operating on @var{m} and @var{n} element lists. Other data structures
1011like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
1012Tables}) are faster.
1013
1014All these procedures take an equality predicate as the first argument.
1015This predicate is used for testing the objects in the list sets for
1016sameness. This predicate must be consistent with @code{eq?}
1017(@pxref{Equality}) in the sense that if two list elements are
1018@code{eq?} then they must also be equal under the predicate. This
1019simply means a given object must be equal to itself.
a0e07ba4 1020
4eb21177
KR
1021@deffn {Scheme Procedure} lset<= = list1 list2 @dots{}
1022Return @code{#t} if each list is a subset of the one following it.
1023Ie.@: @var{list1} a subset of @var{list2}, @var{list2} a subset of
1024@var{list3}, etc, for as many lists as given. If only one list or no
1025lists are given then the return is @code{#t}.
1026
1027A list @var{x} is a subset of @var{y} if each element of @var{x} is
1028equal to some element in @var{y}. Elements are compared using the
1029given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
1030
1031@example
1032(lset<= eq?) @result{} #t
1033(lset<= eqv? '(1 2 3) '(1)) @result{} #f
1034(lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
1035@end example
a0e07ba4
NJ
1036@end deffn
1037
8f85c0c6 1038@deffn {Scheme Procedure} lset= = list1 list2 @dots{}
4eb21177
KR
1039Return @code{#t} if all argument lists are set-equal. @var{list1} is
1040compared to @var{list2}, @var{list2} to @var{list3}, etc, for as many
1041lists as given. If only one list or no lists are given then the
1042return is @code{#t}.
1043
1044Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
1045is equal to some element of @var{y} and conversely each element of
1046@var{y} is equal to some element of @var{x}. The order of the
1047elements in the lists doesn't matter. Element equality is determined
1048with the given @var{=} procedure, called as @code{(@var{=} xelem
1049yelem)}, but exactly which calls are made is unspecified.
1050
1051@example
1052(lset= eq?) @result{} #t
1053(lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
1054(lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
1055@end example
a0e07ba4
NJ
1056@end deffn
1057
4eb21177
KR
1058@deffn {Scheme Procedure} lset-adjoin = list elem1 @dots{}
1059Add to @var{list} any of the given @var{elem}s not already in the
1060list. @var{elem}s are @code{cons}ed onto the start of @var{list} (so
1061the return shares a common tail with @var{list}), but the order
1062they're added is unspecified.
1063
1064The given @var{=} procedure is used for comparing elements, called as
1065@code{(@var{=} listelem elem)}, ie.@: the second argument is one of
1066the given @var{elem} parameters.
1067
1068@example
1069(lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
1070@end example
a0e07ba4
NJ
1071@end deffn
1072
4eb21177
KR
1073@deffn {Scheme Procedure} lset-union = list1 list2 @dots{}
1074@deffnx {Scheme Procedure} lset-union! = list1 list2 @dots{}
1075Return the union of the argument list sets. The result is built by
1076taking the union of @var{list1} and @var{list2}, then the union of
1077that with @var{list3}, etc, for as many lists as given. For one list
1078argument that list itself is the result, for no list arguments the
1079result is the empty list.
1080
1081The union of two lists @var{x} and @var{y} is formed as follows. If
1082@var{x} is empty then the result is @var{y}. Otherwise start with
1083@var{x} as the result and consider each @var{y} element (from first to
1084last). A @var{y} element not equal to something already in the result
1085is @code{cons}ed onto the result.
1086
1087The given @var{=} procedure is used for comparing elements, called as
1088@code{(@var{=} relem yelem)}. The first argument is from the result
1089accumulated so far, and the second is from the list being union-ed in.
1090But exactly which calls are made is otherwise unspecified.
1091
1092Notice that duplicate elements in @var{list1} (or the first non-empty
1093list) are preserved, but that repeated elements in subsequent lists
1094are only added once.
1095
1096@example
1097(lset-union eqv?) @result{} ()
1098(lset-union eqv? '(1 2 3)) @result{} (1 2 3)
1099(lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
1100@end example
1101
1102@code{lset-union} doesn't change the given lists but the result may
1103share a tail with the first non-empty list. @code{lset-union!} can
1104modify all of the given lists to form the result.
a0e07ba4
NJ
1105@end deffn
1106
8f85c0c6
NJ
1107@deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
1108@deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
4eb21177
KR
1109Return the intersection of @var{list1} with the other argument lists,
1110meaning those elements of @var{list1} which are also in all of
1111@var{list2} etc. For one list argument, just that list is returned.
1112
1113The test for an element of @var{list1} to be in the return is simply
1114that it's equal to some element in each of @var{list2} etc. Notice
1115this means an element appearing twice in @var{list1} but only once in
1116each of @var{list2} etc will go into the return twice. The return has
1117its elements in the same order as they were in @var{list1}.
1118
1119The given @var{=} procedure is used for comparing elements, called as
1120@code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1121and the second is from one of the subsequent lists. But exactly which
1122calls are made and in what order is unspecified.
1123
1124@example
1125(lset-intersection eqv? '(x y)) @result{} (x y)
1126(lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
1127(lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
1128@end example
1129
1130The return from @code{lset-intersection} may share a tail with
1131@var{list1}. @code{lset-intersection!} may modify @var{list1} to form
1132its result.
a0e07ba4
NJ
1133@end deffn
1134
8f85c0c6
NJ
1135@deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
1136@deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
4eb21177
KR
1137Return @var{list1} with any elements in @var{list2}, @var{list3} etc
1138removed (ie.@: subtracted). For one list argument, just that list is
1139returned.
1140
1141The given @var{=} procedure is used for comparing elements, called as
1142@code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1143and the second from one of the subsequent lists. But exactly which
1144calls are made and in what order is unspecified.
a0e07ba4 1145
4eb21177
KR
1146@example
1147(lset-difference eqv? '(x y)) @result{} (x y)
1148(lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
1149(lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
1150@end example
1151
1152The return from @code{lset-difference} may share a tail with
1153@var{list1}. @code{lset-difference!} may modify @var{list1} to form
1154its result.
a0e07ba4
NJ
1155@end deffn
1156
8f85c0c6
NJ
1157@deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
1158@deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
4eb21177
KR
1159Return two values (@pxref{Multiple Values}), the difference and
1160intersection of the argument lists as per @code{lset-difference} and
1161@code{lset-intersection} above.
1162
1163For two list arguments this partitions @var{list1} into those elements
1164of @var{list1} which are in @var{list2} and not in @var{list2}. (But
1165for more than two arguments there can be elements of @var{list1} which
1166are neither part of the difference nor the intersection.)
1167
1168One of the return values from @code{lset-diff+intersection} may share
1169a tail with @var{list1}. @code{lset-diff+intersection!} may modify
1170@var{list1} to form its results.
1171@end deffn
1172
1173@deffn {Scheme Procedure} lset-xor = list1 list2 @dots{}
1174@deffnx {Scheme Procedure} lset-xor! = list1 list2 @dots{}
1175Return an XOR of the argument lists. For two lists this means those
1176elements which are in exactly one of the lists. For more than two
1177lists it means those elements which appear in an odd number of the
1178lists.
1179
1180To be precise, the XOR of two lists @var{x} and @var{y} is formed by
1181taking those elements of @var{x} not equal to any element of @var{y},
1182plus those elements of @var{y} not equal to any element of @var{x}.
1183Equality is determined with the given @var{=} procedure, called as
1184@code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
1185from @var{y}, but which way around is unspecified. Exactly which
1186calls are made is also unspecified, as is the order of the elements in
1187the result.
1188
1189@example
1190(lset-xor eqv? '(x y)) @result{} (x y)
1191(lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
1192@end example
1193
1194The return from @code{lset-xor} may share a tail with one of the list
1195arguments. @code{lset-xor!} may modify @var{list1} to form its
1196result.
a0e07ba4
NJ
1197@end deffn
1198
1199
1200@node SRFI-2
3229f68b 1201@subsection SRFI-2 - and-let*
8742c48b 1202@cindex SRFI-2
a0e07ba4 1203
4fd0db14
KR
1204@noindent
1205The following syntax can be obtained with
a0e07ba4 1206
4fd0db14
KR
1207@lisp
1208(use-modules (srfi srfi-2))
1209@end lisp
a0e07ba4 1210
4fd0db14
KR
1211@deffn {library syntax} and-let* (clause @dots{}) body @dots{}
1212A combination of @code{and} and @code{let*}.
1213
1214Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
1215then evaluation stops and @code{#f} is returned. If all are
1216non-@code{#f} then @var{body} is evaluated and the last form gives the
6b1a6e4c
KR
1217return value, or if @var{body} is empty then the result is @code{#t}.
1218Each @var{clause} should be one of the following,
4fd0db14
KR
1219
1220@table @code
1221@item (symbol expr)
1222Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
1223Like @code{let*}, that binding is available to subsequent clauses.
1224@item (expr)
1225Evaluate @var{expr} and check for @code{#f}.
1226@item symbol
1227Get the value bound to @var{symbol} and check for @code{#f}.
1228@end table
a0e07ba4 1229
4fd0db14
KR
1230Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
1231instance @code{((eq? x y))}. One way to remember this is to imagine
1232the @code{symbol} in @code{(symbol expr)} is omitted.
a0e07ba4 1233
4fd0db14
KR
1234@code{and-let*} is good for calculations where a @code{#f} value means
1235termination, but where a non-@code{#f} value is going to be needed in
1236subsequent expressions.
1237
1238The following illustrates this, it returns text between brackets
1239@samp{[...]} in a string, or @code{#f} if there are no such brackets
1240(ie.@: either @code{string-index} gives @code{#f}).
1241
1242@example
1243(define (extract-brackets str)
1244 (and-let* ((start (string-index str #\[))
1245 (end (string-index str #\] start)))
1246 (substring str (1+ start) end)))
1247@end example
1248
1249The following shows plain variables and expressions tested too.
1250@code{diagnostic-levels} is taken to be an alist associating a
1251diagnostic type with a level. @code{str} is printed only if the type
1252is known and its level is high enough.
1253
1254@example
1255(define (show-diagnostic type str)
1256 (and-let* (want-diagnostics
1257 (level (assq-ref diagnostic-levels type))
1258 ((>= level current-diagnostic-level)))
1259 (display str)))
1260@end example
1261
1262The advantage of @code{and-let*} is that an extended sequence of
1263expressions and tests doesn't require lots of nesting as would arise
1264from separate @code{and} and @code{let*}, or from @code{cond} with
1265@code{=>}.
1266
1267@end deffn
a0e07ba4
NJ
1268
1269
1270@node SRFI-4
3229f68b 1271@subsection SRFI-4 - Homogeneous numeric vector datatypes
8742c48b 1272@cindex SRFI-4
a0e07ba4 1273
e6b226b9 1274The SRFI-4 procedures and data types are always available, @xref{Uniform
3dd6e0cf 1275Numeric Vectors}.
a0e07ba4
NJ
1276
1277@node SRFI-6
3229f68b 1278@subsection SRFI-6 - Basic String Ports
8742c48b 1279@cindex SRFI-6
a0e07ba4
NJ
1280
1281SRFI-6 defines the procedures @code{open-input-string},
1282@code{open-output-string} and @code{get-output-string}. These
1283procedures are included in the Guile core, so using this module does not
1284make any difference at the moment. But it is possible that support for
1285SRFI-6 will be factored out of the core library in the future, so using
1286this module does not hurt, after all.
1287
1288@node SRFI-8
3229f68b 1289@subsection SRFI-8 - receive
8742c48b 1290@cindex SRFI-8
a0e07ba4
NJ
1291
1292@code{receive} is a syntax for making the handling of multiple-value
1293procedures easier. It is documented in @xref{Multiple Values}.
1294
1295
1296@node SRFI-9
3229f68b 1297@subsection SRFI-9 - define-record-type
8742c48b 1298@cindex SRFI-9
7c2e18cd 1299@cindex record
a0e07ba4 1300
6afe385d
KR
1301This SRFI is a syntax for defining new record types and creating
1302predicate, constructor, and field getter and setter functions. In
1303Guile this is simply an alternate interface to the core record
1304functionality (@pxref{Records}). It can be used with,
a0e07ba4 1305
6afe385d
KR
1306@example
1307(use-modules (srfi srfi-9))
1308@end example
1309
1310@deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
1311@sp 1
1312Create a new record type, and make various @code{define}s for using
1313it. This syntax can only occur at the top-level, not nested within
1314some other form.
1315
1316@var{type} is bound to the record type, which is as per the return
1317from the core @code{make-record-type}. @var{type} also provides the
1318name for the record, as per @code{record-type-name}.
1319
1320@var{constructor} is bound to a function to be called as
1321@code{(@var{constructor} fieldval @dots{})} to create a new record of
1322this type. The arguments are initial values for the fields, one
1323argument for each field, in the order they appear in the
1324@code{define-record-type} form.
1325
1326The @var{fieldname}s provide the names for the record fields, as per
1327the core @code{record-type-fields} etc, and are referred to in the
1328subsequent accessor/modifier forms.
1329
1330@var{predictate} is bound to a function to be called as
1331@code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
1332according to whether @var{obj} is a record of this type.
1333
1334Each @var{accessor} is bound to a function to be called
1335@code{(@var{accessor} record)} to retrieve the respective field from a
1336@var{record}. Similarly each @var{modifier} is bound to a function to
1337be called @code{(@var{modifier} record val)} to set the respective
1338field in a @var{record}.
1339@end deffn
1340
1341@noindent
1342An example will illustrate typical usage,
a0e07ba4
NJ
1343
1344@example
6afe385d
KR
1345(define-record-type employee-type
1346 (make-employee name age salary)
1347 employee?
1348 (name get-employee-name)
1349 (age get-employee-age set-employee-age)
1350 (salary get-employee-salary set-employee-salary))
a0e07ba4
NJ
1351@end example
1352
6afe385d
KR
1353This creates a new employee data type, with name, age and salary
1354fields. Accessor functions are created for each field, but no
1355modifier function for the name (the intention in this example being
1356that it's established only when an employee object is created). These
1357can all then be used as for example,
a0e07ba4
NJ
1358
1359@example
6afe385d
KR
1360employee-type @result{} #<record-type employee-type>
1361
1362(define fred (make-employee "Fred" 45 20000.00))
1363
1364(employee? fred) @result{} #t
1365(get-employee-age fred) @result{} 45
1366(set-employee-salary fred 25000.00) ;; pay rise
a0e07ba4
NJ
1367@end example
1368
6afe385d
KR
1369The functions created by @code{define-record-type} are ordinary
1370top-level @code{define}s. They can be redefined or @code{set!} as
1371desired, exported from a module, etc.
1372
a0e07ba4
NJ
1373
1374@node SRFI-10
3229f68b 1375@subsection SRFI-10 - Hash-Comma Reader Extension
8742c48b 1376@cindex SRFI-10
a0e07ba4
NJ
1377
1378@cindex hash-comma
1379@cindex #,()
633acbe2
KR
1380This SRFI implements a reader extension @code{#,()} called hash-comma.
1381It allows the reader to give new kinds of objects, for use both in
1382data and as constants or literals in source code. This feature is
1383available with
a0e07ba4 1384
633acbe2
KR
1385@example
1386(use-modules (srfi srfi-10))
1387@end example
1388
1389@noindent
1390The new read syntax is of the form
a0e07ba4
NJ
1391
1392@example
633acbe2 1393#,(@var{tag} @var{arg}@dots{})
a0e07ba4
NJ
1394@end example
1395
633acbe2
KR
1396@noindent
1397where @var{tag} is a symbol and the @var{arg}s are objects taken as
1398parameters. @var{tag}s are registered with the following procedure.
a0e07ba4 1399
633acbe2
KR
1400@deffn {Scheme Procedure} define-reader-ctor tag proc
1401Register @var{proc} as the constructor for a hash-comma read syntax
1402starting with symbol @var{tag}, ie. @nicode{#,(@var{tag} arg@dots{})}.
1403@var{proc} is called with the given arguments @code{(@var{proc}
1404arg@dots{})} and the object it returns is the result of the read.
1405@end deffn
a0e07ba4 1406
633acbe2
KR
1407@noindent
1408For example, a syntax giving a list of @var{N} copies of an object.
1409
1410@example
1411(define-reader-ctor 'repeat
1412 (lambda (obj reps)
1413 (make-list reps obj)))
1414
1415(display '#,(repeat 99 3))
1416@print{} (99 99 99)
1417@end example
1418
1419Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
1420@code{repeat} handler returns a list and the program must quote to use
1421it literally, the same as any other list. Ie.
1422
1423@example
1424(display '#,(repeat 99 3))
a0e07ba4 1425@result{}
633acbe2
KR
1426(display '(99 99 99))
1427@end example
a0e07ba4 1428
633acbe2
KR
1429When a handler returns an object which is self-evaluating, like a
1430number or a string, then there's no need for quoting, just as there's
1431no need when giving those directly as literals. For example an
1432addition,
a0e07ba4 1433
633acbe2
KR
1434@example
1435(define-reader-ctor 'sum
1436 (lambda (x y)
1437 (+ x y)))
1438(display #,(sum 123 456)) @print{} 579
1439@end example
1440
1441A typical use for @nicode{#,()} is to get a read syntax for objects
1442which don't otherwise have one. For example, the following allows a
1443hash table to be given literally, with tags and values, ready for fast
1444lookup.
1445
1446@example
1447(define-reader-ctor 'hash
1448 (lambda elems
1449 (let ((table (make-hash-table)))
1450 (for-each (lambda (elem)
01549abb
KR
1451 (apply hash-set! table elem))
1452 elems)
633acbe2
KR
1453 table)))
1454
1455(define (animal->family animal)
1456 (hash-ref '#,(hash ("tiger" "cat")
1457 ("lion" "cat")
1458 ("wolf" "dog"))
1459 animal))
1460
1461(animal->family "lion") @result{} "cat"
1462@end example
1463
1464Or for example the following is a syntax for a compiled regular
1465expression (@pxref{Regular Expressions}).
1466
1467@example
1468(use-modules (ice-9 regex))
1469
1470(define-reader-ctor 'regexp make-regexp)
1471
1472(define (extract-angs str)
1473 (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
1474 (and match
1475 (match:substring match 1))))
1476
1477(extract-angs "foo <BAR> quux") @result{} "BAR"
1478@end example
1479
1480@sp 1
1481@nicode{#,()} is somewhat similar to @code{define-macro}
1482(@pxref{Macros}) in that handler code is run to produce a result, but
1483@nicode{#,()} operates at the read stage, so it can appear in data for
1484@code{read} (@pxref{Scheme Read}), not just in code to be executed.
1485
1486Because @nicode{#,()} is handled at read-time it has no direct access
1487to variables etc. A symbol in the arguments is just a symbol, not a
1488variable reference. The arguments are essentially constants, though
1489the handler procedure can use them in any complicated way it might
1490want.
1491
1492Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
1493globally, there's no need to use @code{(srfi srfi-10)} in later
1494modules. Similarly the tags registered are global and can be used
1495anywhere once registered.
1496
1497There's no attempt to record what previous @nicode{#,()} forms have
1498been seen, if two identical forms occur then two calls are made to the
1499handler procedure. The handler might like to maintain a cache or
1500similar to avoid making copies of large objects, depending on expected
1501usage.
1502
1503In code the best uses of @nicode{#,()} are generally when there's a
1504lot of objects of a particular kind as literals or constants. If
1505there's just a few then some local variables and initializers are
1506fine, but that becomes tedious and error prone when there's a lot, and
1507the anonymous and compact syntax of @nicode{#,()} is much better.
a0e07ba4
NJ
1508
1509
1510@node SRFI-11
3229f68b 1511@subsection SRFI-11 - let-values
8742c48b 1512@cindex SRFI-11
a0e07ba4 1513
8742c48b
KR
1514@findex let-values
1515@findex let-values*
a0e07ba4
NJ
1516This module implements the binding forms for multiple values
1517@code{let-values} and @code{let-values*}. These forms are similar to
1518@code{let} and @code{let*} (@pxref{Local Bindings}), but they support
1519binding of the values returned by multiple-valued expressions.
1520
1521Write @code{(use-modules (srfi srfi-11))} to make the bindings
1522available.
1523
1524@lisp
1525(let-values (((x y) (values 1 2))
1526 ((z f) (values 3 4)))
1527 (+ x y z f))
1528@result{}
152910
1530@end lisp
1531
1532@code{let-values} performs all bindings simultaneously, which means that
1533no expression in the binding clauses may refer to variables bound in the
1534same clause list. @code{let-values*}, on the other hand, performs the
1535bindings sequentially, just like @code{let*} does for single-valued
1536expressions.
1537
1538
1539@node SRFI-13
3229f68b 1540@subsection SRFI-13 - String Library
8742c48b 1541@cindex SRFI-13
a0e07ba4 1542
5676b4fa 1543The SRFI-13 procedures are always available, @xref{Strings}.
a0e07ba4
NJ
1544
1545@node SRFI-14
3229f68b 1546@subsection SRFI-14 - Character-set Library
8742c48b 1547@cindex SRFI-14
a0e07ba4 1548
050ab45f
MV
1549The SRFI-14 data type and procedures are always available,
1550@xref{Character Sets}.
a0e07ba4
NJ
1551
1552@node SRFI-16
3229f68b 1553@subsection SRFI-16 - case-lambda
8742c48b 1554@cindex SRFI-16
7c2e18cd
KR
1555@cindex variable arity
1556@cindex arity, variable
a0e07ba4
NJ
1557
1558@c FIXME::martin: Review me!
1559
8742c48b 1560@findex case-lambda
a0e07ba4
NJ
1561The syntactic form @code{case-lambda} creates procedures, just like
1562@code{lambda}, but has syntactic extensions for writing procedures of
1563varying arity easier.
1564
1565The syntax of the @code{case-lambda} form is defined in the following
1566EBNF grammar.
1567
1568@example
1569@group
1570<case-lambda>
1571 --> (case-lambda <case-lambda-clause>)
1572<case-lambda-clause>
1573 --> (<formals> <definition-or-command>*)
1574<formals>
1575 --> (<identifier>*)
1576 | (<identifier>* . <identifier>)
1577 | <identifier>
1578@end group
1579@end example
1580
1581The value returned by a @code{case-lambda} form is a procedure which
1582matches the number of actual arguments against the formals in the
1583various clauses, in order. @dfn{Formals} means a formal argument list
1584just like with @code{lambda} (@pxref{Lambda}). The first matching clause
1585is selected, the corresponding values from the actual parameter list are
1586bound to the variable names in the clauses and the body of the clause is
1587evaluated. If no clause matches, an error is signalled.
1588
1589The following (silly) definition creates a procedure @var{foo} which
1590acts differently, depending on the number of actual arguments. If one
1591argument is given, the constant @code{#t} is returned, two arguments are
1592added and if more arguments are passed, their product is calculated.
1593
1594@lisp
1595(define foo (case-lambda
1596 ((x) #t)
1597 ((x y) (+ x y))
1598 (z
1599 (apply * z))))
1600(foo 'bar)
1601@result{}
1602#t
1603(foo 2 4)
1604@result{}
16056
1606(foo 3 3 3)
1607@result{}
160827
1609(foo)
1610@result{}
16111
1612@end lisp
1613
1614The last expression evaluates to 1 because the last clause is matched,
1615@var{z} is bound to the empty list and the following multiplication,
1616applied to zero arguments, yields 1.
1617
1618
1619@node SRFI-17
3229f68b 1620@subsection SRFI-17 - Generalized set!
8742c48b 1621@cindex SRFI-17
a0e07ba4 1622
9a18d8d4
KR
1623This SRFI implements a generalized @code{set!}, allowing some
1624``referencing'' functions to be used as the target location of a
1625@code{set!}. This feature is available from
1626
1627@example
1628(use-modules (srfi srfi-17))
1629@end example
1630
1631@noindent
1632For example @code{vector-ref} is extended so that
1633
1634@example
1635(set! (vector-ref vec idx) new-value)
1636@end example
1637
1638@noindent
1639is equivalent to
1640
1641@example
1642(vector-set! vec idx new-value)
1643@end example
1644
1645The idea is that a @code{vector-ref} expression identifies a location,
1646which may be either fetched or stored. The same form is used for the
1647location in both cases, encouraging visual clarity. This is similar
1648to the idea of an ``lvalue'' in C.
1649
1650The mechanism for this kind of @code{set!} is in the Guile core
1651(@pxref{Procedures with Setters}). This module adds definitions of
1652the following functions as procedures with setters, allowing them to
1653be targets of a @code{set!},
1654
1655@quotation
1656@nicode{car}, @nicode{cdr}, @nicode{caar}, @nicode{cadr},
1657@nicode{cdar}, @nicode{cddr}, @nicode{caaar}, @nicode{caadr},
1658@nicode{cadar}, @nicode{caddr}, @nicode{cdaar}, @nicode{cdadr},
1659@nicode{cddar}, @nicode{cdddr}, @nicode{caaaar}, @nicode{caaadr},
1660@nicode{caadar}, @nicode{caaddr}, @nicode{cadaar}, @nicode{cadadr},
1661@nicode{caddar}, @nicode{cadddr}, @nicode{cdaaar}, @nicode{cdaadr},
1662@nicode{cdadar}, @nicode{cdaddr}, @nicode{cddaar}, @nicode{cddadr},
1663@nicode{cdddar}, @nicode{cddddr}
1664
1665@nicode{string-ref}, @nicode{vector-ref}
1666@end quotation
1667
1668The SRFI specifies @code{setter} (@pxref{Procedures with Setters}) as
1669a procedure with setter, allowing the setter for a procedure to be
1670changed, eg.@: @code{(set! (setter foo) my-new-setter-handler)}.
1671Currently Guile does not implement this, a setter can only be
1672specified on creation (@code{getter-with-setter} below).
1673
1674@defun getter-with-setter
1675The same as the Guile core @code{make-procedure-with-setter}
1676(@pxref{Procedures with Setters}).
1677@end defun
a0e07ba4 1678
12991fed
TTN
1679
1680@node SRFI-19
3229f68b 1681@subsection SRFI-19 - Time/Date Library
8742c48b 1682@cindex SRFI-19
7c2e18cd
KR
1683@cindex time
1684@cindex date
12991fed 1685
85600a0f
KR
1686This is an implementation of the SRFI-19 time/date library. The
1687functions and variables described here are provided by
12991fed
TTN
1688
1689@example
85600a0f 1690(use-modules (srfi srfi-19))
12991fed
TTN
1691@end example
1692
7d281fa5
KR
1693@strong{Caution}: The current code in this module incorrectly extends
1694the Gregorian calendar leap year rule back prior to the introduction
1695of those reforms in 1582 (or the appropriate year in various
1696countries). The Julian calendar was used prior to 1582, and there
1697were 10 days skipped for the reform, but the code doesn't implement
1698that.
1699
1700This will be fixed some time. Until then calculations for 1583
1701onwards are correct, but prior to that any day/month/year and day of
1702the week calculations are wrong.
1703
85600a0f
KR
1704@menu
1705* SRFI-19 Introduction::
1706* SRFI-19 Time::
1707* SRFI-19 Date::
1708* SRFI-19 Time/Date conversions::
1709* SRFI-19 Date to string::
1710* SRFI-19 String to date::
1711@end menu
12991fed 1712
85600a0f 1713@node SRFI-19 Introduction
3229f68b 1714@subsubsection SRFI-19 Introduction
85600a0f
KR
1715
1716@cindex universal time
1717@cindex atomic time
1718@cindex UTC
1719@cindex TAI
1720This module implements time and date representations and calculations,
1721in various time systems, including universal time (UTC) and atomic
1722time (TAI).
1723
1724For those not familiar with these time systems, TAI is based on a
1725fixed length second derived from oscillations of certain atoms. UTC
1726differs from TAI by an integral number of seconds, which is increased
1727or decreased at announced times to keep UTC aligned to a mean solar
1728day (the orbit and rotation of the earth are not quite constant).
1729
1730@cindex leap second
1731So far, only increases in the TAI
1732@tex
1733$\leftrightarrow$
1734@end tex
1735@ifnottex
1736<->
1737@end ifnottex
1738UTC difference have been needed. Such an increase is a ``leap
1739second'', an extra second of TAI introduced at the end of a UTC day.
1740When working entirely within UTC this is never seen, every day simply
1741has 86400 seconds. But when converting from TAI to a UTC date, an
1742extra 23:59:60 is present, where normally a day would end at 23:59:59.
1743Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
1744seconds.
1745
1746@cindex system clock
1747In the current implementation, the system clock is assumed to be UTC,
1748and a table of leap seconds in the code converts to TAI. See comments
1749in @file{srfi-19.scm} for how to update this table.
1750
1751@cindex julian day
1752@cindex modified julian day
1753Also, for those not familiar with the terminology, a @dfn{Julian Day}
1754is a real number which is a count of days and fraction of a day, in
1755UTC, starting from -4713-01-01T12:00:00Z, ie.@: midday Monday 1 Jan
7c2e18cd
KR
17564713 B.C. A @dfn{Modified Julian Day} is the same, but starting from
17571858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. That time
1758is julian day 2400000.5.
85600a0f
KR
1759
1760@c The SRFI-1 spec says -4714-11-24T12:00:00Z (November 24, -4714 at
1761@c noon, UTC), but this is incorrect. It looks like it might have
1762@c arisen from the code incorrectly treating years a multiple of 100
7c2e18cd 1763@c but not 400 prior to 1582 as non-leap years, where instead the Julian
85600a0f
KR
1764@c calendar should be used so all multiples of 4 before 1582 are leap
1765@c years.
1766
1767
1768@node SRFI-19 Time
3229f68b 1769@subsubsection SRFI-19 Time
85600a0f
KR
1770@cindex time
1771
1772A @dfn{time} object has type, seconds and nanoseconds fields
1773representing a point in time starting from some epoch. This is an
1774arbitrary point in time, not just a time of day. Although times are
1775represented in nanoseconds, the actual resolution may be lower.
1776
1777The following variables hold the possible time types. For instance
1778@code{(current-time time-process)} would give the current CPU process
1779time.
1780
1781@defvar time-utc
1782Universal Coordinated Time (UTC).
1783@cindex UTC
1784@end defvar
12991fed 1785
85600a0f
KR
1786@defvar time-tai
1787International Atomic Time (TAI).
1788@cindex TAI
1789@end defvar
12991fed 1790
85600a0f
KR
1791@defvar time-monotonic
1792Monotonic time, meaning a monotonically increasing time starting from
1793an unspecified epoch.
12991fed 1794
85600a0f
KR
1795Note that in the current implementation @code{time-monotonic} is the
1796same as @code{time-tai}, and unfortunately is therefore affected by
1797adjustments to the system clock. Perhaps this will change in the
1798future.
1799@end defvar
12991fed 1800
85600a0f
KR
1801@defvar time-duration
1802A duration, meaning simply a difference between two times.
1803@end defvar
12991fed 1804
85600a0f
KR
1805@defvar time-process
1806CPU time spent in the current process, starting from when the process
1807began.
1808@cindex process time
1809@end defvar
12991fed 1810
85600a0f
KR
1811@defvar time-thread
1812CPU time spent in the current thread. Not currently implemented.
1813@cindex thread time
1814@end defvar
12991fed 1815
85600a0f
KR
1816@sp 1
1817@defun time? obj
1818Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
1819@end defun
1820
1821@defun make-time type nanoseconds seconds
1822Create a time object with the given @var{type}, @var{seconds} and
1823@var{nanoseconds}.
1824@end defun
1825
1826@defun time-type time
1827@defunx time-nanosecond time
1828@defunx time-second time
1829@defunx set-time-type! time type
1830@defunx set-time-nanosecond! time nsec
1831@defunx set-time-second! time sec
1832Get or set the type, seconds or nanoseconds fields of a time object.
1833
1834@code{set-time-type!} merely changes the field, it doesn't convert the
1835time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
1836@end defun
1837
1838@defun copy-time time
1839Return a new time object, which is a copy of the given @var{time}.
1840@end defun
1841
1842@defun current-time [type]
1843Return the current time of the given @var{type}. The default
1844@var{type} is @code{time-utc}.
1845
1846Note that the name @code{current-time} conflicts with the Guile core
1847@code{current-time} function (@pxref{Time}). Applications wanting to
1848use both will need to use a different name for one of them.
1849@end defun
1850
1851@defun time-resolution [type]
1852Return the resolution, in nanoseconds, of the given time @var{type}.
1853The default @var{type} is @code{time-utc}.
1854@end defun
1855
1856@defun time<=? t1 t2
1857@defunx time<? t1 t2
1858@defunx time=? t1 t2
1859@defunx time>=? t1 t2
1860@defunx time>? t1 t2
1861Return @code{#t} or @code{#f} according to the respective relation
1862between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
1863must be the same time type.
1864@end defun
1865
1866@defun time-difference t1 t2
1867@defunx time-difference! t1 t2
1868Return a time object of type @code{time-duration} representing the
1869period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
1870the same time type.
1871
1872@code{time-difference} returns a new time object,
1873@code{time-difference!} may modify @var{t1} to form its return.
1874@end defun
1875
1876@defun add-duration time duration
1877@defunx add-duration! time duration
1878@defunx subtract-duration time duration
1879@defunx subtract-duration! time duration
1880Return a time object which is @var{time} with the given @var{duration}
1881added or subtracted. @var{duration} must be a time object of type
1882@code{time-duration}.
1883
1884@code{add-duration} and @code{subtract-duration} return a new time
1885object. @code{add-duration!} and @code{subtract-duration!} may modify
1886the given @var{time} to form their return.
1887@end defun
1888
1889
1890@node SRFI-19 Date
3229f68b 1891@subsubsection SRFI-19 Date
85600a0f
KR
1892@cindex date
1893
1894A @dfn{date} object represents a date in the Gregorian calendar and a
1895time of day on that date in some timezone.
1896
1897The fields are year, month, day, hour, minute, second, nanoseconds and
1898timezone. A date object is immutable, its fields can be read but they
1899cannot be modified once the object is created.
1900
1901@defun date? obj
1902Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
1903@end defun
1904
1905@defun make-date nsecs seconds minutes hours date month year zone-offset
1906Create a new date object.
1907@c
1908@c FIXME: What can we say about the ranges of the values. The
1909@c current code looks it doesn't normalize, but expects then in their
1910@c usual range already.
1911@c
1912@end defun
1913
1914@defun date-nanosecond date
1915Nanoseconds, 0 to 999999999.
1916@end defun
1917
1918@defun date-second date
7c2e18cd
KR
1919Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
1920entirely within UTC, it's only when converting to or from TAI.
85600a0f
KR
1921@end defun
1922
1923@defun date-minute date
1924Minutes, 0 to 59.
1925@end defun
1926
1927@defun date-hour date
1928Hour, 0 to 23.
1929@end defun
1930
1931@defun date-day date
1932Day of the month, 1 to 31 (or less, according to the month).
1933@end defun
1934
1935@defun date-month date
1936Month, 1 to 12.
1937@end defun
1938
1939@defun date-year date
7c2e18cd
KR
1940Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
1941B.C. There is no year 0, year @math{-1} is followed by year 1.
85600a0f
KR
1942@end defun
1943
1944@defun date-zone-offset date
1945Time zone, an integer number of seconds east of Greenwich.
1946@end defun
1947
1948@defun date-year-day date
1949Day of the year, starting from 1 for 1st January.
1950@end defun
1951
1952@defun date-week-day date
1953Day of the week, starting from 0 for Sunday.
1954@end defun
1955
1956@defun date-week-number date dstartw
1957Week of the year, ignoring a first partial week. @var{dstartw} is the
1958day of the week which is taken to start a week, 0 for Sunday, 1 for
1959Monday, etc.
1960@c
1961@c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
1962@c The code looks like it's 0, if that's the correct intention.
1963@c
1964@end defun
1965
1966@c The SRFI text doesn't actually give the default for tz-offset, but
1967@c the reference implementation has the local timezone and the
1968@c conversions functions all specify that, so it should be ok to
1969@c document it here.
1970@c
1971@defun current-date [tz-offset]
7c2e18cd
KR
1972Return a date object representing the current date/time, in UTC offset
1973by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
1974defaults to the local timezone.
85600a0f
KR
1975@end defun
1976
1977@defun current-julian-day
1978@cindex julian day
1979Return the current Julian Day.
1980@end defun
1981
1982@defun current-modified-julian-day
1983@cindex modified julian day
1984Return the current Modified Julian Day.
1985@end defun
1986
1987
1988@node SRFI-19 Time/Date conversions
3229f68b 1989@subsubsection SRFI-19 Time/Date conversions
7c2e18cd
KR
1990@cindex time conversion
1991@cindex date conversion
85600a0f
KR
1992
1993@defun date->julian-day date
1994@defunx date->modified-julian-day date
1995@defunx date->time-monotonic date
1996@defunx date->time-tai date
1997@defunx date->time-utc date
1998@end defun
1999@defun julian-day->date jdn [tz-offset]
2000@defunx julian-day->time-monotonic jdn
2001@defunx julian-day->time-tai jdn
2002@defunx julian-day->time-utc jdn
2003@end defun
2004@defun modified-julian-day->date jdn [tz-offset]
2005@defunx modified-julian-day->time-monotonic jdn
2006@defunx modified-julian-day->time-tai jdn
2007@defunx modified-julian-day->time-utc jdn
2008@end defun
2009@defun time-monotonic->date time [tz-offset]
2010@defunx time-monotonic->time-tai time
2011@defunx time-monotonic->time-tai! time
2012@defunx time-monotonic->time-utc time
2013@defunx time-monotonic->time-utc! time
2014@end defun
2015@defun time-tai->date time [tz-offset]
2016@defunx time-tai->julian-day time
2017@defunx time-tai->modified-julian-day time
2018@defunx time-tai->time-monotonic time
2019@defunx time-tai->time-monotonic! time
2020@defunx time-tai->time-utc time
2021@defunx time-tai->time-utc! time
2022@end defun
2023@defun time-utc->date time [tz-offset]
2024@defunx time-utc->julian-day time
2025@defunx time-utc->modified-julian-day time
2026@defunx time-utc->time-monotonic time
2027@defunx time-utc->time-monotonic! time
2028@defunx time-utc->time-tai time
2029@defunx time-utc->time-tai! time
2030@sp 1
2031Convert between dates, times and days of the respective types. For
2032instance @code{time-tai->time-utc} accepts a @var{time} object of type
2033@code{time-tai} and returns an object of type @code{time-utc}.
2034
85600a0f
KR
2035The @code{!} variants may modify their @var{time} argument to form
2036their return. The plain functions create a new object.
702e6e09
KR
2037
2038For conversions to dates, @var{tz-offset} is seconds east of
2039Greenwich. The default is the local timezone, at the given time, as
2040provided by the system, using @code{localtime} (@pxref{Time}).
2041
2042On 32-bit systems, @code{localtime} is limited to a 32-bit
2043@code{time_t}, so a default @var{tz-offset} is only available for
2044times between Dec 1901 and Jan 2038. For prior dates an application
2045might like to use the value in 1902, though some locations have zone
2046changes prior to that. For future dates an application might like to
2047assume today's rules extend indefinitely. But for correct daylight
2048savings transitions it will be necessary to take an offset for the
2049same day and time but a year in range and which has the same starting
2050weekday and same leap/non-leap (to support rules like last Sunday in
2051October).
85600a0f
KR
2052@end defun
2053
2054@node SRFI-19 Date to string
3229f68b 2055@subsubsection SRFI-19 Date to string
85600a0f 2056@cindex date to string
7c2e18cd 2057@cindex string, from date
85600a0f
KR
2058
2059@defun date->string date [format]
2060Convert a date to a string under the control of a format.
2061@var{format} should be a string containing @samp{~} escapes, which
2062will be expanded as per the following conversion table. The default
2063@var{format} is @samp{~c}, a locale-dependent date and time.
2064
2065Many of these conversion characters are the same as POSIX
2066@code{strftime} (@pxref{Time}), but there are some extras and some
2067variations.
2068
2069@multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
2070@item @nicode{~~} @tab literal ~
2071@item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
2072@item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
2073@item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
2074@item @nicode{~B} @tab locale full month, eg.@: @samp{January}
2075@item @nicode{~c} @tab locale date and time, eg.@: @*
2076@samp{Fri Jul 14 20:28:42-0400 2000}
2077@item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
2078
2079@c Spec says d/m/y, reference implementation says m/d/y.
2080@c Apparently the reference code was the intention, but would like to
2081@c see an errata published for the spec before contradicting it here.
2082@c
2083@c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
2084
2085@item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
2086@item @nicode{~f} @tab seconds and fractional seconds,
2087with locale decimal point, eg.@: @samp{5.2}
2088@item @nicode{~h} @tab same as @nicode{~b}
2089@item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
2090@item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
2091@item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
2092@item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
2093@item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
2094@item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
2095@item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
2096@item @nicode{~n} @tab newline
2097@item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
2098@item @nicode{~p} @tab locale AM or PM
2099@item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
2100@item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
2101@item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
2102(usual limit is 59, 60 is a leap second)
2103@item @nicode{~t} @tab horizontal tab character
2104@item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
2105@item @nicode{~U} @tab week of year, Sunday first day of week,
2106@samp{00} to @samp{52}
2107@item @nicode{~V} @tab week of year, Monday first day of week,
2108@samp{01} to @samp{53}
2109@item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
2110@item @nicode{~W} @tab week of year, Monday first day of week,
2111@samp{00} to @samp{52}
2112
2113@c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
2114@c date. The reference code has ~x as the locale date and ~X as a
2115@c locale time. The rule is apparently that the code should be
2116@c believed, but would like to see an errata for the spec before
2117@c contradicting it here.
2118@c
2119@c @item @nicode{~x} @tab week of year, Monday as first day of week,
2120@c @samp{00} to @samp{53}
2121@c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
2122
2123@item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
2124@item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
2125@item @nicode{~z} @tab time zone, RFC-822 style
2126@item @nicode{~Z} @tab time zone symbol (not currently implemented)
2127@item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
2128@item @nicode{~2} @tab ISO-8601 time+zone, @samp{~k:~M:~S~z}
2129@item @nicode{~3} @tab ISO-8601 time, @samp{~k:~M:~S}
2130@item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~k:~M:~S~z}
2131@item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~k:~M:~S}
2132@end multitable
2133@end defun
2134
2135Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
2136described here, since the specification and reference implementation
2137differ.
2138
a2f00b9b
LC
2139Conversion is locale-dependent on systems that support it
2140(@pxref{Accessing Locale Information}). @xref{Locales,
2141@code{setlocale}}, for information on how to change the current
2142locale.
85600a0f
KR
2143
2144
2145@node SRFI-19 String to date
3229f68b 2146@subsubsection SRFI-19 String to date
85600a0f 2147@cindex string to date
7c2e18cd 2148@cindex date, from string
85600a0f
KR
2149
2150@c FIXME: Can we say what happens when an incomplete date is
2151@c converted? Ie. fields left as 0, or what? The spec seems to be
2152@c silent on this.
2153
2154@defun string->date input template
2155Convert an @var{input} string to a date under the control of a
2156@var{template} string. Return a newly created date object.
2157
2158Literal characters in @var{template} must match characters in
2159@var{input} and @samp{~} escapes must match the input forms described
2160in the table below. ``Skip to'' means characters up to one of the
2161given type are ignored, or ``no skip'' for no skipping. ``Read'' is
2162what's then read, and ``Set'' is the field affected in the date
2163object.
2164
2165For example @samp{~Y} skips input characters until a digit is reached,
2166at which point it expects a year and stores that to the year field of
2167the date.
2168
2169@multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
2170@item
2171@tab Skip to
2172@tab Read
2173@tab Set
2174
2175@item @nicode{~~}
2176@tab no skip
2177@tab literal ~
2178@tab nothing
2179
2180@item @nicode{~a}
2181@tab @nicode{char-alphabetic?}
2182@tab locale abbreviated weekday name
2183@tab nothing
2184
2185@item @nicode{~A}
2186@tab @nicode{char-alphabetic?}
2187@tab locale full weekday name
2188@tab nothing
2189
2190@c Note that the SRFI spec says that ~b and ~B don't set anything,
2191@c but that looks like a mistake. The reference implementation sets
2192@c the month field, which seems sensible and is what we describe
2193@c here.
2194
2195@item @nicode{~b}
2196@tab @nicode{char-alphabetic?}
2197@tab locale abbreviated month name
2198@tab @nicode{date-month}
2199
2200@item @nicode{~B}
2201@tab @nicode{char-alphabetic?}
2202@tab locale full month name
2203@tab @nicode{date-month}
2204
2205@item @nicode{~d}
2206@tab @nicode{char-numeric?}
2207@tab day of month
2208@tab @nicode{date-day}
2209
2210@item @nicode{~e}
2211@tab no skip
2212@tab day of month, blank padded
2213@tab @nicode{date-day}
2214
2215@item @nicode{~h}
2216@tab same as @samp{~b}
2217
2218@item @nicode{~H}
2219@tab @nicode{char-numeric?}
2220@tab hour
2221@tab @nicode{date-hour}
2222
2223@item @nicode{~k}
2224@tab no skip
2225@tab hour, blank padded
2226@tab @nicode{date-hour}
2227
2228@item @nicode{~m}
2229@tab @nicode{char-numeric?}
2230@tab month
2231@tab @nicode{date-month}
2232
2233@item @nicode{~M}
2234@tab @nicode{char-numeric?}
2235@tab minute
2236@tab @nicode{date-minute}
2237
2238@item @nicode{~S}
2239@tab @nicode{char-numeric?}
2240@tab second
2241@tab @nicode{date-second}
2242
2243@item @nicode{~y}
2244@tab no skip
2245@tab 2-digit year
2246@tab @nicode{date-year} within 50 years
2247
2248@item @nicode{~Y}
2249@tab @nicode{char-numeric?}
2250@tab year
2251@tab @nicode{date-year}
2252
2253@item @nicode{~z}
2254@tab no skip
2255@tab time zone
2256@tab date-zone-offset
2257@end multitable
2258
2259Notice that the weekday matching forms don't affect the date object
2260returned, instead the weekday will be derived from the day, month and
2261year.
2262
a2f00b9b
LC
2263Conversion is locale-dependent on systems that support it
2264(@pxref{Accessing Locale Information}). @xref{Locales,
2265@code{setlocale}}, for information on how to change the current
2266locale.
85600a0f 2267@end defun
12991fed 2268
1de8c1ae 2269
b0b55bd6 2270@node SRFI-26
3229f68b 2271@subsection SRFI-26 - specializing parameters
1de8c1ae 2272@cindex SRFI-26
7c2e18cd
KR
2273@cindex parameter specialize
2274@cindex argument specialize
2275@cindex specialize parameter
1de8c1ae
KR
2276
2277This SRFI provides a syntax for conveniently specializing selected
2278parameters of a function. It can be used with,
2279
2280@example
2281(use-modules (srfi srfi-26))
2282@end example
2283
2284@deffn {library syntax} cut slot @dots{}
2285@deffnx {library syntax} cute slot @dots{}
2286Return a new procedure which will make a call (@var{slot} @dots{}) but
2287with selected parameters specialized to given expressions.
2288
2289An example will illustrate the idea. The following is a
2290specialization of @code{write}, sending output to
2291@code{my-output-port},
2292
2293@example
2294(cut write <> my-output-port)
2295@result{}
2296(lambda (obj) (write obj my-output-port))
2297@end example
2298
2299The special symbol @code{<>} indicates a slot to be filled by an
2300argument to the new procedure. @code{my-output-port} on the other
2301hand is an expression to be evaluated and passed, ie.@: it specializes
2302the behaviour of @code{write}.
2303
2304@table @nicode
2305@item <>
2306A slot to be filled by an argument from the created procedure.
2307Arguments are assigned to @code{<>} slots in the order they appear in
2308the @code{cut} form, there's no way to re-arrange arguments.
2309
2310The first argument to @code{cut} is usually a procedure (or expression
2311giving a procedure), but @code{<>} is allowed there too. For example,
2312
2313@example
2314(cut <> 1 2 3)
2315@result{}
2316(lambda (proc) (proc 1 2 3))
2317@end example
2318
2319@item <...>
2320A slot to be filled by all remaining arguments from the new procedure.
2321This can only occur at the end of a @code{cut} form.
2322
2323For example, a procedure taking a variable number of arguments like
2324@code{max} but in addition enforcing a lower bound,
2325
2326@example
2327(define my-lower-bound 123)
2328
2329(cut max my-lower-bound <...>)
2330@result{}
2331(lambda arglist (apply max my-lower-bound arglist))
2332@end example
2333@end table
2334
2335For @code{cut} the specializing expressions are evaluated each time
2336the new procedure is called. For @code{cute} they're evaluated just
2337once, when the new procedure is created. The name @code{cute} stands
2338for ``@code{cut} with evaluated arguments''. In all cases the
2339evaluations take place in an unspecified order.
2340
2341The following illustrates the difference between @code{cut} and
2342@code{cute},
2343
2344@example
2345(cut format <> "the time is ~s" (current-time))
2346@result{}
2347(lambda (port) (format port "the time is ~s" (current-time)))
2348
2349(cute format <> "the time is ~s" (current-time))
2350@result{}
2351(let ((val (current-time)))
2352 (lambda (port) (format port "the time is ~s" val))
2353@end example
2354
2355(There's no provision for a mixture of @code{cut} and @code{cute}
2356where some expressions would be evaluated every time but others
2357evaluated only once.)
2358
2359@code{cut} is really just a shorthand for the sort of @code{lambda}
2360forms shown in the above examples. But notice @code{cut} avoids the
2361need to name unspecialized parameters, and is more compact. Use in
2362functional programming style or just with @code{map}, @code{for-each}
2363or similar is typical.
2364
2365@example
2366(map (cut * 2 <>) '(1 2 3 4))
2367
2368(for-each (cut write <> my-port) my-list)
2369@end example
2370@end deffn
b0b55bd6 2371
8638c417
RB
2372@node SRFI-31
2373@subsection SRFI-31 - A special form `rec' for recursive evaluation
2374@cindex SRFI-31
7c2e18cd 2375@cindex recursive expression
8638c417
RB
2376@findex rec
2377
2378SRFI-31 defines a special form that can be used to create
2379self-referential expressions more conveniently. The syntax is as
2380follows:
2381
2382@example
2383@group
2384<rec expression> --> (rec <variable> <expression>)
2385<rec expression> --> (rec (<variable>+) <body>)
2386@end group
2387@end example
2388
2389The first syntax can be used to create self-referential expressions,
2390for example:
2391
2392@lisp
2393 guile> (define tmp (rec ones (cons 1 (delay ones))))
2394@end lisp
2395
2396The second syntax can be used to create anonymous recursive functions:
2397
2398@lisp
2399 guile> (define tmp (rec (display-n item n)
2400 (if (positive? n)
2401 (begin (display n) (display-n (- n 1))))))
2402 guile> (tmp 42 3)
2403 424242
2404 guile>
2405@end lisp
12991fed 2406
eeadfda1 2407
f50ca8da
LC
2408@node SRFI-34
2409@subsection SRFI-34 - Exception handling for programs
2410
2411@cindex SRFI-34
2412Guile provides an implementation of
2413@uref{http://srfi.schemers.org/srfi-34/srfi-34.html, SRFI-34's exception
2414handling mechanisms} as an alternative to its own built-in mechanisms
2415(@pxref{Exceptions}). It can be made available as follows:
2416
2417@lisp
2418(use-modules (srfi srfi-34))
2419@end lisp
2420
2421@c FIXME: Document it.
2422
2423
2424@node SRFI-35
2425@subsection SRFI-35 - Conditions
2426
2427@cindex SRFI-35
2428@cindex conditions
2429@cindex exceptions
2430
2431@uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI-35} implements
2432@dfn{conditions}, a data structure akin to records designed to convey
2433information about exceptional conditions between parts of a program. It
2434is normally used in conjunction with SRFI-34's @code{raise}:
2435
2436@lisp
2437(raise (condition (&message
2438 (message "An error occurred"))))
2439@end lisp
2440
2441Users can define @dfn{condition types} containing arbitrary information.
2442Condition types may inherit from one another. This allows the part of
2443the program that handles (or ``catches'') conditions to get accurate
2444information about the exceptional condition that arose.
2445
2446SRFI-35 conditions are made available using:
2447
2448@lisp
2449(use-modules (srfi srfi-35))
2450@end lisp
2451
2452The procedures available to manipulate condition types are the
2453following:
2454
2455@deffn {Scheme Procedure} make-condition-type id parent field-names
2456Return a new condition type named @var{id}, inheriting from
2457@var{parent}, and with the fields whose names are listed in
2458@var{field-names}. @var{field-names} must be a list of symbols and must
2459not contain names already used by @var{parent} or one of its supertypes.
2460@end deffn
2461
2462@deffn {Scheme Procedure} condition-type? obj
2463Return true if @var{obj} is a condition type.
2464@end deffn
2465
2466Conditions can be created and accessed with the following procedures:
2467
2468@deffn {Scheme Procedure} make-condition type . field+value
2469Return a new condition of type @var{type} with fields initialized as
2470specified by @var{field+value}, a sequence of field names (symbols) and
2471values as in the following example:
2472
2473@lisp
1317062f 2474(let ((&ct (make-condition-type 'foo &condition '(a b c))))
f50ca8da
LC
2475 (make-condition &ct 'a 1 'b 2 'c 3))
2476@end lisp
2477
2478Note that all fields of @var{type} and its supertypes must be specified.
2479@end deffn
2480
2481@deffn {Scheme Procedure} make-compound-condition . conditions
2482Return a new compound condition composed of @var{conditions}. The
2483returned condition has the type of each condition of @var{conditions}
2484(per @code{condition-has-type?}).
2485@end deffn
2486
2487@deffn {Scheme Procedure} condition-has-type? c type
2488Return true if condition @var{c} has type @var{type}.
2489@end deffn
2490
2491@deffn {Scheme Procedure} condition-ref c field-name
2492Return the value of the field named @var{field-name} from condition @var{c}.
2493
2494If @var{c} is a compound condition and several underlying condition
2495types contain a field named @var{field-name}, then the value of the
2496first such field is returned, using the order in which conditions were
2497passed to @var{make-compound-condition}.
2498@end deffn
2499
2500@deffn {Scheme Procedure} extract-condition c type
2501Return a condition of condition type @var{type} with the field values
2502specified by @var{c}.
2503
2504If @var{c} is a compound condition, extract the field values from the
2505subcondition belonging to @var{type} that appeared first in the call to
2506@code{make-compound-condition} that created the the condition.
2507@end deffn
2508
2509Convenience macros are also available to create condition types and
2510conditions.
2511
2512@deffn {library syntax} define-condition-type type supertype predicate field-spec...
2513Define a new condition type named @var{type} that inherits from
2514@var{supertype}. In addition, bind @var{predicate} to a type predicate
2515that returns true when passed a condition of type @var{type} or any of
2516its subtypes. @var{field-spec} must have the form @code{(field
2517accessor)} where @var{field} is the name of field of @var{type} and
2518@var{accessor} is the name of a procedure to access field @var{field} in
2519conditions of type @var{type}.
2520
2521The example below defines condition type @code{&foo}, inheriting from
2522@code{&condition} with fields @code{a}, @code{b} and @code{c}:
2523
2524@lisp
2525(define-condition-type &foo &condition
2526 foo-condition?
2527 (a foo-a)
2528 (b foo-b)
2529 (c foo-c))
2530@end lisp
2531@end deffn
2532
2533@deffn {library syntax} condition type-field-bindings...
2534Return a new condition, or compound condition, initialized according to
2535@var{type-field-bindings}. Each @var{type-field-binding} must have the
2536form @code{(type field-specs...)}, where @var{type} is the name of a
2537variable bound to condition type; each @var{field-spec} must have the
2538form @code{(field-name value)} where @var{field-name} is a symbol
2539denoting the field being initialized to @var{value}. As for
2540@code{make-condition}, all fields must be specified.
2541
2542The following example returns a simple condition:
2543
2544@lisp
2545(condition (&message (message "An error occurred")))
2546@end lisp
2547
2548The one below returns a compound condition:
2549
2550@lisp
2551(condition (&message (message "An error occurred"))
2552 (&serious))
2553@end lisp
2554@end deffn
2555
2556Finally, SRFI-35 defines a several standard condition types.
2557
2558@defvar &condition
2559This condition type is the root of all condition types. It has no
2560fields.
2561@end defvar
2562
2563@defvar &message
2564A condition type that carries a message describing the nature of the
2565condition to humans.
2566@end defvar
2567
2568@deffn {Scheme Procedure} message-condition? c
2569Return true if @var{c} is of type @code{&message} or one of its
2570subtypes.
2571@end deffn
2572
2573@deffn {Scheme Procedure} condition-message c
2574Return the message associated with message condition @var{c}.
2575@end deffn
2576
2577@defvar &serious
2578This type describes conditions serious enough that they cannot safely be
2579ignored. It has no fields.
2580@end defvar
2581
2582@deffn {Scheme Procedure} serious-condition? c
2583Return true if @var{c} is of type @code{&serious} or one of its
2584subtypes.
2585@end deffn
2586
2587@defvar &error
2588This condition describes errors, typically caused by something that has
2589gone wrong in the interaction of the program with the external world or
2590the user.
2591@end defvar
2592
2593@deffn {Scheme Procedure} error? c
2594Return true if @var{c} is of type @code{&error} or one of its subtypes.
2595@end deffn
2596
2597
d4c38221
LC
2598@node SRFI-37
2599@subsection SRFI-37 - args-fold
2600@cindex SRFI-37
2601
2602This is a processor for GNU @code{getopt_long}-style program
2603arguments. It provides an alternative, less declarative interface
2604than @code{getopt-long} in @code{(ice-9 getopt-long)}
2605(@pxref{getopt-long,,The (ice-9 getopt-long) Module}). Unlike
2606@code{getopt-long}, it supports repeated options and any number of
2607short and long names per option. Access it with:
2608
2609@lisp
2610(use-modules (srfi srfi-37))
2611@end lisp
2612
2613@acronym{SRFI}-37 principally provides an @code{option} type and the
2614@code{args-fold} function. To use the library, create a set of
2615options with @code{option} and use it as a specification for invoking
2616@code{args-fold}.
2617
2618Here is an example of a simple argument processor for the typical
2619@samp{--version} and @samp{--help} options, which returns a backwards
2620list of files given on the command line:
2621
2622@lisp
2623(args-fold (cdr (program-arguments))
2624 (let ((display-and-exit-proc
2625 (lambda (msg)
2626 (lambda (opt name arg loads)
2627 (display msg) (quit)))))
2628 (list (option '(#\v "version") #f #f
2629 (display-and-exit-proc "Foo version 42.0\n"))
2630 (option '(#\h "help") #f #f
2631 (display-and-exit-proc
2632 "Usage: foo scheme-file ..."))))
2633 (lambda (opt name arg loads)
2634 (error "Unrecognized option `~A'" name))
2635 (lambda (op loads) (cons op loads))
2636 '())
2637@end lisp
2638
2639@deffn {Scheme Procedure} option names required-arg? optional-arg? processor
2640Return an object that specifies a single kind of program option.
2641
2642@var{names} is a list of command-line option names, and should consist of
2643characters for traditional @code{getopt} short options and strings for
2644@code{getopt_long}-style long options.
2645
2646@var{required-arg?} and @var{optional-arg?} are mutually exclusive;
2647one or both must be @code{#f}. If @var{required-arg?}, the option
2648must be followed by an argument on the command line, such as
2649@samp{--opt=value} for long options, or an error will be signalled.
2650If @var{optional-arg?}, an argument will be taken if available.
2651
2652@var{processor} is a procedure that takes at least 3 arguments, called
2653when @code{args-fold} encounters the option: the containing option
2654object, the name used on the command line, and the argument given for
2655the option (or @code{#f} if none). The rest of the arguments are
2656@code{args-fold} ``seeds'', and the @var{processor} should return
2657seeds as well.
2658@end deffn
2659
2660@deffn {Scheme Procedure} option-names opt
2661@deffnx {Scheme Procedure} option-required-arg? opt
2662@deffnx {Scheme Procedure} option-optional-arg? opt
2663@deffnx {Scheme Procedure} option-processor opt
2664Return the specified field of @var{opt}, an option object, as
2665described above for @code{option}.
2666@end deffn
2667
2668@deffn {Scheme Procedure} args-fold args options unrecognized-option-proc operand-proc seeds @dots{}
2669Process @var{args}, a list of program arguments such as that returned
2670by @code{(cdr (program-arguments))}, in order against @var{options}, a
2671list of option objects as described above. All functions called take
2672the ``seeds'', or the last multiple-values as multiple arguments,
2673starting with @var{seeds}, and must return the new seeds. Return the
2674final seeds.
2675
2676Call @code{unrecognized-option-proc}, which is like an option object's
2677processor, for any options not found in @var{options}.
2678
2679Call @code{operand-proc} with any items on the command line that are
2680not named options. This includes arguments after @samp{--}. It is
2681called with the argument in question, as well as the seeds.
2682@end deffn
2683
2684
eeadfda1
KR
2685@node SRFI-39
2686@subsection SRFI-39 - Parameters
2687@cindex SRFI-39
2688@cindex parameter object
2689@tindex Parameter
2690
2691This SRFI provides parameter objects, which implement dynamically
2692bound locations for values. The functions below are available from
2693
2694@example
2695(use-modules (srfi srfi-39))
2696@end example
2697
2698A parameter object is a procedure. Called with no arguments it
2699returns its value, called with one argument it sets the value.
2700
2701@example
2702(define my-param (make-parameter 123))
2703(my-param) @result{} 123
2704(my-param 456)
2705(my-param) @result{} 456
2706@end example
2707
2708The @code{parameterize} special form establishes new locations for
2709parameters, those new locations having effect within the dynamic scope
2710of the @code{parameterize} body. Leaving restores the previous
2711locations, or re-entering through a saved continuation will again use
2712the new locations.
2713
2714@example
2715(parameterize ((my-param 789))
2716 (my-param) @result{} 789
2717 )
2718(my-param) @result{} 456
2719@end example
2720
2721Parameters are like dynamically bound variables in other Lisp dialets.
2722They allow an application to establish parameter settings (as the name
2723suggests) just for the execution of a particular bit of code,
2724restoring when done. Examples of such parameters might be
2725case-sensitivity for a search, or a prompt for user input.
2726
2727Global variables are not as good as parameter objects for this sort of
2728thing. Changes to them are visible to all threads, but in Guile
2729parameter object locations are per-thread, thereby truely limiting the
2730effect of @code{parameterize} to just its dynamic execution.
2731
2732Passing arguments to functions is thread-safe, but that soon becomes
2733tedious when there's more than a few or when they need to pass down
2734through several layers of calls before reaching the point they should
2735affect. And introducing a new setting to existing code is often
2736easier with a parameter object than adding arguments.
2737
2738
2739@sp 1
2740@defun make-parameter init [converter]
2741Return a new parameter object, with initial value @var{init}.
2742
2743A parameter object is a procedure. When called @code{(param)} it
2744returns its value, or a call @code{(param val)} sets its value. For
2745example,
2746
2747@example
2748(define my-param (make-parameter 123))
2749(my-param) @result{} 123
2750
2751(my-param 456)
2752(my-param) @result{} 456
2753@end example
2754
2755If a @var{converter} is given, then a call @code{(@var{converter}
2756val)} is made for each value set, its return is the value stored.
2757Such a call is made for the @var{init} initial value too.
2758
2759A @var{converter} allows values to be validated, or put into a
2760canonical form. For example,
2761
2762@example
2763(define my-param (make-parameter 123
2764 (lambda (val)
2765 (if (not (number? val))
2766 (error "must be a number"))
2767 (inexact->exact val))))
2768(my-param 0.75)
2769(my-param) @result{} 3/4
2770@end example
2771@end defun
2772
2773@deffn {library syntax} parameterize ((param value) @dots{}) body @dots{}
2774Establish a new dynamic scope with the given @var{param}s bound to new
2775locations and set to the given @var{value}s. @var{body} is evaluated
2776in that environment, the result is the return from the last form in
2777@var{body}.
2778
2779Each @var{param} is an expression which is evaluated to get the
2780parameter object. Often this will just be the name of a variable
2781holding the object, but it can be anything that evaluates to a
2782parameter.
2783
2784The @var{param} expressions and @var{value} expressions are all
2785evaluated before establishing the new dynamic bindings, and they're
2786evaluated in an unspecified order.
2787
2788For example,
2789
2790@example
2791(define prompt (make-parameter "Type something: "))
2792(define (get-input)
2793 (display (prompt))
2794 ...)
2795
2796(parameterize ((prompt "Type a number: "))
2797 (get-input)
2798 ...)
2799@end example
2800@end deffn
2801
2802@deffn {Parameter object} current-input-port [new-port]
2803@deffnx {Parameter object} current-output-port [new-port]
2804@deffnx {Parameter object} current-error-port [new-port]
2805This SRFI extends the core @code{current-input-port} and
2806@code{current-output-port}, making them parameter objects. The
2807Guile-specific @code{current-error-port} is extended too, for
2808consistency. (@pxref{Default Ports}.)
2809
2810This is an upwardly compatible extension, a plain call like
2811@code{(current-input-port)} still returns the current input port, and
2812@code{set-current-input-port} can still be used. But the port can now
2813also be set with @code{(current-input-port my-port)} and bound
2814dynamically with @code{parameterize}.
2815@end deffn
2816
2817@defun with-parameters* param-list value-list thunk
2818Establish a new dynamic scope, as per @code{parameterize} above,
2819taking parameters from @var{param-list} and corresponding values from
2820@var{values-list}. A call @code{(@var{thunk})} is made in the new
2821scope and the result from that @var{thunk} is the return from
2822@code{with-parameters*}.
2823
2824This function is a Guile-specific addition to the SRFI, it's similar
b4fddbbe 2825to the core @code{with-fluids*} (@pxref{Fluids and Dynamic States}).
eeadfda1
KR
2826@end defun
2827
2828
2829@sp 1
b4fddbbe
MV
2830Parameter objects are implemented using fluids (@pxref{Fluids and
2831Dynamic States}), so each dynamic state has it's own parameter
2832locations. That includes the separate locations when outside any
2833@code{parameterize} form. When a parameter is created it gets a
2834separate initial location in each dynamic state, all initialized to
2835the given @var{init} value.
2836
2837As alluded to above, because each thread usually has a separate
2838dynamic state, each thread has it's own locations behind parameter
2839objects, and changes in one thread are not visible to any other. When
2840a new dynamic state or thread is created, the values of parameters in
2841the originating context are copied, into new locations.
eeadfda1
KR
2842
2843SRFI-39 doesn't specify the interaction between parameter objects and
2844threads, so the threading behaviour described here should be regarded
2845as Guile-specific.
2846
2847
4ea9becb
KR
2848@node SRFI-55
2849@subsection SRFI-55 - Requiring Features
2850@cindex SRFI-55
2851
2852SRFI-55 provides @code{require-extension} which is a portable
2853mechanism to load selected SRFI modules. This is implemented in the
2854Guile core, there's no module needed to get SRFI-55 itself.
2855
2856@deffn {library syntax} require-extension clause@dots{}
2857Require each of the given @var{clause} features, throwing an error if
2858any are unavailable.
2859
2860A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
2861only @var{identifier} currently supported is @code{srfi} and the
2862arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
2863
2864@example
2865(require-extension (srfi 1 6))
2866@end example
2867
2868@code{require-extension} can only be used at the top-level.
2869
2870A Guile-specific program can simply @code{use-modules} to load SRFIs
2871not already in the core, @code{require-extension} is for programs
2872designed to be portable to other Scheme implementations.
2873@end deffn
2874
2875
8503beb8
KR
2876@node SRFI-60
2877@subsection SRFI-60 - Integers as Bits
2878@cindex SRFI-60
2879@cindex integers as bits
2880@cindex bitwise logical
2881
2882This SRFI provides various functions for treating integers as bits and
2883for bitwise manipulations. These functions can be obtained with,
2884
2885@example
2886(use-modules (srfi srfi-60))
2887@end example
2888
2889Integers are treated as infinite precision twos-complement, the same
2890as in the core logical functions (@pxref{Bitwise Operations}). And
2891likewise bit indexes start from 0 for the least significant bit. The
2892following functions in this SRFI are already in the Guile core,
2893
2894@quotation
2895@code{logand},
2896@code{logior},
2897@code{logxor},
2898@code{lognot},
2899@code{logtest},
2900@code{logcount},
2901@code{integer-length},
2902@code{logbit?},
2903@code{ash}
2904@end quotation
2905
2906@sp 1
2907@defun bitwise-and n1 ...
2908@defunx bitwise-ior n1 ...
2909@defunx bitwise-xor n1 ...
2910@defunx bitwise-not n
2911@defunx any-bits-set? j k
2912@defunx bit-set? index n
2913@defunx arithmetic-shift n count
2914@defunx bit-field n start end
2915@defunx bit-count n
2916Aliases for @code{logand}, @code{logior}, @code{logxor},
2917@code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
2918@code{bit-extract} and @code{logcount} respectively.
2919
2920Note that the name @code{bit-count} conflicts with @code{bit-count} in
2921the core (@pxref{Bit Vectors}).
2922@end defun
2923
2924@defun bitwise-if mask n1 n0
2925@defunx bitwise-merge mask n1 n0
2926Return an integer with bits selected from @var{n1} and @var{n0}
2927according to @var{mask}. Those bits where @var{mask} has 1s are taken
2928from @var{n1}, and those where @var{mask} has 0s are taken from
2929@var{n0}.
2930
2931@example
2932(bitwise-if 3 #b0101 #b1010) @result{} 9
2933@end example
2934@end defun
2935
2936@defun log2-binary-factors n
2937@defunx first-set-bit n
2938Return a count of how many factors of 2 are present in @var{n}. This
2939is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
29400, the return is @math{-1}.
2941
2942@example
2943(log2-binary-factors 6) @result{} 1
2944(log2-binary-factors -8) @result{} 3
2945@end example
2946@end defun
2947
2948@defun copy-bit index n newbit
2949Return @var{n} with the bit at @var{index} set according to
2950@var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
2951or @code{#f} to set it to 0. Bits other than at @var{index} are
2952unchanged in the return.
2953
2954@example
2955(copy-bit 1 #b0101 #t) @result{} 7
2956@end example
2957@end defun
2958
2959@defun copy-bit-field n newbits start end
2960Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2961(exclusive) changed to the value @var{newbits}.
2962
2963The least significant bit in @var{newbits} goes to @var{start}, the
2964next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
2965@var{end} given is ignored.
2966
2967@example
2968(copy-bit-field #b10000 #b11 1 3) @result{} #b10110
2969@end example
2970@end defun
2971
2972@defun rotate-bit-field n count start end
2973Return @var{n} with the bit field from @var{start} (inclusive) to
2974@var{end} (exclusive) rotated upwards by @var{count} bits.
2975
2976@var{count} can be positive or negative, and it can be more than the
2977field width (it'll be reduced modulo the width).
2978
2979@example
2980(rotate-bit-field #b0110 2 1 4) @result{} #b1010
2981@end example
2982@end defun
2983
2984@defun reverse-bit-field n start end
2985Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2986(exclusive) reversed.
2987
2988@example
2989(reverse-bit-field #b101001 2 4) @result{} #b100101
2990@end example
2991@end defun
2992
2993@defun integer->list n [len]
2994Return bits from @var{n} in the form of a list of @code{#t} for 1 and
2995@code{#f} for 0. The least significant @var{len} bits are returned,
2996and the first list element is the most significant of those bits. If
2997@var{len} is not given, the default is @code{(integer-length @var{n})}
2998(@pxref{Bitwise Operations}).
2999
3000@example
3001(integer->list 6) @result{} (#t #t #f)
3002(integer->list 1 4) @result{} (#f #f #f #t)
3003@end example
3004@end defun
3005
3006@defun list->integer lst
3007@defunx booleans->integer bool@dots{}
3008Return an integer formed bitwise from the given @var{lst} list of
3009booleans, or for @code{booleans->integer} from the @var{bool}
3010arguments.
3011
3012Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
3013element becomes the most significant bit in the return.
3014
3015@example
3016(list->integer '(#t #f #t #f)) @result{} 10
3017@end example
3018@end defun
3019
3020
43ed3b69
MV
3021@node SRFI-61
3022@subsection SRFI-61 - A more general @code{cond} clause
3023
3024This SRFI extends RnRS @code{cond} to support test expressions that
3025return multiple values, as well as arbitrary definitions of test
3026success. SRFI 61 is implemented in the Guile core; there's no module
3027needed to get SRFI-61 itself. Extended @code{cond} is documented in
3028@ref{if cond case,, Simple Conditional Evaluation}.
3029
3030
1317062f
LC
3031@node SRFI-69
3032@subsection SRFI-69 - Basic hash tables
3033@cindex SRFI-69
3034
3035This is a portable wrapper around Guile's built-in hash table and weak
3036table support. @xref{Hash Tables}, for information on that built-in
3037support. Above that, this hash-table interface provides association
3038of equality and hash functions with tables at creation time, so
3039variants of each function are not required, as well as a procedure
3040that takes care of most uses for Guile hash table handles, which this
3041SRFI does not provide as such.
3042
3043Access it with:
3044
3045@lisp
3046(use-modules (srfi srfi-69))
3047@end lisp
3048
3049@menu
3050* SRFI-69 Creating hash tables::
3051* SRFI-69 Accessing table items::
3052* SRFI-69 Table properties::
3053* SRFI-69 Hash table algorithms::
3054@end menu
3055
3056@node SRFI-69 Creating hash tables
3057@subsubsection Creating hash tables
3058
3059@deffn {Scheme Procedure} make-hash-table [equal-proc hash-proc #:weak weakness start-size]
3060Create and answer a new hash table with @var{equal-proc} as the
3061equality function and @var{hash-proc} as the hashing function.
3062
3063By default, @var{equal-proc} is @code{equal?}. It can be any
3064two-argument procedure, and should answer whether two keys are the
3065same for this table's purposes.
3066
3067My default @var{hash-proc} assumes that @code{equal-proc} is no
3068coarser than @code{equal?} unless it is literally @code{string-ci=?}.
3069If provided, @var{hash-proc} should be a two-argument procedure that
3070takes a key and the current table size, and answers a reasonably good
3071hash integer between 0 (inclusive) and the size (exclusive).
3072
3073@var{weakness} should be @code{#f} or a symbol indicating how ``weak''
3074the hash table is:
3075
3076@table @code
3077@item #f
3078An ordinary non-weak hash table. This is the default.
3079
3080@item key
3081When the key has no more non-weak references at GC, remove that entry.
3082
3083@item value
3084When the value has no more non-weak references at GC, remove that
3085entry.
3086
3087@item key-or-value
3088When either has no more non-weak references at GC, remove the
3089association.
3090@end table
3091
3092As a legacy of the time when Guile couldn't grow hash tables,
3093@var{start-size} is an optional integer argument that specifies the
dfe8c13b
LC
3094approximate starting size for the hash table, which will be rounded to
3095an algorithmically-sounder number.
1317062f
LC
3096@end deffn
3097
dfe8c13b 3098By @dfn{coarser} than @code{equal?}, we mean that for all @var{x} and
1317062f
LC
3099@var{y} values where @code{(@var{equal-proc} @var{x} @var{y})},
3100@code{(equal? @var{x} @var{y})} as well. If that does not hold for
3101your @var{equal-proc}, you must provide a @var{hash-proc}.
3102
3103In the case of weak tables, remember that @dfn{references} above
3104always refers to @code{eq?}-wise references. Just because you have a
3105reference to some string @code{"foo"} doesn't mean that an association
3106with key @code{"foo"} in a weak-key table @emph{won't} be collected;
3107it only counts as a reference if the two @code{"foo"}s are @code{eq?},
3108regardless of @var{equal-proc}. As such, it is usually only sensible
3109to use @code{eq?} and @code{hashq} as the equivalence and hash
3110functions for a weak table. @xref{Weak References}, for more
3111information on Guile's built-in weak table support.
3112
3113@deffn {Scheme Procedure} alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size]
3114As with @code{make-hash-table}, but initialize it with the
3115associations in @var{alist}. Where keys are repeated in @var{alist},
3116the leftmost association takes precedence.
3117@end deffn
3118
3119@node SRFI-69 Accessing table items
3120@subsubsection Accessing table items
3121
3122@deffn {Scheme Procedure} hash-table-ref table key [default-thunk]
3123@deffnx {Scheme Procedure} hash-table-ref/default table key default
3124Answer the value associated with @var{key} in @var{table}. If
3125@var{key} is not present, answer the result of invoking the thunk
3126@var{default-thunk}, which signals an error instead by default.
3127
3128@code{hash-table-ref/default} is a variant that requires a third
3129argument, @var{default}, and answers @var{default} itself instead of
3130invoking it.
3131@end deffn
3132
3133@deffn {Scheme Procedure} hash-table-set! table key new-value
3134Set @var{key} to @var{new-value} in @var{table}.
3135@end deffn
3136
3137@deffn {Scheme Procedure} hash-table-delete! table key
3138Remove the association of @var{key} in @var{table}, if present. If
3139absent, do nothing.
3140@end deffn
3141
3142@deffn {Scheme Procedure} hash-table-exists? table key
3143Answer whether @var{key} has an association in @var{table}.
3144@end deffn
3145
3146@deffn {Scheme Procedure} hash-table-update! table key modifier [default-thunk]
3147@deffnx {Scheme Procedure} hash-table-update!/default table key modifier default
3148Replace @var{key}'s associated value in @var{table} by invoking
3149@var{modifier} with one argument, the old value.
3150
3151If @var{key} is not present, and @var{default-thunk} is provided,
3152invoke it with no arguments to get the ``old value'' to be passed to
3153@var{modifier} as above. If @var{default-thunk} is not provided in
3154such a case, signal an error.
3155
3156@code{hash-table-update!/default} is a variant that requires the
3157fourth argument, which is used directly as the ``old value'' rather
3158than as a thunk to be invoked to retrieve the ``old value''.
3159@end deffn
3160
3161@node SRFI-69 Table properties
3162@subsubsection Table properties
3163
3164@deffn {Scheme Procedure} hash-table-size table
3165Answer the number of associations in @var{table}. This is guaranteed
3166to run in constant time for non-weak tables.
3167@end deffn
3168
3169@deffn {Scheme Procedure} hash-table-keys table
3170Answer an unordered list of the keys in @var{table}.
3171@end deffn
3172
3173@deffn {Scheme Procedure} hash-table-values table
3174Answer an unordered list of the values in @var{table}.
3175@end deffn
3176
3177@deffn {Scheme Procedure} hash-table-walk table proc
3178Invoke @var{proc} once for each association in @var{table}, passing
3179the key and value as arguments.
3180@end deffn
3181
3182@deffn {Scheme Procedure} hash-table-fold table proc init
3183Invoke @code{(@var{proc} @var{key} @var{value} @var{previous})} for
3184each @var{key} and @var{value} in @var{table}, where @var{previous} is
3185the result of the previous invocation, using @var{init} as the first
3186@var{previous} value. Answer the final @var{proc} result.
3187@end deffn
3188
3189@deffn {Scheme Procedure} hash-table->alist table
3190Answer an alist where each association in @var{table} is an
3191association in the result.
3192@end deffn
3193
3194@node SRFI-69 Hash table algorithms
3195@subsubsection Hash table algorithms
3196
3197Each hash table carries an @dfn{equivalence function} and a @dfn{hash
3198function}, used to implement key lookups. Beginning users should
3199follow the rules for consistency of the default @var{hash-proc}
3200specified above. Advanced users can use these to implement their own
3201equivalence and hash functions for specialized lookup semantics.
3202
3203@deffn {Scheme Procedure} hash-table-equivalence-function hash-table
3204@deffnx {Scheme Procedure} hash-table-hash-function hash-table
3205Answer the equivalence and hash function of @var{hash-table}, respectively.
3206@end deffn
3207
3208@deffn {Scheme Procedure} hash obj [size]
3209@deffnx {Scheme Procedure} string-hash obj [size]
3210@deffnx {Scheme Procedure} string-ci-hash obj [size]
3211@deffnx {Scheme Procedure} hash-by-identity obj [size]
3212Answer a hash value appropriate for equality predicate @code{equal?},
3213@code{string=?}, @code{string-ci=?}, and @code{eq?}, respectively.
3214@end deffn
3215
3216@code{hash} is a backwards-compatible replacement for Guile's built-in
3217@code{hash}.
3218
3219
12991fed 3220@c srfi-modules.texi ends here
193239f1
KR
3221
3222@c Local Variables:
3223@c TeX-master: "guile.texi"
3224@c End: