Merge remote-tracking branch 'local-2.0/stable-2.0'
[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.
99db1bc2 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012
2da09c3f
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
a0e07ba4 7@node SRFI Support
3229f68b 8@section SRFI Support Modules
8742c48b 9@cindex SRFI
a0e07ba4
NJ
10
11SRFI is an acronym for Scheme Request For Implementation. The SRFI
12documents define a lot of syntactic and procedure extensions to standard
13Scheme as defined in R5RS.
14
15Guile has support for a number of SRFIs. This chapter gives an overview
16over the available SRFIs and some usage hints. For complete
17documentation, design rationales and further examples, we advise you to
18get the relevant SRFI documents from the SRFI home page
4b4b1e0b 19@url{http://srfi.schemers.org/}.
a0e07ba4
NJ
20
21@menu
22* About SRFI Usage:: What to know about Guile's SRFI support.
23* SRFI-0:: cond-expand
24* SRFI-1:: List library.
25* SRFI-2:: and-let*.
26* SRFI-4:: Homogeneous numeric vector datatypes.
27* SRFI-6:: Basic String Ports.
28* SRFI-8:: receive.
29* SRFI-9:: define-record-type.
30* SRFI-10:: Hash-Comma Reader Extension.
c010924a 31* SRFI-11:: let-values and let*-values.
a0e07ba4
NJ
32* SRFI-13:: String library.
33* SRFI-14:: Character-set library.
34* SRFI-16:: case-lambda
35* SRFI-17:: Generalized set!
e68f492a 36* SRFI-18:: Multithreading support
bfc9c8e0 37* SRFI-19:: Time/Date library.
8e9af854 38* SRFI-23:: Error reporting
1de8c1ae 39* SRFI-26:: Specializing parameters
56ec46a7 40* SRFI-27:: Sources of Random Bits
620c8965 41* SRFI-30:: Nested multi-line block comments
8638c417 42* SRFI-31:: A special form `rec' for recursive evaluation
f50ca8da
LC
43* SRFI-34:: Exception handling.
44* SRFI-35:: Conditions.
d4c38221 45* SRFI-37:: args-fold program argument processor
12708eeb 46* SRFI-38:: External Representation for Data With Shared Structure
eeadfda1 47* SRFI-39:: Parameter objects
fdc8fd46 48* SRFI-42:: Eager comprehensions
f16a2007 49* SRFI-45:: Primitives for expressing iterative lazy algorithms
4ea9becb 50* SRFI-55:: Requiring Features.
8503beb8 51* SRFI-60:: Integers as bits.
43ed3b69 52* SRFI-61:: A more general `cond' clause
8175a07e 53* SRFI-67:: Compare procedures
1317062f 54* SRFI-69:: Basic hash tables.
189681f5 55* SRFI-88:: Keyword objects.
922d417b 56* SRFI-98:: Accessing environment variables.
a0e07ba4
NJ
57@end menu
58
59
60@node About SRFI Usage
3229f68b 61@subsection About SRFI Usage
a0e07ba4
NJ
62
63@c FIXME::martin: Review me!
64
65SRFI support in Guile is currently implemented partly in the core
66library, and partly as add-on modules. That means that some SRFIs are
67automatically available when the interpreter is started, whereas the
68other SRFIs require you to use the appropriate support module
12991fed 69explicitly.
a0e07ba4
NJ
70
71There are several reasons for this inconsistency. First, the feature
72checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
73available immediately, because it must be there when the user wants to
74check for the Scheme implementation, that is, before she can know that
75it is safe to use @code{use-modules} to load SRFI support modules. The
76second reason is that some features defined in SRFIs had been
77implemented in Guile before the developers started to add SRFI
78implementations as modules (for example SRFI-6 (@pxref{SRFI-6})). In
79the future, it is possible that SRFIs in the core library might be
80factored out into separate modules, requiring explicit module loading
81when they are needed. So you should be prepared to have to use
82@code{use-modules} someday in the future to access SRFI-6 bindings. If
83you want, you can do that already. We have included the module
84@code{(srfi srfi-6)} in the distribution, which currently does nothing,
85but ensures that you can write future-safe code.
86
87Generally, support for a specific SRFI is made available by using
88modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
89number of the SRFI needed. Another possibility is to use the command
90line option @code{--use-srfi}, which will load the necessary modules
91automatically (@pxref{Invoking Guile}).
92
93
94@node SRFI-0
3229f68b 95@subsection SRFI-0 - cond-expand
8742c48b 96@cindex SRFI-0
a0e07ba4 97
5eef0f61
KR
98This SRFI lets a portable Scheme program test for the presence of
99certain features, and adapt itself by using different blocks of code,
100or fail if the necessary features are not available. There's no
101module to load, this is in the Guile core.
a0e07ba4 102
5eef0f61
KR
103A program designed only for Guile will generally not need this
104mechanism, such a program can of course directly use the various
105documented parts of Guile.
a0e07ba4 106
5eef0f61
KR
107@deffn syntax cond-expand (feature body@dots{}) @dots{}
108Expand to the @var{body} of the first clause whose @var{feature}
109specification is satisfied. It is an error if no @var{feature} is
a0e07ba4
NJ
110satisfied.
111
5eef0f61
KR
112Features are symbols such as @code{srfi-1}, and a feature
113specification can use @code{and}, @code{or} and @code{not} forms to
114test combinations. The last clause can be an @code{else}, to be used
115if no other passes.
a0e07ba4 116
5eef0f61
KR
117For example, define a private version of @code{alist-cons} if SRFI-1
118is not available.
a0e07ba4 119
5eef0f61
KR
120@example
121(cond-expand (srfi-1
122 )
123 (else
124 (define (alist-cons key val alist)
125 (cons (cons key val) alist))))
126@end example
a0e07ba4 127
5eef0f61
KR
128Or demand a certain set of SRFIs (list operations, string ports,
129@code{receive} and string operations), failing if they're not
130available.
a0e07ba4 131
5eef0f61
KR
132@example
133(cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
134 ))
135@end example
136@end deffn
a0e07ba4 137
f38d22c5
KR
138@noindent
139The Guile core has the following features,
140
141@example
142guile
60c8ad9e 143guile-2 ;; starting from Guile 2.x
f38d22c5
KR
144r5rs
145srfi-0
146srfi-4
147srfi-6
148srfi-13
149srfi-14
150@end example
151
152Other SRFI feature symbols are defined once their code has been loaded
153with @code{use-modules}, since only then are their bindings available.
a0e07ba4 154
5eef0f61
KR
155The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
156a good way to load SRFIs to satisfy @code{cond-expand} when running a
157portable program.
a0e07ba4 158
5eef0f61
KR
159Testing the @code{guile} feature allows a program to adapt itself to
160the Guile module system, but still run on other Scheme systems. For
161example the following demands SRFI-8 (@code{receive}), but also knows
162how to load it with the Guile mechanism.
a0e07ba4
NJ
163
164@example
5eef0f61
KR
165(cond-expand (srfi-8
166 )
167 (guile
168 (use-modules (srfi srfi-8))))
a0e07ba4
NJ
169@end example
170
60c8ad9e
LC
171@cindex @code{guile-2} SRFI-0 feature
172@cindex portability between 2.0 and older versions
173Likewise, testing the @code{guile-2} feature allows code to be portable
0c81a0c1
AW
174between Guile 2.@var{x} and previous versions of Guile. For instance, it
175makes it possible to write code that accounts for Guile 2.@var{x}'s compiler,
60c8ad9e
LC
176yet be correctly interpreted on 1.8 and earlier versions:
177
178@example
179(cond-expand (guile-2 (eval-when (compile)
180 ;; This must be evaluated at compile time.
181 (fluid-set! current-reader my-reader)))
182 (guile
183 ;; Earlier versions of Guile do not have a
184 ;; separate compilation phase.
185 (fluid-set! current-reader my-reader)))
186@end example
187
5eef0f61
KR
188It should be noted that @code{cond-expand} is separate from the
189@code{*features*} mechanism (@pxref{Feature Tracking}), feature
190symbols in one are unrelated to those in the other.
a0e07ba4
NJ
191
192
193@node SRFI-1
3229f68b 194@subsection SRFI-1 - List library
8742c48b 195@cindex SRFI-1
7c2e18cd 196@cindex list
a0e07ba4
NJ
197
198@c FIXME::martin: Review me!
199
200The list library defined in SRFI-1 contains a lot of useful list
201processing procedures for construction, examining, destructuring and
202manipulating lists and pairs.
203
204Since SRFI-1 also defines some procedures which are already contained
205in R5RS and thus are supported by the Guile core library, some list
206and pair procedures which appear in the SRFI-1 document may not appear
207in this section. So when looking for a particular list/pair
208processing procedure, you should also have a look at the sections
209@ref{Lists} and @ref{Pairs}.
210
211@menu
212* SRFI-1 Constructors:: Constructing new lists.
213* SRFI-1 Predicates:: Testing list for specific properties.
214* SRFI-1 Selectors:: Selecting elements from lists.
215* SRFI-1 Length Append etc:: Length calculation and list appending.
216* SRFI-1 Fold and Map:: Higher-order list processing.
217* SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
85a9b4ed 218* SRFI-1 Searching:: Search for elements.
a0e07ba4
NJ
219* SRFI-1 Deleting:: Delete elements from lists.
220* SRFI-1 Association Lists:: Handle association lists.
221* SRFI-1 Set Operations:: Use lists for representing sets.
222@end menu
223
224@node SRFI-1 Constructors
3229f68b 225@subsubsection Constructors
7c2e18cd 226@cindex list constructor
a0e07ba4
NJ
227
228@c FIXME::martin: Review me!
229
230New lists can be constructed by calling one of the following
231procedures.
232
8f85c0c6 233@deffn {Scheme Procedure} xcons d a
a0e07ba4
NJ
234Like @code{cons}, but with interchanged arguments. Useful mostly when
235passed to higher-order procedures.
236@end deffn
237
8f85c0c6 238@deffn {Scheme Procedure} list-tabulate n init-proc
a0e07ba4
NJ
239Return an @var{n}-element list, where each list element is produced by
240applying the procedure @var{init-proc} to the corresponding list
241index. The order in which @var{init-proc} is applied to the indices
242is not specified.
243@end deffn
244
57066448
KR
245@deffn {Scheme Procedure} list-copy lst
246Return a new list containing the elements of the list @var{lst}.
247
248This function differs from the core @code{list-copy} (@pxref{List
249Constructors}) in accepting improper lists too. And if @var{lst} is
250not a pair at all then it's treated as the final tail of an improper
251list and simply returned.
252@end deffn
253
8f85c0c6 254@deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
a0e07ba4
NJ
255Return a circular list containing the given arguments @var{elt1}
256@var{elt2} @dots{}.
257@end deffn
258
8f85c0c6 259@deffn {Scheme Procedure} iota count [start step]
256853db
KR
260Return a list containing @var{count} numbers, starting from
261@var{start} and adding @var{step} each time. The default @var{start}
262is 0, the default @var{step} is 1. For example,
a0e07ba4 263
256853db
KR
264@example
265(iota 6) @result{} (0 1 2 3 4 5)
266(iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
267@end example
a0e07ba4 268
256853db
KR
269This function takes its name from the corresponding primitive in the
270APL language.
a0e07ba4
NJ
271@end deffn
272
273
274@node SRFI-1 Predicates
3229f68b 275@subsubsection Predicates
7c2e18cd 276@cindex list predicate
a0e07ba4
NJ
277
278@c FIXME::martin: Review me!
279
280The procedures in this section test specific properties of lists.
281
8f85c0c6 282@deffn {Scheme Procedure} proper-list? obj
f18f87aa
KR
283Return @code{#t} if @var{obj} is a proper list, or @code{#f}
284otherwise. This is the same as the core @code{list?} (@pxref{List
285Predicates}).
286
287A proper list is a list which ends with the empty list @code{()} in
288the usual way. The empty list @code{()} itself is a proper list too.
289
290@example
291(proper-list? '(1 2 3)) @result{} #t
292(proper-list? '()) @result{} #t
293@end example
a0e07ba4
NJ
294@end deffn
295
8f85c0c6 296@deffn {Scheme Procedure} circular-list? obj
f18f87aa
KR
297Return @code{#t} if @var{obj} is a circular list, or @code{#f}
298otherwise.
299
300A circular list is a list where at some point the @code{cdr} refers
301back to a previous pair in the list (either the start or some later
302point), so that following the @code{cdr}s takes you around in a
303circle, with no end.
304
305@example
306(define x (list 1 2 3 4))
307(set-cdr! (last-pair x) (cddr x))
308x @result{} (1 2 3 4 3 4 3 4 ...)
309(circular-list? x) @result{} #t
310@end example
a0e07ba4
NJ
311@end deffn
312
8f85c0c6 313@deffn {Scheme Procedure} dotted-list? obj
f18f87aa
KR
314Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
315otherwise.
316
317A dotted list is a list where the @code{cdr} of the last pair is not
318the empty list @code{()}. Any non-pair @var{obj} is also considered a
319dotted list, with length zero.
320
321@example
322(dotted-list? '(1 2 . 3)) @result{} #t
323(dotted-list? 99) @result{} #t
324@end example
a0e07ba4
NJ
325@end deffn
326
f18f87aa
KR
327It will be noted that any Scheme object passes exactly one of the
328above three tests @code{proper-list?}, @code{circular-list?} and
329@code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
330are either @code{proper-list?} or @code{dotted-list?}, and infinite
331lists are @code{circular-list?}.
332
333@sp 1
8f85c0c6 334@deffn {Scheme Procedure} null-list? lst
a0e07ba4
NJ
335Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
336otherwise. If something else than a proper or circular list is passed
85a9b4ed 337as @var{lst}, an error is signalled. This procedure is recommended
a0e07ba4
NJ
338for checking for the end of a list in contexts where dotted lists are
339not allowed.
340@end deffn
341
8f85c0c6 342@deffn {Scheme Procedure} not-pair? obj
a0e07ba4
NJ
343Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
344This is shorthand notation @code{(not (pair? @var{obj}))} and is
345supposed to be used for end-of-list checking in contexts where dotted
346lists are allowed.
347@end deffn
348
8f85c0c6 349@deffn {Scheme Procedure} list= elt= list1 @dots{}
a0e07ba4
NJ
350Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
351List equality is determined by testing whether all lists have the same
352length and the corresponding elements are equal in the sense of the
353equality predicate @var{elt=}. If no or only one list is given,
354@code{#t} is returned.
355@end deffn
356
357
358@node SRFI-1 Selectors
3229f68b 359@subsubsection Selectors
7c2e18cd 360@cindex list selector
a0e07ba4
NJ
361
362@c FIXME::martin: Review me!
363
8f85c0c6
NJ
364@deffn {Scheme Procedure} first pair
365@deffnx {Scheme Procedure} second pair
366@deffnx {Scheme Procedure} third pair
367@deffnx {Scheme Procedure} fourth pair
368@deffnx {Scheme Procedure} fifth pair
369@deffnx {Scheme Procedure} sixth pair
370@deffnx {Scheme Procedure} seventh pair
371@deffnx {Scheme Procedure} eighth pair
372@deffnx {Scheme Procedure} ninth pair
373@deffnx {Scheme Procedure} tenth pair
a0e07ba4
NJ
374These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
375@end deffn
376
8f85c0c6 377@deffn {Scheme Procedure} car+cdr pair
a0e07ba4
NJ
378Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
379@end deffn
380
8f85c0c6
NJ
381@deffn {Scheme Procedure} take lst i
382@deffnx {Scheme Procedure} take! lst i
a0e07ba4
NJ
383Return a list containing the first @var{i} elements of @var{lst}.
384
385@code{take!} may modify the structure of the argument list @var{lst}
386in order to produce the result.
387@end deffn
388
8f85c0c6 389@deffn {Scheme Procedure} drop lst i
a0e07ba4
NJ
390Return a list containing all but the first @var{i} elements of
391@var{lst}.
392@end deffn
393
8f85c0c6 394@deffn {Scheme Procedure} take-right lst i
ecb87335 395Return a list containing the @var{i} last elements of @var{lst}.
64bf8517 396The return shares a common tail with @var{lst}.
a0e07ba4
NJ
397@end deffn
398
8f85c0c6
NJ
399@deffn {Scheme Procedure} drop-right lst i
400@deffnx {Scheme Procedure} drop-right! lst i
ecb87335 401Return a list containing all but the @var{i} last elements of
a0e07ba4
NJ
402@var{lst}.
403
64bf8517
KR
404@code{drop-right} always returns a new list, even when @var{i} is
405zero. @code{drop-right!} may modify the structure of the argument
406list @var{lst} in order to produce the result.
a0e07ba4
NJ
407@end deffn
408
8f85c0c6
NJ
409@deffn {Scheme Procedure} split-at lst i
410@deffnx {Scheme Procedure} split-at! lst i
a0e07ba4
NJ
411Return two values, a list containing the first @var{i} elements of the
412list @var{lst} and a list containing the remaining elements.
413
414@code{split-at!} may modify the structure of the argument list
415@var{lst} in order to produce the result.
416@end deffn
417
8f85c0c6 418@deffn {Scheme Procedure} last lst
a0e07ba4
NJ
419Return the last element of the non-empty, finite list @var{lst}.
420@end deffn
421
422
423@node SRFI-1 Length Append etc
3229f68b 424@subsubsection Length, Append, Concatenate, etc.
a0e07ba4
NJ
425
426@c FIXME::martin: Review me!
427
8f85c0c6 428@deffn {Scheme Procedure} length+ lst
a0e07ba4
NJ
429Return the length of the argument list @var{lst}. When @var{lst} is a
430circular list, @code{#f} is returned.
431@end deffn
432
8f85c0c6
NJ
433@deffn {Scheme Procedure} concatenate list-of-lists
434@deffnx {Scheme Procedure} concatenate! list-of-lists
a0e07ba4
NJ
435Construct a list by appending all lists in @var{list-of-lists}.
436
437@code{concatenate!} may modify the structure of the given lists in
438order to produce the result.
a3e856f2
KR
439
440@code{concatenate} is the same as @code{(apply append
441@var{list-of-lists})}. It exists because some Scheme implementations
442have a limit on the number of arguments a function takes, which the
443@code{apply} might exceed. In Guile there is no such limit.
a0e07ba4
NJ
444@end deffn
445
8f85c0c6
NJ
446@deffn {Scheme Procedure} append-reverse rev-head tail
447@deffnx {Scheme Procedure} append-reverse! rev-head tail
23f2b9a3
KR
448Reverse @var{rev-head}, append @var{tail} to it, and return the
449result. This is equivalent to @code{(append (reverse @var{rev-head})
450@var{tail})}, but its implementation is more efficient.
451
452@example
453(append-reverse '(1 2 3) '(4 5 6)) @result{} (3 2 1 4 5 6)
454@end example
a0e07ba4
NJ
455
456@code{append-reverse!} may modify @var{rev-head} in order to produce
457the result.
458@end deffn
459
8f85c0c6 460@deffn {Scheme Procedure} zip lst1 lst2 @dots{}
a0e07ba4
NJ
461Return a list as long as the shortest of the argument lists, where
462each element is a list. The first list contains the first elements of
463the argument lists, the second list contains the second elements, and
464so on.
465@end deffn
466
8f85c0c6
NJ
467@deffn {Scheme Procedure} unzip1 lst
468@deffnx {Scheme Procedure} unzip2 lst
469@deffnx {Scheme Procedure} unzip3 lst
470@deffnx {Scheme Procedure} unzip4 lst
471@deffnx {Scheme Procedure} unzip5 lst
a0e07ba4
NJ
472@code{unzip1} takes a list of lists, and returns a list containing the
473first elements of each list, @code{unzip2} returns two lists, the
474first containing the first elements of each lists and the second
475containing the second elements of each lists, and so on.
476@end deffn
477
df0a1002 478@deffn {Scheme Procedure} count pred lst1 lst2 @dots{}
e508c863
KR
479Return a count of the number of times @var{pred} returns true when
480called on elements from the given lists.
481
482@var{pred} is called with @var{N} parameters @code{(@var{pred}
df0a1002
BT
483@var{elem1} @dots{} @var{elemN} )}, each element being from the
484corresponding list. The first call is with the first element of each
485list, the second with the second element from each, and so on.
e508c863
KR
486
487Counting stops when the end of the shortest list is reached. At least
488one list must be non-circular.
489@end deffn
490
a0e07ba4
NJ
491
492@node SRFI-1 Fold and Map
3229f68b 493@subsubsection Fold, Unfold & Map
7c2e18cd
KR
494@cindex list fold
495@cindex list map
a0e07ba4
NJ
496
497@c FIXME::martin: Review me!
498
df0a1002
BT
499@deffn {Scheme Procedure} fold proc init lst1 lst2 @dots{}
500@deffnx {Scheme Procedure} fold-right proc init lst1 lst2 @dots{}
501Apply @var{proc} to the elements of @var{lst1} @var{lst2} @dots{} to
1e181a08 502build a result, and return that result.
a0e07ba4 503
df0a1002
BT
504Each @var{proc} call is @code{(@var{proc} @var{elem1} @var{elem2}
505@dots{} @var{previous})}, where @var{elem1} is from @var{lst1},
506@var{elem2} is from @var{lst2}, and so on. @var{previous} is the return
1e181a08
KR
507from the previous call to @var{proc}, or the given @var{init} for the
508first call. If any list is empty, just @var{init} is returned.
a0e07ba4 509
1e181a08
KR
510@code{fold} works through the list elements from first to last. The
511following shows a list reversal and the calls it makes,
a0e07ba4 512
1e181a08
KR
513@example
514(fold cons '() '(1 2 3))
a0e07ba4 515
1e181a08
KR
516(cons 1 '())
517(cons 2 '(1))
518(cons 3 '(2 1)
519@result{} (3 2 1)
520@end example
a0e07ba4 521
1e181a08
KR
522@code{fold-right} works through the list elements from last to first,
523ie.@: from the right. So for example the following finds the longest
524string, and the last among equal longest,
525
526@example
527(fold-right (lambda (str prev)
528 (if (> (string-length str) (string-length prev))
529 str
530 prev))
531 ""
532 '("x" "abc" "xyz" "jk"))
533@result{} "xyz"
534@end example
a0e07ba4 535
df0a1002 536If @var{lst1} @var{lst2} @dots{} have different lengths, @code{fold}
1e181a08 537stops when the end of the shortest is reached; @code{fold-right}
df0a1002
BT
538commences at the last element of the shortest. Ie.@: elements past the
539length of the shortest are ignored in the other @var{lst}s. At least
540one @var{lst} must be non-circular.
1e181a08
KR
541
542@code{fold} should be preferred over @code{fold-right} if the order of
543processing doesn't matter, or can be arranged either way, since
544@code{fold} is a little more efficient.
545
546The way @code{fold} builds a result from iterating is quite general,
547it can do more than other iterations like say @code{map} or
548@code{filter}. The following for example removes adjacent duplicate
549elements from a list,
550
551@example
552(define (delete-adjacent-duplicates lst)
553 (fold-right (lambda (elem ret)
554 (if (equal? elem (first ret))
555 ret
556 (cons elem ret)))
557 (list (last lst))
558 lst))
559(delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
560@result{} (1 2 3 4 5)
561@end example
562
563Clearly the same sort of thing can be done with a @code{for-each} and
5f708db6
KR
564a variable in which to build the result, but a self-contained
565@var{proc} can be re-used in multiple contexts, where a
566@code{for-each} would have to be written out each time.
a0e07ba4
NJ
567@end deffn
568
df0a1002
BT
569@deffn {Scheme Procedure} pair-fold proc init lst1 lst2 @dots{}
570@deffnx {Scheme Procedure} pair-fold-right proc init lst1 lst2 @dots{}
1e181a08
KR
571The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
572the pairs of the lists instead of the list elements.
a0e07ba4
NJ
573@end deffn
574
5f708db6
KR
575@deffn {Scheme Procedure} reduce proc default lst
576@deffnx {Scheme Procedure} reduce-right proc default lst
577@code{reduce} is a variant of @code{fold}, where the first call to
578@var{proc} is on two elements from @var{lst}, rather than one element
579and a given initial value.
1e181a08 580
5f708db6
KR
581If @var{lst} is empty, @code{reduce} returns @var{default} (this is
582the only use for @var{default}). If @var{lst} has just one element
583then that's the return value. Otherwise @var{proc} is called on the
584elements of @var{lst}.
1e181a08 585
5f708db6
KR
586Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
587where @var{elem} is from @var{lst} (the second and subsequent elements
588of @var{lst}), and @var{previous} is the return from the previous call
589to @var{proc}. The first element of @var{lst} is the @var{previous}
590for the first call to @var{proc}.
1e181a08 591
5f708db6
KR
592For example, the following adds a list of numbers, the calls made to
593@code{+} are shown. (Of course @code{+} accepts multiple arguments
594and can add a list directly, with @code{apply}.)
1e181a08
KR
595
596@example
5f708db6
KR
597(reduce + 0 '(5 6 7)) @result{} 18
598
599(+ 6 5) @result{} 11
600(+ 7 11) @result{} 18
1e181a08
KR
601@end example
602
5f708db6
KR
603@code{reduce} can be used instead of @code{fold} where the @var{init}
604value is an ``identity'', meaning a value which under @var{proc}
605doesn't change the result, in this case 0 is an identity since
606@code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
1e181a08
KR
607
608@code{reduce-right} is a similar variation on @code{fold-right},
5f708db6
KR
609working from the end (ie.@: the right) of @var{lst}. The last element
610of @var{lst} is the @var{previous} for the first call to @var{proc},
611and the @var{elem} values go from the second last.
1e181a08
KR
612
613@code{reduce} should be preferred over @code{reduce-right} if the
614order of processing doesn't matter, or can be arranged either way,
615since @code{reduce} is a little more efficient.
a0e07ba4
NJ
616@end deffn
617
8f85c0c6 618@deffn {Scheme Procedure} unfold p f g seed [tail-gen]
a0e07ba4
NJ
619@code{unfold} is defined as follows:
620
621@lisp
622(unfold p f g seed) =
623 (if (p seed) (tail-gen seed)
624 (cons (f seed)
625 (unfold p f g (g seed))))
626@end lisp
627
628@table @var
629@item p
630Determines when to stop unfolding.
631
632@item f
633Maps each seed value to the corresponding list element.
634
635@item g
ecb87335 636Maps each seed value to next seed value.
a0e07ba4
NJ
637
638@item seed
639The state value for the unfold.
640
641@item tail-gen
642Creates the tail of the list; defaults to @code{(lambda (x) '())}.
643@end table
644
645@var{g} produces a series of seed values, which are mapped to list
646elements by @var{f}. These elements are put into a list in
647left-to-right order, and @var{p} tells when to stop unfolding.
648@end deffn
649
8f85c0c6 650@deffn {Scheme Procedure} unfold-right p f g seed [tail]
a0e07ba4
NJ
651Construct a list with the following loop.
652
653@lisp
654(let lp ((seed seed) (lis tail))
655 (if (p seed) lis
656 (lp (g seed)
657 (cons (f seed) lis))))
658@end lisp
659
660@table @var
661@item p
662Determines when to stop unfolding.
663
664@item f
665Maps each seed value to the corresponding list element.
666
667@item g
ecb87335 668Maps each seed value to next seed value.
a0e07ba4
NJ
669
670@item seed
671The state value for the unfold.
672
673@item tail-gen
674Creates the tail of the list; defaults to @code{(lambda (x) '())}.
675@end table
676
677@end deffn
678
8f85c0c6 679@deffn {Scheme Procedure} map f lst1 lst2 @dots{}
a0e07ba4
NJ
680Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
681return a list containing the results of the procedure applications.
682This procedure is extended with respect to R5RS, because the argument
683lists may have different lengths. The result list will have the same
684length as the shortest argument lists. The order in which @var{f}
685will be applied to the list element(s) is not specified.
686@end deffn
687
8f85c0c6 688@deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
a0e07ba4
NJ
689Apply the procedure @var{f} to each pair of corresponding elements of
690the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
691specified. This procedure is extended with respect to R5RS, because
692the argument lists may have different lengths. The shortest argument
693list determines the number of times @var{f} is called. @var{f} will
85a9b4ed 694be applied to the list elements in left-to-right order.
a0e07ba4
NJ
695
696@end deffn
697
8f85c0c6
NJ
698@deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
699@deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
12991fed 700Equivalent to
a0e07ba4
NJ
701
702@lisp
12991fed 703(apply append (map f clist1 clist2 ...))
a0e07ba4
NJ
704@end lisp
705
12991fed 706and
a0e07ba4
NJ
707
708@lisp
12991fed 709(apply append! (map f clist1 clist2 ...))
a0e07ba4
NJ
710@end lisp
711
712Map @var{f} over the elements of the lists, just as in the @code{map}
713function. However, the results of the applications are appended
714together to make the final result. @code{append-map} uses
715@code{append} to append the results together; @code{append-map!} uses
716@code{append!}.
717
718The dynamic order in which the various applications of @var{f} are
719made is not specified.
720@end deffn
721
8f85c0c6 722@deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
a0e07ba4
NJ
723Linear-update variant of @code{map} -- @code{map!} is allowed, but not
724required, to alter the cons cells of @var{lst1} to construct the
725result list.
726
727The dynamic order in which the various applications of @var{f} are
728made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
729@dots{} must have at least as many elements as @var{lst1}.
730@end deffn
731
8f85c0c6 732@deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
a0e07ba4
NJ
733Like @code{for-each}, but applies the procedure @var{f} to the pairs
734from which the argument lists are constructed, instead of the list
735elements. The return value is not specified.
736@end deffn
737
8f85c0c6 738@deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
a0e07ba4
NJ
739Like @code{map}, but only results from the applications of @var{f}
740which are true are saved in the result list.
741@end deffn
742
743
744@node SRFI-1 Filtering and Partitioning
3229f68b 745@subsubsection Filtering and Partitioning
7c2e18cd
KR
746@cindex list filter
747@cindex list partition
a0e07ba4
NJ
748
749@c FIXME::martin: Review me!
750
751Filtering means to collect all elements from a list which satisfy a
752specific condition. Partitioning a list means to make two groups of
753list elements, one which contains the elements satisfying a condition,
754and the other for the elements which don't.
755
60e25dc4
KR
756The @code{filter} and @code{filter!} functions are implemented in the
757Guile core, @xref{List Modification}.
a0e07ba4 758
8f85c0c6
NJ
759@deffn {Scheme Procedure} partition pred lst
760@deffnx {Scheme Procedure} partition! pred lst
193239f1
KR
761Split @var{lst} into those elements which do and don't satisfy the
762predicate @var{pred}.
a0e07ba4 763
193239f1
KR
764The return is two values (@pxref{Multiple Values}), the first being a
765list of all elements from @var{lst} which satisfy @var{pred}, the
766second a list of those which do not.
767
768The elements in the result lists are in the same order as in @var{lst}
769but the order in which the calls @code{(@var{pred} elem)} are made on
770the list elements is unspecified.
771
772@code{partition} does not change @var{lst}, but one of the returned
773lists may share a tail with it. @code{partition!} may modify
774@var{lst} to construct its return.
a0e07ba4
NJ
775@end deffn
776
8f85c0c6
NJ
777@deffn {Scheme Procedure} remove pred lst
778@deffnx {Scheme Procedure} remove! pred lst
a0e07ba4
NJ
779Return a list containing all elements from @var{lst} which do not
780satisfy the predicate @var{pred}. The elements in the result list
781have the same order as in @var{lst}. The order in which @var{pred} is
782applied to the list elements is not specified.
783
784@code{remove!} is allowed, but not required to modify the structure of
785the input list.
786@end deffn
787
788
789@node SRFI-1 Searching
3229f68b 790@subsubsection Searching
7c2e18cd 791@cindex list search
a0e07ba4
NJ
792
793@c FIXME::martin: Review me!
794
795The procedures for searching elements in lists either accept a
796predicate or a comparison object for determining which elements are to
797be searched.
798
8f85c0c6 799@deffn {Scheme Procedure} find pred lst
a0e07ba4
NJ
800Return the first element of @var{lst} which satisfies the predicate
801@var{pred} and @code{#f} if no such element is found.
802@end deffn
803
8f85c0c6 804@deffn {Scheme Procedure} find-tail pred lst
a0e07ba4
NJ
805Return the first pair of @var{lst} whose @sc{car} satisfies the
806predicate @var{pred} and @code{#f} if no such element is found.
807@end deffn
808
8f85c0c6
NJ
809@deffn {Scheme Procedure} take-while pred lst
810@deffnx {Scheme Procedure} take-while! pred lst
a0e07ba4
NJ
811Return the longest initial prefix of @var{lst} whose elements all
812satisfy the predicate @var{pred}.
813
814@code{take-while!} is allowed, but not required to modify the input
815list while producing the result.
816@end deffn
817
8f85c0c6 818@deffn {Scheme Procedure} drop-while pred lst
a0e07ba4
NJ
819Drop the longest initial prefix of @var{lst} whose elements all
820satisfy the predicate @var{pred}.
821@end deffn
822
8f85c0c6
NJ
823@deffn {Scheme Procedure} span pred lst
824@deffnx {Scheme Procedure} span! pred lst
825@deffnx {Scheme Procedure} break pred lst
826@deffnx {Scheme Procedure} break! pred lst
a0e07ba4
NJ
827@code{span} splits the list @var{lst} into the longest initial prefix
828whose elements all satisfy the predicate @var{pred}, and the remaining
829tail. @code{break} inverts the sense of the predicate.
830
831@code{span!} and @code{break!} are allowed, but not required to modify
832the structure of the input list @var{lst} in order to produce the
833result.
3e73b6f9
KR
834
835Note that the name @code{break} conflicts with the @code{break}
836binding established by @code{while} (@pxref{while do}). Applications
837wanting to use @code{break} from within a @code{while} loop will need
838to make a new define under a different name.
a0e07ba4
NJ
839@end deffn
840
df0a1002
BT
841@deffn {Scheme Procedure} any pred lst1 lst2 @dots{}
842Test whether any set of elements from @var{lst1} @var{lst2} @dots{}
843satisfies @var{pred}. If so, the return value is the return value from
844the successful @var{pred} call, or if not, the return value is
845@code{#f}.
62705beb 846
df0a1002
BT
847If there are n list arguments, then @var{pred} must be a predicate
848taking n arguments. Each @var{pred} call is @code{(@var{pred}
849@var{elem1} @var{elem2} @dots{} )} taking an element from each
850@var{lst}. The calls are made successively for the first, second, etc.
851elements of the lists, stopping when @var{pred} returns non-@code{#f},
852or when the end of the shortest list is reached.
62705beb 853
df0a1002 854The @var{pred} call on the last set of elements (i.e., when the end of
62705beb
KR
855the shortest list has been reached), if that point is reached, is a
856tail call.
857@end deffn
858
df0a1002
BT
859@deffn {Scheme Procedure} every pred lst1 lst2 @dots{}
860Test whether every set of elements from @var{lst1} @var{lst2} @dots{}
861satisfies @var{pred}. If so, the return value is the return from the
862final @var{pred} call, or if not, the return value is @code{#f}.
62705beb 863
df0a1002
BT
864If there are n list arguments, then @var{pred} must be a predicate
865taking n arguments. Each @var{pred} call is @code{(@var{pred}
866@var{elem1} @var{elem2 @dots{}})} taking an element from each
867@var{lst}. The calls are made successively for the first, second, etc.
868elements of the lists, stopping if @var{pred} returns @code{#f}, or when
869the end of any of the lists is reached.
62705beb 870
df0a1002 871The @var{pred} call on the last set of elements (i.e., when the end of
62705beb
KR
872the shortest list has been reached) is a tail call.
873
df0a1002
BT
874If one of @var{lst1} @var{lst2} @dots{}is empty then no calls to
875@var{pred} are made, and the return value is @code{#t}.
a0e07ba4
NJ
876@end deffn
877
df0a1002 878@deffn {Scheme Procedure} list-index pred lst1 lst2 @dots{}
d1736abf 879Return the index of the first set of elements, one from each of
df0a1002 880@var{lst1} @var{lst2} @dots{}, which satisfies @var{pred}.
d1736abf 881
df0a1002 882@var{pred} is called as @code{(@var{elem1} @var{elem2 @dots{}})}.
d1736abf
KR
883Searching stops when the end of the shortest @var{lst} is reached.
884The return index starts from 0 for the first set of elements. If no
df0a1002 885set of elements pass, then the return value is @code{#f}.
0166e7f2
KR
886
887@example
888(list-index odd? '(2 4 6 9)) @result{} 3
889(list-index = '(1 2 3) '(3 1 2)) @result{} #f
890@end example
a0e07ba4
NJ
891@end deffn
892
8f85c0c6 893@deffn {Scheme Procedure} member x lst [=]
a0e07ba4 894Return the first sublist of @var{lst} whose @sc{car} is equal to
ca04a5ae 895@var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
ea6ea01b 896
ca04a5ae
KR
897Equality is determined by @code{equal?}, or by the equality predicate
898@var{=} if given. @var{=} is called @code{(= @var{x} elem)},
899ie.@: with the given @var{x} first, so for example to find the first
900element greater than 5,
901
902@example
903(member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
904@end example
905
906This version of @code{member} extends the core @code{member}
907(@pxref{List Searching}) by accepting an equality predicate.
a0e07ba4
NJ
908@end deffn
909
910
911@node SRFI-1 Deleting
3229f68b 912@subsubsection Deleting
7c2e18cd 913@cindex list delete
a0e07ba4 914
8f85c0c6
NJ
915@deffn {Scheme Procedure} delete x lst [=]
916@deffnx {Scheme Procedure} delete! x lst [=]
b6b9376a
KR
917Return a list containing the elements of @var{lst} but with those
918equal to @var{x} deleted. The returned elements will be in the same
919order as they were in @var{lst}.
920
921Equality is determined by the @var{=} predicate, or @code{equal?} if
922not given. An equality call is made just once for each element, but
923the order in which the calls are made on the elements is unspecified.
a0e07ba4 924
243bdb63 925The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
b6b9376a
KR
926is first. This means for instance elements greater than 5 can be
927deleted with @code{(delete 5 lst <)}.
928
929@code{delete} does not modify @var{lst}, but the return might share a
930common tail with @var{lst}. @code{delete!} may modify the structure
931of @var{lst} to construct its return.
ea6ea01b 932
4eb21177
KR
933These functions extend the core @code{delete} and @code{delete!}
934(@pxref{List Modification}) in accepting an equality predicate. See
935also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
936deleting multiple elements from a list.
a0e07ba4
NJ
937@end deffn
938
8f85c0c6
NJ
939@deffn {Scheme Procedure} delete-duplicates lst [=]
940@deffnx {Scheme Procedure} delete-duplicates! lst [=]
b6b9376a
KR
941Return a list containing the elements of @var{lst} but without
942duplicates.
943
944When elements are equal, only the first in @var{lst} is retained.
945Equal elements can be anywhere in @var{lst}, they don't have to be
946adjacent. The returned list will have the retained elements in the
947same order as they were in @var{lst}.
948
949Equality is determined by the @var{=} predicate, or @code{equal?} if
950not given. Calls @code{(= x y)} are made with element @var{x} being
951before @var{y} in @var{lst}. A call is made at most once for each
952combination, but the sequence of the calls across the elements is
953unspecified.
954
955@code{delete-duplicates} does not modify @var{lst}, but the return
956might share a common tail with @var{lst}. @code{delete-duplicates!}
957may modify the structure of @var{lst} to construct its return.
958
959In the worst case, this is an @math{O(N^2)} algorithm because it must
960check each element against all those preceding it. For long lists it
961is more efficient to sort and then compare only adjacent elements.
a0e07ba4
NJ
962@end deffn
963
964
965@node SRFI-1 Association Lists
3229f68b 966@subsubsection Association Lists
7c2e18cd
KR
967@cindex association list
968@cindex alist
a0e07ba4
NJ
969
970@c FIXME::martin: Review me!
971
972Association lists are described in detail in section @ref{Association
973Lists}. The present section only documents the additional procedures
974for dealing with association lists defined by SRFI-1.
975
8f85c0c6 976@deffn {Scheme Procedure} assoc key alist [=]
23f2b9a3
KR
977Return the pair from @var{alist} which matches @var{key}. This
978extends the core @code{assoc} (@pxref{Retrieving Alist Entries}) by
979taking an optional @var{=} comparison procedure.
980
981The default comparison is @code{equal?}. If an @var{=} parameter is
679cceed 982given it's called @code{(@var{=} @var{key} @var{alistcar})}, i.e.@: the
23f2b9a3
KR
983given target @var{key} is the first argument, and a @code{car} from
984@var{alist} is second.
ea6ea01b 985
23f2b9a3
KR
986For example a case-insensitive string lookup,
987
988@example
989(assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
990@result{} ("YY" . 2)
991@end example
a0e07ba4
NJ
992@end deffn
993
8f85c0c6 994@deffn {Scheme Procedure} alist-cons key datum alist
5e5999f9
KR
995Cons a new association @var{key} and @var{datum} onto @var{alist} and
996return the result. This is equivalent to
a0e07ba4
NJ
997
998@lisp
999(cons (cons @var{key} @var{datum}) @var{alist})
1000@end lisp
1001
5e5999f9
KR
1002@code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
1003core does the same thing.
a0e07ba4
NJ
1004@end deffn
1005
8f85c0c6 1006@deffn {Scheme Procedure} alist-copy alist
a0e07ba4
NJ
1007Return a newly allocated copy of @var{alist}, that means that the
1008spine of the list as well as the pairs are copied.
1009@end deffn
1010
8f85c0c6
NJ
1011@deffn {Scheme Procedure} alist-delete key alist [=]
1012@deffnx {Scheme Procedure} alist-delete! key alist [=]
bd35f1f0
KR
1013Return a list containing the elements of @var{alist} but with those
1014elements whose keys are equal to @var{key} deleted. The returned
1015elements will be in the same order as they were in @var{alist}.
a0e07ba4 1016
bd35f1f0
KR
1017Equality is determined by the @var{=} predicate, or @code{equal?} if
1018not given. The order in which elements are tested is unspecified, but
679cceed 1019each equality call is made @code{(= key alistkey)}, i.e.@: the given
bd35f1f0
KR
1020@var{key} parameter is first and the key from @var{alist} second.
1021This means for instance all associations with a key greater than 5 can
1022be removed with @code{(alist-delete 5 alist <)}.
1023
1024@code{alist-delete} does not modify @var{alist}, but the return might
1025share a common tail with @var{alist}. @code{alist-delete!} may modify
1026the list structure of @var{alist} to construct its return.
a0e07ba4
NJ
1027@end deffn
1028
1029
1030@node SRFI-1 Set Operations
3229f68b 1031@subsubsection Set Operations on Lists
7c2e18cd 1032@cindex list set operation
a0e07ba4 1033
4eb21177
KR
1034Lists can be used to represent sets of objects. The procedures in
1035this section operate on such lists as sets.
1036
1037Note that lists are not an efficient way to implement large sets. The
9aa0c3dd 1038procedures here typically take time @math{@var{m}@cross{}@var{n}} when
4eb21177
KR
1039operating on @var{m} and @var{n} element lists. Other data structures
1040like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
1041Tables}) are faster.
1042
1043All these procedures take an equality predicate as the first argument.
1044This predicate is used for testing the objects in the list sets for
1045sameness. This predicate must be consistent with @code{eq?}
1046(@pxref{Equality}) in the sense that if two list elements are
1047@code{eq?} then they must also be equal under the predicate. This
1048simply means a given object must be equal to itself.
a0e07ba4 1049
df0a1002 1050@deffn {Scheme Procedure} lset<= = list @dots{}
4eb21177 1051Return @code{#t} if each list is a subset of the one following it.
df0a1002
BT
1052I.e., @var{list1} is a subset of @var{list2}, @var{list2} is a subset of
1053@var{list3}, etc., for as many lists as given. If only one list or no
1054lists are given, the return value is @code{#t}.
4eb21177
KR
1055
1056A list @var{x} is a subset of @var{y} if each element of @var{x} is
1057equal to some element in @var{y}. Elements are compared using the
1058given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
1059
1060@example
1061(lset<= eq?) @result{} #t
1062(lset<= eqv? '(1 2 3) '(1)) @result{} #f
1063(lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
1064@end example
a0e07ba4
NJ
1065@end deffn
1066
df0a1002 1067@deffn {Scheme Procedure} lset= = list @dots{}
4eb21177 1068Return @code{#t} if all argument lists are set-equal. @var{list1} is
df0a1002
BT
1069compared to @var{list2}, @var{list2} to @var{list3}, etc., for as many
1070lists as given. If only one list or no lists are given, the return
1071value is @code{#t}.
4eb21177
KR
1072
1073Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
1074is equal to some element of @var{y} and conversely each element of
1075@var{y} is equal to some element of @var{x}. The order of the
1076elements in the lists doesn't matter. Element equality is determined
1077with the given @var{=} procedure, called as @code{(@var{=} xelem
1078yelem)}, but exactly which calls are made is unspecified.
1079
1080@example
1081(lset= eq?) @result{} #t
1082(lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
1083(lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
1084@end example
a0e07ba4
NJ
1085@end deffn
1086
df0a1002
BT
1087@deffn {Scheme Procedure} lset-adjoin = list elem @dots{}
1088Add to @var{list} any of the given @var{elem}s not already in the list.
1089@var{elem}s are @code{cons}ed onto the start of @var{list} (so the
1090return value shares a common tail with @var{list}), but the order that
1091the @var{elem}s are added is unspecified.
4eb21177
KR
1092
1093The given @var{=} procedure is used for comparing elements, called as
df0a1002 1094@code{(@var{=} listelem elem)}, i.e., the second argument is one of
4eb21177
KR
1095the given @var{elem} parameters.
1096
1097@example
1098(lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
1099@end example
a0e07ba4
NJ
1100@end deffn
1101
df0a1002
BT
1102@deffn {Scheme Procedure} lset-union = list @dots{}
1103@deffnx {Scheme Procedure} lset-union! = list @dots{}
4eb21177
KR
1104Return the union of the argument list sets. The result is built by
1105taking the union of @var{list1} and @var{list2}, then the union of
df0a1002 1106that with @var{list3}, etc., for as many lists as given. For one list
4eb21177
KR
1107argument that list itself is the result, for no list arguments the
1108result is the empty list.
1109
1110The union of two lists @var{x} and @var{y} is formed as follows. If
1111@var{x} is empty then the result is @var{y}. Otherwise start with
1112@var{x} as the result and consider each @var{y} element (from first to
1113last). A @var{y} element not equal to something already in the result
1114is @code{cons}ed onto the result.
1115
1116The given @var{=} procedure is used for comparing elements, called as
1117@code{(@var{=} relem yelem)}. The first argument is from the result
1118accumulated so far, and the second is from the list being union-ed in.
1119But exactly which calls are made is otherwise unspecified.
1120
1121Notice that duplicate elements in @var{list1} (or the first non-empty
1122list) are preserved, but that repeated elements in subsequent lists
1123are only added once.
1124
1125@example
1126(lset-union eqv?) @result{} ()
1127(lset-union eqv? '(1 2 3)) @result{} (1 2 3)
1128(lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
1129@end example
1130
1131@code{lset-union} doesn't change the given lists but the result may
1132share a tail with the first non-empty list. @code{lset-union!} can
1133modify all of the given lists to form the result.
a0e07ba4
NJ
1134@end deffn
1135
8f85c0c6
NJ
1136@deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
1137@deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
4eb21177
KR
1138Return the intersection of @var{list1} with the other argument lists,
1139meaning those elements of @var{list1} which are also in all of
1140@var{list2} etc. For one list argument, just that list is returned.
1141
1142The test for an element of @var{list1} to be in the return is simply
1143that it's equal to some element in each of @var{list2} etc. Notice
1144this means an element appearing twice in @var{list1} but only once in
1145each of @var{list2} etc will go into the return twice. The return has
1146its elements in the same order as they were in @var{list1}.
1147
1148The given @var{=} procedure is used for comparing elements, called as
1149@code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1150and the second is from one of the subsequent lists. But exactly which
1151calls are made and in what order is unspecified.
1152
1153@example
1154(lset-intersection eqv? '(x y)) @result{} (x y)
1155(lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
1156(lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
1157@end example
1158
1159The return from @code{lset-intersection} may share a tail with
1160@var{list1}. @code{lset-intersection!} may modify @var{list1} to form
1161its result.
a0e07ba4
NJ
1162@end deffn
1163
8f85c0c6
NJ
1164@deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
1165@deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
4eb21177
KR
1166Return @var{list1} with any elements in @var{list2}, @var{list3} etc
1167removed (ie.@: subtracted). For one list argument, just that list is
1168returned.
1169
1170The given @var{=} procedure is used for comparing elements, called as
1171@code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1172and the second from one of the subsequent lists. But exactly which
1173calls are made and in what order is unspecified.
a0e07ba4 1174
4eb21177
KR
1175@example
1176(lset-difference eqv? '(x y)) @result{} (x y)
1177(lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
1178(lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
1179@end example
1180
1181The return from @code{lset-difference} may share a tail with
1182@var{list1}. @code{lset-difference!} may modify @var{list1} to form
1183its result.
a0e07ba4
NJ
1184@end deffn
1185
8f85c0c6
NJ
1186@deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
1187@deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
4eb21177
KR
1188Return two values (@pxref{Multiple Values}), the difference and
1189intersection of the argument lists as per @code{lset-difference} and
1190@code{lset-intersection} above.
1191
1192For two list arguments this partitions @var{list1} into those elements
1193of @var{list1} which are in @var{list2} and not in @var{list2}. (But
1194for more than two arguments there can be elements of @var{list1} which
1195are neither part of the difference nor the intersection.)
1196
1197One of the return values from @code{lset-diff+intersection} may share
1198a tail with @var{list1}. @code{lset-diff+intersection!} may modify
1199@var{list1} to form its results.
1200@end deffn
1201
df0a1002
BT
1202@deffn {Scheme Procedure} lset-xor = list @dots{}
1203@deffnx {Scheme Procedure} lset-xor! = list @dots{}
4eb21177
KR
1204Return an XOR of the argument lists. For two lists this means those
1205elements which are in exactly one of the lists. For more than two
1206lists it means those elements which appear in an odd number of the
1207lists.
1208
1209To be precise, the XOR of two lists @var{x} and @var{y} is formed by
1210taking those elements of @var{x} not equal to any element of @var{y},
1211plus those elements of @var{y} not equal to any element of @var{x}.
1212Equality is determined with the given @var{=} procedure, called as
1213@code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
1214from @var{y}, but which way around is unspecified. Exactly which
1215calls are made is also unspecified, as is the order of the elements in
1216the result.
1217
1218@example
1219(lset-xor eqv? '(x y)) @result{} (x y)
1220(lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
1221@end example
1222
1223The return from @code{lset-xor} may share a tail with one of the list
1224arguments. @code{lset-xor!} may modify @var{list1} to form its
1225result.
a0e07ba4
NJ
1226@end deffn
1227
1228
1229@node SRFI-2
3229f68b 1230@subsection SRFI-2 - and-let*
8742c48b 1231@cindex SRFI-2
a0e07ba4 1232
4fd0db14
KR
1233@noindent
1234The following syntax can be obtained with
a0e07ba4 1235
4fd0db14
KR
1236@lisp
1237(use-modules (srfi srfi-2))
1238@end lisp
a0e07ba4 1239
4fd0db14
KR
1240@deffn {library syntax} and-let* (clause @dots{}) body @dots{}
1241A combination of @code{and} and @code{let*}.
1242
1243Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
1244then evaluation stops and @code{#f} is returned. If all are
1245non-@code{#f} then @var{body} is evaluated and the last form gives the
6b1a6e4c
KR
1246return value, or if @var{body} is empty then the result is @code{#t}.
1247Each @var{clause} should be one of the following,
4fd0db14
KR
1248
1249@table @code
1250@item (symbol expr)
1251Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
1252Like @code{let*}, that binding is available to subsequent clauses.
1253@item (expr)
1254Evaluate @var{expr} and check for @code{#f}.
1255@item symbol
1256Get the value bound to @var{symbol} and check for @code{#f}.
1257@end table
a0e07ba4 1258
4fd0db14
KR
1259Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
1260instance @code{((eq? x y))}. One way to remember this is to imagine
1261the @code{symbol} in @code{(symbol expr)} is omitted.
a0e07ba4 1262
4fd0db14
KR
1263@code{and-let*} is good for calculations where a @code{#f} value means
1264termination, but where a non-@code{#f} value is going to be needed in
1265subsequent expressions.
1266
1267The following illustrates this, it returns text between brackets
1268@samp{[...]} in a string, or @code{#f} if there are no such brackets
1269(ie.@: either @code{string-index} gives @code{#f}).
1270
1271@example
1272(define (extract-brackets str)
1273 (and-let* ((start (string-index str #\[))
1274 (end (string-index str #\] start)))
1275 (substring str (1+ start) end)))
1276@end example
1277
1278The following shows plain variables and expressions tested too.
1279@code{diagnostic-levels} is taken to be an alist associating a
1280diagnostic type with a level. @code{str} is printed only if the type
1281is known and its level is high enough.
1282
1283@example
1284(define (show-diagnostic type str)
1285 (and-let* (want-diagnostics
1286 (level (assq-ref diagnostic-levels type))
1287 ((>= level current-diagnostic-level)))
1288 (display str)))
1289@end example
1290
1291The advantage of @code{and-let*} is that an extended sequence of
1292expressions and tests doesn't require lots of nesting as would arise
1293from separate @code{and} and @code{let*}, or from @code{cond} with
1294@code{=>}.
1295
1296@end deffn
a0e07ba4
NJ
1297
1298
1299@node SRFI-4
3229f68b 1300@subsection SRFI-4 - Homogeneous numeric vector datatypes
8742c48b 1301@cindex SRFI-4
a0e07ba4 1302
27219b32
AW
1303SRFI-4 provides an interface to uniform numeric vectors: vectors whose elements
1304are all of a single numeric type. Guile offers uniform numeric vectors for
1305signed and unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
1306floating point values, and, as an extension to SRFI-4, complex floating-point
1307numbers of these two sizes.
1308
1309The standard SRFI-4 procedures and data types may be included via loading the
1310appropriate module:
1311
1312@example
1313(use-modules (srfi srfi-4))
1314@end example
1315
1316This module is currently a part of the default Guile environment, but it is a
1317good practice to explicitly import the module. In the future, using SRFI-4
1318procedures without importing the SRFI-4 module will cause a deprecation message
1319to be printed. (Of course, one may call the C functions at any time. Would that
1320C had modules!)
1321
1322@menu
1323* SRFI-4 Overview:: The warp and weft of uniform numeric vectors.
1324* SRFI-4 API:: Uniform vectors, from Scheme and from C.
1325* SRFI-4 Generic Operations:: The general, operating on the specific.
1326* SRFI-4 and Bytevectors:: SRFI-4 vectors are backed by bytevectors.
1327* SRFI-4 Extensions:: Guile-specific extensions to the standard.
1328@end menu
1329
1330@node SRFI-4 Overview
1331@subsubsection SRFI-4 - Overview
1332
1333Uniform numeric vectors can be useful since they consume less memory
1334than the non-uniform, general vectors. Also, since the types they can
1335store correspond directly to C types, it is easier to work with them
1336efficiently on a low level. Consider image processing as an example,
1337where you want to apply a filter to some image. While you could store
1338the pixels of an image in a general vector and write a general
1339convolution function, things are much more efficient with uniform
1340vectors: the convolution function knows that all pixels are unsigned
13418-bit values (say), and can use a very tight inner loop.
1342
1343This is implemented in Scheme by having the compiler notice calls to the SRFI-4
1344accessors, and inline them to appropriate compiled code. From C you have access
1345to the raw array; functions for efficiently working with uniform numeric vectors
1346from C are listed at the end of this section.
1347
1348Uniform numeric vectors are the special case of one dimensional uniform
1349numeric arrays.
1350
1351There are 12 standard kinds of uniform numeric vectors, and they all have their
1352own complement of constructors, accessors, and so on. Procedures that operate on
1353a specific kind of uniform numeric vector have a ``tag'' in their name,
1354indicating the element type.
1355
1356@table @nicode
1357@item u8
1358unsigned 8-bit integers
1359
1360@item s8
1361signed 8-bit integers
1362
1363@item u16
1364unsigned 16-bit integers
1365
1366@item s16
1367signed 16-bit integers
1368
1369@item u32
1370unsigned 32-bit integers
1371
1372@item s32
1373signed 32-bit integers
1374
1375@item u64
1376unsigned 64-bit integers
1377
1378@item s64
1379signed 64-bit integers
1380
1381@item f32
1382the C type @code{float}
1383
1384@item f64
1385the C type @code{double}
1386
1387@end table
1388
1389In addition, Guile supports uniform arrays of complex numbers, with the
1390nonstandard tags:
1391
1392@table @nicode
1393
1394@item c32
1395complex numbers in rectangular form with the real and imaginary part
1396being a @code{float}
1397
1398@item c64
1399complex numbers in rectangular form with the real and imaginary part
1400being a @code{double}
1401
1402@end table
1403
1404The external representation (ie.@: read syntax) for these vectors is
1405similar to normal Scheme vectors, but with an additional tag from the
1406tables above indicating the vector's type. For example,
1407
1408@lisp
1409#u16(1 2 3)
1410#f64(3.1415 2.71)
1411@end lisp
1412
1413Note that the read syntax for floating-point here conflicts with
1414@code{#f} for false. In Standard Scheme one can write @code{(1 #f3)}
1415for a three element list @code{(1 #f 3)}, but for Guile @code{(1 #f3)}
1416is invalid. @code{(1 #f 3)} is almost certainly what one should write
1417anyway to make the intention clear, so this is rarely a problem.
1418
1419
1420@node SRFI-4 API
1421@subsubsection SRFI-4 - API
1422
1423Note that the @nicode{c32} and @nicode{c64} functions are only available from
1424@nicode{(srfi srfi-4 gnu)}.
1425
1426@deffn {Scheme Procedure} u8vector? obj
1427@deffnx {Scheme Procedure} s8vector? obj
1428@deffnx {Scheme Procedure} u16vector? obj
1429@deffnx {Scheme Procedure} s16vector? obj
1430@deffnx {Scheme Procedure} u32vector? obj
1431@deffnx {Scheme Procedure} s32vector? obj
1432@deffnx {Scheme Procedure} u64vector? obj
1433@deffnx {Scheme Procedure} s64vector? obj
1434@deffnx {Scheme Procedure} f32vector? obj
1435@deffnx {Scheme Procedure} f64vector? obj
1436@deffnx {Scheme Procedure} c32vector? obj
1437@deffnx {Scheme Procedure} c64vector? obj
1438@deffnx {C Function} scm_u8vector_p (obj)
1439@deffnx {C Function} scm_s8vector_p (obj)
1440@deffnx {C Function} scm_u16vector_p (obj)
1441@deffnx {C Function} scm_s16vector_p (obj)
1442@deffnx {C Function} scm_u32vector_p (obj)
1443@deffnx {C Function} scm_s32vector_p (obj)
1444@deffnx {C Function} scm_u64vector_p (obj)
1445@deffnx {C Function} scm_s64vector_p (obj)
1446@deffnx {C Function} scm_f32vector_p (obj)
1447@deffnx {C Function} scm_f64vector_p (obj)
1448@deffnx {C Function} scm_c32vector_p (obj)
1449@deffnx {C Function} scm_c64vector_p (obj)
1450Return @code{#t} if @var{obj} is a homogeneous numeric vector of the
1451indicated type.
1452@end deffn
1453
1454@deffn {Scheme Procedure} make-u8vector n [value]
1455@deffnx {Scheme Procedure} make-s8vector n [value]
1456@deffnx {Scheme Procedure} make-u16vector n [value]
1457@deffnx {Scheme Procedure} make-s16vector n [value]
1458@deffnx {Scheme Procedure} make-u32vector n [value]
1459@deffnx {Scheme Procedure} make-s32vector n [value]
1460@deffnx {Scheme Procedure} make-u64vector n [value]
1461@deffnx {Scheme Procedure} make-s64vector n [value]
1462@deffnx {Scheme Procedure} make-f32vector n [value]
1463@deffnx {Scheme Procedure} make-f64vector n [value]
1464@deffnx {Scheme Procedure} make-c32vector n [value]
1465@deffnx {Scheme Procedure} make-c64vector n [value]
5f6ffd66
BT
1466@deffnx {C Function} scm_make_u8vector (n, value)
1467@deffnx {C Function} scm_make_s8vector (n, value)
1468@deffnx {C Function} scm_make_u16vector (n, value)
1469@deffnx {C Function} scm_make_s16vector (n, value)
1470@deffnx {C Function} scm_make_u32vector (n, value)
1471@deffnx {C Function} scm_make_s32vector (n, value)
1472@deffnx {C Function} scm_make_u64vector (n, value)
1473@deffnx {C Function} scm_make_s64vector (n, value)
1474@deffnx {C Function} scm_make_f32vector (n, value)
1475@deffnx {C Function} scm_make_f64vector (n, value)
1476@deffnx {C Function} scm_make_c32vector (n, value)
1477@deffnx {C Function} scm_make_c64vector (n, value)
27219b32
AW
1478Return a newly allocated homogeneous numeric vector holding @var{n}
1479elements of the indicated type. If @var{value} is given, the vector
1480is initialized with that value, otherwise the contents are
1481unspecified.
1482@end deffn
1483
1484@deffn {Scheme Procedure} u8vector value @dots{}
1485@deffnx {Scheme Procedure} s8vector value @dots{}
1486@deffnx {Scheme Procedure} u16vector value @dots{}
1487@deffnx {Scheme Procedure} s16vector value @dots{}
1488@deffnx {Scheme Procedure} u32vector value @dots{}
1489@deffnx {Scheme Procedure} s32vector value @dots{}
1490@deffnx {Scheme Procedure} u64vector value @dots{}
1491@deffnx {Scheme Procedure} s64vector value @dots{}
1492@deffnx {Scheme Procedure} f32vector value @dots{}
1493@deffnx {Scheme Procedure} f64vector value @dots{}
1494@deffnx {Scheme Procedure} c32vector value @dots{}
1495@deffnx {Scheme Procedure} c64vector value @dots{}
1496@deffnx {C Function} scm_u8vector (values)
1497@deffnx {C Function} scm_s8vector (values)
1498@deffnx {C Function} scm_u16vector (values)
1499@deffnx {C Function} scm_s16vector (values)
1500@deffnx {C Function} scm_u32vector (values)
1501@deffnx {C Function} scm_s32vector (values)
1502@deffnx {C Function} scm_u64vector (values)
1503@deffnx {C Function} scm_s64vector (values)
1504@deffnx {C Function} scm_f32vector (values)
1505@deffnx {C Function} scm_f64vector (values)
1506@deffnx {C Function} scm_c32vector (values)
1507@deffnx {C Function} scm_c64vector (values)
1508Return a newly allocated homogeneous numeric vector of the indicated
1509type, holding the given parameter @var{value}s. The vector length is
1510the number of parameters given.
1511@end deffn
1512
1513@deffn {Scheme Procedure} u8vector-length vec
1514@deffnx {Scheme Procedure} s8vector-length vec
1515@deffnx {Scheme Procedure} u16vector-length vec
1516@deffnx {Scheme Procedure} s16vector-length vec
1517@deffnx {Scheme Procedure} u32vector-length vec
1518@deffnx {Scheme Procedure} s32vector-length vec
1519@deffnx {Scheme Procedure} u64vector-length vec
1520@deffnx {Scheme Procedure} s64vector-length vec
1521@deffnx {Scheme Procedure} f32vector-length vec
1522@deffnx {Scheme Procedure} f64vector-length vec
1523@deffnx {Scheme Procedure} c32vector-length vec
1524@deffnx {Scheme Procedure} c64vector-length vec
1525@deffnx {C Function} scm_u8vector_length (vec)
1526@deffnx {C Function} scm_s8vector_length (vec)
1527@deffnx {C Function} scm_u16vector_length (vec)
1528@deffnx {C Function} scm_s16vector_length (vec)
1529@deffnx {C Function} scm_u32vector_length (vec)
1530@deffnx {C Function} scm_s32vector_length (vec)
1531@deffnx {C Function} scm_u64vector_length (vec)
1532@deffnx {C Function} scm_s64vector_length (vec)
1533@deffnx {C Function} scm_f32vector_length (vec)
1534@deffnx {C Function} scm_f64vector_length (vec)
1535@deffnx {C Function} scm_c32vector_length (vec)
1536@deffnx {C Function} scm_c64vector_length (vec)
1537Return the number of elements in @var{vec}.
1538@end deffn
1539
1540@deffn {Scheme Procedure} u8vector-ref vec i
1541@deffnx {Scheme Procedure} s8vector-ref vec i
1542@deffnx {Scheme Procedure} u16vector-ref vec i
1543@deffnx {Scheme Procedure} s16vector-ref vec i
1544@deffnx {Scheme Procedure} u32vector-ref vec i
1545@deffnx {Scheme Procedure} s32vector-ref vec i
1546@deffnx {Scheme Procedure} u64vector-ref vec i
1547@deffnx {Scheme Procedure} s64vector-ref vec i
1548@deffnx {Scheme Procedure} f32vector-ref vec i
1549@deffnx {Scheme Procedure} f64vector-ref vec i
1550@deffnx {Scheme Procedure} c32vector-ref vec i
1551@deffnx {Scheme Procedure} c64vector-ref vec i
5f6ffd66
BT
1552@deffnx {C Function} scm_u8vector_ref (vec, i)
1553@deffnx {C Function} scm_s8vector_ref (vec, i)
1554@deffnx {C Function} scm_u16vector_ref (vec, i)
1555@deffnx {C Function} scm_s16vector_ref (vec, i)
1556@deffnx {C Function} scm_u32vector_ref (vec, i)
1557@deffnx {C Function} scm_s32vector_ref (vec, i)
1558@deffnx {C Function} scm_u64vector_ref (vec, i)
1559@deffnx {C Function} scm_s64vector_ref (vec, i)
1560@deffnx {C Function} scm_f32vector_ref (vec, i)
1561@deffnx {C Function} scm_f64vector_ref (vec, i)
1562@deffnx {C Function} scm_c32vector_ref (vec, i)
1563@deffnx {C Function} scm_c64vector_ref (vec, i)
27219b32
AW
1564Return the element at index @var{i} in @var{vec}. The first element
1565in @var{vec} is index 0.
1566@end deffn
1567
1568@deffn {Scheme Procedure} u8vector-set! vec i value
1569@deffnx {Scheme Procedure} s8vector-set! vec i value
1570@deffnx {Scheme Procedure} u16vector-set! vec i value
1571@deffnx {Scheme Procedure} s16vector-set! vec i value
1572@deffnx {Scheme Procedure} u32vector-set! vec i value
1573@deffnx {Scheme Procedure} s32vector-set! vec i value
1574@deffnx {Scheme Procedure} u64vector-set! vec i value
1575@deffnx {Scheme Procedure} s64vector-set! vec i value
1576@deffnx {Scheme Procedure} f32vector-set! vec i value
1577@deffnx {Scheme Procedure} f64vector-set! vec i value
1578@deffnx {Scheme Procedure} c32vector-set! vec i value
1579@deffnx {Scheme Procedure} c64vector-set! vec i value
5f6ffd66
BT
1580@deffnx {C Function} scm_u8vector_set_x (vec, i, value)
1581@deffnx {C Function} scm_s8vector_set_x (vec, i, value)
1582@deffnx {C Function} scm_u16vector_set_x (vec, i, value)
1583@deffnx {C Function} scm_s16vector_set_x (vec, i, value)
1584@deffnx {C Function} scm_u32vector_set_x (vec, i, value)
1585@deffnx {C Function} scm_s32vector_set_x (vec, i, value)
1586@deffnx {C Function} scm_u64vector_set_x (vec, i, value)
1587@deffnx {C Function} scm_s64vector_set_x (vec, i, value)
1588@deffnx {C Function} scm_f32vector_set_x (vec, i, value)
1589@deffnx {C Function} scm_f64vector_set_x (vec, i, value)
1590@deffnx {C Function} scm_c32vector_set_x (vec, i, value)
1591@deffnx {C Function} scm_c64vector_set_x (vec, i, value)
27219b32
AW
1592Set the element at index @var{i} in @var{vec} to @var{value}. The
1593first element in @var{vec} is index 0. The return value is
1594unspecified.
1595@end deffn
1596
1597@deffn {Scheme Procedure} u8vector->list vec
1598@deffnx {Scheme Procedure} s8vector->list vec
1599@deffnx {Scheme Procedure} u16vector->list vec
1600@deffnx {Scheme Procedure} s16vector->list vec
1601@deffnx {Scheme Procedure} u32vector->list vec
1602@deffnx {Scheme Procedure} s32vector->list vec
1603@deffnx {Scheme Procedure} u64vector->list vec
1604@deffnx {Scheme Procedure} s64vector->list vec
1605@deffnx {Scheme Procedure} f32vector->list vec
1606@deffnx {Scheme Procedure} f64vector->list vec
1607@deffnx {Scheme Procedure} c32vector->list vec
1608@deffnx {Scheme Procedure} c64vector->list vec
1609@deffnx {C Function} scm_u8vector_to_list (vec)
1610@deffnx {C Function} scm_s8vector_to_list (vec)
1611@deffnx {C Function} scm_u16vector_to_list (vec)
1612@deffnx {C Function} scm_s16vector_to_list (vec)
1613@deffnx {C Function} scm_u32vector_to_list (vec)
1614@deffnx {C Function} scm_s32vector_to_list (vec)
1615@deffnx {C Function} scm_u64vector_to_list (vec)
1616@deffnx {C Function} scm_s64vector_to_list (vec)
1617@deffnx {C Function} scm_f32vector_to_list (vec)
1618@deffnx {C Function} scm_f64vector_to_list (vec)
1619@deffnx {C Function} scm_c32vector_to_list (vec)
1620@deffnx {C Function} scm_c64vector_to_list (vec)
1621Return a newly allocated list holding all elements of @var{vec}.
1622@end deffn
1623
1624@deffn {Scheme Procedure} list->u8vector lst
1625@deffnx {Scheme Procedure} list->s8vector lst
1626@deffnx {Scheme Procedure} list->u16vector lst
1627@deffnx {Scheme Procedure} list->s16vector lst
1628@deffnx {Scheme Procedure} list->u32vector lst
1629@deffnx {Scheme Procedure} list->s32vector lst
1630@deffnx {Scheme Procedure} list->u64vector lst
1631@deffnx {Scheme Procedure} list->s64vector lst
1632@deffnx {Scheme Procedure} list->f32vector lst
1633@deffnx {Scheme Procedure} list->f64vector lst
1634@deffnx {Scheme Procedure} list->c32vector lst
1635@deffnx {Scheme Procedure} list->c64vector lst
1636@deffnx {C Function} scm_list_to_u8vector (lst)
1637@deffnx {C Function} scm_list_to_s8vector (lst)
1638@deffnx {C Function} scm_list_to_u16vector (lst)
1639@deffnx {C Function} scm_list_to_s16vector (lst)
1640@deffnx {C Function} scm_list_to_u32vector (lst)
1641@deffnx {C Function} scm_list_to_s32vector (lst)
1642@deffnx {C Function} scm_list_to_u64vector (lst)
1643@deffnx {C Function} scm_list_to_s64vector (lst)
1644@deffnx {C Function} scm_list_to_f32vector (lst)
1645@deffnx {C Function} scm_list_to_f64vector (lst)
1646@deffnx {C Function} scm_list_to_c32vector (lst)
1647@deffnx {C Function} scm_list_to_c64vector (lst)
1648Return a newly allocated homogeneous numeric vector of the indicated type,
1649initialized with the elements of the list @var{lst}.
1650@end deffn
1651
1652@deftypefn {C Function} SCM scm_take_u8vector (const scm_t_uint8 *data, size_t len)
1653@deftypefnx {C Function} SCM scm_take_s8vector (const scm_t_int8 *data, size_t len)
1654@deftypefnx {C Function} SCM scm_take_u16vector (const scm_t_uint16 *data, size_t len)
1655@deftypefnx {C Function} SCM scm_take_s16vector (const scm_t_int16 *data, size_t len)
1656@deftypefnx {C Function} SCM scm_take_u32vector (const scm_t_uint32 *data, size_t len)
1657@deftypefnx {C Function} SCM scm_take_s32vector (const scm_t_int32 *data, size_t len)
1658@deftypefnx {C Function} SCM scm_take_u64vector (const scm_t_uint64 *data, size_t len)
1659@deftypefnx {C Function} SCM scm_take_s64vector (const scm_t_int64 *data, size_t len)
1660@deftypefnx {C Function} SCM scm_take_f32vector (const float *data, size_t len)
1661@deftypefnx {C Function} SCM scm_take_f64vector (const double *data, size_t len)
1662@deftypefnx {C Function} SCM scm_take_c32vector (const float *data, size_t len)
1663@deftypefnx {C Function} SCM scm_take_c64vector (const double *data, size_t len)
1664Return a new uniform numeric vector of the indicated type and length
1665that uses the memory pointed to by @var{data} to store its elements.
1666This memory will eventually be freed with @code{free}. The argument
1667@var{len} specifies the number of elements in @var{data}, not its size
1668in bytes.
1669
1670The @code{c32} and @code{c64} variants take a pointer to a C array of
1671@code{float}s or @code{double}s. The real parts of the complex numbers
1672are at even indices in that array, the corresponding imaginary parts are
1673at the following odd index.
1674@end deftypefn
1675
1676@deftypefn {C Function} {const scm_t_uint8 *} scm_u8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1677@deftypefnx {C Function} {const scm_t_int8 *} scm_s8vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1678@deftypefnx {C Function} {const scm_t_uint16 *} scm_u16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1679@deftypefnx {C Function} {const scm_t_int16 *} scm_s16vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1680@deftypefnx {C Function} {const scm_t_uint32 *} scm_u32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1681@deftypefnx {C Function} {const scm_t_int32 *} scm_s32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1682@deftypefnx {C Function} {const scm_t_uint64 *} scm_u64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1683@deftypefnx {C Function} {const scm_t_int64 *} scm_s64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
ecb87335 1684@deftypefnx {C Function} {const float *} scm_f32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
27219b32
AW
1685@deftypefnx {C Function} {const double *} scm_f64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1686@deftypefnx {C Function} {const float *} scm_c32vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1687@deftypefnx {C Function} {const double *} scm_c64vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1688Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
1689returns a pointer to the elements of a uniform numeric vector of the
1690indicated kind.
1691@end deftypefn
1692
1693@deftypefn {C Function} {scm_t_uint8 *} scm_u8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1694@deftypefnx {C Function} {scm_t_int8 *} scm_s8vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1695@deftypefnx {C Function} {scm_t_uint16 *} scm_u16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1696@deftypefnx {C Function} {scm_t_int16 *} scm_s16vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1697@deftypefnx {C Function} {scm_t_uint32 *} scm_u32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1698@deftypefnx {C Function} {scm_t_int32 *} scm_s32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1699@deftypefnx {C Function} {scm_t_uint64 *} scm_u64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1700@deftypefnx {C Function} {scm_t_int64 *} scm_s64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
ecb87335 1701@deftypefnx {C Function} {float *} scm_f32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
27219b32
AW
1702@deftypefnx {C Function} {double *} scm_f64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1703@deftypefnx {C Function} {float *} scm_c32vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1704@deftypefnx {C Function} {double *} scm_c64vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1705Like @code{scm_vector_writable_elements} (@pxref{Vector Accessing from
1706C}), but returns a pointer to the elements of a uniform numeric vector
1707of the indicated kind.
1708@end deftypefn
1709
1710@node SRFI-4 Generic Operations
1711@subsubsection SRFI-4 - Generic operations
1712
1713Guile also provides procedures that operate on all types of uniform numeric
1714vectors. In what is probably a bug, these procedures are currently available in
1715the default environment as well; however prudent hackers will make sure to
1716import @code{(srfi srfi-4 gnu)} before using these.
1717
1718@deftypefn {C Function} int scm_is_uniform_vector (SCM uvec)
1719Return non-zero when @var{uvec} is a uniform numeric vector, zero
1720otherwise.
1721@end deftypefn
1722
1723@deftypefn {C Function} size_t scm_c_uniform_vector_length (SCM uvec)
1724Return the number of elements of @var{uvec} as a @code{size_t}.
1725@end deftypefn
1726
1727@deffn {Scheme Procedure} uniform-vector? obj
1728@deffnx {C Function} scm_uniform_vector_p (obj)
1729Return @code{#t} if @var{obj} is a homogeneous numeric vector of the
1730indicated type.
1731@end deffn
1732
1733@deffn {Scheme Procedure} uniform-vector-length vec
1734@deffnx {C Function} scm_uniform_vector_length (vec)
1735Return the number of elements in @var{vec}.
1736@end deffn
1737
1738@deffn {Scheme Procedure} uniform-vector-ref vec i
5f6ffd66 1739@deffnx {C Function} scm_uniform_vector_ref (vec, i)
27219b32
AW
1740Return the element at index @var{i} in @var{vec}. The first element
1741in @var{vec} is index 0.
1742@end deffn
1743
1744@deffn {Scheme Procedure} uniform-vector-set! vec i value
5f6ffd66 1745@deffnx {C Function} scm_uniform_vector_set_x (vec, i, value)
27219b32
AW
1746Set the element at index @var{i} in @var{vec} to @var{value}. The
1747first element in @var{vec} is index 0. The return value is
1748unspecified.
1749@end deffn
1750
1751@deffn {Scheme Procedure} uniform-vector->list vec
1752@deffnx {C Function} scm_uniform_vector_to_list (vec)
1753Return a newly allocated list holding all elements of @var{vec}.
1754@end deffn
1755
1756@deftypefn {C Function} {const void *} scm_uniform_vector_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1757Like @code{scm_vector_elements} (@pxref{Vector Accessing from C}), but
1758returns a pointer to the elements of a uniform numeric vector.
1759@end deftypefn
1760
1761@deftypefn {C Function} {void *} scm_uniform_vector_writable_elements (SCM vec, scm_t_array_handle *handle, size_t *lenp, ssize_t *incp)
1762Like @code{scm_vector_writable_elements} (@pxref{Vector Accessing from
1763C}), but returns a pointer to the elements of a uniform numeric vector.
1764@end deftypefn
1765
1766Unless you really need to the limited generality of these functions, it is best
1767to use the type-specific functions, or the generalized vector accessors.
1768
1769@node SRFI-4 and Bytevectors
1770@subsubsection SRFI-4 - Relation to bytevectors
1771
1772Guile implements SRFI-4 vectors using bytevectors (@pxref{Bytevectors}). Often
1773when you have a numeric vector, you end up wanting to write its bytes somewhere,
1774or have access to the underlying bytes, or read in bytes from somewhere else.
1775Bytevectors are very good at this sort of thing. But the SRFI-4 APIs are nicer
1776to use when doing number-crunching, because they are addressed by element and
1777not by byte.
1778
1779So as a compromise, Guile allows all bytevector functions to operate on numeric
1780vectors. They address the underlying bytes in the native endianness, as one
1781would expect.
1782
1783Following the same reasoning, that it's just bytes underneath, Guile also allows
1784uniform vectors of a given type to be accessed as if they were of any type. One
1785can fill a @nicode{u32vector}, and access its elements with
1786@nicode{u8vector-ref}. One can use @nicode{f64vector-ref} on bytevectors. It's
1787all the same to Guile.
1788
1789In this way, uniform numeric vectors may be written to and read from
1790input/output ports using the procedures that operate on bytevectors.
1791
1792@xref{Bytevectors}, for more information.
1793
1794
1795@node SRFI-4 Extensions
1796@subsubsection SRFI-4 - Guile extensions
1797
1798Guile defines some useful extensions to SRFI-4, which are not available in the
1799default Guile environment. They may be imported by loading the extensions
1800module:
1801
1802@example
1803(use-modules (srfi srfi-4 gnu))
1804@end example
1805
1806@deffn {Scheme Procedure} any->u8vector obj
1807@deffnx {Scheme Procedure} any->s8vector obj
1808@deffnx {Scheme Procedure} any->u16vector obj
1809@deffnx {Scheme Procedure} any->s16vector obj
1810@deffnx {Scheme Procedure} any->u32vector obj
1811@deffnx {Scheme Procedure} any->s32vector obj
1812@deffnx {Scheme Procedure} any->u64vector obj
1813@deffnx {Scheme Procedure} any->s64vector obj
1814@deffnx {Scheme Procedure} any->f32vector obj
1815@deffnx {Scheme Procedure} any->f64vector obj
1816@deffnx {Scheme Procedure} any->c32vector obj
1817@deffnx {Scheme Procedure} any->c64vector obj
1818@deffnx {C Function} scm_any_to_u8vector (obj)
1819@deffnx {C Function} scm_any_to_s8vector (obj)
1820@deffnx {C Function} scm_any_to_u16vector (obj)
1821@deffnx {C Function} scm_any_to_s16vector (obj)
1822@deffnx {C Function} scm_any_to_u32vector (obj)
1823@deffnx {C Function} scm_any_to_s32vector (obj)
1824@deffnx {C Function} scm_any_to_u64vector (obj)
1825@deffnx {C Function} scm_any_to_s64vector (obj)
1826@deffnx {C Function} scm_any_to_f32vector (obj)
1827@deffnx {C Function} scm_any_to_f64vector (obj)
1828@deffnx {C Function} scm_any_to_c32vector (obj)
1829@deffnx {C Function} scm_any_to_c64vector (obj)
1830Return a (maybe newly allocated) uniform numeric vector of the indicated
1831type, initialized with the elements of @var{obj}, which must be a list,
1832a vector, or a uniform vector. When @var{obj} is already a suitable
1833uniform numeric vector, it is returned unchanged.
1834@end deffn
1835
a0e07ba4
NJ
1836
1837@node SRFI-6
3229f68b 1838@subsection SRFI-6 - Basic String Ports
8742c48b 1839@cindex SRFI-6
a0e07ba4
NJ
1840
1841SRFI-6 defines the procedures @code{open-input-string},
1842@code{open-output-string} and @code{get-output-string}. These
1843procedures are included in the Guile core, so using this module does not
1844make any difference at the moment. But it is possible that support for
1845SRFI-6 will be factored out of the core library in the future, so using
1846this module does not hurt, after all.
1847
1848@node SRFI-8
3229f68b 1849@subsection SRFI-8 - receive
8742c48b 1850@cindex SRFI-8
a0e07ba4
NJ
1851
1852@code{receive} is a syntax for making the handling of multiple-value
1853procedures easier. It is documented in @xref{Multiple Values}.
1854
1855
1856@node SRFI-9
3229f68b 1857@subsection SRFI-9 - define-record-type
8742c48b 1858@cindex SRFI-9
7c2e18cd 1859@cindex record
a0e07ba4 1860
6afe385d
KR
1861This SRFI is a syntax for defining new record types and creating
1862predicate, constructor, and field getter and setter functions. In
1863Guile this is simply an alternate interface to the core record
1864functionality (@pxref{Records}). It can be used with,
a0e07ba4 1865
6afe385d
KR
1866@example
1867(use-modules (srfi srfi-9))
1868@end example
1869
1870@deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
1871@sp 1
1872Create a new record type, and make various @code{define}s for using
1873it. This syntax can only occur at the top-level, not nested within
1874some other form.
1875
1876@var{type} is bound to the record type, which is as per the return
1877from the core @code{make-record-type}. @var{type} also provides the
1878name for the record, as per @code{record-type-name}.
1879
1880@var{constructor} is bound to a function to be called as
1881@code{(@var{constructor} fieldval @dots{})} to create a new record of
1882this type. The arguments are initial values for the fields, one
1883argument for each field, in the order they appear in the
1884@code{define-record-type} form.
1885
1886The @var{fieldname}s provide the names for the record fields, as per
1887the core @code{record-type-fields} etc, and are referred to in the
1888subsequent accessor/modifier forms.
1889
ecb87335 1890@var{predicate} is bound to a function to be called as
6afe385d
KR
1891@code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
1892according to whether @var{obj} is a record of this type.
1893
1894Each @var{accessor} is bound to a function to be called
1895@code{(@var{accessor} record)} to retrieve the respective field from a
1896@var{record}. Similarly each @var{modifier} is bound to a function to
1897be called @code{(@var{modifier} record val)} to set the respective
1898field in a @var{record}.
1899@end deffn
1900
1901@noindent
1902An example will illustrate typical usage,
a0e07ba4
NJ
1903
1904@example
6afe385d
KR
1905(define-record-type employee-type
1906 (make-employee name age salary)
1907 employee?
1908 (name get-employee-name)
1909 (age get-employee-age set-employee-age)
1910 (salary get-employee-salary set-employee-salary))
a0e07ba4
NJ
1911@end example
1912
6afe385d
KR
1913This creates a new employee data type, with name, age and salary
1914fields. Accessor functions are created for each field, but no
1915modifier function for the name (the intention in this example being
1916that it's established only when an employee object is created). These
1917can all then be used as for example,
a0e07ba4
NJ
1918
1919@example
6afe385d
KR
1920employee-type @result{} #<record-type employee-type>
1921
1922(define fred (make-employee "Fred" 45 20000.00))
1923
1924(employee? fred) @result{} #t
1925(get-employee-age fred) @result{} 45
1926(set-employee-salary fred 25000.00) ;; pay rise
a0e07ba4
NJ
1927@end example
1928
6afe385d
KR
1929The functions created by @code{define-record-type} are ordinary
1930top-level @code{define}s. They can be redefined or @code{set!} as
1931desired, exported from a module, etc.
1932
531c9f1d
AR
1933@unnumberedsubsubsec Non-toplevel Record Definitions
1934
1935The SRFI-9 specification explicitly disallows record definitions in a
1936non-toplevel context, such as inside @code{lambda} body or inside a
1937@var{let} block. However, Guile's implementation does not enforce that
1938restriction.
1939
167510bc 1940@unnumberedsubsubsec Custom Printers
e525e4e4 1941
45f3d9b6 1942You may use @code{set-record-type-printer!} to customize the default printing
853cb356
NI
1943behavior of records. This is a Guile extension and is not part of SRFI-9. It
1944is located in the @nicode{(srfi srfi-9 gnu)} module.
e525e4e4 1945
45f3d9b6 1946@deffn {Scheme Syntax} set-record-type-printer! name thunk
e525e4e4
NI
1947Where @var{type} corresponds to the first argument of @code{define-record-type},
1948and @var{thunk} is a procedure accepting two arguments, the record to print, and
1949an output port.
e525e4e4
NI
1950@end deffn
1951
1952@noindent
167510bc 1953This example prints the employee's name in brackets, for instance @code{[Fred]}.
e525e4e4
NI
1954
1955@example
167510bc 1956(set-record-type-printer! employee-type
e525e4e4
NI
1957 (lambda (record port)
1958 (write-char #\[ port)
1959 (display (get-employee-name record) port)
1960 (write-char #\] port)))
1961@end example
a0e07ba4
NJ
1962
1963@node SRFI-10
3229f68b 1964@subsection SRFI-10 - Hash-Comma Reader Extension
8742c48b 1965@cindex SRFI-10
a0e07ba4
NJ
1966
1967@cindex hash-comma
1968@cindex #,()
633acbe2
KR
1969This SRFI implements a reader extension @code{#,()} called hash-comma.
1970It allows the reader to give new kinds of objects, for use both in
1971data and as constants or literals in source code. This feature is
1972available with
a0e07ba4 1973
633acbe2
KR
1974@example
1975(use-modules (srfi srfi-10))
1976@end example
1977
1978@noindent
1979The new read syntax is of the form
a0e07ba4
NJ
1980
1981@example
633acbe2 1982#,(@var{tag} @var{arg}@dots{})
a0e07ba4
NJ
1983@end example
1984
633acbe2
KR
1985@noindent
1986where @var{tag} is a symbol and the @var{arg}s are objects taken as
1987parameters. @var{tag}s are registered with the following procedure.
a0e07ba4 1988
633acbe2
KR
1989@deffn {Scheme Procedure} define-reader-ctor tag proc
1990Register @var{proc} as the constructor for a hash-comma read syntax
679cceed 1991starting with symbol @var{tag}, i.e.@: @nicode{#,(@var{tag} arg@dots{})}.
633acbe2
KR
1992@var{proc} is called with the given arguments @code{(@var{proc}
1993arg@dots{})} and the object it returns is the result of the read.
1994@end deffn
a0e07ba4 1995
633acbe2
KR
1996@noindent
1997For example, a syntax giving a list of @var{N} copies of an object.
1998
1999@example
2000(define-reader-ctor 'repeat
2001 (lambda (obj reps)
2002 (make-list reps obj)))
2003
2004(display '#,(repeat 99 3))
2005@print{} (99 99 99)
2006@end example
2007
2008Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
2009@code{repeat} handler returns a list and the program must quote to use
2010it literally, the same as any other list. Ie.
2011
2012@example
2013(display '#,(repeat 99 3))
a0e07ba4 2014@result{}
633acbe2
KR
2015(display '(99 99 99))
2016@end example
a0e07ba4 2017
633acbe2
KR
2018When a handler returns an object which is self-evaluating, like a
2019number or a string, then there's no need for quoting, just as there's
2020no need when giving those directly as literals. For example an
2021addition,
a0e07ba4 2022
633acbe2
KR
2023@example
2024(define-reader-ctor 'sum
2025 (lambda (x y)
2026 (+ x y)))
2027(display #,(sum 123 456)) @print{} 579
2028@end example
2029
2030A typical use for @nicode{#,()} is to get a read syntax for objects
2031which don't otherwise have one. For example, the following allows a
2032hash table to be given literally, with tags and values, ready for fast
2033lookup.
2034
2035@example
2036(define-reader-ctor 'hash
2037 (lambda elems
2038 (let ((table (make-hash-table)))
2039 (for-each (lambda (elem)
01549abb
KR
2040 (apply hash-set! table elem))
2041 elems)
633acbe2
KR
2042 table)))
2043
2044(define (animal->family animal)
2045 (hash-ref '#,(hash ("tiger" "cat")
2046 ("lion" "cat")
2047 ("wolf" "dog"))
2048 animal))
2049
2050(animal->family "lion") @result{} "cat"
2051@end example
2052
2053Or for example the following is a syntax for a compiled regular
2054expression (@pxref{Regular Expressions}).
2055
2056@example
2057(use-modules (ice-9 regex))
2058
2059(define-reader-ctor 'regexp make-regexp)
2060
2061(define (extract-angs str)
2062 (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
2063 (and match
2064 (match:substring match 1))))
2065
2066(extract-angs "foo <BAR> quux") @result{} "BAR"
2067@end example
2068
2069@sp 1
2070@nicode{#,()} is somewhat similar to @code{define-macro}
2071(@pxref{Macros}) in that handler code is run to produce a result, but
2072@nicode{#,()} operates at the read stage, so it can appear in data for
2073@code{read} (@pxref{Scheme Read}), not just in code to be executed.
2074
2075Because @nicode{#,()} is handled at read-time it has no direct access
2076to variables etc. A symbol in the arguments is just a symbol, not a
2077variable reference. The arguments are essentially constants, though
2078the handler procedure can use them in any complicated way it might
2079want.
2080
2081Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
2082globally, there's no need to use @code{(srfi srfi-10)} in later
2083modules. Similarly the tags registered are global and can be used
2084anywhere once registered.
2085
2086There's no attempt to record what previous @nicode{#,()} forms have
2087been seen, if two identical forms occur then two calls are made to the
2088handler procedure. The handler might like to maintain a cache or
2089similar to avoid making copies of large objects, depending on expected
2090usage.
2091
2092In code the best uses of @nicode{#,()} are generally when there's a
2093lot of objects of a particular kind as literals or constants. If
2094there's just a few then some local variables and initializers are
2095fine, but that becomes tedious and error prone when there's a lot, and
2096the anonymous and compact syntax of @nicode{#,()} is much better.
a0e07ba4
NJ
2097
2098
2099@node SRFI-11
3229f68b 2100@subsection SRFI-11 - let-values
8742c48b 2101@cindex SRFI-11
a0e07ba4 2102
8742c48b 2103@findex let-values
c010924a 2104@findex let*-values
a0e07ba4 2105This module implements the binding forms for multiple values
c010924a 2106@code{let-values} and @code{let*-values}. These forms are similar to
a0e07ba4
NJ
2107@code{let} and @code{let*} (@pxref{Local Bindings}), but they support
2108binding of the values returned by multiple-valued expressions.
2109
2110Write @code{(use-modules (srfi srfi-11))} to make the bindings
2111available.
2112
2113@lisp
2114(let-values (((x y) (values 1 2))
2115 ((z f) (values 3 4)))
2116 (+ x y z f))
2117@result{}
211810
2119@end lisp
2120
2121@code{let-values} performs all bindings simultaneously, which means that
2122no expression in the binding clauses may refer to variables bound in the
c010924a 2123same clause list. @code{let*-values}, on the other hand, performs the
a0e07ba4
NJ
2124bindings sequentially, just like @code{let*} does for single-valued
2125expressions.
2126
2127
2128@node SRFI-13
3229f68b 2129@subsection SRFI-13 - String Library
8742c48b 2130@cindex SRFI-13
a0e07ba4 2131
5676b4fa 2132The SRFI-13 procedures are always available, @xref{Strings}.
a0e07ba4
NJ
2133
2134@node SRFI-14
3229f68b 2135@subsection SRFI-14 - Character-set Library
8742c48b 2136@cindex SRFI-14
a0e07ba4 2137
050ab45f
MV
2138The SRFI-14 data type and procedures are always available,
2139@xref{Character Sets}.
a0e07ba4
NJ
2140
2141@node SRFI-16
3229f68b 2142@subsection SRFI-16 - case-lambda
8742c48b 2143@cindex SRFI-16
7c2e18cd
KR
2144@cindex variable arity
2145@cindex arity, variable
a0e07ba4 2146
f916cbc4
AW
2147SRFI-16 defines a variable-arity @code{lambda} form,
2148@code{case-lambda}. This form is available in the default Guile
2149environment. @xref{Case-lambda}, for more information.
a0e07ba4
NJ
2150
2151@node SRFI-17
3229f68b 2152@subsection SRFI-17 - Generalized set!
8742c48b 2153@cindex SRFI-17
a0e07ba4 2154
9a18d8d4
KR
2155This SRFI implements a generalized @code{set!}, allowing some
2156``referencing'' functions to be used as the target location of a
2157@code{set!}. This feature is available from
2158
2159@example
2160(use-modules (srfi srfi-17))
2161@end example
2162
2163@noindent
2164For example @code{vector-ref} is extended so that
2165
2166@example
2167(set! (vector-ref vec idx) new-value)
2168@end example
2169
2170@noindent
2171is equivalent to
2172
2173@example
2174(vector-set! vec idx new-value)
2175@end example
2176
2177The idea is that a @code{vector-ref} expression identifies a location,
2178which may be either fetched or stored. The same form is used for the
2179location in both cases, encouraging visual clarity. This is similar
2180to the idea of an ``lvalue'' in C.
2181
2182The mechanism for this kind of @code{set!} is in the Guile core
2183(@pxref{Procedures with Setters}). This module adds definitions of
2184the following functions as procedures with setters, allowing them to
2185be targets of a @code{set!},
2186
2187@quotation
2188@nicode{car}, @nicode{cdr}, @nicode{caar}, @nicode{cadr},
2189@nicode{cdar}, @nicode{cddr}, @nicode{caaar}, @nicode{caadr},
2190@nicode{cadar}, @nicode{caddr}, @nicode{cdaar}, @nicode{cdadr},
2191@nicode{cddar}, @nicode{cdddr}, @nicode{caaaar}, @nicode{caaadr},
2192@nicode{caadar}, @nicode{caaddr}, @nicode{cadaar}, @nicode{cadadr},
2193@nicode{caddar}, @nicode{cadddr}, @nicode{cdaaar}, @nicode{cdaadr},
2194@nicode{cdadar}, @nicode{cdaddr}, @nicode{cddaar}, @nicode{cddadr},
2195@nicode{cdddar}, @nicode{cddddr}
2196
2197@nicode{string-ref}, @nicode{vector-ref}
2198@end quotation
2199
2200The SRFI specifies @code{setter} (@pxref{Procedures with Setters}) as
2201a procedure with setter, allowing the setter for a procedure to be
2202changed, eg.@: @code{(set! (setter foo) my-new-setter-handler)}.
2203Currently Guile does not implement this, a setter can only be
2204specified on creation (@code{getter-with-setter} below).
2205
2206@defun getter-with-setter
2207The same as the Guile core @code{make-procedure-with-setter}
2208(@pxref{Procedures with Setters}).
2209@end defun
a0e07ba4 2210
12991fed 2211
e68f492a
JG
2212@node SRFI-18
2213@subsection SRFI-18 - Multithreading support
2214@cindex SRFI-18
2215
2216This is an implementation of the SRFI-18 threading and synchronization
2217library. The functions and variables described here are provided by
2218
2219@example
2220(use-modules (srfi srfi-18))
2221@end example
2222
2223As a general rule, the data types and functions in this SRFI-18
2224implementation are compatible with the types and functions in Guile's
2225core threading code. For example, mutexes created with the SRFI-18
2226@code{make-mutex} function can be passed to the built-in Guile
2227function @code{lock-mutex} (@pxref{Mutexes and Condition Variables}),
2228and mutexes created with the built-in Guile function @code{make-mutex}
2229can be passed to the SRFI-18 function @code{mutex-lock!}. Cases in
2230which this does not hold true are noted in the following sections.
2231
2232@menu
2233* SRFI-18 Threads:: Executing code
2234* SRFI-18 Mutexes:: Mutual exclusion devices
2235* SRFI-18 Condition variables:: Synchronizing of groups of threads
2236* SRFI-18 Time:: Representation of times and durations
2237* SRFI-18 Exceptions:: Signalling and handling errors
2238@end menu
2239
2240@node SRFI-18 Threads
2241@subsubsection SRFI-18 Threads
2242
2243Threads created by SRFI-18 differ in two ways from threads created by
2244Guile's built-in thread functions. First, a thread created by SRFI-18
2245@code{make-thread} begins in a blocked state and will not start
2246execution until @code{thread-start!} is called on it. Second, SRFI-18
2247threads are constructed with a top-level exception handler that
2248captures any exceptions that are thrown on thread exit. In all other
2249regards, SRFI-18 threads are identical to normal Guile threads.
2250
2251@defun current-thread
2252Returns the thread that called this function. This is the same
2253procedure as the same-named built-in procedure @code{current-thread}
2254(@pxref{Threads}).
2255@end defun
2256
2257@defun thread? obj
2258Returns @code{#t} if @var{obj} is a thread, @code{#f} otherwise. This
2259is the same procedure as the same-named built-in procedure
2260@code{thread?} (@pxref{Threads}).
2261@end defun
2262
2263@defun make-thread thunk [name]
2264Call @code{thunk} in a new thread and with a new dynamic state,
2265returning the new thread and optionally assigning it the object name
2266@var{name}, which may be any Scheme object.
2267
2268Note that the name @code{make-thread} conflicts with the
2269@code{(ice-9 threads)} function @code{make-thread}. Applications
2270wanting to use both of these functions will need to refer to them by
2271different names.
2272@end defun
2273
2274@defun thread-name thread
2275Returns the name assigned to @var{thread} at the time of its creation,
2276or @code{#f} if it was not given a name.
2277@end defun
2278
2279@defun thread-specific thread
2280@defunx thread-specific-set! thread obj
2281Get or set the ``object-specific'' property of @var{thread}. In
2282Guile's implementation of SRFI-18, this value is stored as an object
2283property, and will be @code{#f} if not set.
2284@end defun
2285
2286@defun thread-start! thread
2287Unblocks @var{thread} and allows it to begin execution if it has not
2288done so already.
2289@end defun
2290
2291@defun thread-yield!
2292If one or more threads are waiting to execute, calling
2293@code{thread-yield!} forces an immediate context switch to one of them.
2294Otherwise, @code{thread-yield!} has no effect. @code{thread-yield!}
2295behaves identically to the Guile built-in function @code{yield}.
2296@end defun
2297
2298@defun thread-sleep! timeout
2299The current thread waits until the point specified by the time object
2300@var{timeout} is reached (@pxref{SRFI-18 Time}). This blocks the
2301thread only if @var{timeout} represents a point in the future. it is
2302an error for @var{timeout} to be @code{#f}.
2303@end defun
2304
2305@defun thread-terminate! thread
2306Causes an abnormal termination of @var{thread}. If @var{thread} is
2307not already terminated, all mutexes owned by @var{thread} become
2308unlocked/abandoned. If @var{thread} is the current thread,
2309@code{thread-terminate!} does not return. Otherwise
2310@code{thread-terminate!} returns an unspecified value; the termination
2311of @var{thread} will occur before @code{thread-terminate!} returns.
2312Subsequent attempts to join on @var{thread} will cause a ``terminated
2313thread exception'' to be raised.
2314
2315@code{thread-terminate!} is compatible with the thread cancellation
2316procedures in the core threads API (@pxref{Threads}) in that if a
2317cleanup handler has been installed for the target thread, it will be
2318called before the thread exits and its return value (or exception, if
2319any) will be stored for later retrieval via a call to
2320@code{thread-join!}.
2321@end defun
2322
2323@defun thread-join! thread [timeout [timeout-val]]
2324Wait for @var{thread} to terminate and return its exit value. When a
2325time value @var{timeout} is given, it specifies a point in time where
2326the waiting should be aborted. When the waiting is aborted,
64de6db5 2327@var{timeout-val} is returned if it is specified; otherwise, a
e68f492a
JG
2328@code{join-timeout-exception} exception is raised
2329(@pxref{SRFI-18 Exceptions}). Exceptions may also be raised if the
2330thread was terminated by a call to @code{thread-terminate!}
2331(@code{terminated-thread-exception} will be raised) or if the thread
2332exited by raising an exception that was handled by the top-level
2333exception handler (@code{uncaught-exception} will be raised; the
2334original exception can be retrieved using
2335@code{uncaught-exception-reason}).
2336@end defun
2337
2338
2339@node SRFI-18 Mutexes
2340@subsubsection SRFI-18 Mutexes
2341
2342The behavior of Guile's built-in mutexes is parameterized via a set of
2343flags passed to the @code{make-mutex} procedure in the core
2344(@pxref{Mutexes and Condition Variables}). To satisfy the requirements
2345for mutexes specified by SRFI-18, the @code{make-mutex} procedure
2346described below sets the following flags:
2347@itemize @bullet
2348@item
2349@code{recursive}: the mutex can be locked recursively
2350@item
2351@code{unchecked-unlock}: attempts to unlock a mutex that is already
2352unlocked will not raise an exception
2353@item
2354@code{allow-external-unlock}: the mutex can be unlocked by any thread,
2355not just the thread that locked it originally
2356@end itemize
2357
2358@defun make-mutex [name]
2359Returns a new mutex, optionally assigning it the object name
2360@var{name}, which may be any Scheme object. The returned mutex will be
2361created with the configuration described above. Note that the name
2362@code{make-mutex} conflicts with Guile core function @code{make-mutex}.
2363Applications wanting to use both of these functions will need to refer
2364to them by different names.
2365@end defun
2366
2367@defun mutex-name mutex
2368Returns the name assigned to @var{mutex} at the time of its creation,
2369or @code{#f} if it was not given a name.
2370@end defun
2371
2372@defun mutex-specific mutex
2373@defunx mutex-specific-set! mutex obj
2374Get or set the ``object-specific'' property of @var{mutex}. In Guile's
2375implementation of SRFI-18, this value is stored as an object property,
2376and will be @code{#f} if not set.
2377@end defun
2378
2379@defun mutex-state mutex
2380Returns information about the state of @var{mutex}. Possible values
2381are:
2382@itemize @bullet
2383@item
2384thread @code{T}: the mutex is in the locked/owned state and thread T
2385is the owner of the mutex
2386@item
2387symbol @code{not-owned}: the mutex is in the locked/not-owned state
2388@item
2389symbol @code{abandoned}: the mutex is in the unlocked/abandoned state
2390@item
2391symbol @code{not-abandoned}: the mutex is in the
2392unlocked/not-abandoned state
2393@end itemize
2394@end defun
2395
2396@defun mutex-lock! mutex [timeout [thread]]
2397Lock @var{mutex}, optionally specifying a time object @var{timeout}
2398after which to abort the lock attempt and a thread @var{thread} giving
2399a new owner for @var{mutex} different than the current thread. This
2400procedure has the same behavior as the @code{lock-mutex} procedure in
2401the core library.
2402@end defun
2403
2404@defun mutex-unlock! mutex [condition-variable [timeout]]
2405Unlock @var{mutex}, optionally specifying a condition variable
2406@var{condition-variable} on which to wait, either indefinitely or,
2407optionally, until the time object @var{timeout} has passed, to be
2408signalled. This procedure has the same behavior as the
2409@code{unlock-mutex} procedure in the core library.
2410@end defun
2411
2412
2413@node SRFI-18 Condition variables
2414@subsubsection SRFI-18 Condition variables
2415
2416SRFI-18 does not specify a ``wait'' function for condition variables.
2417Waiting on a condition variable can be simulated using the SRFI-18
2418@code{mutex-unlock!} function described in the previous section, or
2419Guile's built-in @code{wait-condition-variable} procedure can be used.
2420
2421@defun condition-variable? obj
2422Returns @code{#t} if @var{obj} is a condition variable, @code{#f}
2423otherwise. This is the same procedure as the same-named built-in
2424procedure
2425(@pxref{Mutexes and Condition Variables, @code{condition-variable?}}).
2426@end defun
2427
2428@defun make-condition-variable [name]
2429Returns a new condition variable, optionally assigning it the object
2430name @var{name}, which may be any Scheme object. This procedure
2431replaces a procedure of the same name in the core library.
2432@end defun
2433
2434@defun condition-variable-name condition-variable
64de6db5
BT
2435Returns the name assigned to @var{condition-variable} at the time of its
2436creation, or @code{#f} if it was not given a name.
e68f492a
JG
2437@end defun
2438
2439@defun condition-variable-specific condition-variable
2440@defunx condition-variable-specific-set! condition-variable obj
2441Get or set the ``object-specific'' property of
2442@var{condition-variable}. In Guile's implementation of SRFI-18, this
2443value is stored as an object property, and will be @code{#f} if not
2444set.
2445@end defun
2446
2447@defun condition-variable-signal! condition-variable
2448@defunx condition-variable-broadcast! condition-variable
2449Wake up one thread that is waiting for @var{condition-variable}, in
2450the case of @code{condition-variable-signal!}, or all threads waiting
2451for it, in the case of @code{condition-variable-broadcast!}. The
2452behavior of these procedures is equivalent to that of the procedures
2453@code{signal-condition-variable} and
2454@code{broadcast-condition-variable} in the core library.
2455@end defun
2456
2457
2458@node SRFI-18 Time
2459@subsubsection SRFI-18 Time
2460
2461The SRFI-18 time functions manipulate time in two formats: a
2462``time object'' type that represents an absolute point in time in some
2463implementation-specific way; and the number of seconds since some
2464unspecified ``epoch''. In Guile's implementation, the epoch is the
2465Unix epoch, 00:00:00 UTC, January 1, 1970.
2466
2467@defun current-time
2468Return the current time as a time object. This procedure replaces
2469the procedure of the same name in the core library, which returns the
2470current time in seconds since the epoch.
2471@end defun
2472
2473@defun time? obj
2474Returns @code{#t} if @var{obj} is a time object, @code{#f} otherwise.
2475@end defun
2476
2477@defun time->seconds time
2478@defunx seconds->time seconds
2479Convert between time objects and numerical values representing the
2480number of seconds since the epoch. When converting from a time object
2481to seconds, the return value is the number of seconds between
2482@var{time} and the epoch. When converting from seconds to a time
2483object, the return value is a time object that represents a time
2484@var{seconds} seconds after the epoch.
2485@end defun
2486
2487
2488@node SRFI-18 Exceptions
2489@subsubsection SRFI-18 Exceptions
2490
2491SRFI-18 exceptions are identical to the exceptions provided by
2492Guile's implementation of SRFI-34. The behavior of exception
2493handlers invoked to handle exceptions thrown from SRFI-18 functions,
2494however, differs from the conventional behavior of SRFI-34 in that
2495the continuation of the handler is the same as that of the call to
2496the function. Handlers are called in a tail-recursive manner; the
2497exceptions do not ``bubble up''.
2498
2499@defun current-exception-handler
2500Returns the current exception handler.
2501@end defun
2502
2503@defun with-exception-handler handler thunk
2504Installs @var{handler} as the current exception handler and calls the
2505procedure @var{thunk} with no arguments, returning its value as the
2506value of the exception. @var{handler} must be a procedure that accepts
2507a single argument. The current exception handler at the time this
2508procedure is called will be restored after the call returns.
2509@end defun
2510
2511@defun raise obj
2512Raise @var{obj} as an exception. This is the same procedure as the
2513same-named procedure defined in SRFI 34.
2514@end defun
2515
2516@defun join-timeout-exception? obj
2517Returns @code{#t} if @var{obj} is an exception raised as the result of
2518performing a timed join on a thread that does not exit within the
2519specified timeout, @code{#f} otherwise.
2520@end defun
2521
2522@defun abandoned-mutex-exception? obj
2523Returns @code{#t} if @var{obj} is an exception raised as the result of
2524attempting to lock a mutex that has been abandoned by its owner thread,
2525@code{#f} otherwise.
2526@end defun
2527
2528@defun terminated-thread-exception? obj
2529Returns @code{#t} if @var{obj} is an exception raised as the result of
2530joining on a thread that exited as the result of a call to
2531@code{thread-terminate!}.
2532@end defun
2533
2534@defun uncaught-exception? obj
2535@defunx uncaught-exception-reason exc
2536@code{uncaught-exception?} returns @code{#t} if @var{obj} is an
2537exception thrown as the result of joining a thread that exited by
2538raising an exception that was handled by the top-level exception
2539handler installed by @code{make-thread}. When this occurs, the
2540original exception is preserved as part of the exception thrown by
2541@code{thread-join!} and can be accessed by calling
2542@code{uncaught-exception-reason} on that exception. Note that
2543because this exception-preservation mechanism is a side-effect of
2544@code{make-thread}, joining on threads that exited as described above
2545but were created by other means will not raise this
2546@code{uncaught-exception} error.
2547@end defun
2548
2549
12991fed 2550@node SRFI-19
3229f68b 2551@subsection SRFI-19 - Time/Date Library
8742c48b 2552@cindex SRFI-19
7c2e18cd
KR
2553@cindex time
2554@cindex date
12991fed 2555
85600a0f
KR
2556This is an implementation of the SRFI-19 time/date library. The
2557functions and variables described here are provided by
12991fed
TTN
2558
2559@example
85600a0f 2560(use-modules (srfi srfi-19))
12991fed
TTN
2561@end example
2562
7d281fa5
KR
2563@strong{Caution}: The current code in this module incorrectly extends
2564the Gregorian calendar leap year rule back prior to the introduction
2565of those reforms in 1582 (or the appropriate year in various
2566countries). The Julian calendar was used prior to 1582, and there
2567were 10 days skipped for the reform, but the code doesn't implement
2568that.
2569
2570This will be fixed some time. Until then calculations for 1583
2571onwards are correct, but prior to that any day/month/year and day of
2572the week calculations are wrong.
2573
85600a0f
KR
2574@menu
2575* SRFI-19 Introduction::
2576* SRFI-19 Time::
2577* SRFI-19 Date::
2578* SRFI-19 Time/Date conversions::
2579* SRFI-19 Date to string::
2580* SRFI-19 String to date::
2581@end menu
12991fed 2582
85600a0f 2583@node SRFI-19 Introduction
3229f68b 2584@subsubsection SRFI-19 Introduction
85600a0f
KR
2585
2586@cindex universal time
2587@cindex atomic time
2588@cindex UTC
2589@cindex TAI
2590This module implements time and date representations and calculations,
2591in various time systems, including universal time (UTC) and atomic
2592time (TAI).
2593
2594For those not familiar with these time systems, TAI is based on a
2595fixed length second derived from oscillations of certain atoms. UTC
2596differs from TAI by an integral number of seconds, which is increased
2597or decreased at announced times to keep UTC aligned to a mean solar
2598day (the orbit and rotation of the earth are not quite constant).
2599
2600@cindex leap second
2601So far, only increases in the TAI
2602@tex
2603$\leftrightarrow$
2604@end tex
2605@ifnottex
2606<->
2607@end ifnottex
2608UTC difference have been needed. Such an increase is a ``leap
2609second'', an extra second of TAI introduced at the end of a UTC day.
2610When working entirely within UTC this is never seen, every day simply
2611has 86400 seconds. But when converting from TAI to a UTC date, an
2612extra 23:59:60 is present, where normally a day would end at 23:59:59.
2613Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
2614seconds.
2615
2616@cindex system clock
2617In the current implementation, the system clock is assumed to be UTC,
2618and a table of leap seconds in the code converts to TAI. See comments
2619in @file{srfi-19.scm} for how to update this table.
2620
2621@cindex julian day
2622@cindex modified julian day
2623Also, for those not familiar with the terminology, a @dfn{Julian Day}
2624is a real number which is a count of days and fraction of a day, in
2625UTC, starting from -4713-01-01T12:00:00Z, ie.@: midday Monday 1 Jan
7c2e18cd
KR
26264713 B.C. A @dfn{Modified Julian Day} is the same, but starting from
26271858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. That time
2628is julian day 2400000.5.
85600a0f
KR
2629
2630@c The SRFI-1 spec says -4714-11-24T12:00:00Z (November 24, -4714 at
2631@c noon, UTC), but this is incorrect. It looks like it might have
2632@c arisen from the code incorrectly treating years a multiple of 100
7c2e18cd 2633@c but not 400 prior to 1582 as non-leap years, where instead the Julian
85600a0f
KR
2634@c calendar should be used so all multiples of 4 before 1582 are leap
2635@c years.
2636
2637
2638@node SRFI-19 Time
3229f68b 2639@subsubsection SRFI-19 Time
85600a0f
KR
2640@cindex time
2641
2642A @dfn{time} object has type, seconds and nanoseconds fields
2643representing a point in time starting from some epoch. This is an
2644arbitrary point in time, not just a time of day. Although times are
2645represented in nanoseconds, the actual resolution may be lower.
2646
2647The following variables hold the possible time types. For instance
2648@code{(current-time time-process)} would give the current CPU process
2649time.
2650
2651@defvar time-utc
2652Universal Coordinated Time (UTC).
2653@cindex UTC
2654@end defvar
12991fed 2655
85600a0f
KR
2656@defvar time-tai
2657International Atomic Time (TAI).
2658@cindex TAI
2659@end defvar
12991fed 2660
85600a0f
KR
2661@defvar time-monotonic
2662Monotonic time, meaning a monotonically increasing time starting from
2663an unspecified epoch.
12991fed 2664
85600a0f
KR
2665Note that in the current implementation @code{time-monotonic} is the
2666same as @code{time-tai}, and unfortunately is therefore affected by
2667adjustments to the system clock. Perhaps this will change in the
2668future.
2669@end defvar
12991fed 2670
85600a0f
KR
2671@defvar time-duration
2672A duration, meaning simply a difference between two times.
2673@end defvar
12991fed 2674
85600a0f
KR
2675@defvar time-process
2676CPU time spent in the current process, starting from when the process
2677began.
2678@cindex process time
2679@end defvar
12991fed 2680
85600a0f
KR
2681@defvar time-thread
2682CPU time spent in the current thread. Not currently implemented.
2683@cindex thread time
2684@end defvar
12991fed 2685
85600a0f
KR
2686@sp 1
2687@defun time? obj
2688Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
2689@end defun
2690
2691@defun make-time type nanoseconds seconds
2692Create a time object with the given @var{type}, @var{seconds} and
2693@var{nanoseconds}.
2694@end defun
2695
2696@defun time-type time
2697@defunx time-nanosecond time
2698@defunx time-second time
2699@defunx set-time-type! time type
2700@defunx set-time-nanosecond! time nsec
2701@defunx set-time-second! time sec
2702Get or set the type, seconds or nanoseconds fields of a time object.
2703
2704@code{set-time-type!} merely changes the field, it doesn't convert the
2705time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
2706@end defun
2707
2708@defun copy-time time
2709Return a new time object, which is a copy of the given @var{time}.
2710@end defun
2711
2712@defun current-time [type]
2713Return the current time of the given @var{type}. The default
2714@var{type} is @code{time-utc}.
2715
2716Note that the name @code{current-time} conflicts with the Guile core
e68f492a
JG
2717@code{current-time} function (@pxref{Time}) as well as the SRFI-18
2718@code{current-time} function (@pxref{SRFI-18 Time}). Applications
2719wanting to use more than one of these functions will need to refer to
2720them by different names.
85600a0f
KR
2721@end defun
2722
2723@defun time-resolution [type]
2724Return the resolution, in nanoseconds, of the given time @var{type}.
2725The default @var{type} is @code{time-utc}.
2726@end defun
2727
2728@defun time<=? t1 t2
2729@defunx time<? t1 t2
2730@defunx time=? t1 t2
2731@defunx time>=? t1 t2
2732@defunx time>? t1 t2
2733Return @code{#t} or @code{#f} according to the respective relation
2734between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
2735must be the same time type.
2736@end defun
2737
2738@defun time-difference t1 t2
2739@defunx time-difference! t1 t2
2740Return a time object of type @code{time-duration} representing the
2741period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
2742the same time type.
2743
2744@code{time-difference} returns a new time object,
2745@code{time-difference!} may modify @var{t1} to form its return.
2746@end defun
2747
2748@defun add-duration time duration
2749@defunx add-duration! time duration
2750@defunx subtract-duration time duration
2751@defunx subtract-duration! time duration
2752Return a time object which is @var{time} with the given @var{duration}
2753added or subtracted. @var{duration} must be a time object of type
2754@code{time-duration}.
2755
2756@code{add-duration} and @code{subtract-duration} return a new time
2757object. @code{add-duration!} and @code{subtract-duration!} may modify
2758the given @var{time} to form their return.
2759@end defun
2760
2761
2762@node SRFI-19 Date
3229f68b 2763@subsubsection SRFI-19 Date
85600a0f
KR
2764@cindex date
2765
2766A @dfn{date} object represents a date in the Gregorian calendar and a
2767time of day on that date in some timezone.
2768
2769The fields are year, month, day, hour, minute, second, nanoseconds and
2770timezone. A date object is immutable, its fields can be read but they
2771cannot be modified once the object is created.
2772
2773@defun date? obj
2774Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
2775@end defun
2776
2777@defun make-date nsecs seconds minutes hours date month year zone-offset
2778Create a new date object.
2779@c
2780@c FIXME: What can we say about the ranges of the values. The
2781@c current code looks it doesn't normalize, but expects then in their
2782@c usual range already.
2783@c
2784@end defun
2785
2786@defun date-nanosecond date
2787Nanoseconds, 0 to 999999999.
2788@end defun
2789
2790@defun date-second date
7c2e18cd
KR
2791Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
2792entirely within UTC, it's only when converting to or from TAI.
85600a0f
KR
2793@end defun
2794
2795@defun date-minute date
2796Minutes, 0 to 59.
2797@end defun
2798
2799@defun date-hour date
2800Hour, 0 to 23.
2801@end defun
2802
2803@defun date-day date
2804Day of the month, 1 to 31 (or less, according to the month).
2805@end defun
2806
2807@defun date-month date
2808Month, 1 to 12.
2809@end defun
2810
2811@defun date-year date
7c2e18cd
KR
2812Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
2813B.C. There is no year 0, year @math{-1} is followed by year 1.
85600a0f
KR
2814@end defun
2815
2816@defun date-zone-offset date
2817Time zone, an integer number of seconds east of Greenwich.
2818@end defun
2819
2820@defun date-year-day date
2821Day of the year, starting from 1 for 1st January.
2822@end defun
2823
2824@defun date-week-day date
2825Day of the week, starting from 0 for Sunday.
2826@end defun
2827
2828@defun date-week-number date dstartw
2829Week of the year, ignoring a first partial week. @var{dstartw} is the
2830day of the week which is taken to start a week, 0 for Sunday, 1 for
2831Monday, etc.
2832@c
2833@c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
2834@c The code looks like it's 0, if that's the correct intention.
2835@c
2836@end defun
2837
2838@c The SRFI text doesn't actually give the default for tz-offset, but
2839@c the reference implementation has the local timezone and the
2840@c conversions functions all specify that, so it should be ok to
2841@c document it here.
2842@c
2843@defun current-date [tz-offset]
7c2e18cd
KR
2844Return a date object representing the current date/time, in UTC offset
2845by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
2846defaults to the local timezone.
85600a0f
KR
2847@end defun
2848
2849@defun current-julian-day
2850@cindex julian day
2851Return the current Julian Day.
2852@end defun
2853
2854@defun current-modified-julian-day
2855@cindex modified julian day
2856Return the current Modified Julian Day.
2857@end defun
2858
2859
2860@node SRFI-19 Time/Date conversions
3229f68b 2861@subsubsection SRFI-19 Time/Date conversions
7c2e18cd
KR
2862@cindex time conversion
2863@cindex date conversion
85600a0f
KR
2864
2865@defun date->julian-day date
2866@defunx date->modified-julian-day date
2867@defunx date->time-monotonic date
2868@defunx date->time-tai date
2869@defunx date->time-utc date
2870@end defun
2871@defun julian-day->date jdn [tz-offset]
2872@defunx julian-day->time-monotonic jdn
2873@defunx julian-day->time-tai jdn
2874@defunx julian-day->time-utc jdn
2875@end defun
2876@defun modified-julian-day->date jdn [tz-offset]
2877@defunx modified-julian-day->time-monotonic jdn
2878@defunx modified-julian-day->time-tai jdn
2879@defunx modified-julian-day->time-utc jdn
2880@end defun
2881@defun time-monotonic->date time [tz-offset]
2882@defunx time-monotonic->time-tai time
2883@defunx time-monotonic->time-tai! time
2884@defunx time-monotonic->time-utc time
2885@defunx time-monotonic->time-utc! time
2886@end defun
2887@defun time-tai->date time [tz-offset]
2888@defunx time-tai->julian-day time
2889@defunx time-tai->modified-julian-day time
2890@defunx time-tai->time-monotonic time
2891@defunx time-tai->time-monotonic! time
2892@defunx time-tai->time-utc time
2893@defunx time-tai->time-utc! time
2894@end defun
2895@defun time-utc->date time [tz-offset]
2896@defunx time-utc->julian-day time
2897@defunx time-utc->modified-julian-day time
2898@defunx time-utc->time-monotonic time
2899@defunx time-utc->time-monotonic! time
2900@defunx time-utc->time-tai time
2901@defunx time-utc->time-tai! time
2902@sp 1
2903Convert between dates, times and days of the respective types. For
2904instance @code{time-tai->time-utc} accepts a @var{time} object of type
2905@code{time-tai} and returns an object of type @code{time-utc}.
2906
85600a0f
KR
2907The @code{!} variants may modify their @var{time} argument to form
2908their return. The plain functions create a new object.
702e6e09
KR
2909
2910For conversions to dates, @var{tz-offset} is seconds east of
2911Greenwich. The default is the local timezone, at the given time, as
2912provided by the system, using @code{localtime} (@pxref{Time}).
2913
2914On 32-bit systems, @code{localtime} is limited to a 32-bit
2915@code{time_t}, so a default @var{tz-offset} is only available for
2916times between Dec 1901 and Jan 2038. For prior dates an application
2917might like to use the value in 1902, though some locations have zone
2918changes prior to that. For future dates an application might like to
2919assume today's rules extend indefinitely. But for correct daylight
2920savings transitions it will be necessary to take an offset for the
2921same day and time but a year in range and which has the same starting
2922weekday and same leap/non-leap (to support rules like last Sunday in
2923October).
85600a0f
KR
2924@end defun
2925
2926@node SRFI-19 Date to string
3229f68b 2927@subsubsection SRFI-19 Date to string
85600a0f 2928@cindex date to string
7c2e18cd 2929@cindex string, from date
85600a0f
KR
2930
2931@defun date->string date [format]
2932Convert a date to a string under the control of a format.
2933@var{format} should be a string containing @samp{~} escapes, which
2934will be expanded as per the following conversion table. The default
2935@var{format} is @samp{~c}, a locale-dependent date and time.
2936
2937Many of these conversion characters are the same as POSIX
2938@code{strftime} (@pxref{Time}), but there are some extras and some
2939variations.
2940
2941@multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
2942@item @nicode{~~} @tab literal ~
2943@item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
2944@item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
2945@item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
2946@item @nicode{~B} @tab locale full month, eg.@: @samp{January}
2947@item @nicode{~c} @tab locale date and time, eg.@: @*
2948@samp{Fri Jul 14 20:28:42-0400 2000}
2949@item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
2950
2951@c Spec says d/m/y, reference implementation says m/d/y.
2952@c Apparently the reference code was the intention, but would like to
2953@c see an errata published for the spec before contradicting it here.
2954@c
2955@c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
2956
2957@item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
2958@item @nicode{~f} @tab seconds and fractional seconds,
2959with locale decimal point, eg.@: @samp{5.2}
2960@item @nicode{~h} @tab same as @nicode{~b}
2961@item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
2962@item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
2963@item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
2964@item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
2965@item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
2966@item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
2967@item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
2968@item @nicode{~n} @tab newline
2969@item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
2970@item @nicode{~p} @tab locale AM or PM
2971@item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
2972@item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
2973@item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
2974(usual limit is 59, 60 is a leap second)
2975@item @nicode{~t} @tab horizontal tab character
2976@item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
2977@item @nicode{~U} @tab week of year, Sunday first day of week,
2978@samp{00} to @samp{52}
2979@item @nicode{~V} @tab week of year, Monday first day of week,
2980@samp{01} to @samp{53}
2981@item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
2982@item @nicode{~W} @tab week of year, Monday first day of week,
2983@samp{00} to @samp{52}
2984
2985@c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
2986@c date. The reference code has ~x as the locale date and ~X as a
2987@c locale time. The rule is apparently that the code should be
2988@c believed, but would like to see an errata for the spec before
2989@c contradicting it here.
2990@c
2991@c @item @nicode{~x} @tab week of year, Monday as first day of week,
2992@c @samp{00} to @samp{53}
2993@c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
2994
2995@item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
2996@item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
2997@item @nicode{~z} @tab time zone, RFC-822 style
2998@item @nicode{~Z} @tab time zone symbol (not currently implemented)
2999@item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
3000@item @nicode{~2} @tab ISO-8601 time+zone, @samp{~k:~M:~S~z}
3001@item @nicode{~3} @tab ISO-8601 time, @samp{~k:~M:~S}
3002@item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~k:~M:~S~z}
3003@item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~k:~M:~S}
3004@end multitable
3005@end defun
3006
3007Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
3008described here, since the specification and reference implementation
3009differ.
3010
a2f00b9b
LC
3011Conversion is locale-dependent on systems that support it
3012(@pxref{Accessing Locale Information}). @xref{Locales,
3013@code{setlocale}}, for information on how to change the current
3014locale.
85600a0f
KR
3015
3016
3017@node SRFI-19 String to date
3229f68b 3018@subsubsection SRFI-19 String to date
85600a0f 3019@cindex string to date
7c2e18cd 3020@cindex date, from string
85600a0f
KR
3021
3022@c FIXME: Can we say what happens when an incomplete date is
679cceed 3023@c converted? I.e. fields left as 0, or what? The spec seems to be
85600a0f
KR
3024@c silent on this.
3025
3026@defun string->date input template
3027Convert an @var{input} string to a date under the control of a
3028@var{template} string. Return a newly created date object.
3029
3030Literal characters in @var{template} must match characters in
3031@var{input} and @samp{~} escapes must match the input forms described
3032in the table below. ``Skip to'' means characters up to one of the
3033given type are ignored, or ``no skip'' for no skipping. ``Read'' is
3034what's then read, and ``Set'' is the field affected in the date
3035object.
3036
3037For example @samp{~Y} skips input characters until a digit is reached,
3038at which point it expects a year and stores that to the year field of
3039the date.
3040
3041@multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
3042@item
3043@tab Skip to
3044@tab Read
3045@tab Set
3046
3047@item @nicode{~~}
3048@tab no skip
3049@tab literal ~
3050@tab nothing
3051
3052@item @nicode{~a}
3053@tab @nicode{char-alphabetic?}
3054@tab locale abbreviated weekday name
3055@tab nothing
3056
3057@item @nicode{~A}
3058@tab @nicode{char-alphabetic?}
3059@tab locale full weekday name
3060@tab nothing
3061
3062@c Note that the SRFI spec says that ~b and ~B don't set anything,
3063@c but that looks like a mistake. The reference implementation sets
3064@c the month field, which seems sensible and is what we describe
3065@c here.
3066
3067@item @nicode{~b}
3068@tab @nicode{char-alphabetic?}
3069@tab locale abbreviated month name
3070@tab @nicode{date-month}
3071
3072@item @nicode{~B}
3073@tab @nicode{char-alphabetic?}
3074@tab locale full month name
3075@tab @nicode{date-month}
3076
3077@item @nicode{~d}
3078@tab @nicode{char-numeric?}
3079@tab day of month
3080@tab @nicode{date-day}
3081
3082@item @nicode{~e}
3083@tab no skip
3084@tab day of month, blank padded
3085@tab @nicode{date-day}
3086
3087@item @nicode{~h}
3088@tab same as @samp{~b}
3089
3090@item @nicode{~H}
3091@tab @nicode{char-numeric?}
3092@tab hour
3093@tab @nicode{date-hour}
3094
3095@item @nicode{~k}
3096@tab no skip
3097@tab hour, blank padded
3098@tab @nicode{date-hour}
3099
3100@item @nicode{~m}
3101@tab @nicode{char-numeric?}
3102@tab month
3103@tab @nicode{date-month}
3104
3105@item @nicode{~M}
3106@tab @nicode{char-numeric?}
3107@tab minute
3108@tab @nicode{date-minute}
3109
3110@item @nicode{~S}
3111@tab @nicode{char-numeric?}
3112@tab second
3113@tab @nicode{date-second}
3114
3115@item @nicode{~y}
3116@tab no skip
3117@tab 2-digit year
3118@tab @nicode{date-year} within 50 years
3119
3120@item @nicode{~Y}
3121@tab @nicode{char-numeric?}
3122@tab year
3123@tab @nicode{date-year}
3124
3125@item @nicode{~z}
3126@tab no skip
3127@tab time zone
3128@tab date-zone-offset
3129@end multitable
3130
3131Notice that the weekday matching forms don't affect the date object
3132returned, instead the weekday will be derived from the day, month and
3133year.
3134
a2f00b9b
LC
3135Conversion is locale-dependent on systems that support it
3136(@pxref{Accessing Locale Information}). @xref{Locales,
3137@code{setlocale}}, for information on how to change the current
3138locale.
85600a0f 3139@end defun
12991fed 3140
8e9af854
NL
3141@node SRFI-23
3142@subsection SRFI-23 - Error Reporting
3143@cindex SRFI-23
3144
3145The SRFI-23 @code{error} procedure is always available.
1de8c1ae 3146
b0b55bd6 3147@node SRFI-26
3229f68b 3148@subsection SRFI-26 - specializing parameters
1de8c1ae 3149@cindex SRFI-26
7c2e18cd
KR
3150@cindex parameter specialize
3151@cindex argument specialize
3152@cindex specialize parameter
1de8c1ae
KR
3153
3154This SRFI provides a syntax for conveniently specializing selected
3155parameters of a function. It can be used with,
3156
3157@example
3158(use-modules (srfi srfi-26))
3159@end example
3160
df0a1002
BT
3161@deffn {library syntax} cut slot1 slot2 @dots{}
3162@deffnx {library syntax} cute slot1 slot2 @dots{}
3163Return a new procedure which will make a call (@var{slot1} @var{slot2}
3164@dots{}) but with selected parameters specialized to given expressions.
1de8c1ae
KR
3165
3166An example will illustrate the idea. The following is a
3167specialization of @code{write}, sending output to
3168@code{my-output-port},
3169
3170@example
3171(cut write <> my-output-port)
3172@result{}
3173(lambda (obj) (write obj my-output-port))
3174@end example
3175
3176The special symbol @code{<>} indicates a slot to be filled by an
3177argument to the new procedure. @code{my-output-port} on the other
3178hand is an expression to be evaluated and passed, ie.@: it specializes
3179the behaviour of @code{write}.
3180
3181@table @nicode
3182@item <>
3183A slot to be filled by an argument from the created procedure.
3184Arguments are assigned to @code{<>} slots in the order they appear in
3185the @code{cut} form, there's no way to re-arrange arguments.
3186
3187The first argument to @code{cut} is usually a procedure (or expression
3188giving a procedure), but @code{<>} is allowed there too. For example,
3189
3190@example
3191(cut <> 1 2 3)
3192@result{}
3193(lambda (proc) (proc 1 2 3))
3194@end example
3195
3196@item <...>
3197A slot to be filled by all remaining arguments from the new procedure.
3198This can only occur at the end of a @code{cut} form.
3199
3200For example, a procedure taking a variable number of arguments like
3201@code{max} but in addition enforcing a lower bound,
3202
3203@example
3204(define my-lower-bound 123)
3205
3206(cut max my-lower-bound <...>)
3207@result{}
3208(lambda arglist (apply max my-lower-bound arglist))
3209@end example
3210@end table
3211
3212For @code{cut} the specializing expressions are evaluated each time
3213the new procedure is called. For @code{cute} they're evaluated just
3214once, when the new procedure is created. The name @code{cute} stands
3215for ``@code{cut} with evaluated arguments''. In all cases the
3216evaluations take place in an unspecified order.
3217
3218The following illustrates the difference between @code{cut} and
3219@code{cute},
3220
3221@example
3222(cut format <> "the time is ~s" (current-time))
3223@result{}
3224(lambda (port) (format port "the time is ~s" (current-time)))
3225
3226(cute format <> "the time is ~s" (current-time))
3227@result{}
3228(let ((val (current-time)))
3229 (lambda (port) (format port "the time is ~s" val))
3230@end example
3231
3232(There's no provision for a mixture of @code{cut} and @code{cute}
3233where some expressions would be evaluated every time but others
3234evaluated only once.)
3235
3236@code{cut} is really just a shorthand for the sort of @code{lambda}
3237forms shown in the above examples. But notice @code{cut} avoids the
3238need to name unspecialized parameters, and is more compact. Use in
3239functional programming style or just with @code{map}, @code{for-each}
3240or similar is typical.
3241
3242@example
3243(map (cut * 2 <>) '(1 2 3 4))
3244
3245(for-each (cut write <> my-port) my-list)
3246@end example
3247@end deffn
b0b55bd6 3248
56ec46a7
AR
3249@node SRFI-27
3250@subsection SRFI-27 - Sources of Random Bits
3251@cindex SRFI-27
3252
6e3d49a0
AR
3253This subsection is based on the
3254@uref{http://srfi.schemers.org/srfi-27/srfi-27.html, specification of
3255SRFI-27} written by Sebastian Egner.
3256
3257@c The copyright notice and license text of the SRFI-27 specification is
3258@c reproduced below:
56ec46a7
AR
3259
3260@c Copyright (C) Sebastian Egner (2002). All Rights Reserved.
3261
3262@c Permission is hereby granted, free of charge, to any person obtaining a
3263@c copy of this software and associated documentation files (the
3264@c "Software"), to deal in the Software without restriction, including
3265@c without limitation the rights to use, copy, modify, merge, publish,
3266@c distribute, sublicense, and/or sell copies of the Software, and to
3267@c permit persons to whom the Software is furnished to do so, subject to
3268@c the following conditions:
3269
3270@c The above copyright notice and this permission notice shall be included
3271@c in all copies or substantial portions of the Software.
3272
3273@c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3274@c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3275@c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
3276@c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
3277@c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
3278@c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
3279@c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3280
56ec46a7
AR
3281This SRFI provides access to a (pseudo) random number generator; for
3282Guile's built-in random number facilities, which SRFI-27 is implemented
3283upon, @xref{Random}. With SRFI-27, random numbers are obtained from a
3284@emph{random source}, which encapsulates a random number generation
3285algorithm and its state.
3286
3287@menu
3288* SRFI-27 Default Random Source:: Obtaining random numbers
3289* SRFI-27 Random Sources:: Creating and manipulating random sources
3290* SRFI-27 Random Number Generators:: Obtaining random number generators
3291@end menu
3292
3293@node SRFI-27 Default Random Source
3294@subsubsection The Default Random Source
3295@cindex SRFI-27
3296
3297@defun random-integer n
3298Return a random number between zero (inclusive) and @var{n} (exclusive),
3299using the default random source. The numbers returned have a uniform
3300distribution.
3301@end defun
3302
3303@defun random-real
3304Return a random number in (0,1), using the default random source. The
3305numbers returned have a uniform distribution.
3306@end defun
3307
3308@defun default-random-source
3309A random source from which @code{random-integer} and @code{random-real}
3310have been derived using @code{random-source-make-integers} and
3311@code{random-source-make-reals} (@pxref{SRFI-27 Random Number Generators}
3312for those procedures). Note that an assignment to
3313@code{default-random-source} does not change @code{random-integer} or
3314@code{random-real}; it is also strongly recommended not to assign a new
3315value.
3316@end defun
3317
3318@node SRFI-27 Random Sources
3319@subsubsection Random Sources
3320@cindex SRFI-27
3321
3322@defun make-random-source
3323Create a new random source. The stream of random numbers obtained from
3324each random source created by this procedure will be identical, unless
3325its state is changed by one of the procedures below.
3326@end defun
3327
3328@defun random-source? object
3329Tests whether @var{object} is a random source. Random sources are a
3330disjoint type.
3331@end defun
3332
3333@defun random-source-randomize! source
3334Attempt to set the state of the random source to a truly random value.
3335The current implementation uses a seed based on the current system time.
3336@end defun
3337
3338@defun random-source-pseudo-randomize! source i j
3339Changes the state of the random source s into the initial state of the
3340(@var{i}, @var{j})-th independent random source, where @var{i} and
3341@var{j} are non-negative integers. This procedure provides a mechanism
3342to obtain a large number of independent random sources (usually all
3343derived from the same backbone generator), indexed by two integers. In
3344contrast to @code{random-source-randomize!}, this procedure is entirely
3345deterministic.
3346@end defun
3347
3348The state associated with a random state can be obtained an reinstated
3349with the following procedures:
3350
3351@defun random-source-state-ref source
3352@defunx random-source-state-set! source state
3353Get and set the state of a random source. No assumptions should be made
3354about the nature of the state object, besides it having an external
679cceed 3355representation (i.e.@: it can be passed to @code{write} and subsequently
56ec46a7
AR
3356@code{read} back).
3357@end defun
3358
3359@node SRFI-27 Random Number Generators
3360@subsubsection Obtaining random number generator procedures
3361@cindex SRFI-27
3362
3363@defun random-source-make-integers source
3364Obtains a procedure to generate random integers using the random source
3365@var{source}. The returned procedure takes a single argument @var{n},
3366which must be a positive integer, and returns the next uniformly
3367distributed random integer from the interval @{0, ..., @var{n}-1@} by
3368advancing the state of @var{source}.
3369
3370If an application obtains and uses several generators for the same
3371random source @var{source}, a call to any of these generators advances
3372the state of @var{source}. Hence, the generators do not produce the
3373same sequence of random integers each but rather share a state. This
3374also holds for all other types of generators derived from a fixed random
3375sources.
3376
3377While the SRFI text specifies that ``Implementations that support
3378concurrency make sure that the state of a generator is properly
3379advanced'', this is currently not the case in Guile's implementation of
3380SRFI-27, as it would cause a severe performance penalty. So in
3381multi-threaded programs, you either must perform locking on random
3382sources shared between threads yourself, or use different random sources
3383for multiple threads.
3384@end defun
3385
3386@defun random-source-make-reals source
3387@defunx random-source-make-reals source unit
3388Obtains a procedure to generate random real numbers @math{0 < x < 1}
3389using the random source @var{source}. The procedure rand is called
3390without arguments.
3391
3392The optional parameter @var{unit} determines the type of numbers being
3393produced by the returned procedure and the quantization of the output.
3394@var{unit} must be a number such that @math{0 < @var{unit} < 1}. The
3395numbers created by the returned procedure are of the same numerical type
3396as @var{unit} and the potential output values are spaced by at most
3397@var{unit}. One can imagine rand to create numbers as @var{x} *
3398@var{unit} where @var{x} is a random integer in @{1, ...,
3399floor(1/unit)-1@}. Note, however, that this need not be the way the
3400values are actually created and that the actual resolution of rand can
3401be much higher than unit. In case @var{unit} is absent it defaults to a
3402reasonably small value (related to the width of the mantissa of an
3403efficient number format).
3404@end defun
3405
620c8965
LC
3406@node SRFI-30
3407@subsection SRFI-30 - Nested Multi-line Comments
3408@cindex SRFI-30
3409
3410Starting from version 2.0, Guile's @code{read} supports SRFI-30/R6RS
3411nested multi-line comments by default, @ref{Block Comments}.
3412
8638c417
RB
3413@node SRFI-31
3414@subsection SRFI-31 - A special form `rec' for recursive evaluation
3415@cindex SRFI-31
7c2e18cd 3416@cindex recursive expression
8638c417
RB
3417@findex rec
3418
3419SRFI-31 defines a special form that can be used to create
3420self-referential expressions more conveniently. The syntax is as
3421follows:
3422
3423@example
3424@group
3425<rec expression> --> (rec <variable> <expression>)
3426<rec expression> --> (rec (<variable>+) <body>)
3427@end group
3428@end example
3429
3430The first syntax can be used to create self-referential expressions,
3431for example:
3432
3433@lisp
3434 guile> (define tmp (rec ones (cons 1 (delay ones))))
3435@end lisp
3436
3437The second syntax can be used to create anonymous recursive functions:
3438
3439@lisp
3440 guile> (define tmp (rec (display-n item n)
3441 (if (positive? n)
3442 (begin (display n) (display-n (- n 1))))))
3443 guile> (tmp 42 3)
3444 424242
3445 guile>
3446@end lisp
12991fed 3447
eeadfda1 3448
f50ca8da
LC
3449@node SRFI-34
3450@subsection SRFI-34 - Exception handling for programs
3451
3452@cindex SRFI-34
3453Guile provides an implementation of
3454@uref{http://srfi.schemers.org/srfi-34/srfi-34.html, SRFI-34's exception
3455handling mechanisms} as an alternative to its own built-in mechanisms
3456(@pxref{Exceptions}). It can be made available as follows:
3457
3458@lisp
3459(use-modules (srfi srfi-34))
3460@end lisp
3461
3462@c FIXME: Document it.
3463
3464
3465@node SRFI-35
3466@subsection SRFI-35 - Conditions
3467
3468@cindex SRFI-35
3469@cindex conditions
3470@cindex exceptions
3471
3472@uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI-35} implements
3473@dfn{conditions}, a data structure akin to records designed to convey
3474information about exceptional conditions between parts of a program. It
3475is normally used in conjunction with SRFI-34's @code{raise}:
3476
3477@lisp
3478(raise (condition (&message
3479 (message "An error occurred"))))
3480@end lisp
3481
3482Users can define @dfn{condition types} containing arbitrary information.
3483Condition types may inherit from one another. This allows the part of
3484the program that handles (or ``catches'') conditions to get accurate
3485information about the exceptional condition that arose.
3486
3487SRFI-35 conditions are made available using:
3488
3489@lisp
3490(use-modules (srfi srfi-35))
3491@end lisp
3492
3493The procedures available to manipulate condition types are the
3494following:
3495
3496@deffn {Scheme Procedure} make-condition-type id parent field-names
3497Return a new condition type named @var{id}, inheriting from
3498@var{parent}, and with the fields whose names are listed in
3499@var{field-names}. @var{field-names} must be a list of symbols and must
3500not contain names already used by @var{parent} or one of its supertypes.
3501@end deffn
3502
3503@deffn {Scheme Procedure} condition-type? obj
3504Return true if @var{obj} is a condition type.
3505@end deffn
3506
3507Conditions can be created and accessed with the following procedures:
3508
3509@deffn {Scheme Procedure} make-condition type . field+value
3510Return a new condition of type @var{type} with fields initialized as
3511specified by @var{field+value}, a sequence of field names (symbols) and
3512values as in the following example:
3513
3514@lisp
1317062f 3515(let ((&ct (make-condition-type 'foo &condition '(a b c))))
f50ca8da
LC
3516 (make-condition &ct 'a 1 'b 2 'c 3))
3517@end lisp
3518
3519Note that all fields of @var{type} and its supertypes must be specified.
3520@end deffn
3521
df0a1002 3522@deffn {Scheme Procedure} make-compound-condition condition1 condition2 @dots{}
f50ca8da
LC
3523Return a new compound condition composed of @var{conditions}. The
3524returned condition has the type of each condition of @var{conditions}
3525(per @code{condition-has-type?}).
3526@end deffn
3527
3528@deffn {Scheme Procedure} condition-has-type? c type
3529Return true if condition @var{c} has type @var{type}.
3530@end deffn
3531
3532@deffn {Scheme Procedure} condition-ref c field-name
3533Return the value of the field named @var{field-name} from condition @var{c}.
3534
3535If @var{c} is a compound condition and several underlying condition
3536types contain a field named @var{field-name}, then the value of the
3537first such field is returned, using the order in which conditions were
64de6db5 3538passed to @code{make-compound-condition}.
f50ca8da
LC
3539@end deffn
3540
3541@deffn {Scheme Procedure} extract-condition c type
3542Return a condition of condition type @var{type} with the field values
3543specified by @var{c}.
3544
3545If @var{c} is a compound condition, extract the field values from the
3546subcondition belonging to @var{type} that appeared first in the call to
72b3aa56 3547@code{make-compound-condition} that created the condition.
f50ca8da
LC
3548@end deffn
3549
3550Convenience macros are also available to create condition types and
3551conditions.
3552
3553@deffn {library syntax} define-condition-type type supertype predicate field-spec...
3554Define a new condition type named @var{type} that inherits from
3555@var{supertype}. In addition, bind @var{predicate} to a type predicate
3556that returns true when passed a condition of type @var{type} or any of
3557its subtypes. @var{field-spec} must have the form @code{(field
3558accessor)} where @var{field} is the name of field of @var{type} and
3559@var{accessor} is the name of a procedure to access field @var{field} in
3560conditions of type @var{type}.
3561
3562The example below defines condition type @code{&foo}, inheriting from
3563@code{&condition} with fields @code{a}, @code{b} and @code{c}:
3564
3565@lisp
3566(define-condition-type &foo &condition
3567 foo-condition?
3568 (a foo-a)
3569 (b foo-b)
3570 (c foo-c))
3571@end lisp
3572@end deffn
3573
df0a1002
BT
3574@deffn {library syntax} condition type-field-binding1 type-field-binding2 @dots{}
3575Return a new condition or compound condition, initialized according to
3576@var{type-field-binding1} @var{type-field-binding2} @enddots{}. Each
3577@var{type-field-binding} must have the form @code{(type
3578field-specs...)}, where @var{type} is the name of a variable bound to a
3579condition type; each @var{field-spec} must have the form
3580@code{(field-name value)} where @var{field-name} is a symbol denoting
3581the field being initialized to @var{value}. As for
f50ca8da
LC
3582@code{make-condition}, all fields must be specified.
3583
3584The following example returns a simple condition:
3585
3586@lisp
3587(condition (&message (message "An error occurred")))
3588@end lisp
3589
3590The one below returns a compound condition:
3591
3592@lisp
3593(condition (&message (message "An error occurred"))
3594 (&serious))
3595@end lisp
3596@end deffn
3597
3598Finally, SRFI-35 defines a several standard condition types.
3599
3600@defvar &condition
3601This condition type is the root of all condition types. It has no
3602fields.
3603@end defvar
3604
3605@defvar &message
3606A condition type that carries a message describing the nature of the
3607condition to humans.
3608@end defvar
3609
3610@deffn {Scheme Procedure} message-condition? c
3611Return true if @var{c} is of type @code{&message} or one of its
3612subtypes.
3613@end deffn
3614
3615@deffn {Scheme Procedure} condition-message c
3616Return the message associated with message condition @var{c}.
3617@end deffn
3618
3619@defvar &serious
3620This type describes conditions serious enough that they cannot safely be
3621ignored. It has no fields.
3622@end defvar
3623
3624@deffn {Scheme Procedure} serious-condition? c
3625Return true if @var{c} is of type @code{&serious} or one of its
3626subtypes.
3627@end deffn
3628
3629@defvar &error
3630This condition describes errors, typically caused by something that has
3631gone wrong in the interaction of the program with the external world or
3632the user.
3633@end defvar
3634
3635@deffn {Scheme Procedure} error? c
3636Return true if @var{c} is of type @code{&error} or one of its subtypes.
3637@end deffn
3638
d4c38221
LC
3639@node SRFI-37
3640@subsection SRFI-37 - args-fold
3641@cindex SRFI-37
3642
3643This is a processor for GNU @code{getopt_long}-style program
3644arguments. It provides an alternative, less declarative interface
3645than @code{getopt-long} in @code{(ice-9 getopt-long)}
3646(@pxref{getopt-long,,The (ice-9 getopt-long) Module}). Unlike
3647@code{getopt-long}, it supports repeated options and any number of
3648short and long names per option. Access it with:
3649
3650@lisp
3651(use-modules (srfi srfi-37))
3652@end lisp
3653
3654@acronym{SRFI}-37 principally provides an @code{option} type and the
3655@code{args-fold} function. To use the library, create a set of
3656options with @code{option} and use it as a specification for invoking
3657@code{args-fold}.
3658
3659Here is an example of a simple argument processor for the typical
3660@samp{--version} and @samp{--help} options, which returns a backwards
3661list of files given on the command line:
3662
3663@lisp
3664(args-fold (cdr (program-arguments))
3665 (let ((display-and-exit-proc
3666 (lambda (msg)
3667 (lambda (opt name arg loads)
3668 (display msg) (quit)))))
3669 (list (option '(#\v "version") #f #f
3670 (display-and-exit-proc "Foo version 42.0\n"))
3671 (option '(#\h "help") #f #f
3672 (display-and-exit-proc
3673 "Usage: foo scheme-file ..."))))
3674 (lambda (opt name arg loads)
3675 (error "Unrecognized option `~A'" name))
3676 (lambda (op loads) (cons op loads))
3677 '())
3678@end lisp
3679
3680@deffn {Scheme Procedure} option names required-arg? optional-arg? processor
3681Return an object that specifies a single kind of program option.
3682
3683@var{names} is a list of command-line option names, and should consist of
3684characters for traditional @code{getopt} short options and strings for
3685@code{getopt_long}-style long options.
3686
3687@var{required-arg?} and @var{optional-arg?} are mutually exclusive;
3688one or both must be @code{#f}. If @var{required-arg?}, the option
3689must be followed by an argument on the command line, such as
3690@samp{--opt=value} for long options, or an error will be signalled.
3691If @var{optional-arg?}, an argument will be taken if available.
3692
3693@var{processor} is a procedure that takes at least 3 arguments, called
3694when @code{args-fold} encounters the option: the containing option
3695object, the name used on the command line, and the argument given for
3696the option (or @code{#f} if none). The rest of the arguments are
3697@code{args-fold} ``seeds'', and the @var{processor} should return
3698seeds as well.
3699@end deffn
3700
3701@deffn {Scheme Procedure} option-names opt
3702@deffnx {Scheme Procedure} option-required-arg? opt
3703@deffnx {Scheme Procedure} option-optional-arg? opt
3704@deffnx {Scheme Procedure} option-processor opt
3705Return the specified field of @var{opt}, an option object, as
3706described above for @code{option}.
3707@end deffn
3708
df0a1002
BT
3709@deffn {Scheme Procedure} args-fold args options unrecognized-option-proc operand-proc seed @dots{}
3710Process @var{args}, a list of program arguments such as that returned by
3711@code{(cdr (program-arguments))}, in order against @var{options}, a list
3712of option objects as described above. All functions called take the
3713``seeds'', or the last multiple-values as multiple arguments, starting
3714with @var{seed} @dots{}, and must return the new seeds. Return the
d4c38221
LC
3715final seeds.
3716
3717Call @code{unrecognized-option-proc}, which is like an option object's
3718processor, for any options not found in @var{options}.
3719
3720Call @code{operand-proc} with any items on the command line that are
3721not named options. This includes arguments after @samp{--}. It is
3722called with the argument in question, as well as the seeds.
3723@end deffn
3724
12708eeb
AR
3725@node SRFI-38
3726@subsection SRFI-38 - External Representation for Data With Shared Structure
3727@cindex SRFI-38
3728
3729This subsection is based on
3730@uref{http://srfi.schemers.org/srfi-38/srfi-38.html, the specification
3731of SRFI-38} written by Ray Dillinger.
3732
3733@c Copyright (C) Ray Dillinger 2003. All Rights Reserved.
3734
3735@c Permission is hereby granted, free of charge, to any person obtaining a
3736@c copy of this software and associated documentation files (the
3737@c "Software"), to deal in the Software without restriction, including
3738@c without limitation the rights to use, copy, modify, merge, publish,
3739@c distribute, sublicense, and/or sell copies of the Software, and to
3740@c permit persons to whom the Software is furnished to do so, subject to
3741@c the following conditions:
3742
3743@c The above copyright notice and this permission notice shall be included
3744@c in all copies or substantial portions of the Software.
3745
3746@c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3747@c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3748@c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
3749@c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
3750@c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
3751@c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
3752@c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3753
3754This SRFI creates an alternative external representation for data
3755written and read using @code{write-with-shared-structure} and
3756@code{read-with-shared-structure}. It is identical to the grammar for
3757external representation for data written and read with @code{write} and
3758@code{read} given in section 7 of R5RS, except that the single
3759production
3760
3761@example
3762<datum> --> <simple datum> | <compound datum>
3763@end example
3764
3765is replaced by the following five productions:
3766
3767@example
3768<datum> --> <defining datum> | <nondefining datum> | <defined datum>
3769<defining datum> --> #<indexnum>=<nondefining datum>
3770<defined datum> --> #<indexnum>#
3771<nondefining datum> --> <simple datum> | <compound datum>
3772<indexnum> --> <digit 10>+
3773@end example
3774
3775@deffn {Scheme procedure} write-with-shared-structure obj
3776@deffnx {Scheme procedure} write-with-shared-structure obj port
3777@deffnx {Scheme procedure} write-with-shared-structure obj port optarg
3778
3779Writes an external representation of @var{obj} to the given port.
3780Strings that appear in the written representation are enclosed in
3781doublequotes, and within those strings backslash and doublequote
3782characters are escaped by backslashes. Character objects are written
3783using the @code{#\} notation.
3784
3785Objects which denote locations rather than values (cons cells, vectors,
3786and non-zero-length strings in R5RS scheme; also Guile's structs,
3787bytevectors and ports and hash-tables), if they appear at more than one
3788point in the data being written, are preceded by @samp{#@var{N}=} the
3789first time they are written and replaced by @samp{#@var{N}#} all
3790subsequent times they are written, where @var{N} is a natural number
3791used to identify that particular object. If objects which denote
3792locations occur only once in the structure, then
3793@code{write-with-shared-structure} must produce the same external
3794representation for those objects as @code{write}.
3795
3796@code{write-with-shared-structure} terminates in finite time and
3797produces a finite representation when writing finite data.
3798
3799@code{write-with-shared-structure} returns an unspecified value. The
3800@var{port} argument may be omitted, in which case it defaults to the
3801value returned by @code{(current-output-port)}. The @var{optarg}
3802argument may also be omitted. If present, its effects on the output and
3803return value are unspecified but @code{write-with-shared-structure} must
3804still write a representation that can be read by
3805@code{read-with-shared-structure}. Some implementations may wish to use
3806@var{optarg} to specify formatting conventions, numeric radixes, or
3807return values. Guile's implementation ignores @var{optarg}.
3808
3809For example, the code
3810
3811@lisp
3812(begin (define a (cons 'val1 'val2))
3813 (set-cdr! a a)
3814 (write-with-shared-structure a))
3815@end lisp
3816
3817should produce the output @code{#1=(val1 . #1#)}. This shows a cons
3818cell whose @code{cdr} contains itself.
3819
3820@end deffn
3821
3822@deffn {Scheme procedure} read-with-shared-structure
3823@deffnx {Scheme procedure} read-with-shared-structure port
3824
3825@code{read-with-shared-structure} converts the external representations
3826of Scheme objects produced by @code{write-with-shared-structure} into
3827Scheme objects. That is, it is a parser for the nonterminal
3828@samp{<datum>} in the augmented external representation grammar defined
3829above. @code{read-with-shared-structure} returns the next object
3830parsable from the given input port, updating @var{port} to point to the
3831first character past the end of the external representation of the
3832object.
3833
3834If an end-of-file is encountered in the input before any characters are
3835found that can begin an object, then an end-of-file object is returned.
3836The port remains open, and further attempts to read it (by
3837@code{read-with-shared-structure} or @code{read} will also return an
3838end-of-file object. If an end of file is encountered after the
3839beginning of an object's external representation, but the external
3840representation is incomplete and therefore not parsable, an error is
3841signalled.
3842
3843The @var{port} argument may be omitted, in which case it defaults to the
3844value returned by @code{(current-input-port)}. It is an error to read
3845from a closed port.
3846
3847@end deffn
d4c38221 3848
eeadfda1
KR
3849@node SRFI-39
3850@subsection SRFI-39 - Parameters
3851@cindex SRFI-39
eeadfda1 3852
99db1bc2
AW
3853This SRFI adds support for dynamically-scoped parameters. SRFI 39 is
3854implemented in the Guile core; there's no module needed to get SRFI-39
3855itself. Parameters are documented in @ref{Parameters}.
eeadfda1 3856
99db1bc2
AW
3857This module does export one extra function: @code{with-parameters*}.
3858This is a Guile-specific addition to the SRFI, similar to the core
3859@code{with-fluids*} (@pxref{Fluids and Dynamic States}).
eeadfda1
KR
3860
3861@defun with-parameters* param-list value-list thunk
3862Establish a new dynamic scope, as per @code{parameterize} above,
3863taking parameters from @var{param-list} and corresponding values from
64de6db5 3864@var{value-list}. A call @code{(@var{thunk})} is made in the new
eeadfda1
KR
3865scope and the result from that @var{thunk} is the return from
3866@code{with-parameters*}.
eeadfda1
KR
3867@end defun
3868
fdc8fd46
AR
3869@node SRFI-42
3870@subsection SRFI-42 - Eager Comprehensions
3871@cindex SRFI-42
3872
3873See @uref{http://srfi.schemers.org/srfi-42/srfi-42.html, the
3874specification of SRFI-42}.
eeadfda1 3875
f16a2007
AR
3876@node SRFI-45
3877@subsection SRFI-45 - Primitives for Expressing Iterative Lazy Algorithms
3878@cindex SRFI-45
3879
3880This subsection is based on @uref{http://srfi.schemers.org/srfi-45/srfi-45.html, the
3881specification of SRFI-45} written by Andr@'e van Tonder.
3882
3883@c Copyright (C) André van Tonder (2003). All Rights Reserved.
3884
3885@c Permission is hereby granted, free of charge, to any person obtaining a
3886@c copy of this software and associated documentation files (the
3887@c "Software"), to deal in the Software without restriction, including
3888@c without limitation the rights to use, copy, modify, merge, publish,
3889@c distribute, sublicense, and/or sell copies of the Software, and to
3890@c permit persons to whom the Software is furnished to do so, subject to
3891@c the following conditions:
3892
3893@c The above copyright notice and this permission notice shall be included
3894@c in all copies or substantial portions of the Software.
3895
3896@c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3897@c OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3898@c MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
3899@c NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
3900@c LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
3901@c OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
3902@c WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3903
3904Lazy evaluation is traditionally simulated in Scheme using @code{delay}
3905and @code{force}. However, these primitives are not powerful enough to
3906express a large class of lazy algorithms that are iterative. Indeed, it
3907is folklore in the Scheme community that typical iterative lazy
3908algorithms written using delay and force will often require unbounded
3909memory.
3910
3911This SRFI provides set of three operations: @{@code{lazy}, @code{delay},
3912@code{force}@}, which allow the programmer to succinctly express lazy
3913algorithms while retaining bounded space behavior in cases that are
3914properly tail-recursive. A general recipe for using these primitives is
3915provided. An additional procedure @code{eager} is provided for the
3916construction of eager promises in cases where efficiency is a concern.
3917
3918Although this SRFI redefines @code{delay} and @code{force}, the
3919extension is conservative in the sense that the semantics of the subset
3920@{@code{delay}, @code{force}@} in isolation (i.e., as long as the
3921program does not use @code{lazy}) agrees with that in R5RS. In other
3922words, no program that uses the R5RS definitions of delay and force will
3923break if those definition are replaced by the SRFI-45 definitions of
3924delay and force.
3925
3926@deffn {Scheme Syntax} delay expression
3927Takes an expression of arbitrary type @var{a} and returns a promise of
3928type @code{(Promise @var{a})} which at some point in the future may be
3929asked (by the @code{force} procedure) to evaluate the expression and
3930deliver the resulting value.
3931@end deffn
3932
3933@deffn {Scheme Syntax} lazy expression
3934Takes an expression of type @code{(Promise @var{a})} and returns a
3935promise of type @code{(Promise @var{a})} which at some point in the
3936future may be asked (by the @code{force} procedure) to evaluate the
3937expression and deliver the resulting promise.
3938@end deffn
3939
3940@deffn {Scheme Procedure} force expression
3941Takes an argument of type @code{(Promise @var{a})} and returns a value
3942of type @var{a} as follows: If a value of type @var{a} has been computed
3943for the promise, this value is returned. Otherwise, the promise is
3944first evaluated, then overwritten by the obtained promise or value, and
3945then force is again applied (iteratively) to the promise.
3946@end deffn
3947
3948@deffn {Scheme Procedure} eager expression
3949Takes an argument of type @var{a} and returns a value of type
3950@code{(Promise @var{a})}. As opposed to @code{delay}, the argument is
3951evaluated eagerly. Semantically, writing @code{(eager expression)} is
3952equivalent to writing
3953
3954@lisp
3955(let ((value expression)) (delay value)).
3956@end lisp
3957
3958However, the former is more efficient since it does not require
3959unnecessary creation and evaluation of thunks. We also have the
3960equivalence
3961
3962@lisp
3963(delay expression) = (lazy (eager expression))
3964@end lisp
3965@end deffn
3966
3967The following reduction rules may be helpful for reasoning about these
3968primitives. However, they do not express the memoization and memory
3969usage semantics specified above:
3970
3971@lisp
3972(force (delay expression)) -> expression
3973(force (lazy expression)) -> (force expression)
3974(force (eager value)) -> value
3975@end lisp
3976
3977@subsubheading Correct usage
3978
3979We now provide a general recipe for using the primitives @{@code{lazy},
3980@code{delay}, @code{force}@} to express lazy algorithms in Scheme. The
3981transformation is best described by way of an example: Consider the
3982stream-filter algorithm, expressed in a hypothetical lazy language as
3983
3984@lisp
3985(define (stream-filter p? s)
3986 (if (null? s) '()
3987 (let ((h (car s))
3988 (t (cdr s)))
3989 (if (p? h)
3990 (cons h (stream-filter p? t))
3991 (stream-filter p? t)))))
3992@end lisp
3993
ecb87335 3994This algorithm can be expressed as follows in Scheme:
f16a2007
AR
3995
3996@lisp
3997(define (stream-filter p? s)
3998 (lazy
3999 (if (null? (force s)) (delay '())
4000 (let ((h (car (force s)))
4001 (t (cdr (force s))))
4002 (if (p? h)
4003 (delay (cons h (stream-filter p? t)))
4004 (stream-filter p? t))))))
4005@end lisp
4006
4007In other words, we
4008
4009@itemize @bullet
4010@item
4011wrap all constructors (e.g., @code{'()}, @code{cons}) with @code{delay},
4012@item
4013apply @code{force} to arguments of deconstructors (e.g., @code{car},
4014@code{cdr} and @code{null?}),
4015@item
4016wrap procedure bodies with @code{(lazy ...)}.
4017@end itemize
4018
4ea9becb
KR
4019@node SRFI-55
4020@subsection SRFI-55 - Requiring Features
4021@cindex SRFI-55
4022
4023SRFI-55 provides @code{require-extension} which is a portable
4024mechanism to load selected SRFI modules. This is implemented in the
4025Guile core, there's no module needed to get SRFI-55 itself.
4026
df0a1002
BT
4027@deffn {library syntax} require-extension clause1 clause2 @dots{}
4028Require the features of @var{clause1} @var{clause2} @dots{} , throwing
4029an error if any are unavailable.
4ea9becb
KR
4030
4031A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
4032only @var{identifier} currently supported is @code{srfi} and the
4033arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
4034
4035@example
4036(require-extension (srfi 1 6))
4037@end example
4038
4039@code{require-extension} can only be used at the top-level.
4040
4041A Guile-specific program can simply @code{use-modules} to load SRFIs
4042not already in the core, @code{require-extension} is for programs
4043designed to be portable to other Scheme implementations.
4044@end deffn
4045
4046
8503beb8
KR
4047@node SRFI-60
4048@subsection SRFI-60 - Integers as Bits
4049@cindex SRFI-60
4050@cindex integers as bits
4051@cindex bitwise logical
4052
4053This SRFI provides various functions for treating integers as bits and
4054for bitwise manipulations. These functions can be obtained with,
4055
4056@example
4057(use-modules (srfi srfi-60))
4058@end example
4059
4060Integers are treated as infinite precision twos-complement, the same
4061as in the core logical functions (@pxref{Bitwise Operations}). And
4062likewise bit indexes start from 0 for the least significant bit. The
4063following functions in this SRFI are already in the Guile core,
4064
4065@quotation
4066@code{logand},
4067@code{logior},
4068@code{logxor},
4069@code{lognot},
4070@code{logtest},
4071@code{logcount},
4072@code{integer-length},
4073@code{logbit?},
4074@code{ash}
4075@end quotation
4076
4077@sp 1
4078@defun bitwise-and n1 ...
4079@defunx bitwise-ior n1 ...
4080@defunx bitwise-xor n1 ...
4081@defunx bitwise-not n
4082@defunx any-bits-set? j k
4083@defunx bit-set? index n
4084@defunx arithmetic-shift n count
4085@defunx bit-field n start end
4086@defunx bit-count n
4087Aliases for @code{logand}, @code{logior}, @code{logxor},
4088@code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
4089@code{bit-extract} and @code{logcount} respectively.
4090
4091Note that the name @code{bit-count} conflicts with @code{bit-count} in
4092the core (@pxref{Bit Vectors}).
4093@end defun
4094
4095@defun bitwise-if mask n1 n0
4096@defunx bitwise-merge mask n1 n0
4097Return an integer with bits selected from @var{n1} and @var{n0}
4098according to @var{mask}. Those bits where @var{mask} has 1s are taken
4099from @var{n1}, and those where @var{mask} has 0s are taken from
4100@var{n0}.
4101
4102@example
4103(bitwise-if 3 #b0101 #b1010) @result{} 9
4104@end example
4105@end defun
4106
4107@defun log2-binary-factors n
4108@defunx first-set-bit n
4109Return a count of how many factors of 2 are present in @var{n}. This
4110is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
41110, the return is @math{-1}.
4112
4113@example
4114(log2-binary-factors 6) @result{} 1
4115(log2-binary-factors -8) @result{} 3
4116@end example
4117@end defun
4118
4119@defun copy-bit index n newbit
4120Return @var{n} with the bit at @var{index} set according to
4121@var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
4122or @code{#f} to set it to 0. Bits other than at @var{index} are
4123unchanged in the return.
4124
4125@example
4126(copy-bit 1 #b0101 #t) @result{} 7
4127@end example
4128@end defun
4129
4130@defun copy-bit-field n newbits start end
4131Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
4132(exclusive) changed to the value @var{newbits}.
4133
4134The least significant bit in @var{newbits} goes to @var{start}, the
4135next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
4136@var{end} given is ignored.
4137
4138@example
4139(copy-bit-field #b10000 #b11 1 3) @result{} #b10110
4140@end example
4141@end defun
4142
4143@defun rotate-bit-field n count start end
4144Return @var{n} with the bit field from @var{start} (inclusive) to
4145@var{end} (exclusive) rotated upwards by @var{count} bits.
4146
4147@var{count} can be positive or negative, and it can be more than the
4148field width (it'll be reduced modulo the width).
4149
4150@example
4151(rotate-bit-field #b0110 2 1 4) @result{} #b1010
4152@end example
4153@end defun
4154
4155@defun reverse-bit-field n start end
4156Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
4157(exclusive) reversed.
4158
4159@example
4160(reverse-bit-field #b101001 2 4) @result{} #b100101
4161@end example
4162@end defun
4163
4164@defun integer->list n [len]
4165Return bits from @var{n} in the form of a list of @code{#t} for 1 and
4166@code{#f} for 0. The least significant @var{len} bits are returned,
4167and the first list element is the most significant of those bits. If
4168@var{len} is not given, the default is @code{(integer-length @var{n})}
4169(@pxref{Bitwise Operations}).
4170
4171@example
4172(integer->list 6) @result{} (#t #t #f)
4173(integer->list 1 4) @result{} (#f #f #f #t)
4174@end example
4175@end defun
4176
4177@defun list->integer lst
4178@defunx booleans->integer bool@dots{}
4179Return an integer formed bitwise from the given @var{lst} list of
4180booleans, or for @code{booleans->integer} from the @var{bool}
4181arguments.
4182
4183Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
4184element becomes the most significant bit in the return.
4185
4186@example
4187(list->integer '(#t #f #t #f)) @result{} 10
4188@end example
4189@end defun
4190
4191
43ed3b69
MV
4192@node SRFI-61
4193@subsection SRFI-61 - A more general @code{cond} clause
4194
4195This SRFI extends RnRS @code{cond} to support test expressions that
4196return multiple values, as well as arbitrary definitions of test
4197success. SRFI 61 is implemented in the Guile core; there's no module
4198needed to get SRFI-61 itself. Extended @code{cond} is documented in
9accf3d9 4199@ref{Conditionals,, Simple Conditional Evaluation}.
43ed3b69 4200
8175a07e
AR
4201@node SRFI-67
4202@subsection SRFI-67 - Compare procedures
4203@cindex SRFI-67
4204
4205See @uref{http://srfi.schemers.org/srfi-67/srfi-67.html, the
4206specification of SRFI-67}.
43ed3b69 4207
1317062f
LC
4208@node SRFI-69
4209@subsection SRFI-69 - Basic hash tables
4210@cindex SRFI-69
4211
4212This is a portable wrapper around Guile's built-in hash table and weak
4213table support. @xref{Hash Tables}, for information on that built-in
4214support. Above that, this hash-table interface provides association
4215of equality and hash functions with tables at creation time, so
4216variants of each function are not required, as well as a procedure
4217that takes care of most uses for Guile hash table handles, which this
4218SRFI does not provide as such.
4219
4220Access it with:
4221
4222@lisp
4223(use-modules (srfi srfi-69))
4224@end lisp
4225
4226@menu
4227* SRFI-69 Creating hash tables::
4228* SRFI-69 Accessing table items::
4229* SRFI-69 Table properties::
4230* SRFI-69 Hash table algorithms::
4231@end menu
4232
4233@node SRFI-69 Creating hash tables
4234@subsubsection Creating hash tables
4235
4236@deffn {Scheme Procedure} make-hash-table [equal-proc hash-proc #:weak weakness start-size]
4237Create and answer a new hash table with @var{equal-proc} as the
4238equality function and @var{hash-proc} as the hashing function.
4239
4240By default, @var{equal-proc} is @code{equal?}. It can be any
4241two-argument procedure, and should answer whether two keys are the
4242same for this table's purposes.
4243
4244My default @var{hash-proc} assumes that @code{equal-proc} is no
4245coarser than @code{equal?} unless it is literally @code{string-ci=?}.
4246If provided, @var{hash-proc} should be a two-argument procedure that
4247takes a key and the current table size, and answers a reasonably good
4248hash integer between 0 (inclusive) and the size (exclusive).
4249
4250@var{weakness} should be @code{#f} or a symbol indicating how ``weak''
4251the hash table is:
4252
4253@table @code
4254@item #f
4255An ordinary non-weak hash table. This is the default.
4256
4257@item key
4258When the key has no more non-weak references at GC, remove that entry.
4259
4260@item value
4261When the value has no more non-weak references at GC, remove that
4262entry.
4263
4264@item key-or-value
4265When either has no more non-weak references at GC, remove the
4266association.
4267@end table
4268
4269As a legacy of the time when Guile couldn't grow hash tables,
4270@var{start-size} is an optional integer argument that specifies the
dfe8c13b
LC
4271approximate starting size for the hash table, which will be rounded to
4272an algorithmically-sounder number.
1317062f
LC
4273@end deffn
4274
dfe8c13b 4275By @dfn{coarser} than @code{equal?}, we mean that for all @var{x} and
1317062f
LC
4276@var{y} values where @code{(@var{equal-proc} @var{x} @var{y})},
4277@code{(equal? @var{x} @var{y})} as well. If that does not hold for
4278your @var{equal-proc}, you must provide a @var{hash-proc}.
4279
4280In the case of weak tables, remember that @dfn{references} above
4281always refers to @code{eq?}-wise references. Just because you have a
4282reference to some string @code{"foo"} doesn't mean that an association
4283with key @code{"foo"} in a weak-key table @emph{won't} be collected;
4284it only counts as a reference if the two @code{"foo"}s are @code{eq?},
4285regardless of @var{equal-proc}. As such, it is usually only sensible
4286to use @code{eq?} and @code{hashq} as the equivalence and hash
4287functions for a weak table. @xref{Weak References}, for more
4288information on Guile's built-in weak table support.
4289
4290@deffn {Scheme Procedure} alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size]
4291As with @code{make-hash-table}, but initialize it with the
4292associations in @var{alist}. Where keys are repeated in @var{alist},
4293the leftmost association takes precedence.
4294@end deffn
4295
4296@node SRFI-69 Accessing table items
4297@subsubsection Accessing table items
4298
4299@deffn {Scheme Procedure} hash-table-ref table key [default-thunk]
4300@deffnx {Scheme Procedure} hash-table-ref/default table key default
4301Answer the value associated with @var{key} in @var{table}. If
4302@var{key} is not present, answer the result of invoking the thunk
4303@var{default-thunk}, which signals an error instead by default.
4304
4305@code{hash-table-ref/default} is a variant that requires a third
4306argument, @var{default}, and answers @var{default} itself instead of
4307invoking it.
4308@end deffn
4309
4310@deffn {Scheme Procedure} hash-table-set! table key new-value
4311Set @var{key} to @var{new-value} in @var{table}.
4312@end deffn
4313
4314@deffn {Scheme Procedure} hash-table-delete! table key
4315Remove the association of @var{key} in @var{table}, if present. If
4316absent, do nothing.
4317@end deffn
4318
4319@deffn {Scheme Procedure} hash-table-exists? table key
4320Answer whether @var{key} has an association in @var{table}.
4321@end deffn
4322
4323@deffn {Scheme Procedure} hash-table-update! table key modifier [default-thunk]
4324@deffnx {Scheme Procedure} hash-table-update!/default table key modifier default
4325Replace @var{key}'s associated value in @var{table} by invoking
4326@var{modifier} with one argument, the old value.
4327
4328If @var{key} is not present, and @var{default-thunk} is provided,
4329invoke it with no arguments to get the ``old value'' to be passed to
4330@var{modifier} as above. If @var{default-thunk} is not provided in
4331such a case, signal an error.
4332
4333@code{hash-table-update!/default} is a variant that requires the
4334fourth argument, which is used directly as the ``old value'' rather
4335than as a thunk to be invoked to retrieve the ``old value''.
4336@end deffn
4337
4338@node SRFI-69 Table properties
4339@subsubsection Table properties
4340
4341@deffn {Scheme Procedure} hash-table-size table
4342Answer the number of associations in @var{table}. This is guaranteed
4343to run in constant time for non-weak tables.
4344@end deffn
4345
4346@deffn {Scheme Procedure} hash-table-keys table
4347Answer an unordered list of the keys in @var{table}.
4348@end deffn
4349
4350@deffn {Scheme Procedure} hash-table-values table
4351Answer an unordered list of the values in @var{table}.
4352@end deffn
4353
4354@deffn {Scheme Procedure} hash-table-walk table proc
4355Invoke @var{proc} once for each association in @var{table}, passing
4356the key and value as arguments.
4357@end deffn
4358
4359@deffn {Scheme Procedure} hash-table-fold table proc init
4360Invoke @code{(@var{proc} @var{key} @var{value} @var{previous})} for
4361each @var{key} and @var{value} in @var{table}, where @var{previous} is
4362the result of the previous invocation, using @var{init} as the first
4363@var{previous} value. Answer the final @var{proc} result.
4364@end deffn
4365
4366@deffn {Scheme Procedure} hash-table->alist table
4367Answer an alist where each association in @var{table} is an
4368association in the result.
4369@end deffn
4370
4371@node SRFI-69 Hash table algorithms
4372@subsubsection Hash table algorithms
4373
4374Each hash table carries an @dfn{equivalence function} and a @dfn{hash
4375function}, used to implement key lookups. Beginning users should
4376follow the rules for consistency of the default @var{hash-proc}
4377specified above. Advanced users can use these to implement their own
4378equivalence and hash functions for specialized lookup semantics.
4379
4380@deffn {Scheme Procedure} hash-table-equivalence-function hash-table
4381@deffnx {Scheme Procedure} hash-table-hash-function hash-table
4382Answer the equivalence and hash function of @var{hash-table}, respectively.
4383@end deffn
4384
4385@deffn {Scheme Procedure} hash obj [size]
4386@deffnx {Scheme Procedure} string-hash obj [size]
4387@deffnx {Scheme Procedure} string-ci-hash obj [size]
4388@deffnx {Scheme Procedure} hash-by-identity obj [size]
4389Answer a hash value appropriate for equality predicate @code{equal?},
4390@code{string=?}, @code{string-ci=?}, and @code{eq?}, respectively.
4391@end deffn
4392
4393@code{hash} is a backwards-compatible replacement for Guile's built-in
4394@code{hash}.
4395
189681f5
LC
4396@node SRFI-88
4397@subsection SRFI-88 Keyword Objects
4398@cindex SRFI-88
4399@cindex keyword objects
4400
e36280cb 4401@uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI-88} provides
189681f5
LC
4402@dfn{keyword objects}, which are equivalent to Guile's keywords
4403(@pxref{Keywords}). SRFI-88 keywords can be entered using the
4404@dfn{postfix keyword syntax}, which consists of an identifier followed
1518f649 4405by @code{:} (@pxref{Scheme Read, @code{postfix} keyword syntax}).
189681f5
LC
4406SRFI-88 can be made available with:
4407
4408@example
4409(use-modules (srfi srfi-88))
4410@end example
4411
4412Doing so installs the right reader option for keyword syntax, using
4413@code{(read-set! keywords 'postfix)}. It also provides the procedures
4414described below.
4415
4416@deffn {Scheme Procedure} keyword? obj
4417Return @code{#t} if @var{obj} is a keyword. This is the same procedure
4418as the same-named built-in procedure (@pxref{Keyword Procedures,
4419@code{keyword?}}).
4420
4421@example
4422(keyword? foo:) @result{} #t
4423(keyword? 'foo:) @result{} #t
4424(keyword? "foo") @result{} #f
4425@end example
4426@end deffn
4427
4428@deffn {Scheme Procedure} keyword->string kw
4429Return the name of @var{kw} as a string, i.e., without the trailing
4430colon. The returned string may not be modified, e.g., with
4431@code{string-set!}.
4432
4433@example
4434(keyword->string foo:) @result{} "foo"
4435@end example
4436@end deffn
4437
4438@deffn {Scheme Procedure} string->keyword str
4439Return the keyword object whose name is @var{str}.
4440
4441@example
4442(keyword->string (string->keyword "a b c")) @result{} "a b c"
4443@end example
4444@end deffn
4445
922d417b
JG
4446@node SRFI-98
4447@subsection SRFI-98 Accessing environment variables.
4448@cindex SRFI-98
4449@cindex environment variables
4450
4451This is a portable wrapper around Guile's built-in support for
4452interacting with the current environment, @xref{Runtime Environment}.
4453
4454@deffn {Scheme Procedure} get-environment-variable name
4455Returns a string containing the value of the environment variable
4456given by the string @code{name}, or @code{#f} if the named
4457environment variable is not found. This is equivalent to
4458@code{(getenv name)}.
4459@end deffn
4460
4461@deffn {Scheme Procedure} get-environment-variables
4462Returns the names and values of all the environment variables as an
4463association list in which both the keys and the values are strings.
4464@end deffn
1317062f 4465
12991fed 4466@c srfi-modules.texi ends here
193239f1
KR
4467
4468@c Local Variables:
4469@c TeX-master: "guile.texi"
4470@c End: