Rewrite SRFI-35 macros using `syntax-rules'.
[bpt/guile.git] / doc / ref / srfi-modules.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node SRFI Support
9 @section SRFI Support Modules
10 @cindex SRFI
11
12 SRFI is an acronym for Scheme Request For Implementation. The SRFI
13 documents define a lot of syntactic and procedure extensions to standard
14 Scheme as defined in R5RS.
15
16 Guile has support for a number of SRFIs. This chapter gives an overview
17 over the available SRFIs and some usage hints. For complete
18 documentation, design rationales and further examples, we advise you to
19 get the relevant SRFI documents from the SRFI home page
20 @url{http://srfi.schemers.org}.
21
22 @menu
23 * About SRFI Usage:: What to know about Guile's SRFI support.
24 * SRFI-0:: cond-expand
25 * SRFI-1:: List library.
26 * SRFI-2:: and-let*.
27 * SRFI-4:: Homogeneous numeric vector datatypes.
28 * SRFI-6:: Basic String Ports.
29 * SRFI-8:: receive.
30 * SRFI-9:: define-record-type.
31 * SRFI-10:: Hash-Comma Reader Extension.
32 * SRFI-11:: let-values and let*-values.
33 * SRFI-13:: String library.
34 * SRFI-14:: Character-set library.
35 * SRFI-16:: case-lambda
36 * SRFI-17:: Generalized set!
37 * SRFI-18:: Multithreading support
38 * SRFI-19:: Time/Date library.
39 * SRFI-26:: Specializing parameters
40 * SRFI-31:: A special form `rec' for recursive evaluation
41 * SRFI-34:: Exception handling.
42 * SRFI-35:: Conditions.
43 * SRFI-37:: args-fold program argument processor
44 * SRFI-39:: Parameter objects
45 * SRFI-55:: Requiring Features.
46 * SRFI-60:: Integers as bits.
47 * SRFI-61:: A more general `cond' clause
48 * SRFI-69:: Basic hash tables.
49 * SRFI-88:: Keyword objects.
50 @end menu
51
52
53 @node About SRFI Usage
54 @subsection About SRFI Usage
55
56 @c FIXME::martin: Review me!
57
58 SRFI support in Guile is currently implemented partly in the core
59 library, and partly as add-on modules. That means that some SRFIs are
60 automatically available when the interpreter is started, whereas the
61 other SRFIs require you to use the appropriate support module
62 explicitly.
63
64 There are several reasons for this inconsistency. First, the feature
65 checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
66 available immediately, because it must be there when the user wants to
67 check for the Scheme implementation, that is, before she can know that
68 it is safe to use @code{use-modules} to load SRFI support modules. The
69 second reason is that some features defined in SRFIs had been
70 implemented in Guile before the developers started to add SRFI
71 implementations as modules (for example SRFI-6 (@pxref{SRFI-6})). In
72 the future, it is possible that SRFIs in the core library might be
73 factored out into separate modules, requiring explicit module loading
74 when they are needed. So you should be prepared to have to use
75 @code{use-modules} someday in the future to access SRFI-6 bindings. If
76 you want, you can do that already. We have included the module
77 @code{(srfi srfi-6)} in the distribution, which currently does nothing,
78 but ensures that you can write future-safe code.
79
80 Generally, support for a specific SRFI is made available by using
81 modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
82 number of the SRFI needed. Another possibility is to use the command
83 line option @code{--use-srfi}, which will load the necessary modules
84 automatically (@pxref{Invoking Guile}).
85
86
87 @node SRFI-0
88 @subsection SRFI-0 - cond-expand
89 @cindex SRFI-0
90
91 This SRFI lets a portable Scheme program test for the presence of
92 certain features, and adapt itself by using different blocks of code,
93 or fail if the necessary features are not available. There's no
94 module to load, this is in the Guile core.
95
96 A program designed only for Guile will generally not need this
97 mechanism, such a program can of course directly use the various
98 documented parts of Guile.
99
100 @deffn syntax cond-expand (feature body@dots{}) @dots{}
101 Expand to the @var{body} of the first clause whose @var{feature}
102 specification is satisfied. It is an error if no @var{feature} is
103 satisfied.
104
105 Features are symbols such as @code{srfi-1}, and a feature
106 specification can use @code{and}, @code{or} and @code{not} forms to
107 test combinations. The last clause can be an @code{else}, to be used
108 if no other passes.
109
110 For example, define a private version of @code{alist-cons} if SRFI-1
111 is not available.
112
113 @example
114 (cond-expand (srfi-1
115 )
116 (else
117 (define (alist-cons key val alist)
118 (cons (cons key val) alist))))
119 @end example
120
121 Or demand a certain set of SRFIs (list operations, string ports,
122 @code{receive} and string operations), failing if they're not
123 available.
124
125 @example
126 (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
127 ))
128 @end example
129 @end deffn
130
131 @noindent
132 The Guile core has the following features,
133
134 @example
135 guile
136 r5rs
137 srfi-0
138 srfi-4
139 srfi-6
140 srfi-13
141 srfi-14
142 @end example
143
144 Other SRFI feature symbols are defined once their code has been loaded
145 with @code{use-modules}, since only then are their bindings available.
146
147 The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
148 a good way to load SRFIs to satisfy @code{cond-expand} when running a
149 portable program.
150
151 Testing the @code{guile} feature allows a program to adapt itself to
152 the Guile module system, but still run on other Scheme systems. For
153 example the following demands SRFI-8 (@code{receive}), but also knows
154 how to load it with the Guile mechanism.
155
156 @example
157 (cond-expand (srfi-8
158 )
159 (guile
160 (use-modules (srfi srfi-8))))
161 @end example
162
163 It should be noted that @code{cond-expand} is separate from the
164 @code{*features*} mechanism (@pxref{Feature Tracking}), feature
165 symbols in one are unrelated to those in the other.
166
167
168 @node SRFI-1
169 @subsection SRFI-1 - List library
170 @cindex SRFI-1
171 @cindex list
172
173 @c FIXME::martin: Review me!
174
175 The list library defined in SRFI-1 contains a lot of useful list
176 processing procedures for construction, examining, destructuring and
177 manipulating lists and pairs.
178
179 Since SRFI-1 also defines some procedures which are already contained
180 in R5RS and thus are supported by the Guile core library, some list
181 and pair procedures which appear in the SRFI-1 document may not appear
182 in this section. So when looking for a particular list/pair
183 processing procedure, you should also have a look at the sections
184 @ref{Lists} and @ref{Pairs}.
185
186 @menu
187 * SRFI-1 Constructors:: Constructing new lists.
188 * SRFI-1 Predicates:: Testing list for specific properties.
189 * SRFI-1 Selectors:: Selecting elements from lists.
190 * SRFI-1 Length Append etc:: Length calculation and list appending.
191 * SRFI-1 Fold and Map:: Higher-order list processing.
192 * SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
193 * SRFI-1 Searching:: Search for elements.
194 * SRFI-1 Deleting:: Delete elements from lists.
195 * SRFI-1 Association Lists:: Handle association lists.
196 * SRFI-1 Set Operations:: Use lists for representing sets.
197 @end menu
198
199 @node SRFI-1 Constructors
200 @subsubsection Constructors
201 @cindex list constructor
202
203 @c FIXME::martin: Review me!
204
205 New lists can be constructed by calling one of the following
206 procedures.
207
208 @deffn {Scheme Procedure} xcons d a
209 Like @code{cons}, but with interchanged arguments. Useful mostly when
210 passed to higher-order procedures.
211 @end deffn
212
213 @deffn {Scheme Procedure} list-tabulate n init-proc
214 Return an @var{n}-element list, where each list element is produced by
215 applying the procedure @var{init-proc} to the corresponding list
216 index. The order in which @var{init-proc} is applied to the indices
217 is not specified.
218 @end deffn
219
220 @deffn {Scheme Procedure} list-copy lst
221 Return a new list containing the elements of the list @var{lst}.
222
223 This function differs from the core @code{list-copy} (@pxref{List
224 Constructors}) in accepting improper lists too. And if @var{lst} is
225 not a pair at all then it's treated as the final tail of an improper
226 list and simply returned.
227 @end deffn
228
229 @deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
230 Return a circular list containing the given arguments @var{elt1}
231 @var{elt2} @dots{}.
232 @end deffn
233
234 @deffn {Scheme Procedure} iota count [start step]
235 Return a list containing @var{count} numbers, starting from
236 @var{start} and adding @var{step} each time. The default @var{start}
237 is 0, the default @var{step} is 1. For example,
238
239 @example
240 (iota 6) @result{} (0 1 2 3 4 5)
241 (iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
242 @end example
243
244 This function takes its name from the corresponding primitive in the
245 APL language.
246 @end deffn
247
248
249 @node SRFI-1 Predicates
250 @subsubsection Predicates
251 @cindex list predicate
252
253 @c FIXME::martin: Review me!
254
255 The procedures in this section test specific properties of lists.
256
257 @deffn {Scheme Procedure} proper-list? obj
258 Return @code{#t} if @var{obj} is a proper list, or @code{#f}
259 otherwise. This is the same as the core @code{list?} (@pxref{List
260 Predicates}).
261
262 A proper list is a list which ends with the empty list @code{()} in
263 the usual way. The empty list @code{()} itself is a proper list too.
264
265 @example
266 (proper-list? '(1 2 3)) @result{} #t
267 (proper-list? '()) @result{} #t
268 @end example
269 @end deffn
270
271 @deffn {Scheme Procedure} circular-list? obj
272 Return @code{#t} if @var{obj} is a circular list, or @code{#f}
273 otherwise.
274
275 A circular list is a list where at some point the @code{cdr} refers
276 back to a previous pair in the list (either the start or some later
277 point), so that following the @code{cdr}s takes you around in a
278 circle, with no end.
279
280 @example
281 (define x (list 1 2 3 4))
282 (set-cdr! (last-pair x) (cddr x))
283 x @result{} (1 2 3 4 3 4 3 4 ...)
284 (circular-list? x) @result{} #t
285 @end example
286 @end deffn
287
288 @deffn {Scheme Procedure} dotted-list? obj
289 Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
290 otherwise.
291
292 A dotted list is a list where the @code{cdr} of the last pair is not
293 the empty list @code{()}. Any non-pair @var{obj} is also considered a
294 dotted list, with length zero.
295
296 @example
297 (dotted-list? '(1 2 . 3)) @result{} #t
298 (dotted-list? 99) @result{} #t
299 @end example
300 @end deffn
301
302 It will be noted that any Scheme object passes exactly one of the
303 above three tests @code{proper-list?}, @code{circular-list?} and
304 @code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
305 are either @code{proper-list?} or @code{dotted-list?}, and infinite
306 lists are @code{circular-list?}.
307
308 @sp 1
309 @deffn {Scheme Procedure} null-list? lst
310 Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
311 otherwise. If something else than a proper or circular list is passed
312 as @var{lst}, an error is signalled. This procedure is recommended
313 for checking for the end of a list in contexts where dotted lists are
314 not allowed.
315 @end deffn
316
317 @deffn {Scheme Procedure} not-pair? obj
318 Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
319 This is shorthand notation @code{(not (pair? @var{obj}))} and is
320 supposed to be used for end-of-list checking in contexts where dotted
321 lists are allowed.
322 @end deffn
323
324 @deffn {Scheme Procedure} list= elt= list1 @dots{}
325 Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
326 List equality is determined by testing whether all lists have the same
327 length and the corresponding elements are equal in the sense of the
328 equality predicate @var{elt=}. If no or only one list is given,
329 @code{#t} is returned.
330 @end deffn
331
332
333 @node SRFI-1 Selectors
334 @subsubsection Selectors
335 @cindex list selector
336
337 @c FIXME::martin: Review me!
338
339 @deffn {Scheme Procedure} first pair
340 @deffnx {Scheme Procedure} second pair
341 @deffnx {Scheme Procedure} third pair
342 @deffnx {Scheme Procedure} fourth pair
343 @deffnx {Scheme Procedure} fifth pair
344 @deffnx {Scheme Procedure} sixth pair
345 @deffnx {Scheme Procedure} seventh pair
346 @deffnx {Scheme Procedure} eighth pair
347 @deffnx {Scheme Procedure} ninth pair
348 @deffnx {Scheme Procedure} tenth pair
349 These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
350 @end deffn
351
352 @deffn {Scheme Procedure} car+cdr pair
353 Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
354 @end deffn
355
356 @deffn {Scheme Procedure} take lst i
357 @deffnx {Scheme Procedure} take! lst i
358 Return a list containing the first @var{i} elements of @var{lst}.
359
360 @code{take!} may modify the structure of the argument list @var{lst}
361 in order to produce the result.
362 @end deffn
363
364 @deffn {Scheme Procedure} drop lst i
365 Return a list containing all but the first @var{i} elements of
366 @var{lst}.
367 @end deffn
368
369 @deffn {Scheme Procedure} take-right lst i
370 Return the a list containing the @var{i} last elements of @var{lst}.
371 The return shares a common tail with @var{lst}.
372 @end deffn
373
374 @deffn {Scheme Procedure} drop-right lst i
375 @deffnx {Scheme Procedure} drop-right! lst i
376 Return the a list containing all but the @var{i} last elements of
377 @var{lst}.
378
379 @code{drop-right} always returns a new list, even when @var{i} is
380 zero. @code{drop-right!} may modify the structure of the argument
381 list @var{lst} in order to produce the result.
382 @end deffn
383
384 @deffn {Scheme Procedure} split-at lst i
385 @deffnx {Scheme Procedure} split-at! lst i
386 Return two values, a list containing the first @var{i} elements of the
387 list @var{lst} and a list containing the remaining elements.
388
389 @code{split-at!} may modify the structure of the argument list
390 @var{lst} in order to produce the result.
391 @end deffn
392
393 @deffn {Scheme Procedure} last lst
394 Return the last element of the non-empty, finite list @var{lst}.
395 @end deffn
396
397
398 @node SRFI-1 Length Append etc
399 @subsubsection Length, Append, Concatenate, etc.
400
401 @c FIXME::martin: Review me!
402
403 @deffn {Scheme Procedure} length+ lst
404 Return the length of the argument list @var{lst}. When @var{lst} is a
405 circular list, @code{#f} is returned.
406 @end deffn
407
408 @deffn {Scheme Procedure} concatenate list-of-lists
409 @deffnx {Scheme Procedure} concatenate! list-of-lists
410 Construct a list by appending all lists in @var{list-of-lists}.
411
412 @code{concatenate!} may modify the structure of the given lists in
413 order to produce the result.
414
415 @code{concatenate} is the same as @code{(apply append
416 @var{list-of-lists})}. It exists because some Scheme implementations
417 have a limit on the number of arguments a function takes, which the
418 @code{apply} might exceed. In Guile there is no such limit.
419 @end deffn
420
421 @deffn {Scheme Procedure} append-reverse rev-head tail
422 @deffnx {Scheme Procedure} append-reverse! rev-head tail
423 Reverse @var{rev-head}, append @var{tail} to it, and return the
424 result. This is equivalent to @code{(append (reverse @var{rev-head})
425 @var{tail})}, but its implementation is more efficient.
426
427 @example
428 (append-reverse '(1 2 3) '(4 5 6)) @result{} (3 2 1 4 5 6)
429 @end example
430
431 @code{append-reverse!} may modify @var{rev-head} in order to produce
432 the result.
433 @end deffn
434
435 @deffn {Scheme Procedure} zip lst1 lst2 @dots{}
436 Return a list as long as the shortest of the argument lists, where
437 each element is a list. The first list contains the first elements of
438 the argument lists, the second list contains the second elements, and
439 so on.
440 @end deffn
441
442 @deffn {Scheme Procedure} unzip1 lst
443 @deffnx {Scheme Procedure} unzip2 lst
444 @deffnx {Scheme Procedure} unzip3 lst
445 @deffnx {Scheme Procedure} unzip4 lst
446 @deffnx {Scheme Procedure} unzip5 lst
447 @code{unzip1} takes a list of lists, and returns a list containing the
448 first elements of each list, @code{unzip2} returns two lists, the
449 first containing the first elements of each lists and the second
450 containing the second elements of each lists, and so on.
451 @end deffn
452
453 @deffn {Scheme Procedure} count pred lst1 @dots{} lstN
454 Return a count of the number of times @var{pred} returns true when
455 called on elements from the given lists.
456
457 @var{pred} is called with @var{N} parameters @code{(@var{pred}
458 @var{elem1} @dots{} @var{elemN})}, each element being from the
459 corresponding @var{lst1} @dots{} @var{lstN}. The first call is with
460 the first element of each list, the second with the second element
461 from each, and so on.
462
463 Counting stops when the end of the shortest list is reached. At least
464 one list must be non-circular.
465 @end deffn
466
467
468 @node SRFI-1 Fold and Map
469 @subsubsection Fold, Unfold & Map
470 @cindex list fold
471 @cindex list map
472
473 @c FIXME::martin: Review me!
474
475 @deffn {Scheme Procedure} fold proc init lst1 @dots{} lstN
476 @deffnx {Scheme Procedure} fold-right proc init lst1 @dots{} lstN
477 Apply @var{proc} to the elements of @var{lst1} @dots{} @var{lstN} to
478 build a result, and return that result.
479
480 Each @var{proc} call is @code{(@var{proc} @var{elem1} @dots{}
481 @var{elemN} @var{previous})}, where @var{elem1} is from @var{lst1},
482 through @var{elemN} from @var{lstN}. @var{previous} is the return
483 from the previous call to @var{proc}, or the given @var{init} for the
484 first call. If any list is empty, just @var{init} is returned.
485
486 @code{fold} works through the list elements from first to last. The
487 following shows a list reversal and the calls it makes,
488
489 @example
490 (fold cons '() '(1 2 3))
491
492 (cons 1 '())
493 (cons 2 '(1))
494 (cons 3 '(2 1)
495 @result{} (3 2 1)
496 @end example
497
498 @code{fold-right} works through the list elements from last to first,
499 ie.@: from the right. So for example the following finds the longest
500 string, and the last among equal longest,
501
502 @example
503 (fold-right (lambda (str prev)
504 (if (> (string-length str) (string-length prev))
505 str
506 prev))
507 ""
508 '("x" "abc" "xyz" "jk"))
509 @result{} "xyz"
510 @end example
511
512 If @var{lst1} through @var{lstN} have different lengths, @code{fold}
513 stops when the end of the shortest is reached; @code{fold-right}
514 commences at the last element of the shortest. Ie.@: elements past
515 the length of the shortest are ignored in the other @var{lst}s. At
516 least one @var{lst} must be non-circular.
517
518 @code{fold} should be preferred over @code{fold-right} if the order of
519 processing doesn't matter, or can be arranged either way, since
520 @code{fold} is a little more efficient.
521
522 The way @code{fold} builds a result from iterating is quite general,
523 it can do more than other iterations like say @code{map} or
524 @code{filter}. The following for example removes adjacent duplicate
525 elements from a list,
526
527 @example
528 (define (delete-adjacent-duplicates lst)
529 (fold-right (lambda (elem ret)
530 (if (equal? elem (first ret))
531 ret
532 (cons elem ret)))
533 (list (last lst))
534 lst))
535 (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
536 @result{} (1 2 3 4 5)
537 @end example
538
539 Clearly the same sort of thing can be done with a @code{for-each} and
540 a variable in which to build the result, but a self-contained
541 @var{proc} can be re-used in multiple contexts, where a
542 @code{for-each} would have to be written out each time.
543 @end deffn
544
545 @deffn {Scheme Procedure} pair-fold proc init lst1 @dots{} lstN
546 @deffnx {Scheme Procedure} pair-fold-right proc init lst1 @dots{} lstN
547 The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
548 the pairs of the lists instead of the list elements.
549 @end deffn
550
551 @deffn {Scheme Procedure} reduce proc default lst
552 @deffnx {Scheme Procedure} reduce-right proc default lst
553 @code{reduce} is a variant of @code{fold}, where the first call to
554 @var{proc} is on two elements from @var{lst}, rather than one element
555 and a given initial value.
556
557 If @var{lst} is empty, @code{reduce} returns @var{default} (this is
558 the only use for @var{default}). If @var{lst} has just one element
559 then that's the return value. Otherwise @var{proc} is called on the
560 elements of @var{lst}.
561
562 Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
563 where @var{elem} is from @var{lst} (the second and subsequent elements
564 of @var{lst}), and @var{previous} is the return from the previous call
565 to @var{proc}. The first element of @var{lst} is the @var{previous}
566 for the first call to @var{proc}.
567
568 For example, the following adds a list of numbers, the calls made to
569 @code{+} are shown. (Of course @code{+} accepts multiple arguments
570 and can add a list directly, with @code{apply}.)
571
572 @example
573 (reduce + 0 '(5 6 7)) @result{} 18
574
575 (+ 6 5) @result{} 11
576 (+ 7 11) @result{} 18
577 @end example
578
579 @code{reduce} can be used instead of @code{fold} where the @var{init}
580 value is an ``identity'', meaning a value which under @var{proc}
581 doesn't change the result, in this case 0 is an identity since
582 @code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
583
584 @code{reduce-right} is a similar variation on @code{fold-right},
585 working from the end (ie.@: the right) of @var{lst}. The last element
586 of @var{lst} is the @var{previous} for the first call to @var{proc},
587 and the @var{elem} values go from the second last.
588
589 @code{reduce} should be preferred over @code{reduce-right} if the
590 order of processing doesn't matter, or can be arranged either way,
591 since @code{reduce} is a little more efficient.
592 @end deffn
593
594 @deffn {Scheme Procedure} unfold p f g seed [tail-gen]
595 @code{unfold} is defined as follows:
596
597 @lisp
598 (unfold p f g seed) =
599 (if (p seed) (tail-gen seed)
600 (cons (f seed)
601 (unfold p f g (g seed))))
602 @end lisp
603
604 @table @var
605 @item p
606 Determines when to stop unfolding.
607
608 @item f
609 Maps each seed value to the corresponding list element.
610
611 @item g
612 Maps each seed value to next seed valu.
613
614 @item seed
615 The state value for the unfold.
616
617 @item tail-gen
618 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
619 @end table
620
621 @var{g} produces a series of seed values, which are mapped to list
622 elements by @var{f}. These elements are put into a list in
623 left-to-right order, and @var{p} tells when to stop unfolding.
624 @end deffn
625
626 @deffn {Scheme Procedure} unfold-right p f g seed [tail]
627 Construct a list with the following loop.
628
629 @lisp
630 (let lp ((seed seed) (lis tail))
631 (if (p seed) lis
632 (lp (g seed)
633 (cons (f seed) lis))))
634 @end lisp
635
636 @table @var
637 @item p
638 Determines when to stop unfolding.
639
640 @item f
641 Maps each seed value to the corresponding list element.
642
643 @item g
644 Maps each seed value to next seed valu.
645
646 @item seed
647 The state value for the unfold.
648
649 @item tail-gen
650 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
651 @end table
652
653 @end deffn
654
655 @deffn {Scheme Procedure} map f lst1 lst2 @dots{}
656 Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
657 return a list containing the results of the procedure applications.
658 This procedure is extended with respect to R5RS, because the argument
659 lists may have different lengths. The result list will have the same
660 length as the shortest argument lists. The order in which @var{f}
661 will be applied to the list element(s) is not specified.
662 @end deffn
663
664 @deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
665 Apply the procedure @var{f} to each pair of corresponding elements of
666 the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
667 specified. This procedure is extended with respect to R5RS, because
668 the argument lists may have different lengths. The shortest argument
669 list determines the number of times @var{f} is called. @var{f} will
670 be applied to the list elements in left-to-right order.
671
672 @end deffn
673
674 @deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
675 @deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
676 Equivalent to
677
678 @lisp
679 (apply append (map f clist1 clist2 ...))
680 @end lisp
681
682 and
683
684 @lisp
685 (apply append! (map f clist1 clist2 ...))
686 @end lisp
687
688 Map @var{f} over the elements of the lists, just as in the @code{map}
689 function. However, the results of the applications are appended
690 together to make the final result. @code{append-map} uses
691 @code{append} to append the results together; @code{append-map!} uses
692 @code{append!}.
693
694 The dynamic order in which the various applications of @var{f} are
695 made is not specified.
696 @end deffn
697
698 @deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
699 Linear-update variant of @code{map} -- @code{map!} is allowed, but not
700 required, to alter the cons cells of @var{lst1} to construct the
701 result list.
702
703 The dynamic order in which the various applications of @var{f} are
704 made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
705 @dots{} must have at least as many elements as @var{lst1}.
706 @end deffn
707
708 @deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
709 Like @code{for-each}, but applies the procedure @var{f} to the pairs
710 from which the argument lists are constructed, instead of the list
711 elements. The return value is not specified.
712 @end deffn
713
714 @deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
715 Like @code{map}, but only results from the applications of @var{f}
716 which are true are saved in the result list.
717 @end deffn
718
719
720 @node SRFI-1 Filtering and Partitioning
721 @subsubsection Filtering and Partitioning
722 @cindex list filter
723 @cindex list partition
724
725 @c FIXME::martin: Review me!
726
727 Filtering means to collect all elements from a list which satisfy a
728 specific condition. Partitioning a list means to make two groups of
729 list elements, one which contains the elements satisfying a condition,
730 and the other for the elements which don't.
731
732 The @code{filter} and @code{filter!} functions are implemented in the
733 Guile core, @xref{List Modification}.
734
735 @deffn {Scheme Procedure} partition pred lst
736 @deffnx {Scheme Procedure} partition! pred lst
737 Split @var{lst} into those elements which do and don't satisfy the
738 predicate @var{pred}.
739
740 The return is two values (@pxref{Multiple Values}), the first being a
741 list of all elements from @var{lst} which satisfy @var{pred}, the
742 second a list of those which do not.
743
744 The elements in the result lists are in the same order as in @var{lst}
745 but the order in which the calls @code{(@var{pred} elem)} are made on
746 the list elements is unspecified.
747
748 @code{partition} does not change @var{lst}, but one of the returned
749 lists may share a tail with it. @code{partition!} may modify
750 @var{lst} to construct its return.
751 @end deffn
752
753 @deffn {Scheme Procedure} remove pred lst
754 @deffnx {Scheme Procedure} remove! pred lst
755 Return a list containing all elements from @var{lst} which do not
756 satisfy the predicate @var{pred}. The elements in the result list
757 have the same order as in @var{lst}. The order in which @var{pred} is
758 applied to the list elements is not specified.
759
760 @code{remove!} is allowed, but not required to modify the structure of
761 the input list.
762 @end deffn
763
764
765 @node SRFI-1 Searching
766 @subsubsection Searching
767 @cindex list search
768
769 @c FIXME::martin: Review me!
770
771 The procedures for searching elements in lists either accept a
772 predicate or a comparison object for determining which elements are to
773 be searched.
774
775 @deffn {Scheme Procedure} find pred lst
776 Return the first element of @var{lst} which satisfies the predicate
777 @var{pred} and @code{#f} if no such element is found.
778 @end deffn
779
780 @deffn {Scheme Procedure} find-tail pred lst
781 Return the first pair of @var{lst} whose @sc{car} satisfies the
782 predicate @var{pred} and @code{#f} if no such element is found.
783 @end deffn
784
785 @deffn {Scheme Procedure} take-while pred lst
786 @deffnx {Scheme Procedure} take-while! pred lst
787 Return the longest initial prefix of @var{lst} whose elements all
788 satisfy the predicate @var{pred}.
789
790 @code{take-while!} is allowed, but not required to modify the input
791 list while producing the result.
792 @end deffn
793
794 @deffn {Scheme Procedure} drop-while pred lst
795 Drop the longest initial prefix of @var{lst} whose elements all
796 satisfy the predicate @var{pred}.
797 @end deffn
798
799 @deffn {Scheme Procedure} span pred lst
800 @deffnx {Scheme Procedure} span! pred lst
801 @deffnx {Scheme Procedure} break pred lst
802 @deffnx {Scheme Procedure} break! pred lst
803 @code{span} splits the list @var{lst} into the longest initial prefix
804 whose elements all satisfy the predicate @var{pred}, and the remaining
805 tail. @code{break} inverts the sense of the predicate.
806
807 @code{span!} and @code{break!} are allowed, but not required to modify
808 the structure of the input list @var{lst} in order to produce the
809 result.
810
811 Note that the name @code{break} conflicts with the @code{break}
812 binding established by @code{while} (@pxref{while do}). Applications
813 wanting to use @code{break} from within a @code{while} loop will need
814 to make a new define under a different name.
815 @end deffn
816
817 @deffn {Scheme Procedure} any pred lst1 lst2 @dots{} lstN
818 Test whether any set of elements from @var{lst1} @dots{} lstN
819 satisfies @var{pred}. If so the return value is the return from the
820 successful @var{pred} call, or if not the return is @code{#f}.
821
822 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
823 @var{elemN})} taking an element from each @var{lst}. The calls are
824 made successively for the first, second, etc elements of the lists,
825 stopping when @var{pred} returns non-@code{#f}, or when the end of the
826 shortest list is reached.
827
828 The @var{pred} call on the last set of elements (ie.@: when the end of
829 the shortest list has been reached), if that point is reached, is a
830 tail call.
831 @end deffn
832
833 @deffn {Scheme Procedure} every pred lst1 lst2 @dots{} lstN
834 Test whether every set of elements from @var{lst1} @dots{} lstN
835 satisfies @var{pred}. If so the return value is the return from the
836 final @var{pred} call, or if not the return is @code{#f}.
837
838 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
839 @var{elemN})} taking an element from each @var{lst}. The calls are
840 made successively for the first, second, etc elements of the lists,
841 stopping if @var{pred} returns @code{#f}, or when the end of any of
842 the lists is reached.
843
844 The @var{pred} call on the last set of elements (ie.@: when the end of
845 the shortest list has been reached) is a tail call.
846
847 If one of @var{lst1} @dots{} @var{lstN} is empty then no calls to
848 @var{pred} are made, and the return is @code{#t}.
849 @end deffn
850
851 @deffn {Scheme Procedure} list-index pred lst1 @dots{} lstN
852 Return the index of the first set of elements, one from each of
853 @var{lst1}@dots{}@var{lstN}, which satisfies @var{pred}.
854
855 @var{pred} is called as @code{(@var{pred} elem1 @dots{} elemN)}.
856 Searching stops when the end of the shortest @var{lst} is reached.
857 The return index starts from 0 for the first set of elements. If no
858 set of elements pass then the return is @code{#f}.
859
860 @example
861 (list-index odd? '(2 4 6 9)) @result{} 3
862 (list-index = '(1 2 3) '(3 1 2)) @result{} #f
863 @end example
864 @end deffn
865
866 @deffn {Scheme Procedure} member x lst [=]
867 Return the first sublist of @var{lst} whose @sc{car} is equal to
868 @var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
869
870 Equality is determined by @code{equal?}, or by the equality predicate
871 @var{=} if given. @var{=} is called @code{(= @var{x} elem)},
872 ie.@: with the given @var{x} first, so for example to find the first
873 element greater than 5,
874
875 @example
876 (member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
877 @end example
878
879 This version of @code{member} extends the core @code{member}
880 (@pxref{List Searching}) by accepting an equality predicate.
881 @end deffn
882
883
884 @node SRFI-1 Deleting
885 @subsubsection Deleting
886 @cindex list delete
887
888 @deffn {Scheme Procedure} delete x lst [=]
889 @deffnx {Scheme Procedure} delete! x lst [=]
890 Return a list containing the elements of @var{lst} but with those
891 equal to @var{x} deleted. The returned elements will be in the same
892 order as they were in @var{lst}.
893
894 Equality is determined by the @var{=} predicate, or @code{equal?} if
895 not given. An equality call is made just once for each element, but
896 the order in which the calls are made on the elements is unspecified.
897
898 The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
899 is first. This means for instance elements greater than 5 can be
900 deleted with @code{(delete 5 lst <)}.
901
902 @code{delete} does not modify @var{lst}, but the return might share a
903 common tail with @var{lst}. @code{delete!} may modify the structure
904 of @var{lst} to construct its return.
905
906 These functions extend the core @code{delete} and @code{delete!}
907 (@pxref{List Modification}) in accepting an equality predicate. See
908 also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
909 deleting multiple elements from a list.
910 @end deffn
911
912 @deffn {Scheme Procedure} delete-duplicates lst [=]
913 @deffnx {Scheme Procedure} delete-duplicates! lst [=]
914 Return a list containing the elements of @var{lst} but without
915 duplicates.
916
917 When elements are equal, only the first in @var{lst} is retained.
918 Equal elements can be anywhere in @var{lst}, they don't have to be
919 adjacent. The returned list will have the retained elements in the
920 same order as they were in @var{lst}.
921
922 Equality is determined by the @var{=} predicate, or @code{equal?} if
923 not given. Calls @code{(= x y)} are made with element @var{x} being
924 before @var{y} in @var{lst}. A call is made at most once for each
925 combination, but the sequence of the calls across the elements is
926 unspecified.
927
928 @code{delete-duplicates} does not modify @var{lst}, but the return
929 might share a common tail with @var{lst}. @code{delete-duplicates!}
930 may modify the structure of @var{lst} to construct its return.
931
932 In the worst case, this is an @math{O(N^2)} algorithm because it must
933 check each element against all those preceding it. For long lists it
934 is more efficient to sort and then compare only adjacent elements.
935 @end deffn
936
937
938 @node SRFI-1 Association Lists
939 @subsubsection Association Lists
940 @cindex association list
941 @cindex alist
942
943 @c FIXME::martin: Review me!
944
945 Association lists are described in detail in section @ref{Association
946 Lists}. The present section only documents the additional procedures
947 for dealing with association lists defined by SRFI-1.
948
949 @deffn {Scheme Procedure} assoc key alist [=]
950 Return the pair from @var{alist} which matches @var{key}. This
951 extends the core @code{assoc} (@pxref{Retrieving Alist Entries}) by
952 taking an optional @var{=} comparison procedure.
953
954 The default comparison is @code{equal?}. If an @var{=} parameter is
955 given it's called @code{(@var{=} @var{key} @var{alistcar})}, ie. the
956 given target @var{key} is the first argument, and a @code{car} from
957 @var{alist} is second.
958
959 For example a case-insensitive string lookup,
960
961 @example
962 (assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
963 @result{} ("YY" . 2)
964 @end example
965 @end deffn
966
967 @deffn {Scheme Procedure} alist-cons key datum alist
968 Cons a new association @var{key} and @var{datum} onto @var{alist} and
969 return the result. This is equivalent to
970
971 @lisp
972 (cons (cons @var{key} @var{datum}) @var{alist})
973 @end lisp
974
975 @code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
976 core does the same thing.
977 @end deffn
978
979 @deffn {Scheme Procedure} alist-copy alist
980 Return a newly allocated copy of @var{alist}, that means that the
981 spine of the list as well as the pairs are copied.
982 @end deffn
983
984 @deffn {Scheme Procedure} alist-delete key alist [=]
985 @deffnx {Scheme Procedure} alist-delete! key alist [=]
986 Return a list containing the elements of @var{alist} but with those
987 elements whose keys are equal to @var{key} deleted. The returned
988 elements will be in the same order as they were in @var{alist}.
989
990 Equality is determined by the @var{=} predicate, or @code{equal?} if
991 not given. The order in which elements are tested is unspecified, but
992 each equality call is made @code{(= key alistkey)}, ie. the given
993 @var{key} parameter is first and the key from @var{alist} second.
994 This means for instance all associations with a key greater than 5 can
995 be removed with @code{(alist-delete 5 alist <)}.
996
997 @code{alist-delete} does not modify @var{alist}, but the return might
998 share a common tail with @var{alist}. @code{alist-delete!} may modify
999 the list structure of @var{alist} to construct its return.
1000 @end deffn
1001
1002
1003 @node SRFI-1 Set Operations
1004 @subsubsection Set Operations on Lists
1005 @cindex list set operation
1006
1007 Lists can be used to represent sets of objects. The procedures in
1008 this section operate on such lists as sets.
1009
1010 Note that lists are not an efficient way to implement large sets. The
1011 procedures here typically take time @math{@var{m}@cross{}@var{n}} when
1012 operating on @var{m} and @var{n} element lists. Other data structures
1013 like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
1014 Tables}) are faster.
1015
1016 All these procedures take an equality predicate as the first argument.
1017 This predicate is used for testing the objects in the list sets for
1018 sameness. This predicate must be consistent with @code{eq?}
1019 (@pxref{Equality}) in the sense that if two list elements are
1020 @code{eq?} then they must also be equal under the predicate. This
1021 simply means a given object must be equal to itself.
1022
1023 @deffn {Scheme Procedure} lset<= = list1 list2 @dots{}
1024 Return @code{#t} if each list is a subset of the one following it.
1025 Ie.@: @var{list1} a subset of @var{list2}, @var{list2} a subset of
1026 @var{list3}, etc, for as many lists as given. If only one list or no
1027 lists are given then the return is @code{#t}.
1028
1029 A list @var{x} is a subset of @var{y} if each element of @var{x} is
1030 equal to some element in @var{y}. Elements are compared using the
1031 given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
1032
1033 @example
1034 (lset<= eq?) @result{} #t
1035 (lset<= eqv? '(1 2 3) '(1)) @result{} #f
1036 (lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
1037 @end example
1038 @end deffn
1039
1040 @deffn {Scheme Procedure} lset= = list1 list2 @dots{}
1041 Return @code{#t} if all argument lists are set-equal. @var{list1} is
1042 compared to @var{list2}, @var{list2} to @var{list3}, etc, for as many
1043 lists as given. If only one list or no lists are given then the
1044 return is @code{#t}.
1045
1046 Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
1047 is equal to some element of @var{y} and conversely each element of
1048 @var{y} is equal to some element of @var{x}. The order of the
1049 elements in the lists doesn't matter. Element equality is determined
1050 with the given @var{=} procedure, called as @code{(@var{=} xelem
1051 yelem)}, but exactly which calls are made is unspecified.
1052
1053 @example
1054 (lset= eq?) @result{} #t
1055 (lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
1056 (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
1057 @end example
1058 @end deffn
1059
1060 @deffn {Scheme Procedure} lset-adjoin = list elem1 @dots{}
1061 Add to @var{list} any of the given @var{elem}s not already in the
1062 list. @var{elem}s are @code{cons}ed onto the start of @var{list} (so
1063 the return shares a common tail with @var{list}), but the order
1064 they're added is unspecified.
1065
1066 The given @var{=} procedure is used for comparing elements, called as
1067 @code{(@var{=} listelem elem)}, ie.@: the second argument is one of
1068 the given @var{elem} parameters.
1069
1070 @example
1071 (lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
1072 @end example
1073 @end deffn
1074
1075 @deffn {Scheme Procedure} lset-union = list1 list2 @dots{}
1076 @deffnx {Scheme Procedure} lset-union! = list1 list2 @dots{}
1077 Return the union of the argument list sets. The result is built by
1078 taking the union of @var{list1} and @var{list2}, then the union of
1079 that with @var{list3}, etc, for as many lists as given. For one list
1080 argument that list itself is the result, for no list arguments the
1081 result is the empty list.
1082
1083 The union of two lists @var{x} and @var{y} is formed as follows. If
1084 @var{x} is empty then the result is @var{y}. Otherwise start with
1085 @var{x} as the result and consider each @var{y} element (from first to
1086 last). A @var{y} element not equal to something already in the result
1087 is @code{cons}ed onto the result.
1088
1089 The given @var{=} procedure is used for comparing elements, called as
1090 @code{(@var{=} relem yelem)}. The first argument is from the result
1091 accumulated so far, and the second is from the list being union-ed in.
1092 But exactly which calls are made is otherwise unspecified.
1093
1094 Notice that duplicate elements in @var{list1} (or the first non-empty
1095 list) are preserved, but that repeated elements in subsequent lists
1096 are only added once.
1097
1098 @example
1099 (lset-union eqv?) @result{} ()
1100 (lset-union eqv? '(1 2 3)) @result{} (1 2 3)
1101 (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
1102 @end example
1103
1104 @code{lset-union} doesn't change the given lists but the result may
1105 share a tail with the first non-empty list. @code{lset-union!} can
1106 modify all of the given lists to form the result.
1107 @end deffn
1108
1109 @deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
1110 @deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
1111 Return the intersection of @var{list1} with the other argument lists,
1112 meaning those elements of @var{list1} which are also in all of
1113 @var{list2} etc. For one list argument, just that list is returned.
1114
1115 The test for an element of @var{list1} to be in the return is simply
1116 that it's equal to some element in each of @var{list2} etc. Notice
1117 this means an element appearing twice in @var{list1} but only once in
1118 each of @var{list2} etc will go into the return twice. The return has
1119 its elements in the same order as they were in @var{list1}.
1120
1121 The given @var{=} procedure is used for comparing elements, called as
1122 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1123 and the second is from one of the subsequent lists. But exactly which
1124 calls are made and in what order is unspecified.
1125
1126 @example
1127 (lset-intersection eqv? '(x y)) @result{} (x y)
1128 (lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
1129 (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
1130 @end example
1131
1132 The return from @code{lset-intersection} may share a tail with
1133 @var{list1}. @code{lset-intersection!} may modify @var{list1} to form
1134 its result.
1135 @end deffn
1136
1137 @deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
1138 @deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
1139 Return @var{list1} with any elements in @var{list2}, @var{list3} etc
1140 removed (ie.@: subtracted). For one list argument, just that list is
1141 returned.
1142
1143 The given @var{=} procedure is used for comparing elements, called as
1144 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1145 and the second from one of the subsequent lists. But exactly which
1146 calls are made and in what order is unspecified.
1147
1148 @example
1149 (lset-difference eqv? '(x y)) @result{} (x y)
1150 (lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
1151 (lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
1152 @end example
1153
1154 The return from @code{lset-difference} may share a tail with
1155 @var{list1}. @code{lset-difference!} may modify @var{list1} to form
1156 its result.
1157 @end deffn
1158
1159 @deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
1160 @deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
1161 Return two values (@pxref{Multiple Values}), the difference and
1162 intersection of the argument lists as per @code{lset-difference} and
1163 @code{lset-intersection} above.
1164
1165 For two list arguments this partitions @var{list1} into those elements
1166 of @var{list1} which are in @var{list2} and not in @var{list2}. (But
1167 for more than two arguments there can be elements of @var{list1} which
1168 are neither part of the difference nor the intersection.)
1169
1170 One of the return values from @code{lset-diff+intersection} may share
1171 a tail with @var{list1}. @code{lset-diff+intersection!} may modify
1172 @var{list1} to form its results.
1173 @end deffn
1174
1175 @deffn {Scheme Procedure} lset-xor = list1 list2 @dots{}
1176 @deffnx {Scheme Procedure} lset-xor! = list1 list2 @dots{}
1177 Return an XOR of the argument lists. For two lists this means those
1178 elements which are in exactly one of the lists. For more than two
1179 lists it means those elements which appear in an odd number of the
1180 lists.
1181
1182 To be precise, the XOR of two lists @var{x} and @var{y} is formed by
1183 taking those elements of @var{x} not equal to any element of @var{y},
1184 plus those elements of @var{y} not equal to any element of @var{x}.
1185 Equality is determined with the given @var{=} procedure, called as
1186 @code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
1187 from @var{y}, but which way around is unspecified. Exactly which
1188 calls are made is also unspecified, as is the order of the elements in
1189 the result.
1190
1191 @example
1192 (lset-xor eqv? '(x y)) @result{} (x y)
1193 (lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
1194 @end example
1195
1196 The return from @code{lset-xor} may share a tail with one of the list
1197 arguments. @code{lset-xor!} may modify @var{list1} to form its
1198 result.
1199 @end deffn
1200
1201
1202 @node SRFI-2
1203 @subsection SRFI-2 - and-let*
1204 @cindex SRFI-2
1205
1206 @noindent
1207 The following syntax can be obtained with
1208
1209 @lisp
1210 (use-modules (srfi srfi-2))
1211 @end lisp
1212
1213 @deffn {library syntax} and-let* (clause @dots{}) body @dots{}
1214 A combination of @code{and} and @code{let*}.
1215
1216 Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
1217 then evaluation stops and @code{#f} is returned. If all are
1218 non-@code{#f} then @var{body} is evaluated and the last form gives the
1219 return value, or if @var{body} is empty then the result is @code{#t}.
1220 Each @var{clause} should be one of the following,
1221
1222 @table @code
1223 @item (symbol expr)
1224 Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
1225 Like @code{let*}, that binding is available to subsequent clauses.
1226 @item (expr)
1227 Evaluate @var{expr} and check for @code{#f}.
1228 @item symbol
1229 Get the value bound to @var{symbol} and check for @code{#f}.
1230 @end table
1231
1232 Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
1233 instance @code{((eq? x y))}. One way to remember this is to imagine
1234 the @code{symbol} in @code{(symbol expr)} is omitted.
1235
1236 @code{and-let*} is good for calculations where a @code{#f} value means
1237 termination, but where a non-@code{#f} value is going to be needed in
1238 subsequent expressions.
1239
1240 The following illustrates this, it returns text between brackets
1241 @samp{[...]} in a string, or @code{#f} if there are no such brackets
1242 (ie.@: either @code{string-index} gives @code{#f}).
1243
1244 @example
1245 (define (extract-brackets str)
1246 (and-let* ((start (string-index str #\[))
1247 (end (string-index str #\] start)))
1248 (substring str (1+ start) end)))
1249 @end example
1250
1251 The following shows plain variables and expressions tested too.
1252 @code{diagnostic-levels} is taken to be an alist associating a
1253 diagnostic type with a level. @code{str} is printed only if the type
1254 is known and its level is high enough.
1255
1256 @example
1257 (define (show-diagnostic type str)
1258 (and-let* (want-diagnostics
1259 (level (assq-ref diagnostic-levels type))
1260 ((>= level current-diagnostic-level)))
1261 (display str)))
1262 @end example
1263
1264 The advantage of @code{and-let*} is that an extended sequence of
1265 expressions and tests doesn't require lots of nesting as would arise
1266 from separate @code{and} and @code{let*}, or from @code{cond} with
1267 @code{=>}.
1268
1269 @end deffn
1270
1271
1272 @node SRFI-4
1273 @subsection SRFI-4 - Homogeneous numeric vector datatypes
1274 @cindex SRFI-4
1275
1276 The SRFI-4 procedures and data types are always available, @xref{Uniform
1277 Numeric Vectors}.
1278
1279 @node SRFI-6
1280 @subsection SRFI-6 - Basic String Ports
1281 @cindex SRFI-6
1282
1283 SRFI-6 defines the procedures @code{open-input-string},
1284 @code{open-output-string} and @code{get-output-string}. These
1285 procedures are included in the Guile core, so using this module does not
1286 make any difference at the moment. But it is possible that support for
1287 SRFI-6 will be factored out of the core library in the future, so using
1288 this module does not hurt, after all.
1289
1290 @node SRFI-8
1291 @subsection SRFI-8 - receive
1292 @cindex SRFI-8
1293
1294 @code{receive} is a syntax for making the handling of multiple-value
1295 procedures easier. It is documented in @xref{Multiple Values}.
1296
1297
1298 @node SRFI-9
1299 @subsection SRFI-9 - define-record-type
1300 @cindex SRFI-9
1301 @cindex record
1302
1303 This SRFI is a syntax for defining new record types and creating
1304 predicate, constructor, and field getter and setter functions. In
1305 Guile this is simply an alternate interface to the core record
1306 functionality (@pxref{Records}). It can be used with,
1307
1308 @example
1309 (use-modules (srfi srfi-9))
1310 @end example
1311
1312 @deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
1313 @sp 1
1314 Create a new record type, and make various @code{define}s for using
1315 it. This syntax can only occur at the top-level, not nested within
1316 some other form.
1317
1318 @var{type} is bound to the record type, which is as per the return
1319 from the core @code{make-record-type}. @var{type} also provides the
1320 name for the record, as per @code{record-type-name}.
1321
1322 @var{constructor} is bound to a function to be called as
1323 @code{(@var{constructor} fieldval @dots{})} to create a new record of
1324 this type. The arguments are initial values for the fields, one
1325 argument for each field, in the order they appear in the
1326 @code{define-record-type} form.
1327
1328 The @var{fieldname}s provide the names for the record fields, as per
1329 the core @code{record-type-fields} etc, and are referred to in the
1330 subsequent accessor/modifier forms.
1331
1332 @var{predictate} is bound to a function to be called as
1333 @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
1334 according to whether @var{obj} is a record of this type.
1335
1336 Each @var{accessor} is bound to a function to be called
1337 @code{(@var{accessor} record)} to retrieve the respective field from a
1338 @var{record}. Similarly each @var{modifier} is bound to a function to
1339 be called @code{(@var{modifier} record val)} to set the respective
1340 field in a @var{record}.
1341 @end deffn
1342
1343 @noindent
1344 An example will illustrate typical usage,
1345
1346 @example
1347 (define-record-type employee-type
1348 (make-employee name age salary)
1349 employee?
1350 (name get-employee-name)
1351 (age get-employee-age set-employee-age)
1352 (salary get-employee-salary set-employee-salary))
1353 @end example
1354
1355 This creates a new employee data type, with name, age and salary
1356 fields. Accessor functions are created for each field, but no
1357 modifier function for the name (the intention in this example being
1358 that it's established only when an employee object is created). These
1359 can all then be used as for example,
1360
1361 @example
1362 employee-type @result{} #<record-type employee-type>
1363
1364 (define fred (make-employee "Fred" 45 20000.00))
1365
1366 (employee? fred) @result{} #t
1367 (get-employee-age fred) @result{} 45
1368 (set-employee-salary fred 25000.00) ;; pay rise
1369 @end example
1370
1371 The functions created by @code{define-record-type} are ordinary
1372 top-level @code{define}s. They can be redefined or @code{set!} as
1373 desired, exported from a module, etc.
1374
1375
1376 @node SRFI-10
1377 @subsection SRFI-10 - Hash-Comma Reader Extension
1378 @cindex SRFI-10
1379
1380 @cindex hash-comma
1381 @cindex #,()
1382 This SRFI implements a reader extension @code{#,()} called hash-comma.
1383 It allows the reader to give new kinds of objects, for use both in
1384 data and as constants or literals in source code. This feature is
1385 available with
1386
1387 @example
1388 (use-modules (srfi srfi-10))
1389 @end example
1390
1391 @noindent
1392 The new read syntax is of the form
1393
1394 @example
1395 #,(@var{tag} @var{arg}@dots{})
1396 @end example
1397
1398 @noindent
1399 where @var{tag} is a symbol and the @var{arg}s are objects taken as
1400 parameters. @var{tag}s are registered with the following procedure.
1401
1402 @deffn {Scheme Procedure} define-reader-ctor tag proc
1403 Register @var{proc} as the constructor for a hash-comma read syntax
1404 starting with symbol @var{tag}, ie. @nicode{#,(@var{tag} arg@dots{})}.
1405 @var{proc} is called with the given arguments @code{(@var{proc}
1406 arg@dots{})} and the object it returns is the result of the read.
1407 @end deffn
1408
1409 @noindent
1410 For example, a syntax giving a list of @var{N} copies of an object.
1411
1412 @example
1413 (define-reader-ctor 'repeat
1414 (lambda (obj reps)
1415 (make-list reps obj)))
1416
1417 (display '#,(repeat 99 3))
1418 @print{} (99 99 99)
1419 @end example
1420
1421 Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
1422 @code{repeat} handler returns a list and the program must quote to use
1423 it literally, the same as any other list. Ie.
1424
1425 @example
1426 (display '#,(repeat 99 3))
1427 @result{}
1428 (display '(99 99 99))
1429 @end example
1430
1431 When a handler returns an object which is self-evaluating, like a
1432 number or a string, then there's no need for quoting, just as there's
1433 no need when giving those directly as literals. For example an
1434 addition,
1435
1436 @example
1437 (define-reader-ctor 'sum
1438 (lambda (x y)
1439 (+ x y)))
1440 (display #,(sum 123 456)) @print{} 579
1441 @end example
1442
1443 A typical use for @nicode{#,()} is to get a read syntax for objects
1444 which don't otherwise have one. For example, the following allows a
1445 hash table to be given literally, with tags and values, ready for fast
1446 lookup.
1447
1448 @example
1449 (define-reader-ctor 'hash
1450 (lambda elems
1451 (let ((table (make-hash-table)))
1452 (for-each (lambda (elem)
1453 (apply hash-set! table elem))
1454 elems)
1455 table)))
1456
1457 (define (animal->family animal)
1458 (hash-ref '#,(hash ("tiger" "cat")
1459 ("lion" "cat")
1460 ("wolf" "dog"))
1461 animal))
1462
1463 (animal->family "lion") @result{} "cat"
1464 @end example
1465
1466 Or for example the following is a syntax for a compiled regular
1467 expression (@pxref{Regular Expressions}).
1468
1469 @example
1470 (use-modules (ice-9 regex))
1471
1472 (define-reader-ctor 'regexp make-regexp)
1473
1474 (define (extract-angs str)
1475 (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
1476 (and match
1477 (match:substring match 1))))
1478
1479 (extract-angs "foo <BAR> quux") @result{} "BAR"
1480 @end example
1481
1482 @sp 1
1483 @nicode{#,()} is somewhat similar to @code{define-macro}
1484 (@pxref{Macros}) in that handler code is run to produce a result, but
1485 @nicode{#,()} operates at the read stage, so it can appear in data for
1486 @code{read} (@pxref{Scheme Read}), not just in code to be executed.
1487
1488 Because @nicode{#,()} is handled at read-time it has no direct access
1489 to variables etc. A symbol in the arguments is just a symbol, not a
1490 variable reference. The arguments are essentially constants, though
1491 the handler procedure can use them in any complicated way it might
1492 want.
1493
1494 Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
1495 globally, there's no need to use @code{(srfi srfi-10)} in later
1496 modules. Similarly the tags registered are global and can be used
1497 anywhere once registered.
1498
1499 There's no attempt to record what previous @nicode{#,()} forms have
1500 been seen, if two identical forms occur then two calls are made to the
1501 handler procedure. The handler might like to maintain a cache or
1502 similar to avoid making copies of large objects, depending on expected
1503 usage.
1504
1505 In code the best uses of @nicode{#,()} are generally when there's a
1506 lot of objects of a particular kind as literals or constants. If
1507 there's just a few then some local variables and initializers are
1508 fine, but that becomes tedious and error prone when there's a lot, and
1509 the anonymous and compact syntax of @nicode{#,()} is much better.
1510
1511
1512 @node SRFI-11
1513 @subsection SRFI-11 - let-values
1514 @cindex SRFI-11
1515
1516 @findex let-values
1517 @findex let*-values
1518 This module implements the binding forms for multiple values
1519 @code{let-values} and @code{let*-values}. These forms are similar to
1520 @code{let} and @code{let*} (@pxref{Local Bindings}), but they support
1521 binding of the values returned by multiple-valued expressions.
1522
1523 Write @code{(use-modules (srfi srfi-11))} to make the bindings
1524 available.
1525
1526 @lisp
1527 (let-values (((x y) (values 1 2))
1528 ((z f) (values 3 4)))
1529 (+ x y z f))
1530 @result{}
1531 10
1532 @end lisp
1533
1534 @code{let-values} performs all bindings simultaneously, which means that
1535 no expression in the binding clauses may refer to variables bound in the
1536 same clause list. @code{let*-values}, on the other hand, performs the
1537 bindings sequentially, just like @code{let*} does for single-valued
1538 expressions.
1539
1540
1541 @node SRFI-13
1542 @subsection SRFI-13 - String Library
1543 @cindex SRFI-13
1544
1545 The SRFI-13 procedures are always available, @xref{Strings}.
1546
1547 @node SRFI-14
1548 @subsection SRFI-14 - Character-set Library
1549 @cindex SRFI-14
1550
1551 The SRFI-14 data type and procedures are always available,
1552 @xref{Character Sets}.
1553
1554 @node SRFI-16
1555 @subsection SRFI-16 - case-lambda
1556 @cindex SRFI-16
1557 @cindex variable arity
1558 @cindex arity, variable
1559
1560 @c FIXME::martin: Review me!
1561
1562 @findex case-lambda
1563 The syntactic form @code{case-lambda} creates procedures, just like
1564 @code{lambda}, but has syntactic extensions for writing procedures of
1565 varying arity easier.
1566
1567 The syntax of the @code{case-lambda} form is defined in the following
1568 EBNF grammar.
1569
1570 @example
1571 @group
1572 <case-lambda>
1573 --> (case-lambda <case-lambda-clause>)
1574 <case-lambda-clause>
1575 --> (<formals> <definition-or-command>*)
1576 <formals>
1577 --> (<identifier>*)
1578 | (<identifier>* . <identifier>)
1579 | <identifier>
1580 @end group
1581 @end example
1582
1583 The value returned by a @code{case-lambda} form is a procedure which
1584 matches the number of actual arguments against the formals in the
1585 various clauses, in order. @dfn{Formals} means a formal argument list
1586 just like with @code{lambda} (@pxref{Lambda}). The first matching clause
1587 is selected, the corresponding values from the actual parameter list are
1588 bound to the variable names in the clauses and the body of the clause is
1589 evaluated. If no clause matches, an error is signalled.
1590
1591 The following (silly) definition creates a procedure @var{foo} which
1592 acts differently, depending on the number of actual arguments. If one
1593 argument is given, the constant @code{#t} is returned, two arguments are
1594 added and if more arguments are passed, their product is calculated.
1595
1596 @lisp
1597 (define foo (case-lambda
1598 ((x) #t)
1599 ((x y) (+ x y))
1600 (z
1601 (apply * z))))
1602 (foo 'bar)
1603 @result{}
1604 #t
1605 (foo 2 4)
1606 @result{}
1607 6
1608 (foo 3 3 3)
1609 @result{}
1610 27
1611 (foo)
1612 @result{}
1613 1
1614 @end lisp
1615
1616 The last expression evaluates to 1 because the last clause is matched,
1617 @var{z} is bound to the empty list and the following multiplication,
1618 applied to zero arguments, yields 1.
1619
1620
1621 @node SRFI-17
1622 @subsection SRFI-17 - Generalized set!
1623 @cindex SRFI-17
1624
1625 This SRFI implements a generalized @code{set!}, allowing some
1626 ``referencing'' functions to be used as the target location of a
1627 @code{set!}. This feature is available from
1628
1629 @example
1630 (use-modules (srfi srfi-17))
1631 @end example
1632
1633 @noindent
1634 For example @code{vector-ref} is extended so that
1635
1636 @example
1637 (set! (vector-ref vec idx) new-value)
1638 @end example
1639
1640 @noindent
1641 is equivalent to
1642
1643 @example
1644 (vector-set! vec idx new-value)
1645 @end example
1646
1647 The idea is that a @code{vector-ref} expression identifies a location,
1648 which may be either fetched or stored. The same form is used for the
1649 location in both cases, encouraging visual clarity. This is similar
1650 to the idea of an ``lvalue'' in C.
1651
1652 The mechanism for this kind of @code{set!} is in the Guile core
1653 (@pxref{Procedures with Setters}). This module adds definitions of
1654 the following functions as procedures with setters, allowing them to
1655 be targets of a @code{set!},
1656
1657 @quotation
1658 @nicode{car}, @nicode{cdr}, @nicode{caar}, @nicode{cadr},
1659 @nicode{cdar}, @nicode{cddr}, @nicode{caaar}, @nicode{caadr},
1660 @nicode{cadar}, @nicode{caddr}, @nicode{cdaar}, @nicode{cdadr},
1661 @nicode{cddar}, @nicode{cdddr}, @nicode{caaaar}, @nicode{caaadr},
1662 @nicode{caadar}, @nicode{caaddr}, @nicode{cadaar}, @nicode{cadadr},
1663 @nicode{caddar}, @nicode{cadddr}, @nicode{cdaaar}, @nicode{cdaadr},
1664 @nicode{cdadar}, @nicode{cdaddr}, @nicode{cddaar}, @nicode{cddadr},
1665 @nicode{cdddar}, @nicode{cddddr}
1666
1667 @nicode{string-ref}, @nicode{vector-ref}
1668 @end quotation
1669
1670 The SRFI specifies @code{setter} (@pxref{Procedures with Setters}) as
1671 a procedure with setter, allowing the setter for a procedure to be
1672 changed, eg.@: @code{(set! (setter foo) my-new-setter-handler)}.
1673 Currently Guile does not implement this, a setter can only be
1674 specified on creation (@code{getter-with-setter} below).
1675
1676 @defun getter-with-setter
1677 The same as the Guile core @code{make-procedure-with-setter}
1678 (@pxref{Procedures with Setters}).
1679 @end defun
1680
1681
1682 @node SRFI-18
1683 @subsection SRFI-18 - Multithreading support
1684 @cindex SRFI-18
1685
1686 This is an implementation of the SRFI-18 threading and synchronization
1687 library. The functions and variables described here are provided by
1688
1689 @example
1690 (use-modules (srfi srfi-18))
1691 @end example
1692
1693 As a general rule, the data types and functions in this SRFI-18
1694 implementation are compatible with the types and functions in Guile's
1695 core threading code. For example, mutexes created with the SRFI-18
1696 @code{make-mutex} function can be passed to the built-in Guile
1697 function @code{lock-mutex} (@pxref{Mutexes and Condition Variables}),
1698 and mutexes created with the built-in Guile function @code{make-mutex}
1699 can be passed to the SRFI-18 function @code{mutex-lock!}. Cases in
1700 which this does not hold true are noted in the following sections.
1701
1702 @menu
1703 * SRFI-18 Threads:: Executing code
1704 * SRFI-18 Mutexes:: Mutual exclusion devices
1705 * SRFI-18 Condition variables:: Synchronizing of groups of threads
1706 * SRFI-18 Time:: Representation of times and durations
1707 * SRFI-18 Exceptions:: Signalling and handling errors
1708 @end menu
1709
1710 @node SRFI-18 Threads
1711 @subsubsection SRFI-18 Threads
1712
1713 Threads created by SRFI-18 differ in two ways from threads created by
1714 Guile's built-in thread functions. First, a thread created by SRFI-18
1715 @code{make-thread} begins in a blocked state and will not start
1716 execution until @code{thread-start!} is called on it. Second, SRFI-18
1717 threads are constructed with a top-level exception handler that
1718 captures any exceptions that are thrown on thread exit. In all other
1719 regards, SRFI-18 threads are identical to normal Guile threads.
1720
1721 @defun current-thread
1722 Returns the thread that called this function. This is the same
1723 procedure as the same-named built-in procedure @code{current-thread}
1724 (@pxref{Threads}).
1725 @end defun
1726
1727 @defun thread? obj
1728 Returns @code{#t} if @var{obj} is a thread, @code{#f} otherwise. This
1729 is the same procedure as the same-named built-in procedure
1730 @code{thread?} (@pxref{Threads}).
1731 @end defun
1732
1733 @defun make-thread thunk [name]
1734 Call @code{thunk} in a new thread and with a new dynamic state,
1735 returning the new thread and optionally assigning it the object name
1736 @var{name}, which may be any Scheme object.
1737
1738 Note that the name @code{make-thread} conflicts with the
1739 @code{(ice-9 threads)} function @code{make-thread}. Applications
1740 wanting to use both of these functions will need to refer to them by
1741 different names.
1742 @end defun
1743
1744 @defun thread-name thread
1745 Returns the name assigned to @var{thread} at the time of its creation,
1746 or @code{#f} if it was not given a name.
1747 @end defun
1748
1749 @defun thread-specific thread
1750 @defunx thread-specific-set! thread obj
1751 Get or set the ``object-specific'' property of @var{thread}. In
1752 Guile's implementation of SRFI-18, this value is stored as an object
1753 property, and will be @code{#f} if not set.
1754 @end defun
1755
1756 @defun thread-start! thread
1757 Unblocks @var{thread} and allows it to begin execution if it has not
1758 done so already.
1759 @end defun
1760
1761 @defun thread-yield!
1762 If one or more threads are waiting to execute, calling
1763 @code{thread-yield!} forces an immediate context switch to one of them.
1764 Otherwise, @code{thread-yield!} has no effect. @code{thread-yield!}
1765 behaves identically to the Guile built-in function @code{yield}.
1766 @end defun
1767
1768 @defun thread-sleep! timeout
1769 The current thread waits until the point specified by the time object
1770 @var{timeout} is reached (@pxref{SRFI-18 Time}). This blocks the
1771 thread only if @var{timeout} represents a point in the future. it is
1772 an error for @var{timeout} to be @code{#f}.
1773 @end defun
1774
1775 @defun thread-terminate! thread
1776 Causes an abnormal termination of @var{thread}. If @var{thread} is
1777 not already terminated, all mutexes owned by @var{thread} become
1778 unlocked/abandoned. If @var{thread} is the current thread,
1779 @code{thread-terminate!} does not return. Otherwise
1780 @code{thread-terminate!} returns an unspecified value; the termination
1781 of @var{thread} will occur before @code{thread-terminate!} returns.
1782 Subsequent attempts to join on @var{thread} will cause a ``terminated
1783 thread exception'' to be raised.
1784
1785 @code{thread-terminate!} is compatible with the thread cancellation
1786 procedures in the core threads API (@pxref{Threads}) in that if a
1787 cleanup handler has been installed for the target thread, it will be
1788 called before the thread exits and its return value (or exception, if
1789 any) will be stored for later retrieval via a call to
1790 @code{thread-join!}.
1791 @end defun
1792
1793 @defun thread-join! thread [timeout [timeout-val]]
1794 Wait for @var{thread} to terminate and return its exit value. When a
1795 time value @var{timeout} is given, it specifies a point in time where
1796 the waiting should be aborted. When the waiting is aborted,
1797 @var{timeoutval} is returned if it is specified; otherwise, a
1798 @code{join-timeout-exception} exception is raised
1799 (@pxref{SRFI-18 Exceptions}). Exceptions may also be raised if the
1800 thread was terminated by a call to @code{thread-terminate!}
1801 (@code{terminated-thread-exception} will be raised) or if the thread
1802 exited by raising an exception that was handled by the top-level
1803 exception handler (@code{uncaught-exception} will be raised; the
1804 original exception can be retrieved using
1805 @code{uncaught-exception-reason}).
1806 @end defun
1807
1808
1809 @node SRFI-18 Mutexes
1810 @subsubsection SRFI-18 Mutexes
1811
1812 The behavior of Guile's built-in mutexes is parameterized via a set of
1813 flags passed to the @code{make-mutex} procedure in the core
1814 (@pxref{Mutexes and Condition Variables}). To satisfy the requirements
1815 for mutexes specified by SRFI-18, the @code{make-mutex} procedure
1816 described below sets the following flags:
1817 @itemize @bullet
1818 @item
1819 @code{recursive}: the mutex can be locked recursively
1820 @item
1821 @code{unchecked-unlock}: attempts to unlock a mutex that is already
1822 unlocked will not raise an exception
1823 @item
1824 @code{allow-external-unlock}: the mutex can be unlocked by any thread,
1825 not just the thread that locked it originally
1826 @end itemize
1827
1828 @defun make-mutex [name]
1829 Returns a new mutex, optionally assigning it the object name
1830 @var{name}, which may be any Scheme object. The returned mutex will be
1831 created with the configuration described above. Note that the name
1832 @code{make-mutex} conflicts with Guile core function @code{make-mutex}.
1833 Applications wanting to use both of these functions will need to refer
1834 to them by different names.
1835 @end defun
1836
1837 @defun mutex-name mutex
1838 Returns the name assigned to @var{mutex} at the time of its creation,
1839 or @code{#f} if it was not given a name.
1840 @end defun
1841
1842 @defun mutex-specific mutex
1843 @defunx mutex-specific-set! mutex obj
1844 Get or set the ``object-specific'' property of @var{mutex}. In Guile's
1845 implementation of SRFI-18, this value is stored as an object property,
1846 and will be @code{#f} if not set.
1847 @end defun
1848
1849 @defun mutex-state mutex
1850 Returns information about the state of @var{mutex}. Possible values
1851 are:
1852 @itemize @bullet
1853 @item
1854 thread @code{T}: the mutex is in the locked/owned state and thread T
1855 is the owner of the mutex
1856 @item
1857 symbol @code{not-owned}: the mutex is in the locked/not-owned state
1858 @item
1859 symbol @code{abandoned}: the mutex is in the unlocked/abandoned state
1860 @item
1861 symbol @code{not-abandoned}: the mutex is in the
1862 unlocked/not-abandoned state
1863 @end itemize
1864 @end defun
1865
1866 @defun mutex-lock! mutex [timeout [thread]]
1867 Lock @var{mutex}, optionally specifying a time object @var{timeout}
1868 after which to abort the lock attempt and a thread @var{thread} giving
1869 a new owner for @var{mutex} different than the current thread. This
1870 procedure has the same behavior as the @code{lock-mutex} procedure in
1871 the core library.
1872 @end defun
1873
1874 @defun mutex-unlock! mutex [condition-variable [timeout]]
1875 Unlock @var{mutex}, optionally specifying a condition variable
1876 @var{condition-variable} on which to wait, either indefinitely or,
1877 optionally, until the time object @var{timeout} has passed, to be
1878 signalled. This procedure has the same behavior as the
1879 @code{unlock-mutex} procedure in the core library.
1880 @end defun
1881
1882
1883 @node SRFI-18 Condition variables
1884 @subsubsection SRFI-18 Condition variables
1885
1886 SRFI-18 does not specify a ``wait'' function for condition variables.
1887 Waiting on a condition variable can be simulated using the SRFI-18
1888 @code{mutex-unlock!} function described in the previous section, or
1889 Guile's built-in @code{wait-condition-variable} procedure can be used.
1890
1891 @defun condition-variable? obj
1892 Returns @code{#t} if @var{obj} is a condition variable, @code{#f}
1893 otherwise. This is the same procedure as the same-named built-in
1894 procedure
1895 (@pxref{Mutexes and Condition Variables, @code{condition-variable?}}).
1896 @end defun
1897
1898 @defun make-condition-variable [name]
1899 Returns a new condition variable, optionally assigning it the object
1900 name @var{name}, which may be any Scheme object. This procedure
1901 replaces a procedure of the same name in the core library.
1902 @end defun
1903
1904 @defun condition-variable-name condition-variable
1905 Returns the name assigned to @var{thread} at the time of its creation,
1906 or @code{#f} if it was not given a name.
1907 @end defun
1908
1909 @defun condition-variable-specific condition-variable
1910 @defunx condition-variable-specific-set! condition-variable obj
1911 Get or set the ``object-specific'' property of
1912 @var{condition-variable}. In Guile's implementation of SRFI-18, this
1913 value is stored as an object property, and will be @code{#f} if not
1914 set.
1915 @end defun
1916
1917 @defun condition-variable-signal! condition-variable
1918 @defunx condition-variable-broadcast! condition-variable
1919 Wake up one thread that is waiting for @var{condition-variable}, in
1920 the case of @code{condition-variable-signal!}, or all threads waiting
1921 for it, in the case of @code{condition-variable-broadcast!}. The
1922 behavior of these procedures is equivalent to that of the procedures
1923 @code{signal-condition-variable} and
1924 @code{broadcast-condition-variable} in the core library.
1925 @end defun
1926
1927
1928 @node SRFI-18 Time
1929 @subsubsection SRFI-18 Time
1930
1931 The SRFI-18 time functions manipulate time in two formats: a
1932 ``time object'' type that represents an absolute point in time in some
1933 implementation-specific way; and the number of seconds since some
1934 unspecified ``epoch''. In Guile's implementation, the epoch is the
1935 Unix epoch, 00:00:00 UTC, January 1, 1970.
1936
1937 @defun current-time
1938 Return the current time as a time object. This procedure replaces
1939 the procedure of the same name in the core library, which returns the
1940 current time in seconds since the epoch.
1941 @end defun
1942
1943 @defun time? obj
1944 Returns @code{#t} if @var{obj} is a time object, @code{#f} otherwise.
1945 @end defun
1946
1947 @defun time->seconds time
1948 @defunx seconds->time seconds
1949 Convert between time objects and numerical values representing the
1950 number of seconds since the epoch. When converting from a time object
1951 to seconds, the return value is the number of seconds between
1952 @var{time} and the epoch. When converting from seconds to a time
1953 object, the return value is a time object that represents a time
1954 @var{seconds} seconds after the epoch.
1955 @end defun
1956
1957
1958 @node SRFI-18 Exceptions
1959 @subsubsection SRFI-18 Exceptions
1960
1961 SRFI-18 exceptions are identical to the exceptions provided by
1962 Guile's implementation of SRFI-34. The behavior of exception
1963 handlers invoked to handle exceptions thrown from SRFI-18 functions,
1964 however, differs from the conventional behavior of SRFI-34 in that
1965 the continuation of the handler is the same as that of the call to
1966 the function. Handlers are called in a tail-recursive manner; the
1967 exceptions do not ``bubble up''.
1968
1969 @defun current-exception-handler
1970 Returns the current exception handler.
1971 @end defun
1972
1973 @defun with-exception-handler handler thunk
1974 Installs @var{handler} as the current exception handler and calls the
1975 procedure @var{thunk} with no arguments, returning its value as the
1976 value of the exception. @var{handler} must be a procedure that accepts
1977 a single argument. The current exception handler at the time this
1978 procedure is called will be restored after the call returns.
1979 @end defun
1980
1981 @defun raise obj
1982 Raise @var{obj} as an exception. This is the same procedure as the
1983 same-named procedure defined in SRFI 34.
1984 @end defun
1985
1986 @defun join-timeout-exception? obj
1987 Returns @code{#t} if @var{obj} is an exception raised as the result of
1988 performing a timed join on a thread that does not exit within the
1989 specified timeout, @code{#f} otherwise.
1990 @end defun
1991
1992 @defun abandoned-mutex-exception? obj
1993 Returns @code{#t} if @var{obj} is an exception raised as the result of
1994 attempting to lock a mutex that has been abandoned by its owner thread,
1995 @code{#f} otherwise.
1996 @end defun
1997
1998 @defun terminated-thread-exception? obj
1999 Returns @code{#t} if @var{obj} is an exception raised as the result of
2000 joining on a thread that exited as the result of a call to
2001 @code{thread-terminate!}.
2002 @end defun
2003
2004 @defun uncaught-exception? obj
2005 @defunx uncaught-exception-reason exc
2006 @code{uncaught-exception?} returns @code{#t} if @var{obj} is an
2007 exception thrown as the result of joining a thread that exited by
2008 raising an exception that was handled by the top-level exception
2009 handler installed by @code{make-thread}. When this occurs, the
2010 original exception is preserved as part of the exception thrown by
2011 @code{thread-join!} and can be accessed by calling
2012 @code{uncaught-exception-reason} on that exception. Note that
2013 because this exception-preservation mechanism is a side-effect of
2014 @code{make-thread}, joining on threads that exited as described above
2015 but were created by other means will not raise this
2016 @code{uncaught-exception} error.
2017 @end defun
2018
2019
2020 @node SRFI-19
2021 @subsection SRFI-19 - Time/Date Library
2022 @cindex SRFI-19
2023 @cindex time
2024 @cindex date
2025
2026 This is an implementation of the SRFI-19 time/date library. The
2027 functions and variables described here are provided by
2028
2029 @example
2030 (use-modules (srfi srfi-19))
2031 @end example
2032
2033 @strong{Caution}: The current code in this module incorrectly extends
2034 the Gregorian calendar leap year rule back prior to the introduction
2035 of those reforms in 1582 (or the appropriate year in various
2036 countries). The Julian calendar was used prior to 1582, and there
2037 were 10 days skipped for the reform, but the code doesn't implement
2038 that.
2039
2040 This will be fixed some time. Until then calculations for 1583
2041 onwards are correct, but prior to that any day/month/year and day of
2042 the week calculations are wrong.
2043
2044 @menu
2045 * SRFI-19 Introduction::
2046 * SRFI-19 Time::
2047 * SRFI-19 Date::
2048 * SRFI-19 Time/Date conversions::
2049 * SRFI-19 Date to string::
2050 * SRFI-19 String to date::
2051 @end menu
2052
2053 @node SRFI-19 Introduction
2054 @subsubsection SRFI-19 Introduction
2055
2056 @cindex universal time
2057 @cindex atomic time
2058 @cindex UTC
2059 @cindex TAI
2060 This module implements time and date representations and calculations,
2061 in various time systems, including universal time (UTC) and atomic
2062 time (TAI).
2063
2064 For those not familiar with these time systems, TAI is based on a
2065 fixed length second derived from oscillations of certain atoms. UTC
2066 differs from TAI by an integral number of seconds, which is increased
2067 or decreased at announced times to keep UTC aligned to a mean solar
2068 day (the orbit and rotation of the earth are not quite constant).
2069
2070 @cindex leap second
2071 So far, only increases in the TAI
2072 @tex
2073 $\leftrightarrow$
2074 @end tex
2075 @ifnottex
2076 <->
2077 @end ifnottex
2078 UTC difference have been needed. Such an increase is a ``leap
2079 second'', an extra second of TAI introduced at the end of a UTC day.
2080 When working entirely within UTC this is never seen, every day simply
2081 has 86400 seconds. But when converting from TAI to a UTC date, an
2082 extra 23:59:60 is present, where normally a day would end at 23:59:59.
2083 Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
2084 seconds.
2085
2086 @cindex system clock
2087 In the current implementation, the system clock is assumed to be UTC,
2088 and a table of leap seconds in the code converts to TAI. See comments
2089 in @file{srfi-19.scm} for how to update this table.
2090
2091 @cindex julian day
2092 @cindex modified julian day
2093 Also, for those not familiar with the terminology, a @dfn{Julian Day}
2094 is a real number which is a count of days and fraction of a day, in
2095 UTC, starting from -4713-01-01T12:00:00Z, ie.@: midday Monday 1 Jan
2096 4713 B.C. A @dfn{Modified Julian Day} is the same, but starting from
2097 1858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. That time
2098 is julian day 2400000.5.
2099
2100 @c The SRFI-1 spec says -4714-11-24T12:00:00Z (November 24, -4714 at
2101 @c noon, UTC), but this is incorrect. It looks like it might have
2102 @c arisen from the code incorrectly treating years a multiple of 100
2103 @c but not 400 prior to 1582 as non-leap years, where instead the Julian
2104 @c calendar should be used so all multiples of 4 before 1582 are leap
2105 @c years.
2106
2107
2108 @node SRFI-19 Time
2109 @subsubsection SRFI-19 Time
2110 @cindex time
2111
2112 A @dfn{time} object has type, seconds and nanoseconds fields
2113 representing a point in time starting from some epoch. This is an
2114 arbitrary point in time, not just a time of day. Although times are
2115 represented in nanoseconds, the actual resolution may be lower.
2116
2117 The following variables hold the possible time types. For instance
2118 @code{(current-time time-process)} would give the current CPU process
2119 time.
2120
2121 @defvar time-utc
2122 Universal Coordinated Time (UTC).
2123 @cindex UTC
2124 @end defvar
2125
2126 @defvar time-tai
2127 International Atomic Time (TAI).
2128 @cindex TAI
2129 @end defvar
2130
2131 @defvar time-monotonic
2132 Monotonic time, meaning a monotonically increasing time starting from
2133 an unspecified epoch.
2134
2135 Note that in the current implementation @code{time-monotonic} is the
2136 same as @code{time-tai}, and unfortunately is therefore affected by
2137 adjustments to the system clock. Perhaps this will change in the
2138 future.
2139 @end defvar
2140
2141 @defvar time-duration
2142 A duration, meaning simply a difference between two times.
2143 @end defvar
2144
2145 @defvar time-process
2146 CPU time spent in the current process, starting from when the process
2147 began.
2148 @cindex process time
2149 @end defvar
2150
2151 @defvar time-thread
2152 CPU time spent in the current thread. Not currently implemented.
2153 @cindex thread time
2154 @end defvar
2155
2156 @sp 1
2157 @defun time? obj
2158 Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
2159 @end defun
2160
2161 @defun make-time type nanoseconds seconds
2162 Create a time object with the given @var{type}, @var{seconds} and
2163 @var{nanoseconds}.
2164 @end defun
2165
2166 @defun time-type time
2167 @defunx time-nanosecond time
2168 @defunx time-second time
2169 @defunx set-time-type! time type
2170 @defunx set-time-nanosecond! time nsec
2171 @defunx set-time-second! time sec
2172 Get or set the type, seconds or nanoseconds fields of a time object.
2173
2174 @code{set-time-type!} merely changes the field, it doesn't convert the
2175 time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
2176 @end defun
2177
2178 @defun copy-time time
2179 Return a new time object, which is a copy of the given @var{time}.
2180 @end defun
2181
2182 @defun current-time [type]
2183 Return the current time of the given @var{type}. The default
2184 @var{type} is @code{time-utc}.
2185
2186 Note that the name @code{current-time} conflicts with the Guile core
2187 @code{current-time} function (@pxref{Time}) as well as the SRFI-18
2188 @code{current-time} function (@pxref{SRFI-18 Time}). Applications
2189 wanting to use more than one of these functions will need to refer to
2190 them by different names.
2191 @end defun
2192
2193 @defun time-resolution [type]
2194 Return the resolution, in nanoseconds, of the given time @var{type}.
2195 The default @var{type} is @code{time-utc}.
2196 @end defun
2197
2198 @defun time<=? t1 t2
2199 @defunx time<? t1 t2
2200 @defunx time=? t1 t2
2201 @defunx time>=? t1 t2
2202 @defunx time>? t1 t2
2203 Return @code{#t} or @code{#f} according to the respective relation
2204 between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
2205 must be the same time type.
2206 @end defun
2207
2208 @defun time-difference t1 t2
2209 @defunx time-difference! t1 t2
2210 Return a time object of type @code{time-duration} representing the
2211 period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
2212 the same time type.
2213
2214 @code{time-difference} returns a new time object,
2215 @code{time-difference!} may modify @var{t1} to form its return.
2216 @end defun
2217
2218 @defun add-duration time duration
2219 @defunx add-duration! time duration
2220 @defunx subtract-duration time duration
2221 @defunx subtract-duration! time duration
2222 Return a time object which is @var{time} with the given @var{duration}
2223 added or subtracted. @var{duration} must be a time object of type
2224 @code{time-duration}.
2225
2226 @code{add-duration} and @code{subtract-duration} return a new time
2227 object. @code{add-duration!} and @code{subtract-duration!} may modify
2228 the given @var{time} to form their return.
2229 @end defun
2230
2231
2232 @node SRFI-19 Date
2233 @subsubsection SRFI-19 Date
2234 @cindex date
2235
2236 A @dfn{date} object represents a date in the Gregorian calendar and a
2237 time of day on that date in some timezone.
2238
2239 The fields are year, month, day, hour, minute, second, nanoseconds and
2240 timezone. A date object is immutable, its fields can be read but they
2241 cannot be modified once the object is created.
2242
2243 @defun date? obj
2244 Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
2245 @end defun
2246
2247 @defun make-date nsecs seconds minutes hours date month year zone-offset
2248 Create a new date object.
2249 @c
2250 @c FIXME: What can we say about the ranges of the values. The
2251 @c current code looks it doesn't normalize, but expects then in their
2252 @c usual range already.
2253 @c
2254 @end defun
2255
2256 @defun date-nanosecond date
2257 Nanoseconds, 0 to 999999999.
2258 @end defun
2259
2260 @defun date-second date
2261 Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
2262 entirely within UTC, it's only when converting to or from TAI.
2263 @end defun
2264
2265 @defun date-minute date
2266 Minutes, 0 to 59.
2267 @end defun
2268
2269 @defun date-hour date
2270 Hour, 0 to 23.
2271 @end defun
2272
2273 @defun date-day date
2274 Day of the month, 1 to 31 (or less, according to the month).
2275 @end defun
2276
2277 @defun date-month date
2278 Month, 1 to 12.
2279 @end defun
2280
2281 @defun date-year date
2282 Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
2283 B.C. There is no year 0, year @math{-1} is followed by year 1.
2284 @end defun
2285
2286 @defun date-zone-offset date
2287 Time zone, an integer number of seconds east of Greenwich.
2288 @end defun
2289
2290 @defun date-year-day date
2291 Day of the year, starting from 1 for 1st January.
2292 @end defun
2293
2294 @defun date-week-day date
2295 Day of the week, starting from 0 for Sunday.
2296 @end defun
2297
2298 @defun date-week-number date dstartw
2299 Week of the year, ignoring a first partial week. @var{dstartw} is the
2300 day of the week which is taken to start a week, 0 for Sunday, 1 for
2301 Monday, etc.
2302 @c
2303 @c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
2304 @c The code looks like it's 0, if that's the correct intention.
2305 @c
2306 @end defun
2307
2308 @c The SRFI text doesn't actually give the default for tz-offset, but
2309 @c the reference implementation has the local timezone and the
2310 @c conversions functions all specify that, so it should be ok to
2311 @c document it here.
2312 @c
2313 @defun current-date [tz-offset]
2314 Return a date object representing the current date/time, in UTC offset
2315 by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
2316 defaults to the local timezone.
2317 @end defun
2318
2319 @defun current-julian-day
2320 @cindex julian day
2321 Return the current Julian Day.
2322 @end defun
2323
2324 @defun current-modified-julian-day
2325 @cindex modified julian day
2326 Return the current Modified Julian Day.
2327 @end defun
2328
2329
2330 @node SRFI-19 Time/Date conversions
2331 @subsubsection SRFI-19 Time/Date conversions
2332 @cindex time conversion
2333 @cindex date conversion
2334
2335 @defun date->julian-day date
2336 @defunx date->modified-julian-day date
2337 @defunx date->time-monotonic date
2338 @defunx date->time-tai date
2339 @defunx date->time-utc date
2340 @end defun
2341 @defun julian-day->date jdn [tz-offset]
2342 @defunx julian-day->time-monotonic jdn
2343 @defunx julian-day->time-tai jdn
2344 @defunx julian-day->time-utc jdn
2345 @end defun
2346 @defun modified-julian-day->date jdn [tz-offset]
2347 @defunx modified-julian-day->time-monotonic jdn
2348 @defunx modified-julian-day->time-tai jdn
2349 @defunx modified-julian-day->time-utc jdn
2350 @end defun
2351 @defun time-monotonic->date time [tz-offset]
2352 @defunx time-monotonic->time-tai time
2353 @defunx time-monotonic->time-tai! time
2354 @defunx time-monotonic->time-utc time
2355 @defunx time-monotonic->time-utc! time
2356 @end defun
2357 @defun time-tai->date time [tz-offset]
2358 @defunx time-tai->julian-day time
2359 @defunx time-tai->modified-julian-day time
2360 @defunx time-tai->time-monotonic time
2361 @defunx time-tai->time-monotonic! time
2362 @defunx time-tai->time-utc time
2363 @defunx time-tai->time-utc! time
2364 @end defun
2365 @defun time-utc->date time [tz-offset]
2366 @defunx time-utc->julian-day time
2367 @defunx time-utc->modified-julian-day time
2368 @defunx time-utc->time-monotonic time
2369 @defunx time-utc->time-monotonic! time
2370 @defunx time-utc->time-tai time
2371 @defunx time-utc->time-tai! time
2372 @sp 1
2373 Convert between dates, times and days of the respective types. For
2374 instance @code{time-tai->time-utc} accepts a @var{time} object of type
2375 @code{time-tai} and returns an object of type @code{time-utc}.
2376
2377 The @code{!} variants may modify their @var{time} argument to form
2378 their return. The plain functions create a new object.
2379
2380 For conversions to dates, @var{tz-offset} is seconds east of
2381 Greenwich. The default is the local timezone, at the given time, as
2382 provided by the system, using @code{localtime} (@pxref{Time}).
2383
2384 On 32-bit systems, @code{localtime} is limited to a 32-bit
2385 @code{time_t}, so a default @var{tz-offset} is only available for
2386 times between Dec 1901 and Jan 2038. For prior dates an application
2387 might like to use the value in 1902, though some locations have zone
2388 changes prior to that. For future dates an application might like to
2389 assume today's rules extend indefinitely. But for correct daylight
2390 savings transitions it will be necessary to take an offset for the
2391 same day and time but a year in range and which has the same starting
2392 weekday and same leap/non-leap (to support rules like last Sunday in
2393 October).
2394 @end defun
2395
2396 @node SRFI-19 Date to string
2397 @subsubsection SRFI-19 Date to string
2398 @cindex date to string
2399 @cindex string, from date
2400
2401 @defun date->string date [format]
2402 Convert a date to a string under the control of a format.
2403 @var{format} should be a string containing @samp{~} escapes, which
2404 will be expanded as per the following conversion table. The default
2405 @var{format} is @samp{~c}, a locale-dependent date and time.
2406
2407 Many of these conversion characters are the same as POSIX
2408 @code{strftime} (@pxref{Time}), but there are some extras and some
2409 variations.
2410
2411 @multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
2412 @item @nicode{~~} @tab literal ~
2413 @item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
2414 @item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
2415 @item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
2416 @item @nicode{~B} @tab locale full month, eg.@: @samp{January}
2417 @item @nicode{~c} @tab locale date and time, eg.@: @*
2418 @samp{Fri Jul 14 20:28:42-0400 2000}
2419 @item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
2420
2421 @c Spec says d/m/y, reference implementation says m/d/y.
2422 @c Apparently the reference code was the intention, but would like to
2423 @c see an errata published for the spec before contradicting it here.
2424 @c
2425 @c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
2426
2427 @item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
2428 @item @nicode{~f} @tab seconds and fractional seconds,
2429 with locale decimal point, eg.@: @samp{5.2}
2430 @item @nicode{~h} @tab same as @nicode{~b}
2431 @item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
2432 @item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
2433 @item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
2434 @item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
2435 @item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
2436 @item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
2437 @item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
2438 @item @nicode{~n} @tab newline
2439 @item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
2440 @item @nicode{~p} @tab locale AM or PM
2441 @item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
2442 @item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
2443 @item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
2444 (usual limit is 59, 60 is a leap second)
2445 @item @nicode{~t} @tab horizontal tab character
2446 @item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
2447 @item @nicode{~U} @tab week of year, Sunday first day of week,
2448 @samp{00} to @samp{52}
2449 @item @nicode{~V} @tab week of year, Monday first day of week,
2450 @samp{01} to @samp{53}
2451 @item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
2452 @item @nicode{~W} @tab week of year, Monday first day of week,
2453 @samp{00} to @samp{52}
2454
2455 @c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
2456 @c date. The reference code has ~x as the locale date and ~X as a
2457 @c locale time. The rule is apparently that the code should be
2458 @c believed, but would like to see an errata for the spec before
2459 @c contradicting it here.
2460 @c
2461 @c @item @nicode{~x} @tab week of year, Monday as first day of week,
2462 @c @samp{00} to @samp{53}
2463 @c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
2464
2465 @item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
2466 @item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
2467 @item @nicode{~z} @tab time zone, RFC-822 style
2468 @item @nicode{~Z} @tab time zone symbol (not currently implemented)
2469 @item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
2470 @item @nicode{~2} @tab ISO-8601 time+zone, @samp{~k:~M:~S~z}
2471 @item @nicode{~3} @tab ISO-8601 time, @samp{~k:~M:~S}
2472 @item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~k:~M:~S~z}
2473 @item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~k:~M:~S}
2474 @end multitable
2475 @end defun
2476
2477 Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
2478 described here, since the specification and reference implementation
2479 differ.
2480
2481 Conversion is locale-dependent on systems that support it
2482 (@pxref{Accessing Locale Information}). @xref{Locales,
2483 @code{setlocale}}, for information on how to change the current
2484 locale.
2485
2486
2487 @node SRFI-19 String to date
2488 @subsubsection SRFI-19 String to date
2489 @cindex string to date
2490 @cindex date, from string
2491
2492 @c FIXME: Can we say what happens when an incomplete date is
2493 @c converted? Ie. fields left as 0, or what? The spec seems to be
2494 @c silent on this.
2495
2496 @defun string->date input template
2497 Convert an @var{input} string to a date under the control of a
2498 @var{template} string. Return a newly created date object.
2499
2500 Literal characters in @var{template} must match characters in
2501 @var{input} and @samp{~} escapes must match the input forms described
2502 in the table below. ``Skip to'' means characters up to one of the
2503 given type are ignored, or ``no skip'' for no skipping. ``Read'' is
2504 what's then read, and ``Set'' is the field affected in the date
2505 object.
2506
2507 For example @samp{~Y} skips input characters until a digit is reached,
2508 at which point it expects a year and stores that to the year field of
2509 the date.
2510
2511 @multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
2512 @item
2513 @tab Skip to
2514 @tab Read
2515 @tab Set
2516
2517 @item @nicode{~~}
2518 @tab no skip
2519 @tab literal ~
2520 @tab nothing
2521
2522 @item @nicode{~a}
2523 @tab @nicode{char-alphabetic?}
2524 @tab locale abbreviated weekday name
2525 @tab nothing
2526
2527 @item @nicode{~A}
2528 @tab @nicode{char-alphabetic?}
2529 @tab locale full weekday name
2530 @tab nothing
2531
2532 @c Note that the SRFI spec says that ~b and ~B don't set anything,
2533 @c but that looks like a mistake. The reference implementation sets
2534 @c the month field, which seems sensible and is what we describe
2535 @c here.
2536
2537 @item @nicode{~b}
2538 @tab @nicode{char-alphabetic?}
2539 @tab locale abbreviated month name
2540 @tab @nicode{date-month}
2541
2542 @item @nicode{~B}
2543 @tab @nicode{char-alphabetic?}
2544 @tab locale full month name
2545 @tab @nicode{date-month}
2546
2547 @item @nicode{~d}
2548 @tab @nicode{char-numeric?}
2549 @tab day of month
2550 @tab @nicode{date-day}
2551
2552 @item @nicode{~e}
2553 @tab no skip
2554 @tab day of month, blank padded
2555 @tab @nicode{date-day}
2556
2557 @item @nicode{~h}
2558 @tab same as @samp{~b}
2559
2560 @item @nicode{~H}
2561 @tab @nicode{char-numeric?}
2562 @tab hour
2563 @tab @nicode{date-hour}
2564
2565 @item @nicode{~k}
2566 @tab no skip
2567 @tab hour, blank padded
2568 @tab @nicode{date-hour}
2569
2570 @item @nicode{~m}
2571 @tab @nicode{char-numeric?}
2572 @tab month
2573 @tab @nicode{date-month}
2574
2575 @item @nicode{~M}
2576 @tab @nicode{char-numeric?}
2577 @tab minute
2578 @tab @nicode{date-minute}
2579
2580 @item @nicode{~S}
2581 @tab @nicode{char-numeric?}
2582 @tab second
2583 @tab @nicode{date-second}
2584
2585 @item @nicode{~y}
2586 @tab no skip
2587 @tab 2-digit year
2588 @tab @nicode{date-year} within 50 years
2589
2590 @item @nicode{~Y}
2591 @tab @nicode{char-numeric?}
2592 @tab year
2593 @tab @nicode{date-year}
2594
2595 @item @nicode{~z}
2596 @tab no skip
2597 @tab time zone
2598 @tab date-zone-offset
2599 @end multitable
2600
2601 Notice that the weekday matching forms don't affect the date object
2602 returned, instead the weekday will be derived from the day, month and
2603 year.
2604
2605 Conversion is locale-dependent on systems that support it
2606 (@pxref{Accessing Locale Information}). @xref{Locales,
2607 @code{setlocale}}, for information on how to change the current
2608 locale.
2609 @end defun
2610
2611
2612 @node SRFI-26
2613 @subsection SRFI-26 - specializing parameters
2614 @cindex SRFI-26
2615 @cindex parameter specialize
2616 @cindex argument specialize
2617 @cindex specialize parameter
2618
2619 This SRFI provides a syntax for conveniently specializing selected
2620 parameters of a function. It can be used with,
2621
2622 @example
2623 (use-modules (srfi srfi-26))
2624 @end example
2625
2626 @deffn {library syntax} cut slot @dots{}
2627 @deffnx {library syntax} cute slot @dots{}
2628 Return a new procedure which will make a call (@var{slot} @dots{}) but
2629 with selected parameters specialized to given expressions.
2630
2631 An example will illustrate the idea. The following is a
2632 specialization of @code{write}, sending output to
2633 @code{my-output-port},
2634
2635 @example
2636 (cut write <> my-output-port)
2637 @result{}
2638 (lambda (obj) (write obj my-output-port))
2639 @end example
2640
2641 The special symbol @code{<>} indicates a slot to be filled by an
2642 argument to the new procedure. @code{my-output-port} on the other
2643 hand is an expression to be evaluated and passed, ie.@: it specializes
2644 the behaviour of @code{write}.
2645
2646 @table @nicode
2647 @item <>
2648 A slot to be filled by an argument from the created procedure.
2649 Arguments are assigned to @code{<>} slots in the order they appear in
2650 the @code{cut} form, there's no way to re-arrange arguments.
2651
2652 The first argument to @code{cut} is usually a procedure (or expression
2653 giving a procedure), but @code{<>} is allowed there too. For example,
2654
2655 @example
2656 (cut <> 1 2 3)
2657 @result{}
2658 (lambda (proc) (proc 1 2 3))
2659 @end example
2660
2661 @item <...>
2662 A slot to be filled by all remaining arguments from the new procedure.
2663 This can only occur at the end of a @code{cut} form.
2664
2665 For example, a procedure taking a variable number of arguments like
2666 @code{max} but in addition enforcing a lower bound,
2667
2668 @example
2669 (define my-lower-bound 123)
2670
2671 (cut max my-lower-bound <...>)
2672 @result{}
2673 (lambda arglist (apply max my-lower-bound arglist))
2674 @end example
2675 @end table
2676
2677 For @code{cut} the specializing expressions are evaluated each time
2678 the new procedure is called. For @code{cute} they're evaluated just
2679 once, when the new procedure is created. The name @code{cute} stands
2680 for ``@code{cut} with evaluated arguments''. In all cases the
2681 evaluations take place in an unspecified order.
2682
2683 The following illustrates the difference between @code{cut} and
2684 @code{cute},
2685
2686 @example
2687 (cut format <> "the time is ~s" (current-time))
2688 @result{}
2689 (lambda (port) (format port "the time is ~s" (current-time)))
2690
2691 (cute format <> "the time is ~s" (current-time))
2692 @result{}
2693 (let ((val (current-time)))
2694 (lambda (port) (format port "the time is ~s" val))
2695 @end example
2696
2697 (There's no provision for a mixture of @code{cut} and @code{cute}
2698 where some expressions would be evaluated every time but others
2699 evaluated only once.)
2700
2701 @code{cut} is really just a shorthand for the sort of @code{lambda}
2702 forms shown in the above examples. But notice @code{cut} avoids the
2703 need to name unspecialized parameters, and is more compact. Use in
2704 functional programming style or just with @code{map}, @code{for-each}
2705 or similar is typical.
2706
2707 @example
2708 (map (cut * 2 <>) '(1 2 3 4))
2709
2710 (for-each (cut write <> my-port) my-list)
2711 @end example
2712 @end deffn
2713
2714 @node SRFI-31
2715 @subsection SRFI-31 - A special form `rec' for recursive evaluation
2716 @cindex SRFI-31
2717 @cindex recursive expression
2718 @findex rec
2719
2720 SRFI-31 defines a special form that can be used to create
2721 self-referential expressions more conveniently. The syntax is as
2722 follows:
2723
2724 @example
2725 @group
2726 <rec expression> --> (rec <variable> <expression>)
2727 <rec expression> --> (rec (<variable>+) <body>)
2728 @end group
2729 @end example
2730
2731 The first syntax can be used to create self-referential expressions,
2732 for example:
2733
2734 @lisp
2735 guile> (define tmp (rec ones (cons 1 (delay ones))))
2736 @end lisp
2737
2738 The second syntax can be used to create anonymous recursive functions:
2739
2740 @lisp
2741 guile> (define tmp (rec (display-n item n)
2742 (if (positive? n)
2743 (begin (display n) (display-n (- n 1))))))
2744 guile> (tmp 42 3)
2745 424242
2746 guile>
2747 @end lisp
2748
2749
2750 @node SRFI-34
2751 @subsection SRFI-34 - Exception handling for programs
2752
2753 @cindex SRFI-34
2754 Guile provides an implementation of
2755 @uref{http://srfi.schemers.org/srfi-34/srfi-34.html, SRFI-34's exception
2756 handling mechanisms} as an alternative to its own built-in mechanisms
2757 (@pxref{Exceptions}). It can be made available as follows:
2758
2759 @lisp
2760 (use-modules (srfi srfi-34))
2761 @end lisp
2762
2763 @c FIXME: Document it.
2764
2765
2766 @node SRFI-35
2767 @subsection SRFI-35 - Conditions
2768
2769 @cindex SRFI-35
2770 @cindex conditions
2771 @cindex exceptions
2772
2773 @uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI-35} implements
2774 @dfn{conditions}, a data structure akin to records designed to convey
2775 information about exceptional conditions between parts of a program. It
2776 is normally used in conjunction with SRFI-34's @code{raise}:
2777
2778 @lisp
2779 (raise (condition (&message
2780 (message "An error occurred"))))
2781 @end lisp
2782
2783 Users can define @dfn{condition types} containing arbitrary information.
2784 Condition types may inherit from one another. This allows the part of
2785 the program that handles (or ``catches'') conditions to get accurate
2786 information about the exceptional condition that arose.
2787
2788 SRFI-35 conditions are made available using:
2789
2790 @lisp
2791 (use-modules (srfi srfi-35))
2792 @end lisp
2793
2794 The procedures available to manipulate condition types are the
2795 following:
2796
2797 @deffn {Scheme Procedure} make-condition-type id parent field-names
2798 Return a new condition type named @var{id}, inheriting from
2799 @var{parent}, and with the fields whose names are listed in
2800 @var{field-names}. @var{field-names} must be a list of symbols and must
2801 not contain names already used by @var{parent} or one of its supertypes.
2802 @end deffn
2803
2804 @deffn {Scheme Procedure} condition-type? obj
2805 Return true if @var{obj} is a condition type.
2806 @end deffn
2807
2808 Conditions can be created and accessed with the following procedures:
2809
2810 @deffn {Scheme Procedure} make-condition type . field+value
2811 Return a new condition of type @var{type} with fields initialized as
2812 specified by @var{field+value}, a sequence of field names (symbols) and
2813 values as in the following example:
2814
2815 @lisp
2816 (let ((&ct (make-condition-type 'foo &condition '(a b c))))
2817 (make-condition &ct 'a 1 'b 2 'c 3))
2818 @end lisp
2819
2820 Note that all fields of @var{type} and its supertypes must be specified.
2821 @end deffn
2822
2823 @deffn {Scheme Procedure} make-compound-condition . conditions
2824 Return a new compound condition composed of @var{conditions}. The
2825 returned condition has the type of each condition of @var{conditions}
2826 (per @code{condition-has-type?}).
2827 @end deffn
2828
2829 @deffn {Scheme Procedure} condition-has-type? c type
2830 Return true if condition @var{c} has type @var{type}.
2831 @end deffn
2832
2833 @deffn {Scheme Procedure} condition-ref c field-name
2834 Return the value of the field named @var{field-name} from condition @var{c}.
2835
2836 If @var{c} is a compound condition and several underlying condition
2837 types contain a field named @var{field-name}, then the value of the
2838 first such field is returned, using the order in which conditions were
2839 passed to @var{make-compound-condition}.
2840 @end deffn
2841
2842 @deffn {Scheme Procedure} extract-condition c type
2843 Return a condition of condition type @var{type} with the field values
2844 specified by @var{c}.
2845
2846 If @var{c} is a compound condition, extract the field values from the
2847 subcondition belonging to @var{type} that appeared first in the call to
2848 @code{make-compound-condition} that created the the condition.
2849 @end deffn
2850
2851 Convenience macros are also available to create condition types and
2852 conditions.
2853
2854 @deffn {library syntax} define-condition-type type supertype predicate field-spec...
2855 Define a new condition type named @var{type} that inherits from
2856 @var{supertype}. In addition, bind @var{predicate} to a type predicate
2857 that returns true when passed a condition of type @var{type} or any of
2858 its subtypes. @var{field-spec} must have the form @code{(field
2859 accessor)} where @var{field} is the name of field of @var{type} and
2860 @var{accessor} is the name of a procedure to access field @var{field} in
2861 conditions of type @var{type}.
2862
2863 The example below defines condition type @code{&foo}, inheriting from
2864 @code{&condition} with fields @code{a}, @code{b} and @code{c}:
2865
2866 @lisp
2867 (define-condition-type &foo &condition
2868 foo-condition?
2869 (a foo-a)
2870 (b foo-b)
2871 (c foo-c))
2872 @end lisp
2873 @end deffn
2874
2875 @deffn {library syntax} condition type-field-bindings...
2876 Return a new condition, or compound condition, initialized according to
2877 @var{type-field-bindings}. Each @var{type-field-binding} must have the
2878 form @code{(type field-specs...)}, where @var{type} is the name of a
2879 variable bound to condition type; each @var{field-spec} must have the
2880 form @code{(field-name value)} where @var{field-name} is a symbol
2881 denoting the field being initialized to @var{value}. As for
2882 @code{make-condition}, all fields must be specified.
2883
2884 The following example returns a simple condition:
2885
2886 @lisp
2887 (condition (&message (message "An error occurred")))
2888 @end lisp
2889
2890 The one below returns a compound condition:
2891
2892 @lisp
2893 (condition (&message (message "An error occurred"))
2894 (&serious))
2895 @end lisp
2896 @end deffn
2897
2898 Finally, SRFI-35 defines a several standard condition types.
2899
2900 @defvar &condition
2901 This condition type is the root of all condition types. It has no
2902 fields.
2903 @end defvar
2904
2905 @defvar &message
2906 A condition type that carries a message describing the nature of the
2907 condition to humans.
2908 @end defvar
2909
2910 @deffn {Scheme Procedure} message-condition? c
2911 Return true if @var{c} is of type @code{&message} or one of its
2912 subtypes.
2913 @end deffn
2914
2915 @deffn {Scheme Procedure} condition-message c
2916 Return the message associated with message condition @var{c}.
2917 @end deffn
2918
2919 @defvar &serious
2920 This type describes conditions serious enough that they cannot safely be
2921 ignored. It has no fields.
2922 @end defvar
2923
2924 @deffn {Scheme Procedure} serious-condition? c
2925 Return true if @var{c} is of type @code{&serious} or one of its
2926 subtypes.
2927 @end deffn
2928
2929 @defvar &error
2930 This condition describes errors, typically caused by something that has
2931 gone wrong in the interaction of the program with the external world or
2932 the user.
2933 @end defvar
2934
2935 @deffn {Scheme Procedure} error? c
2936 Return true if @var{c} is of type @code{&error} or one of its subtypes.
2937 @end deffn
2938
2939
2940 @node SRFI-37
2941 @subsection SRFI-37 - args-fold
2942 @cindex SRFI-37
2943
2944 This is a processor for GNU @code{getopt_long}-style program
2945 arguments. It provides an alternative, less declarative interface
2946 than @code{getopt-long} in @code{(ice-9 getopt-long)}
2947 (@pxref{getopt-long,,The (ice-9 getopt-long) Module}). Unlike
2948 @code{getopt-long}, it supports repeated options and any number of
2949 short and long names per option. Access it with:
2950
2951 @lisp
2952 (use-modules (srfi srfi-37))
2953 @end lisp
2954
2955 @acronym{SRFI}-37 principally provides an @code{option} type and the
2956 @code{args-fold} function. To use the library, create a set of
2957 options with @code{option} and use it as a specification for invoking
2958 @code{args-fold}.
2959
2960 Here is an example of a simple argument processor for the typical
2961 @samp{--version} and @samp{--help} options, which returns a backwards
2962 list of files given on the command line:
2963
2964 @lisp
2965 (args-fold (cdr (program-arguments))
2966 (let ((display-and-exit-proc
2967 (lambda (msg)
2968 (lambda (opt name arg loads)
2969 (display msg) (quit)))))
2970 (list (option '(#\v "version") #f #f
2971 (display-and-exit-proc "Foo version 42.0\n"))
2972 (option '(#\h "help") #f #f
2973 (display-and-exit-proc
2974 "Usage: foo scheme-file ..."))))
2975 (lambda (opt name arg loads)
2976 (error "Unrecognized option `~A'" name))
2977 (lambda (op loads) (cons op loads))
2978 '())
2979 @end lisp
2980
2981 @deffn {Scheme Procedure} option names required-arg? optional-arg? processor
2982 Return an object that specifies a single kind of program option.
2983
2984 @var{names} is a list of command-line option names, and should consist of
2985 characters for traditional @code{getopt} short options and strings for
2986 @code{getopt_long}-style long options.
2987
2988 @var{required-arg?} and @var{optional-arg?} are mutually exclusive;
2989 one or both must be @code{#f}. If @var{required-arg?}, the option
2990 must be followed by an argument on the command line, such as
2991 @samp{--opt=value} for long options, or an error will be signalled.
2992 If @var{optional-arg?}, an argument will be taken if available.
2993
2994 @var{processor} is a procedure that takes at least 3 arguments, called
2995 when @code{args-fold} encounters the option: the containing option
2996 object, the name used on the command line, and the argument given for
2997 the option (or @code{#f} if none). The rest of the arguments are
2998 @code{args-fold} ``seeds'', and the @var{processor} should return
2999 seeds as well.
3000 @end deffn
3001
3002 @deffn {Scheme Procedure} option-names opt
3003 @deffnx {Scheme Procedure} option-required-arg? opt
3004 @deffnx {Scheme Procedure} option-optional-arg? opt
3005 @deffnx {Scheme Procedure} option-processor opt
3006 Return the specified field of @var{opt}, an option object, as
3007 described above for @code{option}.
3008 @end deffn
3009
3010 @deffn {Scheme Procedure} args-fold args options unrecognized-option-proc operand-proc seeds @dots{}
3011 Process @var{args}, a list of program arguments such as that returned
3012 by @code{(cdr (program-arguments))}, in order against @var{options}, a
3013 list of option objects as described above. All functions called take
3014 the ``seeds'', or the last multiple-values as multiple arguments,
3015 starting with @var{seeds}, and must return the new seeds. Return the
3016 final seeds.
3017
3018 Call @code{unrecognized-option-proc}, which is like an option object's
3019 processor, for any options not found in @var{options}.
3020
3021 Call @code{operand-proc} with any items on the command line that are
3022 not named options. This includes arguments after @samp{--}. It is
3023 called with the argument in question, as well as the seeds.
3024 @end deffn
3025
3026
3027 @node SRFI-39
3028 @subsection SRFI-39 - Parameters
3029 @cindex SRFI-39
3030 @cindex parameter object
3031 @tindex Parameter
3032
3033 This SRFI provides parameter objects, which implement dynamically
3034 bound locations for values. The functions below are available from
3035
3036 @example
3037 (use-modules (srfi srfi-39))
3038 @end example
3039
3040 A parameter object is a procedure. Called with no arguments it
3041 returns its value, called with one argument it sets the value.
3042
3043 @example
3044 (define my-param (make-parameter 123))
3045 (my-param) @result{} 123
3046 (my-param 456)
3047 (my-param) @result{} 456
3048 @end example
3049
3050 The @code{parameterize} special form establishes new locations for
3051 parameters, those new locations having effect within the dynamic scope
3052 of the @code{parameterize} body. Leaving restores the previous
3053 locations, or re-entering through a saved continuation will again use
3054 the new locations.
3055
3056 @example
3057 (parameterize ((my-param 789))
3058 (my-param) @result{} 789
3059 )
3060 (my-param) @result{} 456
3061 @end example
3062
3063 Parameters are like dynamically bound variables in other Lisp dialets.
3064 They allow an application to establish parameter settings (as the name
3065 suggests) just for the execution of a particular bit of code,
3066 restoring when done. Examples of such parameters might be
3067 case-sensitivity for a search, or a prompt for user input.
3068
3069 Global variables are not as good as parameter objects for this sort of
3070 thing. Changes to them are visible to all threads, but in Guile
3071 parameter object locations are per-thread, thereby truely limiting the
3072 effect of @code{parameterize} to just its dynamic execution.
3073
3074 Passing arguments to functions is thread-safe, but that soon becomes
3075 tedious when there's more than a few or when they need to pass down
3076 through several layers of calls before reaching the point they should
3077 affect. And introducing a new setting to existing code is often
3078 easier with a parameter object than adding arguments.
3079
3080
3081 @sp 1
3082 @defun make-parameter init [converter]
3083 Return a new parameter object, with initial value @var{init}.
3084
3085 A parameter object is a procedure. When called @code{(param)} it
3086 returns its value, or a call @code{(param val)} sets its value. For
3087 example,
3088
3089 @example
3090 (define my-param (make-parameter 123))
3091 (my-param) @result{} 123
3092
3093 (my-param 456)
3094 (my-param) @result{} 456
3095 @end example
3096
3097 If a @var{converter} is given, then a call @code{(@var{converter}
3098 val)} is made for each value set, its return is the value stored.
3099 Such a call is made for the @var{init} initial value too.
3100
3101 A @var{converter} allows values to be validated, or put into a
3102 canonical form. For example,
3103
3104 @example
3105 (define my-param (make-parameter 123
3106 (lambda (val)
3107 (if (not (number? val))
3108 (error "must be a number"))
3109 (inexact->exact val))))
3110 (my-param 0.75)
3111 (my-param) @result{} 3/4
3112 @end example
3113 @end defun
3114
3115 @deffn {library syntax} parameterize ((param value) @dots{}) body @dots{}
3116 Establish a new dynamic scope with the given @var{param}s bound to new
3117 locations and set to the given @var{value}s. @var{body} is evaluated
3118 in that environment, the result is the return from the last form in
3119 @var{body}.
3120
3121 Each @var{param} is an expression which is evaluated to get the
3122 parameter object. Often this will just be the name of a variable
3123 holding the object, but it can be anything that evaluates to a
3124 parameter.
3125
3126 The @var{param} expressions and @var{value} expressions are all
3127 evaluated before establishing the new dynamic bindings, and they're
3128 evaluated in an unspecified order.
3129
3130 For example,
3131
3132 @example
3133 (define prompt (make-parameter "Type something: "))
3134 (define (get-input)
3135 (display (prompt))
3136 ...)
3137
3138 (parameterize ((prompt "Type a number: "))
3139 (get-input)
3140 ...)
3141 @end example
3142 @end deffn
3143
3144 @deffn {Parameter object} current-input-port [new-port]
3145 @deffnx {Parameter object} current-output-port [new-port]
3146 @deffnx {Parameter object} current-error-port [new-port]
3147 This SRFI extends the core @code{current-input-port} and
3148 @code{current-output-port}, making them parameter objects. The
3149 Guile-specific @code{current-error-port} is extended too, for
3150 consistency. (@pxref{Default Ports}.)
3151
3152 This is an upwardly compatible extension, a plain call like
3153 @code{(current-input-port)} still returns the current input port, and
3154 @code{set-current-input-port} can still be used. But the port can now
3155 also be set with @code{(current-input-port my-port)} and bound
3156 dynamically with @code{parameterize}.
3157 @end deffn
3158
3159 @defun with-parameters* param-list value-list thunk
3160 Establish a new dynamic scope, as per @code{parameterize} above,
3161 taking parameters from @var{param-list} and corresponding values from
3162 @var{values-list}. A call @code{(@var{thunk})} is made in the new
3163 scope and the result from that @var{thunk} is the return from
3164 @code{with-parameters*}.
3165
3166 This function is a Guile-specific addition to the SRFI, it's similar
3167 to the core @code{with-fluids*} (@pxref{Fluids and Dynamic States}).
3168 @end defun
3169
3170
3171 @sp 1
3172 Parameter objects are implemented using fluids (@pxref{Fluids and
3173 Dynamic States}), so each dynamic state has it's own parameter
3174 locations. That includes the separate locations when outside any
3175 @code{parameterize} form. When a parameter is created it gets a
3176 separate initial location in each dynamic state, all initialized to
3177 the given @var{init} value.
3178
3179 As alluded to above, because each thread usually has a separate
3180 dynamic state, each thread has it's own locations behind parameter
3181 objects, and changes in one thread are not visible to any other. When
3182 a new dynamic state or thread is created, the values of parameters in
3183 the originating context are copied, into new locations.
3184
3185 SRFI-39 doesn't specify the interaction between parameter objects and
3186 threads, so the threading behaviour described here should be regarded
3187 as Guile-specific.
3188
3189
3190 @node SRFI-55
3191 @subsection SRFI-55 - Requiring Features
3192 @cindex SRFI-55
3193
3194 SRFI-55 provides @code{require-extension} which is a portable
3195 mechanism to load selected SRFI modules. This is implemented in the
3196 Guile core, there's no module needed to get SRFI-55 itself.
3197
3198 @deffn {library syntax} require-extension clause@dots{}
3199 Require each of the given @var{clause} features, throwing an error if
3200 any are unavailable.
3201
3202 A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
3203 only @var{identifier} currently supported is @code{srfi} and the
3204 arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
3205
3206 @example
3207 (require-extension (srfi 1 6))
3208 @end example
3209
3210 @code{require-extension} can only be used at the top-level.
3211
3212 A Guile-specific program can simply @code{use-modules} to load SRFIs
3213 not already in the core, @code{require-extension} is for programs
3214 designed to be portable to other Scheme implementations.
3215 @end deffn
3216
3217
3218 @node SRFI-60
3219 @subsection SRFI-60 - Integers as Bits
3220 @cindex SRFI-60
3221 @cindex integers as bits
3222 @cindex bitwise logical
3223
3224 This SRFI provides various functions for treating integers as bits and
3225 for bitwise manipulations. These functions can be obtained with,
3226
3227 @example
3228 (use-modules (srfi srfi-60))
3229 @end example
3230
3231 Integers are treated as infinite precision twos-complement, the same
3232 as in the core logical functions (@pxref{Bitwise Operations}). And
3233 likewise bit indexes start from 0 for the least significant bit. The
3234 following functions in this SRFI are already in the Guile core,
3235
3236 @quotation
3237 @code{logand},
3238 @code{logior},
3239 @code{logxor},
3240 @code{lognot},
3241 @code{logtest},
3242 @code{logcount},
3243 @code{integer-length},
3244 @code{logbit?},
3245 @code{ash}
3246 @end quotation
3247
3248 @sp 1
3249 @defun bitwise-and n1 ...
3250 @defunx bitwise-ior n1 ...
3251 @defunx bitwise-xor n1 ...
3252 @defunx bitwise-not n
3253 @defunx any-bits-set? j k
3254 @defunx bit-set? index n
3255 @defunx arithmetic-shift n count
3256 @defunx bit-field n start end
3257 @defunx bit-count n
3258 Aliases for @code{logand}, @code{logior}, @code{logxor},
3259 @code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
3260 @code{bit-extract} and @code{logcount} respectively.
3261
3262 Note that the name @code{bit-count} conflicts with @code{bit-count} in
3263 the core (@pxref{Bit Vectors}).
3264 @end defun
3265
3266 @defun bitwise-if mask n1 n0
3267 @defunx bitwise-merge mask n1 n0
3268 Return an integer with bits selected from @var{n1} and @var{n0}
3269 according to @var{mask}. Those bits where @var{mask} has 1s are taken
3270 from @var{n1}, and those where @var{mask} has 0s are taken from
3271 @var{n0}.
3272
3273 @example
3274 (bitwise-if 3 #b0101 #b1010) @result{} 9
3275 @end example
3276 @end defun
3277
3278 @defun log2-binary-factors n
3279 @defunx first-set-bit n
3280 Return a count of how many factors of 2 are present in @var{n}. This
3281 is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
3282 0, the return is @math{-1}.
3283
3284 @example
3285 (log2-binary-factors 6) @result{} 1
3286 (log2-binary-factors -8) @result{} 3
3287 @end example
3288 @end defun
3289
3290 @defun copy-bit index n newbit
3291 Return @var{n} with the bit at @var{index} set according to
3292 @var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
3293 or @code{#f} to set it to 0. Bits other than at @var{index} are
3294 unchanged in the return.
3295
3296 @example
3297 (copy-bit 1 #b0101 #t) @result{} 7
3298 @end example
3299 @end defun
3300
3301 @defun copy-bit-field n newbits start end
3302 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
3303 (exclusive) changed to the value @var{newbits}.
3304
3305 The least significant bit in @var{newbits} goes to @var{start}, the
3306 next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
3307 @var{end} given is ignored.
3308
3309 @example
3310 (copy-bit-field #b10000 #b11 1 3) @result{} #b10110
3311 @end example
3312 @end defun
3313
3314 @defun rotate-bit-field n count start end
3315 Return @var{n} with the bit field from @var{start} (inclusive) to
3316 @var{end} (exclusive) rotated upwards by @var{count} bits.
3317
3318 @var{count} can be positive or negative, and it can be more than the
3319 field width (it'll be reduced modulo the width).
3320
3321 @example
3322 (rotate-bit-field #b0110 2 1 4) @result{} #b1010
3323 @end example
3324 @end defun
3325
3326 @defun reverse-bit-field n start end
3327 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
3328 (exclusive) reversed.
3329
3330 @example
3331 (reverse-bit-field #b101001 2 4) @result{} #b100101
3332 @end example
3333 @end defun
3334
3335 @defun integer->list n [len]
3336 Return bits from @var{n} in the form of a list of @code{#t} for 1 and
3337 @code{#f} for 0. The least significant @var{len} bits are returned,
3338 and the first list element is the most significant of those bits. If
3339 @var{len} is not given, the default is @code{(integer-length @var{n})}
3340 (@pxref{Bitwise Operations}).
3341
3342 @example
3343 (integer->list 6) @result{} (#t #t #f)
3344 (integer->list 1 4) @result{} (#f #f #f #t)
3345 @end example
3346 @end defun
3347
3348 @defun list->integer lst
3349 @defunx booleans->integer bool@dots{}
3350 Return an integer formed bitwise from the given @var{lst} list of
3351 booleans, or for @code{booleans->integer} from the @var{bool}
3352 arguments.
3353
3354 Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
3355 element becomes the most significant bit in the return.
3356
3357 @example
3358 (list->integer '(#t #f #t #f)) @result{} 10
3359 @end example
3360 @end defun
3361
3362
3363 @node SRFI-61
3364 @subsection SRFI-61 - A more general @code{cond} clause
3365
3366 This SRFI extends RnRS @code{cond} to support test expressions that
3367 return multiple values, as well as arbitrary definitions of test
3368 success. SRFI 61 is implemented in the Guile core; there's no module
3369 needed to get SRFI-61 itself. Extended @code{cond} is documented in
3370 @ref{if cond case,, Simple Conditional Evaluation}.
3371
3372
3373 @node SRFI-69
3374 @subsection SRFI-69 - Basic hash tables
3375 @cindex SRFI-69
3376
3377 This is a portable wrapper around Guile's built-in hash table and weak
3378 table support. @xref{Hash Tables}, for information on that built-in
3379 support. Above that, this hash-table interface provides association
3380 of equality and hash functions with tables at creation time, so
3381 variants of each function are not required, as well as a procedure
3382 that takes care of most uses for Guile hash table handles, which this
3383 SRFI does not provide as such.
3384
3385 Access it with:
3386
3387 @lisp
3388 (use-modules (srfi srfi-69))
3389 @end lisp
3390
3391 @menu
3392 * SRFI-69 Creating hash tables::
3393 * SRFI-69 Accessing table items::
3394 * SRFI-69 Table properties::
3395 * SRFI-69 Hash table algorithms::
3396 @end menu
3397
3398 @node SRFI-69 Creating hash tables
3399 @subsubsection Creating hash tables
3400
3401 @deffn {Scheme Procedure} make-hash-table [equal-proc hash-proc #:weak weakness start-size]
3402 Create and answer a new hash table with @var{equal-proc} as the
3403 equality function and @var{hash-proc} as the hashing function.
3404
3405 By default, @var{equal-proc} is @code{equal?}. It can be any
3406 two-argument procedure, and should answer whether two keys are the
3407 same for this table's purposes.
3408
3409 My default @var{hash-proc} assumes that @code{equal-proc} is no
3410 coarser than @code{equal?} unless it is literally @code{string-ci=?}.
3411 If provided, @var{hash-proc} should be a two-argument procedure that
3412 takes a key and the current table size, and answers a reasonably good
3413 hash integer between 0 (inclusive) and the size (exclusive).
3414
3415 @var{weakness} should be @code{#f} or a symbol indicating how ``weak''
3416 the hash table is:
3417
3418 @table @code
3419 @item #f
3420 An ordinary non-weak hash table. This is the default.
3421
3422 @item key
3423 When the key has no more non-weak references at GC, remove that entry.
3424
3425 @item value
3426 When the value has no more non-weak references at GC, remove that
3427 entry.
3428
3429 @item key-or-value
3430 When either has no more non-weak references at GC, remove the
3431 association.
3432 @end table
3433
3434 As a legacy of the time when Guile couldn't grow hash tables,
3435 @var{start-size} is an optional integer argument that specifies the
3436 approximate starting size for the hash table, which will be rounded to
3437 an algorithmically-sounder number.
3438 @end deffn
3439
3440 By @dfn{coarser} than @code{equal?}, we mean that for all @var{x} and
3441 @var{y} values where @code{(@var{equal-proc} @var{x} @var{y})},
3442 @code{(equal? @var{x} @var{y})} as well. If that does not hold for
3443 your @var{equal-proc}, you must provide a @var{hash-proc}.
3444
3445 In the case of weak tables, remember that @dfn{references} above
3446 always refers to @code{eq?}-wise references. Just because you have a
3447 reference to some string @code{"foo"} doesn't mean that an association
3448 with key @code{"foo"} in a weak-key table @emph{won't} be collected;
3449 it only counts as a reference if the two @code{"foo"}s are @code{eq?},
3450 regardless of @var{equal-proc}. As such, it is usually only sensible
3451 to use @code{eq?} and @code{hashq} as the equivalence and hash
3452 functions for a weak table. @xref{Weak References}, for more
3453 information on Guile's built-in weak table support.
3454
3455 @deffn {Scheme Procedure} alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size]
3456 As with @code{make-hash-table}, but initialize it with the
3457 associations in @var{alist}. Where keys are repeated in @var{alist},
3458 the leftmost association takes precedence.
3459 @end deffn
3460
3461 @node SRFI-69 Accessing table items
3462 @subsubsection Accessing table items
3463
3464 @deffn {Scheme Procedure} hash-table-ref table key [default-thunk]
3465 @deffnx {Scheme Procedure} hash-table-ref/default table key default
3466 Answer the value associated with @var{key} in @var{table}. If
3467 @var{key} is not present, answer the result of invoking the thunk
3468 @var{default-thunk}, which signals an error instead by default.
3469
3470 @code{hash-table-ref/default} is a variant that requires a third
3471 argument, @var{default}, and answers @var{default} itself instead of
3472 invoking it.
3473 @end deffn
3474
3475 @deffn {Scheme Procedure} hash-table-set! table key new-value
3476 Set @var{key} to @var{new-value} in @var{table}.
3477 @end deffn
3478
3479 @deffn {Scheme Procedure} hash-table-delete! table key
3480 Remove the association of @var{key} in @var{table}, if present. If
3481 absent, do nothing.
3482 @end deffn
3483
3484 @deffn {Scheme Procedure} hash-table-exists? table key
3485 Answer whether @var{key} has an association in @var{table}.
3486 @end deffn
3487
3488 @deffn {Scheme Procedure} hash-table-update! table key modifier [default-thunk]
3489 @deffnx {Scheme Procedure} hash-table-update!/default table key modifier default
3490 Replace @var{key}'s associated value in @var{table} by invoking
3491 @var{modifier} with one argument, the old value.
3492
3493 If @var{key} is not present, and @var{default-thunk} is provided,
3494 invoke it with no arguments to get the ``old value'' to be passed to
3495 @var{modifier} as above. If @var{default-thunk} is not provided in
3496 such a case, signal an error.
3497
3498 @code{hash-table-update!/default} is a variant that requires the
3499 fourth argument, which is used directly as the ``old value'' rather
3500 than as a thunk to be invoked to retrieve the ``old value''.
3501 @end deffn
3502
3503 @node SRFI-69 Table properties
3504 @subsubsection Table properties
3505
3506 @deffn {Scheme Procedure} hash-table-size table
3507 Answer the number of associations in @var{table}. This is guaranteed
3508 to run in constant time for non-weak tables.
3509 @end deffn
3510
3511 @deffn {Scheme Procedure} hash-table-keys table
3512 Answer an unordered list of the keys in @var{table}.
3513 @end deffn
3514
3515 @deffn {Scheme Procedure} hash-table-values table
3516 Answer an unordered list of the values in @var{table}.
3517 @end deffn
3518
3519 @deffn {Scheme Procedure} hash-table-walk table proc
3520 Invoke @var{proc} once for each association in @var{table}, passing
3521 the key and value as arguments.
3522 @end deffn
3523
3524 @deffn {Scheme Procedure} hash-table-fold table proc init
3525 Invoke @code{(@var{proc} @var{key} @var{value} @var{previous})} for
3526 each @var{key} and @var{value} in @var{table}, where @var{previous} is
3527 the result of the previous invocation, using @var{init} as the first
3528 @var{previous} value. Answer the final @var{proc} result.
3529 @end deffn
3530
3531 @deffn {Scheme Procedure} hash-table->alist table
3532 Answer an alist where each association in @var{table} is an
3533 association in the result.
3534 @end deffn
3535
3536 @node SRFI-69 Hash table algorithms
3537 @subsubsection Hash table algorithms
3538
3539 Each hash table carries an @dfn{equivalence function} and a @dfn{hash
3540 function}, used to implement key lookups. Beginning users should
3541 follow the rules for consistency of the default @var{hash-proc}
3542 specified above. Advanced users can use these to implement their own
3543 equivalence and hash functions for specialized lookup semantics.
3544
3545 @deffn {Scheme Procedure} hash-table-equivalence-function hash-table
3546 @deffnx {Scheme Procedure} hash-table-hash-function hash-table
3547 Answer the equivalence and hash function of @var{hash-table}, respectively.
3548 @end deffn
3549
3550 @deffn {Scheme Procedure} hash obj [size]
3551 @deffnx {Scheme Procedure} string-hash obj [size]
3552 @deffnx {Scheme Procedure} string-ci-hash obj [size]
3553 @deffnx {Scheme Procedure} hash-by-identity obj [size]
3554 Answer a hash value appropriate for equality predicate @code{equal?},
3555 @code{string=?}, @code{string-ci=?}, and @code{eq?}, respectively.
3556 @end deffn
3557
3558 @code{hash} is a backwards-compatible replacement for Guile's built-in
3559 @code{hash}.
3560
3561 @node SRFI-88
3562 @subsection SRFI-88 Keyword Objects
3563 @cindex SRFI-88
3564 @cindex keyword objects
3565
3566 @uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI-88} provides
3567 @dfn{keyword objects}, which are equivalent to Guile's keywords
3568 (@pxref{Keywords}). SRFI-88 keywords can be entered using the
3569 @dfn{postfix keyword syntax}, which consists of an identifier followed
3570 by @code{:} (@pxref{Reader options, @code{postfix} keyword syntax}).
3571 SRFI-88 can be made available with:
3572
3573 @example
3574 (use-modules (srfi srfi-88))
3575 @end example
3576
3577 Doing so installs the right reader option for keyword syntax, using
3578 @code{(read-set! keywords 'postfix)}. It also provides the procedures
3579 described below.
3580
3581 @deffn {Scheme Procedure} keyword? obj
3582 Return @code{#t} if @var{obj} is a keyword. This is the same procedure
3583 as the same-named built-in procedure (@pxref{Keyword Procedures,
3584 @code{keyword?}}).
3585
3586 @example
3587 (keyword? foo:) @result{} #t
3588 (keyword? 'foo:) @result{} #t
3589 (keyword? "foo") @result{} #f
3590 @end example
3591 @end deffn
3592
3593 @deffn {Scheme Procedure} keyword->string kw
3594 Return the name of @var{kw} as a string, i.e., without the trailing
3595 colon. The returned string may not be modified, e.g., with
3596 @code{string-set!}.
3597
3598 @example
3599 (keyword->string foo:) @result{} "foo"
3600 @end example
3601 @end deffn
3602
3603 @deffn {Scheme Procedure} string->keyword str
3604 Return the keyword object whose name is @var{str}.
3605
3606 @example
3607 (keyword->string (string->keyword "a b c")) @result{} "a b c"
3608 @end example
3609 @end deffn
3610
3611
3612 @c srfi-modules.texi ends here
3613
3614 @c Local Variables:
3615 @c TeX-master: "guile.texi"
3616 @c End: