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