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