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