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