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