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