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