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