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