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