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