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