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