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