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