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