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.
9 @section SRFI Support Modules
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.
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}.
23 * About SRFI Usage:: What to know about Guile's SRFI support.
24 * SRFI-0:: cond-expand
25 * SRFI-1:: List library.
27 * SRFI-4:: Homogeneous numeric vector datatypes.
28 * SRFI-6:: Basic String Ports.
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-19:: Time/Date library.
38 * SRFI-26:: Specializing parameters
39 * SRFI-31:: A special form `rec' for recursive evaluation
40 * SRFI-34:: Exception handling.
41 * SRFI-35:: Conditions.
42 * SRFI-37:: args-fold program argument processor
43 * SRFI-39:: Parameter objects
44 * SRFI-55:: Requiring Features.
45 * SRFI-60:: Integers as bits.
46 * SRFI-61:: A more general `cond' clause
47 * SRFI-69:: Basic hash tables.
48 * SRFI-88:: Keyword objects.
52 @node About SRFI Usage
53 @subsection About SRFI Usage
55 @c FIXME::martin: Review me!
57 SRFI support in Guile is currently implemented partly in the core
58 library, and partly as add-on modules. That means that some SRFIs are
59 automatically available when the interpreter is started, whereas the
60 other SRFIs require you to use the appropriate support module
63 There are several reasons for this inconsistency. First, the feature
64 checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
65 available immediately, because it must be there when the user wants to
66 check for the Scheme implementation, that is, before she can know that
67 it is safe to use @code{use-modules} to load SRFI support modules. The
68 second reason is that some features defined in SRFIs had been
69 implemented in Guile before the developers started to add SRFI
70 implementations as modules (for example SRFI-6 (@pxref{SRFI-6})). In
71 the future, it is possible that SRFIs in the core library might be
72 factored out into separate modules, requiring explicit module loading
73 when they are needed. So you should be prepared to have to use
74 @code{use-modules} someday in the future to access SRFI-6 bindings. If
75 you want, you can do that already. We have included the module
76 @code{(srfi srfi-6)} in the distribution, which currently does nothing,
77 but ensures that you can write future-safe code.
79 Generally, support for a specific SRFI is made available by using
80 modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
81 number of the SRFI needed. Another possibility is to use the command
82 line option @code{--use-srfi}, which will load the necessary modules
83 automatically (@pxref{Invoking Guile}).
87 @subsection SRFI-0 - cond-expand
90 This SRFI lets a portable Scheme program test for the presence of
91 certain features, and adapt itself by using different blocks of code,
92 or fail if the necessary features are not available. There's no
93 module to load, this is in the Guile core.
95 A program designed only for Guile will generally not need this
96 mechanism, such a program can of course directly use the various
97 documented parts of Guile.
99 @deffn syntax cond-expand (feature body@dots{}) @dots{}
100 Expand to the @var{body} of the first clause whose @var{feature}
101 specification is satisfied. It is an error if no @var{feature} is
104 Features are symbols such as @code{srfi-1}, and a feature
105 specification can use @code{and}, @code{or} and @code{not} forms to
106 test combinations. The last clause can be an @code{else}, to be used
109 For example, define a private version of @code{alist-cons} if SRFI-1
116 (define (alist-cons key val alist)
117 (cons (cons key val) alist))))
120 Or demand a certain set of SRFIs (list operations, string ports,
121 @code{receive} and string operations), failing if they're not
125 (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
131 The Guile core has the following features,
143 Other SRFI feature symbols are defined once their code has been loaded
144 with @code{use-modules}, since only then are their bindings available.
146 The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
147 a good way to load SRFIs to satisfy @code{cond-expand} when running a
150 Testing the @code{guile} feature allows a program to adapt itself to
151 the Guile module system, but still run on other Scheme systems. For
152 example the following demands SRFI-8 (@code{receive}), but also knows
153 how to load it with the Guile mechanism.
159 (use-modules (srfi srfi-8))))
162 It should be noted that @code{cond-expand} is separate from the
163 @code{*features*} mechanism (@pxref{Feature Tracking}), feature
164 symbols in one are unrelated to those in the other.
168 @subsection SRFI-1 - List library
172 @c FIXME::martin: Review me!
174 The list library defined in SRFI-1 contains a lot of useful list
175 processing procedures for construction, examining, destructuring and
176 manipulating lists and pairs.
178 Since SRFI-1 also defines some procedures which are already contained
179 in R5RS and thus are supported by the Guile core library, some list
180 and pair procedures which appear in the SRFI-1 document may not appear
181 in this section. So when looking for a particular list/pair
182 processing procedure, you should also have a look at the sections
183 @ref{Lists} and @ref{Pairs}.
186 * SRFI-1 Constructors:: Constructing new lists.
187 * SRFI-1 Predicates:: Testing list for specific properties.
188 * SRFI-1 Selectors:: Selecting elements from lists.
189 * SRFI-1 Length Append etc:: Length calculation and list appending.
190 * SRFI-1 Fold and Map:: Higher-order list processing.
191 * SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
192 * SRFI-1 Searching:: Search for elements.
193 * SRFI-1 Deleting:: Delete elements from lists.
194 * SRFI-1 Association Lists:: Handle association lists.
195 * SRFI-1 Set Operations:: Use lists for representing sets.
198 @node SRFI-1 Constructors
199 @subsubsection Constructors
200 @cindex list constructor
202 @c FIXME::martin: Review me!
204 New lists can be constructed by calling one of the following
207 @deffn {Scheme Procedure} xcons d a
208 Like @code{cons}, but with interchanged arguments. Useful mostly when
209 passed to higher-order procedures.
212 @deffn {Scheme Procedure} list-tabulate n init-proc
213 Return an @var{n}-element list, where each list element is produced by
214 applying the procedure @var{init-proc} to the corresponding list
215 index. The order in which @var{init-proc} is applied to the indices
219 @deffn {Scheme Procedure} list-copy lst
220 Return a new list containing the elements of the list @var{lst}.
222 This function differs from the core @code{list-copy} (@pxref{List
223 Constructors}) in accepting improper lists too. And if @var{lst} is
224 not a pair at all then it's treated as the final tail of an improper
225 list and simply returned.
228 @deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
229 Return a circular list containing the given arguments @var{elt1}
233 @deffn {Scheme Procedure} iota count [start step]
234 Return a list containing @var{count} numbers, starting from
235 @var{start} and adding @var{step} each time. The default @var{start}
236 is 0, the default @var{step} is 1. For example,
239 (iota 6) @result{} (0 1 2 3 4 5)
240 (iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
243 This function takes its name from the corresponding primitive in the
248 @node SRFI-1 Predicates
249 @subsubsection Predicates
250 @cindex list predicate
252 @c FIXME::martin: Review me!
254 The procedures in this section test specific properties of lists.
256 @deffn {Scheme Procedure} proper-list? obj
257 Return @code{#t} if @var{obj} is a proper list, or @code{#f}
258 otherwise. This is the same as the core @code{list?} (@pxref{List
261 A proper list is a list which ends with the empty list @code{()} in
262 the usual way. The empty list @code{()} itself is a proper list too.
265 (proper-list? '(1 2 3)) @result{} #t
266 (proper-list? '()) @result{} #t
270 @deffn {Scheme Procedure} circular-list? obj
271 Return @code{#t} if @var{obj} is a circular list, or @code{#f}
274 A circular list is a list where at some point the @code{cdr} refers
275 back to a previous pair in the list (either the start or some later
276 point), so that following the @code{cdr}s takes you around in a
280 (define x (list 1 2 3 4))
281 (set-cdr! (last-pair x) (cddr x))
282 x @result{} (1 2 3 4 3 4 3 4 ...)
283 (circular-list? x) @result{} #t
287 @deffn {Scheme Procedure} dotted-list? obj
288 Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
291 A dotted list is a list where the @code{cdr} of the last pair is not
292 the empty list @code{()}. Any non-pair @var{obj} is also considered a
293 dotted list, with length zero.
296 (dotted-list? '(1 2 . 3)) @result{} #t
297 (dotted-list? 99) @result{} #t
301 It will be noted that any Scheme object passes exactly one of the
302 above three tests @code{proper-list?}, @code{circular-list?} and
303 @code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
304 are either @code{proper-list?} or @code{dotted-list?}, and infinite
305 lists are @code{circular-list?}.
308 @deffn {Scheme Procedure} null-list? lst
309 Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
310 otherwise. If something else than a proper or circular list is passed
311 as @var{lst}, an error is signalled. This procedure is recommended
312 for checking for the end of a list in contexts where dotted lists are
316 @deffn {Scheme Procedure} not-pair? obj
317 Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
318 This is shorthand notation @code{(not (pair? @var{obj}))} and is
319 supposed to be used for end-of-list checking in contexts where dotted
323 @deffn {Scheme Procedure} list= elt= list1 @dots{}
324 Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
325 List equality is determined by testing whether all lists have the same
326 length and the corresponding elements are equal in the sense of the
327 equality predicate @var{elt=}. If no or only one list is given,
328 @code{#t} is returned.
332 @node SRFI-1 Selectors
333 @subsubsection Selectors
334 @cindex list selector
336 @c FIXME::martin: Review me!
338 @deffn {Scheme Procedure} first pair
339 @deffnx {Scheme Procedure} second pair
340 @deffnx {Scheme Procedure} third pair
341 @deffnx {Scheme Procedure} fourth pair
342 @deffnx {Scheme Procedure} fifth pair
343 @deffnx {Scheme Procedure} sixth pair
344 @deffnx {Scheme Procedure} seventh pair
345 @deffnx {Scheme Procedure} eighth pair
346 @deffnx {Scheme Procedure} ninth pair
347 @deffnx {Scheme Procedure} tenth pair
348 These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
351 @deffn {Scheme Procedure} car+cdr pair
352 Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
355 @deffn {Scheme Procedure} take lst i
356 @deffnx {Scheme Procedure} take! lst i
357 Return a list containing the first @var{i} elements of @var{lst}.
359 @code{take!} may modify the structure of the argument list @var{lst}
360 in order to produce the result.
363 @deffn {Scheme Procedure} drop lst i
364 Return a list containing all but the first @var{i} elements of
368 @deffn {Scheme Procedure} take-right lst i
369 Return the a list containing the @var{i} last elements of @var{lst}.
370 The return shares a common tail with @var{lst}.
373 @deffn {Scheme Procedure} drop-right lst i
374 @deffnx {Scheme Procedure} drop-right! lst i
375 Return the a list containing all but the @var{i} last elements of
378 @code{drop-right} always returns a new list, even when @var{i} is
379 zero. @code{drop-right!} may modify the structure of the argument
380 list @var{lst} in order to produce the result.
383 @deffn {Scheme Procedure} split-at lst i
384 @deffnx {Scheme Procedure} split-at! lst i
385 Return two values, a list containing the first @var{i} elements of the
386 list @var{lst} and a list containing the remaining elements.
388 @code{split-at!} may modify the structure of the argument list
389 @var{lst} in order to produce the result.
392 @deffn {Scheme Procedure} last lst
393 Return the last element of the non-empty, finite list @var{lst}.
397 @node SRFI-1 Length Append etc
398 @subsubsection Length, Append, Concatenate, etc.
400 @c FIXME::martin: Review me!
402 @deffn {Scheme Procedure} length+ lst
403 Return the length of the argument list @var{lst}. When @var{lst} is a
404 circular list, @code{#f} is returned.
407 @deffn {Scheme Procedure} concatenate list-of-lists
408 @deffnx {Scheme Procedure} concatenate! list-of-lists
409 Construct a list by appending all lists in @var{list-of-lists}.
411 @code{concatenate!} may modify the structure of the given lists in
412 order to produce the result.
414 @code{concatenate} is the same as @code{(apply append
415 @var{list-of-lists})}. It exists because some Scheme implementations
416 have a limit on the number of arguments a function takes, which the
417 @code{apply} might exceed. In Guile there is no such limit.
420 @deffn {Scheme Procedure} append-reverse rev-head tail
421 @deffnx {Scheme Procedure} append-reverse! rev-head tail
422 Reverse @var{rev-head}, append @var{tail} to it, and return the
423 result. This is equivalent to @code{(append (reverse @var{rev-head})
424 @var{tail})}, but its implementation is more efficient.
427 (append-reverse '(1 2 3) '(4 5 6)) @result{} (3 2 1 4 5 6)
430 @code{append-reverse!} may modify @var{rev-head} in order to produce
434 @deffn {Scheme Procedure} zip lst1 lst2 @dots{}
435 Return a list as long as the shortest of the argument lists, where
436 each element is a list. The first list contains the first elements of
437 the argument lists, the second list contains the second elements, and
441 @deffn {Scheme Procedure} unzip1 lst
442 @deffnx {Scheme Procedure} unzip2 lst
443 @deffnx {Scheme Procedure} unzip3 lst
444 @deffnx {Scheme Procedure} unzip4 lst
445 @deffnx {Scheme Procedure} unzip5 lst
446 @code{unzip1} takes a list of lists, and returns a list containing the
447 first elements of each list, @code{unzip2} returns two lists, the
448 first containing the first elements of each lists and the second
449 containing the second elements of each lists, and so on.
452 @deffn {Scheme Procedure} count pred lst1 @dots{} lstN
453 Return a count of the number of times @var{pred} returns true when
454 called on elements from the given lists.
456 @var{pred} is called with @var{N} parameters @code{(@var{pred}
457 @var{elem1} @dots{} @var{elemN})}, each element being from the
458 corresponding @var{lst1} @dots{} @var{lstN}. The first call is with
459 the first element of each list, the second with the second element
460 from each, and so on.
462 Counting stops when the end of the shortest list is reached. At least
463 one list must be non-circular.
467 @node SRFI-1 Fold and Map
468 @subsubsection Fold, Unfold & Map
472 @c FIXME::martin: Review me!
474 @deffn {Scheme Procedure} fold proc init lst1 @dots{} lstN
475 @deffnx {Scheme Procedure} fold-right proc init lst1 @dots{} lstN
476 Apply @var{proc} to the elements of @var{lst1} @dots{} @var{lstN} to
477 build a result, and return that result.
479 Each @var{proc} call is @code{(@var{proc} @var{elem1} @dots{}
480 @var{elemN} @var{previous})}, where @var{elem1} is from @var{lst1},
481 through @var{elemN} from @var{lstN}. @var{previous} is the return
482 from the previous call to @var{proc}, or the given @var{init} for the
483 first call. If any list is empty, just @var{init} is returned.
485 @code{fold} works through the list elements from first to last. The
486 following shows a list reversal and the calls it makes,
489 (fold cons '() '(1 2 3))
497 @code{fold-right} works through the list elements from last to first,
498 ie.@: from the right. So for example the following finds the longest
499 string, and the last among equal longest,
502 (fold-right (lambda (str prev)
503 (if (> (string-length str) (string-length prev))
507 '("x" "abc" "xyz" "jk"))
511 If @var{lst1} through @var{lstN} have different lengths, @code{fold}
512 stops when the end of the shortest is reached; @code{fold-right}
513 commences at the last element of the shortest. Ie.@: elements past
514 the length of the shortest are ignored in the other @var{lst}s. At
515 least one @var{lst} must be non-circular.
517 @code{fold} should be preferred over @code{fold-right} if the order of
518 processing doesn't matter, or can be arranged either way, since
519 @code{fold} is a little more efficient.
521 The way @code{fold} builds a result from iterating is quite general,
522 it can do more than other iterations like say @code{map} or
523 @code{filter}. The following for example removes adjacent duplicate
524 elements from a list,
527 (define (delete-adjacent-duplicates lst)
528 (fold-right (lambda (elem ret)
529 (if (equal? elem (first ret))
534 (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
535 @result{} (1 2 3 4 5)
538 Clearly the same sort of thing can be done with a @code{for-each} and
539 a variable in which to build the result, but a self-contained
540 @var{proc} can be re-used in multiple contexts, where a
541 @code{for-each} would have to be written out each time.
544 @deffn {Scheme Procedure} pair-fold proc init lst1 @dots{} lstN
545 @deffnx {Scheme Procedure} pair-fold-right proc init lst1 @dots{} lstN
546 The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
547 the pairs of the lists instead of the list elements.
550 @deffn {Scheme Procedure} reduce proc default lst
551 @deffnx {Scheme Procedure} reduce-right proc default lst
552 @code{reduce} is a variant of @code{fold}, where the first call to
553 @var{proc} is on two elements from @var{lst}, rather than one element
554 and a given initial value.
556 If @var{lst} is empty, @code{reduce} returns @var{default} (this is
557 the only use for @var{default}). If @var{lst} has just one element
558 then that's the return value. Otherwise @var{proc} is called on the
559 elements of @var{lst}.
561 Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
562 where @var{elem} is from @var{lst} (the second and subsequent elements
563 of @var{lst}), and @var{previous} is the return from the previous call
564 to @var{proc}. The first element of @var{lst} is the @var{previous}
565 for the first call to @var{proc}.
567 For example, the following adds a list of numbers, the calls made to
568 @code{+} are shown. (Of course @code{+} accepts multiple arguments
569 and can add a list directly, with @code{apply}.)
572 (reduce + 0 '(5 6 7)) @result{} 18
575 (+ 7 11) @result{} 18
578 @code{reduce} can be used instead of @code{fold} where the @var{init}
579 value is an ``identity'', meaning a value which under @var{proc}
580 doesn't change the result, in this case 0 is an identity since
581 @code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
583 @code{reduce-right} is a similar variation on @code{fold-right},
584 working from the end (ie.@: the right) of @var{lst}. The last element
585 of @var{lst} is the @var{previous} for the first call to @var{proc},
586 and the @var{elem} values go from the second last.
588 @code{reduce} should be preferred over @code{reduce-right} if the
589 order of processing doesn't matter, or can be arranged either way,
590 since @code{reduce} is a little more efficient.
593 @deffn {Scheme Procedure} unfold p f g seed [tail-gen]
594 @code{unfold} is defined as follows:
597 (unfold p f g seed) =
598 (if (p seed) (tail-gen seed)
600 (unfold p f g (g seed))))
605 Determines when to stop unfolding.
608 Maps each seed value to the corresponding list element.
611 Maps each seed value to next seed valu.
614 The state value for the unfold.
617 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
620 @var{g} produces a series of seed values, which are mapped to list
621 elements by @var{f}. These elements are put into a list in
622 left-to-right order, and @var{p} tells when to stop unfolding.
625 @deffn {Scheme Procedure} unfold-right p f g seed [tail]
626 Construct a list with the following loop.
629 (let lp ((seed seed) (lis tail))
632 (cons (f seed) lis))))
637 Determines when to stop unfolding.
640 Maps each seed value to the corresponding list element.
643 Maps each seed value to next seed valu.
646 The state value for the unfold.
649 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
654 @deffn {Scheme Procedure} map f lst1 lst2 @dots{}
655 Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
656 return a list containing the results of the procedure applications.
657 This procedure is extended with respect to R5RS, because the argument
658 lists may have different lengths. The result list will have the same
659 length as the shortest argument lists. The order in which @var{f}
660 will be applied to the list element(s) is not specified.
663 @deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
664 Apply the procedure @var{f} to each pair of corresponding elements of
665 the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
666 specified. This procedure is extended with respect to R5RS, because
667 the argument lists may have different lengths. The shortest argument
668 list determines the number of times @var{f} is called. @var{f} will
669 be applied to the list elements in left-to-right order.
673 @deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
674 @deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
678 (apply append (map f clist1 clist2 ...))
684 (apply append! (map f clist1 clist2 ...))
687 Map @var{f} over the elements of the lists, just as in the @code{map}
688 function. However, the results of the applications are appended
689 together to make the final result. @code{append-map} uses
690 @code{append} to append the results together; @code{append-map!} uses
693 The dynamic order in which the various applications of @var{f} are
694 made is not specified.
697 @deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
698 Linear-update variant of @code{map} -- @code{map!} is allowed, but not
699 required, to alter the cons cells of @var{lst1} to construct the
702 The dynamic order in which the various applications of @var{f} are
703 made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
704 @dots{} must have at least as many elements as @var{lst1}.
707 @deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
708 Like @code{for-each}, but applies the procedure @var{f} to the pairs
709 from which the argument lists are constructed, instead of the list
710 elements. The return value is not specified.
713 @deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
714 Like @code{map}, but only results from the applications of @var{f}
715 which are true are saved in the result list.
719 @node SRFI-1 Filtering and Partitioning
720 @subsubsection Filtering and Partitioning
722 @cindex list partition
724 @c FIXME::martin: Review me!
726 Filtering means to collect all elements from a list which satisfy a
727 specific condition. Partitioning a list means to make two groups of
728 list elements, one which contains the elements satisfying a condition,
729 and the other for the elements which don't.
731 The @code{filter} and @code{filter!} functions are implemented in the
732 Guile core, @xref{List Modification}.
734 @deffn {Scheme Procedure} partition pred lst
735 @deffnx {Scheme Procedure} partition! pred lst
736 Split @var{lst} into those elements which do and don't satisfy the
737 predicate @var{pred}.
739 The return is two values (@pxref{Multiple Values}), the first being a
740 list of all elements from @var{lst} which satisfy @var{pred}, the
741 second a list of those which do not.
743 The elements in the result lists are in the same order as in @var{lst}
744 but the order in which the calls @code{(@var{pred} elem)} are made on
745 the list elements is unspecified.
747 @code{partition} does not change @var{lst}, but one of the returned
748 lists may share a tail with it. @code{partition!} may modify
749 @var{lst} to construct its return.
752 @deffn {Scheme Procedure} remove pred lst
753 @deffnx {Scheme Procedure} remove! pred lst
754 Return a list containing all elements from @var{lst} which do not
755 satisfy the predicate @var{pred}. The elements in the result list
756 have the same order as in @var{lst}. The order in which @var{pred} is
757 applied to the list elements is not specified.
759 @code{remove!} is allowed, but not required to modify the structure of
764 @node SRFI-1 Searching
765 @subsubsection Searching
768 @c FIXME::martin: Review me!
770 The procedures for searching elements in lists either accept a
771 predicate or a comparison object for determining which elements are to
774 @deffn {Scheme Procedure} find pred lst
775 Return the first element of @var{lst} which satisfies the predicate
776 @var{pred} and @code{#f} if no such element is found.
779 @deffn {Scheme Procedure} find-tail pred lst
780 Return the first pair of @var{lst} whose @sc{car} satisfies the
781 predicate @var{pred} and @code{#f} if no such element is found.
784 @deffn {Scheme Procedure} take-while pred lst
785 @deffnx {Scheme Procedure} take-while! pred lst
786 Return the longest initial prefix of @var{lst} whose elements all
787 satisfy the predicate @var{pred}.
789 @code{take-while!} is allowed, but not required to modify the input
790 list while producing the result.
793 @deffn {Scheme Procedure} drop-while pred lst
794 Drop the longest initial prefix of @var{lst} whose elements all
795 satisfy the predicate @var{pred}.
798 @deffn {Scheme Procedure} span pred lst
799 @deffnx {Scheme Procedure} span! pred lst
800 @deffnx {Scheme Procedure} break pred lst
801 @deffnx {Scheme Procedure} break! pred lst
802 @code{span} splits the list @var{lst} into the longest initial prefix
803 whose elements all satisfy the predicate @var{pred}, and the remaining
804 tail. @code{break} inverts the sense of the predicate.
806 @code{span!} and @code{break!} are allowed, but not required to modify
807 the structure of the input list @var{lst} in order to produce the
810 Note that the name @code{break} conflicts with the @code{break}
811 binding established by @code{while} (@pxref{while do}). Applications
812 wanting to use @code{break} from within a @code{while} loop will need
813 to make a new define under a different name.
816 @deffn {Scheme Procedure} any pred lst1 lst2 @dots{} lstN
817 Test whether any set of elements from @var{lst1} @dots{} lstN
818 satisfies @var{pred}. If so the return value is the return from the
819 successful @var{pred} call, or if not the return is @code{#f}.
821 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
822 @var{elemN})} taking an element from each @var{lst}. The calls are
823 made successively for the first, second, etc elements of the lists,
824 stopping when @var{pred} returns non-@code{#f}, or when the end of the
825 shortest list is reached.
827 The @var{pred} call on the last set of elements (ie.@: when the end of
828 the shortest list has been reached), if that point is reached, is a
832 @deffn {Scheme Procedure} every pred lst1 lst2 @dots{} lstN
833 Test whether every set of elements from @var{lst1} @dots{} lstN
834 satisfies @var{pred}. If so the return value is the return from the
835 final @var{pred} call, or if not the return is @code{#f}.
837 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
838 @var{elemN})} taking an element from each @var{lst}. The calls are
839 made successively for the first, second, etc elements of the lists,
840 stopping if @var{pred} returns @code{#f}, or when the end of any of
841 the lists is reached.
843 The @var{pred} call on the last set of elements (ie.@: when the end of
844 the shortest list has been reached) is a tail call.
846 If one of @var{lst1} @dots{} @var{lstN} is empty then no calls to
847 @var{pred} are made, and the return is @code{#t}.
850 @deffn {Scheme Procedure} list-index pred lst1 @dots{} lstN
851 Return the index of the first set of elements, one from each of
852 @var{lst1}@dots{}@var{lstN}, which satisfies @var{pred}.
854 @var{pred} is called as @code{(@var{pred} elem1 @dots{} elemN)}.
855 Searching stops when the end of the shortest @var{lst} is reached.
856 The return index starts from 0 for the first set of elements. If no
857 set of elements pass then the return is @code{#f}.
860 (list-index odd? '(2 4 6 9)) @result{} 3
861 (list-index = '(1 2 3) '(3 1 2)) @result{} #f
865 @deffn {Scheme Procedure} member x lst [=]
866 Return the first sublist of @var{lst} whose @sc{car} is equal to
867 @var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
869 Equality is determined by @code{equal?}, or by the equality predicate
870 @var{=} if given. @var{=} is called @code{(= @var{x} elem)},
871 ie.@: with the given @var{x} first, so for example to find the first
872 element greater than 5,
875 (member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
878 This version of @code{member} extends the core @code{member}
879 (@pxref{List Searching}) by accepting an equality predicate.
883 @node SRFI-1 Deleting
884 @subsubsection Deleting
887 @deffn {Scheme Procedure} delete x lst [=]
888 @deffnx {Scheme Procedure} delete! x lst [=]
889 Return a list containing the elements of @var{lst} but with those
890 equal to @var{x} deleted. The returned elements will be in the same
891 order as they were in @var{lst}.
893 Equality is determined by the @var{=} predicate, or @code{equal?} if
894 not given. An equality call is made just once for each element, but
895 the order in which the calls are made on the elements is unspecified.
897 The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
898 is first. This means for instance elements greater than 5 can be
899 deleted with @code{(delete 5 lst <)}.
901 @code{delete} does not modify @var{lst}, but the return might share a
902 common tail with @var{lst}. @code{delete!} may modify the structure
903 of @var{lst} to construct its return.
905 These functions extend the core @code{delete} and @code{delete!}
906 (@pxref{List Modification}) in accepting an equality predicate. See
907 also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
908 deleting multiple elements from a list.
911 @deffn {Scheme Procedure} delete-duplicates lst [=]
912 @deffnx {Scheme Procedure} delete-duplicates! lst [=]
913 Return a list containing the elements of @var{lst} but without
916 When elements are equal, only the first in @var{lst} is retained.
917 Equal elements can be anywhere in @var{lst}, they don't have to be
918 adjacent. The returned list will have the retained elements in the
919 same order as they were in @var{lst}.
921 Equality is determined by the @var{=} predicate, or @code{equal?} if
922 not given. Calls @code{(= x y)} are made with element @var{x} being
923 before @var{y} in @var{lst}. A call is made at most once for each
924 combination, but the sequence of the calls across the elements is
927 @code{delete-duplicates} does not modify @var{lst}, but the return
928 might share a common tail with @var{lst}. @code{delete-duplicates!}
929 may modify the structure of @var{lst} to construct its return.
931 In the worst case, this is an @math{O(N^2)} algorithm because it must
932 check each element against all those preceding it. For long lists it
933 is more efficient to sort and then compare only adjacent elements.
937 @node SRFI-1 Association Lists
938 @subsubsection Association Lists
939 @cindex association list
942 @c FIXME::martin: Review me!
944 Association lists are described in detail in section @ref{Association
945 Lists}. The present section only documents the additional procedures
946 for dealing with association lists defined by SRFI-1.
948 @deffn {Scheme Procedure} assoc key alist [=]
949 Return the pair from @var{alist} which matches @var{key}. This
950 extends the core @code{assoc} (@pxref{Retrieving Alist Entries}) by
951 taking an optional @var{=} comparison procedure.
953 The default comparison is @code{equal?}. If an @var{=} parameter is
954 given it's called @code{(@var{=} @var{key} @var{alistcar})}, ie. the
955 given target @var{key} is the first argument, and a @code{car} from
956 @var{alist} is second.
958 For example a case-insensitive string lookup,
961 (assoc "yy" '(("XX" . 1) ("YY" . 2)) string-ci=?)
966 @deffn {Scheme Procedure} alist-cons key datum alist
967 Cons a new association @var{key} and @var{datum} onto @var{alist} and
968 return the result. This is equivalent to
971 (cons (cons @var{key} @var{datum}) @var{alist})
974 @code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
975 core does the same thing.
978 @deffn {Scheme Procedure} alist-copy alist
979 Return a newly allocated copy of @var{alist}, that means that the
980 spine of the list as well as the pairs are copied.
983 @deffn {Scheme Procedure} alist-delete key alist [=]
984 @deffnx {Scheme Procedure} alist-delete! key alist [=]
985 Return a list containing the elements of @var{alist} but with those
986 elements whose keys are equal to @var{key} deleted. The returned
987 elements will be in the same order as they were in @var{alist}.
989 Equality is determined by the @var{=} predicate, or @code{equal?} if
990 not given. The order in which elements are tested is unspecified, but
991 each equality call is made @code{(= key alistkey)}, ie. the given
992 @var{key} parameter is first and the key from @var{alist} second.
993 This means for instance all associations with a key greater than 5 can
994 be removed with @code{(alist-delete 5 alist <)}.
996 @code{alist-delete} does not modify @var{alist}, but the return might
997 share a common tail with @var{alist}. @code{alist-delete!} may modify
998 the list structure of @var{alist} to construct its return.
1002 @node SRFI-1 Set Operations
1003 @subsubsection Set Operations on Lists
1004 @cindex list set operation
1006 Lists can be used to represent sets of objects. The procedures in
1007 this section operate on such lists as sets.
1009 Note that lists are not an efficient way to implement large sets. The
1010 procedures here typically take time @math{@var{m}@cross{}@var{n}} when
1011 operating on @var{m} and @var{n} element lists. Other data structures
1012 like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
1013 Tables}) are faster.
1015 All these procedures take an equality predicate as the first argument.
1016 This predicate is used for testing the objects in the list sets for
1017 sameness. This predicate must be consistent with @code{eq?}
1018 (@pxref{Equality}) in the sense that if two list elements are
1019 @code{eq?} then they must also be equal under the predicate. This
1020 simply means a given object must be equal to itself.
1022 @deffn {Scheme Procedure} lset<= = list1 list2 @dots{}
1023 Return @code{#t} if each list is a subset of the one following it.
1024 Ie.@: @var{list1} a subset of @var{list2}, @var{list2} a subset of
1025 @var{list3}, etc, for as many lists as given. If only one list or no
1026 lists are given then the return is @code{#t}.
1028 A list @var{x} is a subset of @var{y} if each element of @var{x} is
1029 equal to some element in @var{y}. Elements are compared using the
1030 given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
1033 (lset<= eq?) @result{} #t
1034 (lset<= eqv? '(1 2 3) '(1)) @result{} #f
1035 (lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
1039 @deffn {Scheme Procedure} lset= = list1 list2 @dots{}
1040 Return @code{#t} if all argument lists are set-equal. @var{list1} is
1041 compared to @var{list2}, @var{list2} to @var{list3}, etc, for as many
1042 lists as given. If only one list or no lists are given then the
1043 return is @code{#t}.
1045 Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
1046 is equal to some element of @var{y} and conversely each element of
1047 @var{y} is equal to some element of @var{x}. The order of the
1048 elements in the lists doesn't matter. Element equality is determined
1049 with the given @var{=} procedure, called as @code{(@var{=} xelem
1050 yelem)}, but exactly which calls are made is unspecified.
1053 (lset= eq?) @result{} #t
1054 (lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
1055 (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
1059 @deffn {Scheme Procedure} lset-adjoin = list elem1 @dots{}
1060 Add to @var{list} any of the given @var{elem}s not already in the
1061 list. @var{elem}s are @code{cons}ed onto the start of @var{list} (so
1062 the return shares a common tail with @var{list}), but the order
1063 they're added is unspecified.
1065 The given @var{=} procedure is used for comparing elements, called as
1066 @code{(@var{=} listelem elem)}, ie.@: the second argument is one of
1067 the given @var{elem} parameters.
1070 (lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
1074 @deffn {Scheme Procedure} lset-union = list1 list2 @dots{}
1075 @deffnx {Scheme Procedure} lset-union! = list1 list2 @dots{}
1076 Return the union of the argument list sets. The result is built by
1077 taking the union of @var{list1} and @var{list2}, then the union of
1078 that with @var{list3}, etc, for as many lists as given. For one list
1079 argument that list itself is the result, for no list arguments the
1080 result is the empty list.
1082 The union of two lists @var{x} and @var{y} is formed as follows. If
1083 @var{x} is empty then the result is @var{y}. Otherwise start with
1084 @var{x} as the result and consider each @var{y} element (from first to
1085 last). A @var{y} element not equal to something already in the result
1086 is @code{cons}ed onto the result.
1088 The given @var{=} procedure is used for comparing elements, called as
1089 @code{(@var{=} relem yelem)}. The first argument is from the result
1090 accumulated so far, and the second is from the list being union-ed in.
1091 But exactly which calls are made is otherwise unspecified.
1093 Notice that duplicate elements in @var{list1} (or the first non-empty
1094 list) are preserved, but that repeated elements in subsequent lists
1095 are only added once.
1098 (lset-union eqv?) @result{} ()
1099 (lset-union eqv? '(1 2 3)) @result{} (1 2 3)
1100 (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
1103 @code{lset-union} doesn't change the given lists but the result may
1104 share a tail with the first non-empty list. @code{lset-union!} can
1105 modify all of the given lists to form the result.
1108 @deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
1109 @deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
1110 Return the intersection of @var{list1} with the other argument lists,
1111 meaning those elements of @var{list1} which are also in all of
1112 @var{list2} etc. For one list argument, just that list is returned.
1114 The test for an element of @var{list1} to be in the return is simply
1115 that it's equal to some element in each of @var{list2} etc. Notice
1116 this means an element appearing twice in @var{list1} but only once in
1117 each of @var{list2} etc will go into the return twice. The return has
1118 its elements in the same order as they were in @var{list1}.
1120 The given @var{=} procedure is used for comparing elements, called as
1121 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1122 and the second is from one of the subsequent lists. But exactly which
1123 calls are made and in what order is unspecified.
1126 (lset-intersection eqv? '(x y)) @result{} (x y)
1127 (lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
1128 (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
1131 The return from @code{lset-intersection} may share a tail with
1132 @var{list1}. @code{lset-intersection!} may modify @var{list1} to form
1136 @deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
1137 @deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
1138 Return @var{list1} with any elements in @var{list2}, @var{list3} etc
1139 removed (ie.@: subtracted). For one list argument, just that list is
1142 The given @var{=} procedure is used for comparing elements, called as
1143 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1144 and the second from one of the subsequent lists. But exactly which
1145 calls are made and in what order is unspecified.
1148 (lset-difference eqv? '(x y)) @result{} (x y)
1149 (lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
1150 (lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
1153 The return from @code{lset-difference} may share a tail with
1154 @var{list1}. @code{lset-difference!} may modify @var{list1} to form
1158 @deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
1159 @deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
1160 Return two values (@pxref{Multiple Values}), the difference and
1161 intersection of the argument lists as per @code{lset-difference} and
1162 @code{lset-intersection} above.
1164 For two list arguments this partitions @var{list1} into those elements
1165 of @var{list1} which are in @var{list2} and not in @var{list2}. (But
1166 for more than two arguments there can be elements of @var{list1} which
1167 are neither part of the difference nor the intersection.)
1169 One of the return values from @code{lset-diff+intersection} may share
1170 a tail with @var{list1}. @code{lset-diff+intersection!} may modify
1171 @var{list1} to form its results.
1174 @deffn {Scheme Procedure} lset-xor = list1 list2 @dots{}
1175 @deffnx {Scheme Procedure} lset-xor! = list1 list2 @dots{}
1176 Return an XOR of the argument lists. For two lists this means those
1177 elements which are in exactly one of the lists. For more than two
1178 lists it means those elements which appear in an odd number of the
1181 To be precise, the XOR of two lists @var{x} and @var{y} is formed by
1182 taking those elements of @var{x} not equal to any element of @var{y},
1183 plus those elements of @var{y} not equal to any element of @var{x}.
1184 Equality is determined with the given @var{=} procedure, called as
1185 @code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
1186 from @var{y}, but which way around is unspecified. Exactly which
1187 calls are made is also unspecified, as is the order of the elements in
1191 (lset-xor eqv? '(x y)) @result{} (x y)
1192 (lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
1195 The return from @code{lset-xor} may share a tail with one of the list
1196 arguments. @code{lset-xor!} may modify @var{list1} to form its
1202 @subsection SRFI-2 - and-let*
1206 The following syntax can be obtained with
1209 (use-modules (srfi srfi-2))
1212 @deffn {library syntax} and-let* (clause @dots{}) body @dots{}
1213 A combination of @code{and} and @code{let*}.
1215 Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
1216 then evaluation stops and @code{#f} is returned. If all are
1217 non-@code{#f} then @var{body} is evaluated and the last form gives the
1218 return value, or if @var{body} is empty then the result is @code{#t}.
1219 Each @var{clause} should be one of the following,
1223 Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
1224 Like @code{let*}, that binding is available to subsequent clauses.
1226 Evaluate @var{expr} and check for @code{#f}.
1228 Get the value bound to @var{symbol} and check for @code{#f}.
1231 Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
1232 instance @code{((eq? x y))}. One way to remember this is to imagine
1233 the @code{symbol} in @code{(symbol expr)} is omitted.
1235 @code{and-let*} is good for calculations where a @code{#f} value means
1236 termination, but where a non-@code{#f} value is going to be needed in
1237 subsequent expressions.
1239 The following illustrates this, it returns text between brackets
1240 @samp{[...]} in a string, or @code{#f} if there are no such brackets
1241 (ie.@: either @code{string-index} gives @code{#f}).
1244 (define (extract-brackets str)
1245 (and-let* ((start (string-index str #\[))
1246 (end (string-index str #\] start)))
1247 (substring str (1+ start) end)))
1250 The following shows plain variables and expressions tested too.
1251 @code{diagnostic-levels} is taken to be an alist associating a
1252 diagnostic type with a level. @code{str} is printed only if the type
1253 is known and its level is high enough.
1256 (define (show-diagnostic type str)
1257 (and-let* (want-diagnostics
1258 (level (assq-ref diagnostic-levels type))
1259 ((>= level current-diagnostic-level)))
1263 The advantage of @code{and-let*} is that an extended sequence of
1264 expressions and tests doesn't require lots of nesting as would arise
1265 from separate @code{and} and @code{let*}, or from @code{cond} with
1272 @subsection SRFI-4 - Homogeneous numeric vector datatypes
1275 The SRFI-4 procedures and data types are always available, @xref{Uniform
1279 @subsection SRFI-6 - Basic String Ports
1282 SRFI-6 defines the procedures @code{open-input-string},
1283 @code{open-output-string} and @code{get-output-string}. These
1284 procedures are included in the Guile core, so using this module does not
1285 make any difference at the moment. But it is possible that support for
1286 SRFI-6 will be factored out of the core library in the future, so using
1287 this module does not hurt, after all.
1290 @subsection SRFI-8 - receive
1293 @code{receive} is a syntax for making the handling of multiple-value
1294 procedures easier. It is documented in @xref{Multiple Values}.
1298 @subsection SRFI-9 - define-record-type
1302 This SRFI is a syntax for defining new record types and creating
1303 predicate, constructor, and field getter and setter functions. In
1304 Guile this is simply an alternate interface to the core record
1305 functionality (@pxref{Records}). It can be used with,
1308 (use-modules (srfi srfi-9))
1311 @deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
1313 Create a new record type, and make various @code{define}s for using
1314 it. This syntax can only occur at the top-level, not nested within
1317 @var{type} is bound to the record type, which is as per the return
1318 from the core @code{make-record-type}. @var{type} also provides the
1319 name for the record, as per @code{record-type-name}.
1321 @var{constructor} is bound to a function to be called as
1322 @code{(@var{constructor} fieldval @dots{})} to create a new record of
1323 this type. The arguments are initial values for the fields, one
1324 argument for each field, in the order they appear in the
1325 @code{define-record-type} form.
1327 The @var{fieldname}s provide the names for the record fields, as per
1328 the core @code{record-type-fields} etc, and are referred to in the
1329 subsequent accessor/modifier forms.
1331 @var{predictate} is bound to a function to be called as
1332 @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
1333 according to whether @var{obj} is a record of this type.
1335 Each @var{accessor} is bound to a function to be called
1336 @code{(@var{accessor} record)} to retrieve the respective field from a
1337 @var{record}. Similarly each @var{modifier} is bound to a function to
1338 be called @code{(@var{modifier} record val)} to set the respective
1339 field in a @var{record}.
1343 An example will illustrate typical usage,
1346 (define-record-type employee-type
1347 (make-employee name age salary)
1349 (name get-employee-name)
1350 (age get-employee-age set-employee-age)
1351 (salary get-employee-salary set-employee-salary))
1354 This creates a new employee data type, with name, age and salary
1355 fields. Accessor functions are created for each field, but no
1356 modifier function for the name (the intention in this example being
1357 that it's established only when an employee object is created). These
1358 can all then be used as for example,
1361 employee-type @result{} #<record-type employee-type>
1363 (define fred (make-employee "Fred" 45 20000.00))
1365 (employee? fred) @result{} #t
1366 (get-employee-age fred) @result{} 45
1367 (set-employee-salary fred 25000.00) ;; pay rise
1370 The functions created by @code{define-record-type} are ordinary
1371 top-level @code{define}s. They can be redefined or @code{set!} as
1372 desired, exported from a module, etc.
1376 @subsection SRFI-10 - Hash-Comma Reader Extension
1381 This SRFI implements a reader extension @code{#,()} called hash-comma.
1382 It allows the reader to give new kinds of objects, for use both in
1383 data and as constants or literals in source code. This feature is
1387 (use-modules (srfi srfi-10))
1391 The new read syntax is of the form
1394 #,(@var{tag} @var{arg}@dots{})
1398 where @var{tag} is a symbol and the @var{arg}s are objects taken as
1399 parameters. @var{tag}s are registered with the following procedure.
1401 @deffn {Scheme Procedure} define-reader-ctor tag proc
1402 Register @var{proc} as the constructor for a hash-comma read syntax
1403 starting with symbol @var{tag}, ie. @nicode{#,(@var{tag} arg@dots{})}.
1404 @var{proc} is called with the given arguments @code{(@var{proc}
1405 arg@dots{})} and the object it returns is the result of the read.
1409 For example, a syntax giving a list of @var{N} copies of an object.
1412 (define-reader-ctor 'repeat
1414 (make-list reps obj)))
1416 (display '#,(repeat 99 3))
1420 Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
1421 @code{repeat} handler returns a list and the program must quote to use
1422 it literally, the same as any other list. Ie.
1425 (display '#,(repeat 99 3))
1427 (display '(99 99 99))
1430 When a handler returns an object which is self-evaluating, like a
1431 number or a string, then there's no need for quoting, just as there's
1432 no need when giving those directly as literals. For example an
1436 (define-reader-ctor 'sum
1439 (display #,(sum 123 456)) @print{} 579
1442 A typical use for @nicode{#,()} is to get a read syntax for objects
1443 which don't otherwise have one. For example, the following allows a
1444 hash table to be given literally, with tags and values, ready for fast
1448 (define-reader-ctor 'hash
1450 (let ((table (make-hash-table)))
1451 (for-each (lambda (elem)
1452 (apply hash-set! table elem))
1456 (define (animal->family animal)
1457 (hash-ref '#,(hash ("tiger" "cat")
1462 (animal->family "lion") @result{} "cat"
1465 Or for example the following is a syntax for a compiled regular
1466 expression (@pxref{Regular Expressions}).
1469 (use-modules (ice-9 regex))
1471 (define-reader-ctor 'regexp make-regexp)
1473 (define (extract-angs str)
1474 (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
1476 (match:substring match 1))))
1478 (extract-angs "foo <BAR> quux") @result{} "BAR"
1482 @nicode{#,()} is somewhat similar to @code{define-macro}
1483 (@pxref{Macros}) in that handler code is run to produce a result, but
1484 @nicode{#,()} operates at the read stage, so it can appear in data for
1485 @code{read} (@pxref{Scheme Read}), not just in code to be executed.
1487 Because @nicode{#,()} is handled at read-time it has no direct access
1488 to variables etc. A symbol in the arguments is just a symbol, not a
1489 variable reference. The arguments are essentially constants, though
1490 the handler procedure can use them in any complicated way it might
1493 Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
1494 globally, there's no need to use @code{(srfi srfi-10)} in later
1495 modules. Similarly the tags registered are global and can be used
1496 anywhere once registered.
1498 There's no attempt to record what previous @nicode{#,()} forms have
1499 been seen, if two identical forms occur then two calls are made to the
1500 handler procedure. The handler might like to maintain a cache or
1501 similar to avoid making copies of large objects, depending on expected
1504 In code the best uses of @nicode{#,()} are generally when there's a
1505 lot of objects of a particular kind as literals or constants. If
1506 there's just a few then some local variables and initializers are
1507 fine, but that becomes tedious and error prone when there's a lot, and
1508 the anonymous and compact syntax of @nicode{#,()} is much better.
1512 @subsection SRFI-11 - let-values
1517 This module implements the binding forms for multiple values
1518 @code{let-values} and @code{let*-values}. These forms are similar to
1519 @code{let} and @code{let*} (@pxref{Local Bindings}), but they support
1520 binding of the values returned by multiple-valued expressions.
1522 Write @code{(use-modules (srfi srfi-11))} to make the bindings
1526 (let-values (((x y) (values 1 2))
1527 ((z f) (values 3 4)))
1533 @code{let-values} performs all bindings simultaneously, which means that
1534 no expression in the binding clauses may refer to variables bound in the
1535 same clause list. @code{let*-values}, on the other hand, performs the
1536 bindings sequentially, just like @code{let*} does for single-valued
1541 @subsection SRFI-13 - String Library
1544 The SRFI-13 procedures are always available, @xref{Strings}.
1547 @subsection SRFI-14 - Character-set Library
1550 The SRFI-14 data type and procedures are always available,
1551 @xref{Character Sets}.
1554 @subsection SRFI-16 - case-lambda
1556 @cindex variable arity
1557 @cindex arity, variable
1559 @c FIXME::martin: Review me!
1562 The syntactic form @code{case-lambda} creates procedures, just like
1563 @code{lambda}, but has syntactic extensions for writing procedures of
1564 varying arity easier.
1566 The syntax of the @code{case-lambda} form is defined in the following
1572 --> (case-lambda <case-lambda-clause>)
1573 <case-lambda-clause>
1574 --> (<formals> <definition-or-command>*)
1577 | (<identifier>* . <identifier>)
1582 The value returned by a @code{case-lambda} form is a procedure which
1583 matches the number of actual arguments against the formals in the
1584 various clauses, in order. @dfn{Formals} means a formal argument list
1585 just like with @code{lambda} (@pxref{Lambda}). The first matching clause
1586 is selected, the corresponding values from the actual parameter list are
1587 bound to the variable names in the clauses and the body of the clause is
1588 evaluated. If no clause matches, an error is signalled.
1590 The following (silly) definition creates a procedure @var{foo} which
1591 acts differently, depending on the number of actual arguments. If one
1592 argument is given, the constant @code{#t} is returned, two arguments are
1593 added and if more arguments are passed, their product is calculated.
1596 (define foo (case-lambda
1615 The last expression evaluates to 1 because the last clause is matched,
1616 @var{z} is bound to the empty list and the following multiplication,
1617 applied to zero arguments, yields 1.
1621 @subsection SRFI-17 - Generalized set!
1624 This SRFI implements a generalized @code{set!}, allowing some
1625 ``referencing'' functions to be used as the target location of a
1626 @code{set!}. This feature is available from
1629 (use-modules (srfi srfi-17))
1633 For example @code{vector-ref} is extended so that
1636 (set! (vector-ref vec idx) new-value)
1643 (vector-set! vec idx new-value)
1646 The idea is that a @code{vector-ref} expression identifies a location,
1647 which may be either fetched or stored. The same form is used for the
1648 location in both cases, encouraging visual clarity. This is similar
1649 to the idea of an ``lvalue'' in C.
1651 The mechanism for this kind of @code{set!} is in the Guile core
1652 (@pxref{Procedures with Setters}). This module adds definitions of
1653 the following functions as procedures with setters, allowing them to
1654 be targets of a @code{set!},
1657 @nicode{car}, @nicode{cdr}, @nicode{caar}, @nicode{cadr},
1658 @nicode{cdar}, @nicode{cddr}, @nicode{caaar}, @nicode{caadr},
1659 @nicode{cadar}, @nicode{caddr}, @nicode{cdaar}, @nicode{cdadr},
1660 @nicode{cddar}, @nicode{cdddr}, @nicode{caaaar}, @nicode{caaadr},
1661 @nicode{caadar}, @nicode{caaddr}, @nicode{cadaar}, @nicode{cadadr},
1662 @nicode{caddar}, @nicode{cadddr}, @nicode{cdaaar}, @nicode{cdaadr},
1663 @nicode{cdadar}, @nicode{cdaddr}, @nicode{cddaar}, @nicode{cddadr},
1664 @nicode{cdddar}, @nicode{cddddr}
1666 @nicode{string-ref}, @nicode{vector-ref}
1669 The SRFI specifies @code{setter} (@pxref{Procedures with Setters}) as
1670 a procedure with setter, allowing the setter for a procedure to be
1671 changed, eg.@: @code{(set! (setter foo) my-new-setter-handler)}.
1672 Currently Guile does not implement this, a setter can only be
1673 specified on creation (@code{getter-with-setter} below).
1675 @defun getter-with-setter
1676 The same as the Guile core @code{make-procedure-with-setter}
1677 (@pxref{Procedures with Setters}).
1682 @subsection SRFI-19 - Time/Date Library
1687 This is an implementation of the SRFI-19 time/date library. The
1688 functions and variables described here are provided by
1691 (use-modules (srfi srfi-19))
1694 @strong{Caution}: The current code in this module incorrectly extends
1695 the Gregorian calendar leap year rule back prior to the introduction
1696 of those reforms in 1582 (or the appropriate year in various
1697 countries). The Julian calendar was used prior to 1582, and there
1698 were 10 days skipped for the reform, but the code doesn't implement
1701 This will be fixed some time. Until then calculations for 1583
1702 onwards are correct, but prior to that any day/month/year and day of
1703 the week calculations are wrong.
1706 * SRFI-19 Introduction::
1709 * SRFI-19 Time/Date conversions::
1710 * SRFI-19 Date to string::
1711 * SRFI-19 String to date::
1714 @node SRFI-19 Introduction
1715 @subsubsection SRFI-19 Introduction
1717 @cindex universal time
1721 This module implements time and date representations and calculations,
1722 in various time systems, including universal time (UTC) and atomic
1725 For those not familiar with these time systems, TAI is based on a
1726 fixed length second derived from oscillations of certain atoms. UTC
1727 differs from TAI by an integral number of seconds, which is increased
1728 or decreased at announced times to keep UTC aligned to a mean solar
1729 day (the orbit and rotation of the earth are not quite constant).
1732 So far, only increases in the TAI
1739 UTC difference have been needed. Such an increase is a ``leap
1740 second'', an extra second of TAI introduced at the end of a UTC day.
1741 When working entirely within UTC this is never seen, every day simply
1742 has 86400 seconds. But when converting from TAI to a UTC date, an
1743 extra 23:59:60 is present, where normally a day would end at 23:59:59.
1744 Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
1747 @cindex system clock
1748 In the current implementation, the system clock is assumed to be UTC,
1749 and a table of leap seconds in the code converts to TAI. See comments
1750 in @file{srfi-19.scm} for how to update this table.
1753 @cindex modified julian day
1754 Also, for those not familiar with the terminology, a @dfn{Julian Day}
1755 is a real number which is a count of days and fraction of a day, in
1756 UTC, starting from -4713-01-01T12:00:00Z, ie.@: midday Monday 1 Jan
1757 4713 B.C. A @dfn{Modified Julian Day} is the same, but starting from
1758 1858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. That time
1759 is julian day 2400000.5.
1761 @c The SRFI-1 spec says -4714-11-24T12:00:00Z (November 24, -4714 at
1762 @c noon, UTC), but this is incorrect. It looks like it might have
1763 @c arisen from the code incorrectly treating years a multiple of 100
1764 @c but not 400 prior to 1582 as non-leap years, where instead the Julian
1765 @c calendar should be used so all multiples of 4 before 1582 are leap
1770 @subsubsection SRFI-19 Time
1773 A @dfn{time} object has type, seconds and nanoseconds fields
1774 representing a point in time starting from some epoch. This is an
1775 arbitrary point in time, not just a time of day. Although times are
1776 represented in nanoseconds, the actual resolution may be lower.
1778 The following variables hold the possible time types. For instance
1779 @code{(current-time time-process)} would give the current CPU process
1783 Universal Coordinated Time (UTC).
1788 International Atomic Time (TAI).
1792 @defvar time-monotonic
1793 Monotonic time, meaning a monotonically increasing time starting from
1794 an unspecified epoch.
1796 Note that in the current implementation @code{time-monotonic} is the
1797 same as @code{time-tai}, and unfortunately is therefore affected by
1798 adjustments to the system clock. Perhaps this will change in the
1802 @defvar time-duration
1803 A duration, meaning simply a difference between two times.
1806 @defvar time-process
1807 CPU time spent in the current process, starting from when the process
1809 @cindex process time
1813 CPU time spent in the current thread. Not currently implemented.
1819 Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
1822 @defun make-time type nanoseconds seconds
1823 Create a time object with the given @var{type}, @var{seconds} and
1827 @defun time-type time
1828 @defunx time-nanosecond time
1829 @defunx time-second time
1830 @defunx set-time-type! time type
1831 @defunx set-time-nanosecond! time nsec
1832 @defunx set-time-second! time sec
1833 Get or set the type, seconds or nanoseconds fields of a time object.
1835 @code{set-time-type!} merely changes the field, it doesn't convert the
1836 time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
1839 @defun copy-time time
1840 Return a new time object, which is a copy of the given @var{time}.
1843 @defun current-time [type]
1844 Return the current time of the given @var{type}. The default
1845 @var{type} is @code{time-utc}.
1847 Note that the name @code{current-time} conflicts with the Guile core
1848 @code{current-time} function (@pxref{Time}). Applications wanting to
1849 use both will need to use a different name for one of them.
1852 @defun time-resolution [type]
1853 Return the resolution, in nanoseconds, of the given time @var{type}.
1854 The default @var{type} is @code{time-utc}.
1857 @defun time<=? t1 t2
1858 @defunx time<? t1 t2
1859 @defunx time=? t1 t2
1860 @defunx time>=? t1 t2
1861 @defunx time>? t1 t2
1862 Return @code{#t} or @code{#f} according to the respective relation
1863 between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
1864 must be the same time type.
1867 @defun time-difference t1 t2
1868 @defunx time-difference! t1 t2
1869 Return a time object of type @code{time-duration} representing the
1870 period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
1873 @code{time-difference} returns a new time object,
1874 @code{time-difference!} may modify @var{t1} to form its return.
1877 @defun add-duration time duration
1878 @defunx add-duration! time duration
1879 @defunx subtract-duration time duration
1880 @defunx subtract-duration! time duration
1881 Return a time object which is @var{time} with the given @var{duration}
1882 added or subtracted. @var{duration} must be a time object of type
1883 @code{time-duration}.
1885 @code{add-duration} and @code{subtract-duration} return a new time
1886 object. @code{add-duration!} and @code{subtract-duration!} may modify
1887 the given @var{time} to form their return.
1892 @subsubsection SRFI-19 Date
1895 A @dfn{date} object represents a date in the Gregorian calendar and a
1896 time of day on that date in some timezone.
1898 The fields are year, month, day, hour, minute, second, nanoseconds and
1899 timezone. A date object is immutable, its fields can be read but they
1900 cannot be modified once the object is created.
1903 Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
1906 @defun make-date nsecs seconds minutes hours date month year zone-offset
1907 Create a new date object.
1909 @c FIXME: What can we say about the ranges of the values. The
1910 @c current code looks it doesn't normalize, but expects then in their
1911 @c usual range already.
1915 @defun date-nanosecond date
1916 Nanoseconds, 0 to 999999999.
1919 @defun date-second date
1920 Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
1921 entirely within UTC, it's only when converting to or from TAI.
1924 @defun date-minute date
1928 @defun date-hour date
1932 @defun date-day date
1933 Day of the month, 1 to 31 (or less, according to the month).
1936 @defun date-month date
1940 @defun date-year date
1941 Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
1942 B.C. There is no year 0, year @math{-1} is followed by year 1.
1945 @defun date-zone-offset date
1946 Time zone, an integer number of seconds east of Greenwich.
1949 @defun date-year-day date
1950 Day of the year, starting from 1 for 1st January.
1953 @defun date-week-day date
1954 Day of the week, starting from 0 for Sunday.
1957 @defun date-week-number date dstartw
1958 Week of the year, ignoring a first partial week. @var{dstartw} is the
1959 day of the week which is taken to start a week, 0 for Sunday, 1 for
1962 @c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
1963 @c The code looks like it's 0, if that's the correct intention.
1967 @c The SRFI text doesn't actually give the default for tz-offset, but
1968 @c the reference implementation has the local timezone and the
1969 @c conversions functions all specify that, so it should be ok to
1970 @c document it here.
1972 @defun current-date [tz-offset]
1973 Return a date object representing the current date/time, in UTC offset
1974 by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
1975 defaults to the local timezone.
1978 @defun current-julian-day
1980 Return the current Julian Day.
1983 @defun current-modified-julian-day
1984 @cindex modified julian day
1985 Return the current Modified Julian Day.
1989 @node SRFI-19 Time/Date conversions
1990 @subsubsection SRFI-19 Time/Date conversions
1991 @cindex time conversion
1992 @cindex date conversion
1994 @defun date->julian-day date
1995 @defunx date->modified-julian-day date
1996 @defunx date->time-monotonic date
1997 @defunx date->time-tai date
1998 @defunx date->time-utc date
2000 @defun julian-day->date jdn [tz-offset]
2001 @defunx julian-day->time-monotonic jdn
2002 @defunx julian-day->time-tai jdn
2003 @defunx julian-day->time-utc jdn
2005 @defun modified-julian-day->date jdn [tz-offset]
2006 @defunx modified-julian-day->time-monotonic jdn
2007 @defunx modified-julian-day->time-tai jdn
2008 @defunx modified-julian-day->time-utc jdn
2010 @defun time-monotonic->date time [tz-offset]
2011 @defunx time-monotonic->time-tai time
2012 @defunx time-monotonic->time-tai! time
2013 @defunx time-monotonic->time-utc time
2014 @defunx time-monotonic->time-utc! time
2016 @defun time-tai->date time [tz-offset]
2017 @defunx time-tai->julian-day time
2018 @defunx time-tai->modified-julian-day time
2019 @defunx time-tai->time-monotonic time
2020 @defunx time-tai->time-monotonic! time
2021 @defunx time-tai->time-utc time
2022 @defunx time-tai->time-utc! time
2024 @defun time-utc->date time [tz-offset]
2025 @defunx time-utc->julian-day time
2026 @defunx time-utc->modified-julian-day time
2027 @defunx time-utc->time-monotonic time
2028 @defunx time-utc->time-monotonic! time
2029 @defunx time-utc->time-tai time
2030 @defunx time-utc->time-tai! time
2032 Convert between dates, times and days of the respective types. For
2033 instance @code{time-tai->time-utc} accepts a @var{time} object of type
2034 @code{time-tai} and returns an object of type @code{time-utc}.
2036 The @code{!} variants may modify their @var{time} argument to form
2037 their return. The plain functions create a new object.
2039 For conversions to dates, @var{tz-offset} is seconds east of
2040 Greenwich. The default is the local timezone, at the given time, as
2041 provided by the system, using @code{localtime} (@pxref{Time}).
2043 On 32-bit systems, @code{localtime} is limited to a 32-bit
2044 @code{time_t}, so a default @var{tz-offset} is only available for
2045 times between Dec 1901 and Jan 2038. For prior dates an application
2046 might like to use the value in 1902, though some locations have zone
2047 changes prior to that. For future dates an application might like to
2048 assume today's rules extend indefinitely. But for correct daylight
2049 savings transitions it will be necessary to take an offset for the
2050 same day and time but a year in range and which has the same starting
2051 weekday and same leap/non-leap (to support rules like last Sunday in
2055 @node SRFI-19 Date to string
2056 @subsubsection SRFI-19 Date to string
2057 @cindex date to string
2058 @cindex string, from date
2060 @defun date->string date [format]
2061 Convert a date to a string under the control of a format.
2062 @var{format} should be a string containing @samp{~} escapes, which
2063 will be expanded as per the following conversion table. The default
2064 @var{format} is @samp{~c}, a locale-dependent date and time.
2066 Many of these conversion characters are the same as POSIX
2067 @code{strftime} (@pxref{Time}), but there are some extras and some
2070 @multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
2071 @item @nicode{~~} @tab literal ~
2072 @item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
2073 @item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
2074 @item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
2075 @item @nicode{~B} @tab locale full month, eg.@: @samp{January}
2076 @item @nicode{~c} @tab locale date and time, eg.@: @*
2077 @samp{Fri Jul 14 20:28:42-0400 2000}
2078 @item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
2080 @c Spec says d/m/y, reference implementation says m/d/y.
2081 @c Apparently the reference code was the intention, but would like to
2082 @c see an errata published for the spec before contradicting it here.
2084 @c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
2086 @item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
2087 @item @nicode{~f} @tab seconds and fractional seconds,
2088 with locale decimal point, eg.@: @samp{5.2}
2089 @item @nicode{~h} @tab same as @nicode{~b}
2090 @item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
2091 @item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
2092 @item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
2093 @item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
2094 @item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
2095 @item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
2096 @item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
2097 @item @nicode{~n} @tab newline
2098 @item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
2099 @item @nicode{~p} @tab locale AM or PM
2100 @item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
2101 @item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
2102 @item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
2103 (usual limit is 59, 60 is a leap second)
2104 @item @nicode{~t} @tab horizontal tab character
2105 @item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
2106 @item @nicode{~U} @tab week of year, Sunday first day of week,
2107 @samp{00} to @samp{52}
2108 @item @nicode{~V} @tab week of year, Monday first day of week,
2109 @samp{01} to @samp{53}
2110 @item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
2111 @item @nicode{~W} @tab week of year, Monday first day of week,
2112 @samp{00} to @samp{52}
2114 @c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
2115 @c date. The reference code has ~x as the locale date and ~X as a
2116 @c locale time. The rule is apparently that the code should be
2117 @c believed, but would like to see an errata for the spec before
2118 @c contradicting it here.
2120 @c @item @nicode{~x} @tab week of year, Monday as first day of week,
2121 @c @samp{00} to @samp{53}
2122 @c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
2124 @item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
2125 @item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
2126 @item @nicode{~z} @tab time zone, RFC-822 style
2127 @item @nicode{~Z} @tab time zone symbol (not currently implemented)
2128 @item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
2129 @item @nicode{~2} @tab ISO-8601 time+zone, @samp{~k:~M:~S~z}
2130 @item @nicode{~3} @tab ISO-8601 time, @samp{~k:~M:~S}
2131 @item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~k:~M:~S~z}
2132 @item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~k:~M:~S}
2136 Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
2137 described here, since the specification and reference implementation
2140 Currently Guile doesn't implement any localizations for the above, all
2141 outputs are in English, and the @samp{~c} conversion is POSIX
2142 @code{ctime} style @samp{~a ~b ~d ~H:~M:~S~z ~Y}. This may change in
2146 @node SRFI-19 String to date
2147 @subsubsection SRFI-19 String to date
2148 @cindex string to date
2149 @cindex date, from string
2151 @c FIXME: Can we say what happens when an incomplete date is
2152 @c converted? Ie. fields left as 0, or what? The spec seems to be
2155 @defun string->date input template
2156 Convert an @var{input} string to a date under the control of a
2157 @var{template} string. Return a newly created date object.
2159 Literal characters in @var{template} must match characters in
2160 @var{input} and @samp{~} escapes must match the input forms described
2161 in the table below. ``Skip to'' means characters up to one of the
2162 given type are ignored, or ``no skip'' for no skipping. ``Read'' is
2163 what's then read, and ``Set'' is the field affected in the date
2166 For example @samp{~Y} skips input characters until a digit is reached,
2167 at which point it expects a year and stores that to the year field of
2170 @multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
2182 @tab @nicode{char-alphabetic?}
2183 @tab locale abbreviated weekday name
2187 @tab @nicode{char-alphabetic?}
2188 @tab locale full weekday name
2191 @c Note that the SRFI spec says that ~b and ~B don't set anything,
2192 @c but that looks like a mistake. The reference implementation sets
2193 @c the month field, which seems sensible and is what we describe
2197 @tab @nicode{char-alphabetic?}
2198 @tab locale abbreviated month name
2199 @tab @nicode{date-month}
2202 @tab @nicode{char-alphabetic?}
2203 @tab locale full month name
2204 @tab @nicode{date-month}
2207 @tab @nicode{char-numeric?}
2209 @tab @nicode{date-day}
2213 @tab day of month, blank padded
2214 @tab @nicode{date-day}
2217 @tab same as @samp{~b}
2220 @tab @nicode{char-numeric?}
2222 @tab @nicode{date-hour}
2226 @tab hour, blank padded
2227 @tab @nicode{date-hour}
2230 @tab @nicode{char-numeric?}
2232 @tab @nicode{date-month}
2235 @tab @nicode{char-numeric?}
2237 @tab @nicode{date-minute}
2240 @tab @nicode{char-numeric?}
2242 @tab @nicode{date-second}
2247 @tab @nicode{date-year} within 50 years
2250 @tab @nicode{char-numeric?}
2252 @tab @nicode{date-year}
2257 @tab date-zone-offset
2260 Notice that the weekday matching forms don't affect the date object
2261 returned, instead the weekday will be derived from the day, month and
2264 Currently Guile doesn't implement any localizations for the above,
2265 month and weekday names are always expected in English. This may
2266 change in the future.
2271 @subsection SRFI-26 - specializing parameters
2273 @cindex parameter specialize
2274 @cindex argument specialize
2275 @cindex specialize parameter
2277 This SRFI provides a syntax for conveniently specializing selected
2278 parameters of a function. It can be used with,
2281 (use-modules (srfi srfi-26))
2284 @deffn {library syntax} cut slot @dots{}
2285 @deffnx {library syntax} cute slot @dots{}
2286 Return a new procedure which will make a call (@var{slot} @dots{}) but
2287 with selected parameters specialized to given expressions.
2289 An example will illustrate the idea. The following is a
2290 specialization of @code{write}, sending output to
2291 @code{my-output-port},
2294 (cut write <> my-output-port)
2296 (lambda (obj) (write obj my-output-port))
2299 The special symbol @code{<>} indicates a slot to be filled by an
2300 argument to the new procedure. @code{my-output-port} on the other
2301 hand is an expression to be evaluated and passed, ie.@: it specializes
2302 the behaviour of @code{write}.
2306 A slot to be filled by an argument from the created procedure.
2307 Arguments are assigned to @code{<>} slots in the order they appear in
2308 the @code{cut} form, there's no way to re-arrange arguments.
2310 The first argument to @code{cut} is usually a procedure (or expression
2311 giving a procedure), but @code{<>} is allowed there too. For example,
2316 (lambda (proc) (proc 1 2 3))
2320 A slot to be filled by all remaining arguments from the new procedure.
2321 This can only occur at the end of a @code{cut} form.
2323 For example, a procedure taking a variable number of arguments like
2324 @code{max} but in addition enforcing a lower bound,
2327 (define my-lower-bound 123)
2329 (cut max my-lower-bound <...>)
2331 (lambda arglist (apply max my-lower-bound arglist))
2335 For @code{cut} the specializing expressions are evaluated each time
2336 the new procedure is called. For @code{cute} they're evaluated just
2337 once, when the new procedure is created. The name @code{cute} stands
2338 for ``@code{cut} with evaluated arguments''. In all cases the
2339 evaluations take place in an unspecified order.
2341 The following illustrates the difference between @code{cut} and
2345 (cut format <> "the time is ~s" (current-time))
2347 (lambda (port) (format port "the time is ~s" (current-time)))
2349 (cute format <> "the time is ~s" (current-time))
2351 (let ((val (current-time)))
2352 (lambda (port) (format port "the time is ~s" val))
2355 (There's no provision for a mixture of @code{cut} and @code{cute}
2356 where some expressions would be evaluated every time but others
2357 evaluated only once.)
2359 @code{cut} is really just a shorthand for the sort of @code{lambda}
2360 forms shown in the above examples. But notice @code{cut} avoids the
2361 need to name unspecialized parameters, and is more compact. Use in
2362 functional programming style or just with @code{map}, @code{for-each}
2363 or similar is typical.
2366 (map (cut * 2 <>) '(1 2 3 4))
2368 (for-each (cut write <> my-port) my-list)
2373 @subsection SRFI-31 - A special form `rec' for recursive evaluation
2375 @cindex recursive expression
2378 SRFI-31 defines a special form that can be used to create
2379 self-referential expressions more conveniently. The syntax is as
2384 <rec expression> --> (rec <variable> <expression>)
2385 <rec expression> --> (rec (<variable>+) <body>)
2389 The first syntax can be used to create self-referential expressions,
2393 guile> (define tmp (rec ones (cons 1 (delay ones))))
2396 The second syntax can be used to create anonymous recursive functions:
2399 guile> (define tmp (rec (display-n item n)
2401 (begin (display n) (display-n (- n 1))))))
2409 @subsection SRFI-34 - Exception handling for programs
2412 Guile provides an implementation of
2413 @uref{http://srfi.schemers.org/srfi-34/srfi-34.html, SRFI-34's exception
2414 handling mechanisms} as an alternative to its own built-in mechanisms
2415 (@pxref{Exceptions}). It can be made available as follows:
2418 (use-modules (srfi srfi-34))
2421 @c FIXME: Document it.
2425 @subsection SRFI-35 - Conditions
2431 @uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI-35} implements
2432 @dfn{conditions}, a data structure akin to records designed to convey
2433 information about exceptional conditions between parts of a program. It
2434 is normally used in conjunction with SRFI-34's @code{raise}:
2437 (raise (condition (&message
2438 (message "An error occurred"))))
2441 Users can define @dfn{condition types} containing arbitrary information.
2442 Condition types may inherit from one another. This allows the part of
2443 the program that handles (or ``catches'') conditions to get accurate
2444 information about the exceptional condition that arose.
2446 SRFI-35 conditions are made available using:
2449 (use-modules (srfi srfi-35))
2452 The procedures available to manipulate condition types are the
2455 @deffn {Scheme Procedure} make-condition-type id parent field-names
2456 Return a new condition type named @var{id}, inheriting from
2457 @var{parent}, and with the fields whose names are listed in
2458 @var{field-names}. @var{field-names} must be a list of symbols and must
2459 not contain names already used by @var{parent} or one of its supertypes.
2462 @deffn {Scheme Procedure} condition-type? obj
2463 Return true if @var{obj} is a condition type.
2466 Conditions can be created and accessed with the following procedures:
2468 @deffn {Scheme Procedure} make-condition type . field+value
2469 Return a new condition of type @var{type} with fields initialized as
2470 specified by @var{field+value}, a sequence of field names (symbols) and
2471 values as in the following example:
2474 (let ((&ct (make-condition-type 'foo &condition '(a b c))))
2475 (make-condition &ct 'a 1 'b 2 'c 3))
2478 Note that all fields of @var{type} and its supertypes must be specified.
2481 @deffn {Scheme Procedure} make-compound-condition . conditions
2482 Return a new compound condition composed of @var{conditions}. The
2483 returned condition has the type of each condition of @var{conditions}
2484 (per @code{condition-has-type?}).
2487 @deffn {Scheme Procedure} condition-has-type? c type
2488 Return true if condition @var{c} has type @var{type}.
2491 @deffn {Scheme Procedure} condition-ref c field-name
2492 Return the value of the field named @var{field-name} from condition @var{c}.
2494 If @var{c} is a compound condition and several underlying condition
2495 types contain a field named @var{field-name}, then the value of the
2496 first such field is returned, using the order in which conditions were
2497 passed to @var{make-compound-condition}.
2500 @deffn {Scheme Procedure} extract-condition c type
2501 Return a condition of condition type @var{type} with the field values
2502 specified by @var{c}.
2504 If @var{c} is a compound condition, extract the field values from the
2505 subcondition belonging to @var{type} that appeared first in the call to
2506 @code{make-compound-condition} that created the the condition.
2509 Convenience macros are also available to create condition types and
2512 @deffn {library syntax} define-condition-type type supertype predicate field-spec...
2513 Define a new condition type named @var{type} that inherits from
2514 @var{supertype}. In addition, bind @var{predicate} to a type predicate
2515 that returns true when passed a condition of type @var{type} or any of
2516 its subtypes. @var{field-spec} must have the form @code{(field
2517 accessor)} where @var{field} is the name of field of @var{type} and
2518 @var{accessor} is the name of a procedure to access field @var{field} in
2519 conditions of type @var{type}.
2521 The example below defines condition type @code{&foo}, inheriting from
2522 @code{&condition} with fields @code{a}, @code{b} and @code{c}:
2525 (define-condition-type &foo &condition
2533 @deffn {library syntax} condition type-field-bindings...
2534 Return a new condition, or compound condition, initialized according to
2535 @var{type-field-bindings}. Each @var{type-field-binding} must have the
2536 form @code{(type field-specs...)}, where @var{type} is the name of a
2537 variable bound to condition type; each @var{field-spec} must have the
2538 form @code{(field-name value)} where @var{field-name} is a symbol
2539 denoting the field being initialized to @var{value}. As for
2540 @code{make-condition}, all fields must be specified.
2542 The following example returns a simple condition:
2545 (condition (&message (message "An error occurred")))
2548 The one below returns a compound condition:
2551 (condition (&message (message "An error occurred"))
2556 Finally, SRFI-35 defines a several standard condition types.
2559 This condition type is the root of all condition types. It has no
2564 A condition type that carries a message describing the nature of the
2565 condition to humans.
2568 @deffn {Scheme Procedure} message-condition? c
2569 Return true if @var{c} is of type @code{&message} or one of its
2573 @deffn {Scheme Procedure} condition-message c
2574 Return the message associated with message condition @var{c}.
2578 This type describes conditions serious enough that they cannot safely be
2579 ignored. It has no fields.
2582 @deffn {Scheme Procedure} serious-condition? c
2583 Return true if @var{c} is of type @code{&serious} or one of its
2588 This condition describes errors, typically caused by something that has
2589 gone wrong in the interaction of the program with the external world or
2593 @deffn {Scheme Procedure} error? c
2594 Return true if @var{c} is of type @code{&error} or one of its subtypes.
2599 @subsection SRFI-37 - args-fold
2602 This is a processor for GNU @code{getopt_long}-style program
2603 arguments. It provides an alternative, less declarative interface
2604 than @code{getopt-long} in @code{(ice-9 getopt-long)}
2605 (@pxref{getopt-long,,The (ice-9 getopt-long) Module}). Unlike
2606 @code{getopt-long}, it supports repeated options and any number of
2607 short and long names per option. Access it with:
2610 (use-modules (srfi srfi-37))
2613 @acronym{SRFI}-37 principally provides an @code{option} type and the
2614 @code{args-fold} function. To use the library, create a set of
2615 options with @code{option} and use it as a specification for invoking
2618 Here is an example of a simple argument processor for the typical
2619 @samp{--version} and @samp{--help} options, which returns a backwards
2620 list of files given on the command line:
2623 (args-fold (cdr (program-arguments))
2624 (let ((display-and-exit-proc
2626 (lambda (opt name arg loads)
2627 (display msg) (quit)))))
2628 (list (option '(#\v "version") #f #f
2629 (display-and-exit-proc "Foo version 42.0\n"))
2630 (option '(#\h "help") #f #f
2631 (display-and-exit-proc
2632 "Usage: foo scheme-file ..."))))
2633 (lambda (opt name arg loads)
2634 (error "Unrecognized option `~A'" name))
2635 (lambda (op loads) (cons op loads))
2639 @deffn {Scheme Procedure} option names required-arg? optional-arg? processor
2640 Return an object that specifies a single kind of program option.
2642 @var{names} is a list of command-line option names, and should consist of
2643 characters for traditional @code{getopt} short options and strings for
2644 @code{getopt_long}-style long options.
2646 @var{required-arg?} and @var{optional-arg?} are mutually exclusive;
2647 one or both must be @code{#f}. If @var{required-arg?}, the option
2648 must be followed by an argument on the command line, such as
2649 @samp{--opt=value} for long options, or an error will be signalled.
2650 If @var{optional-arg?}, an argument will be taken if available.
2652 @var{processor} is a procedure that takes at least 3 arguments, called
2653 when @code{args-fold} encounters the option: the containing option
2654 object, the name used on the command line, and the argument given for
2655 the option (or @code{#f} if none). The rest of the arguments are
2656 @code{args-fold} ``seeds'', and the @var{processor} should return
2660 @deffn {Scheme Procedure} option-names opt
2661 @deffnx {Scheme Procedure} option-required-arg? opt
2662 @deffnx {Scheme Procedure} option-optional-arg? opt
2663 @deffnx {Scheme Procedure} option-processor opt
2664 Return the specified field of @var{opt}, an option object, as
2665 described above for @code{option}.
2668 @deffn {Scheme Procedure} args-fold args options unrecognized-option-proc operand-proc seeds @dots{}
2669 Process @var{args}, a list of program arguments such as that returned
2670 by @code{(cdr (program-arguments))}, in order against @var{options}, a
2671 list of option objects as described above. All functions called take
2672 the ``seeds'', or the last multiple-values as multiple arguments,
2673 starting with @var{seeds}, and must return the new seeds. Return the
2676 Call @code{unrecognized-option-proc}, which is like an option object's
2677 processor, for any options not found in @var{options}.
2679 Call @code{operand-proc} with any items on the command line that are
2680 not named options. This includes arguments after @samp{--}. It is
2681 called with the argument in question, as well as the seeds.
2686 @subsection SRFI-39 - Parameters
2688 @cindex parameter object
2691 This SRFI provides parameter objects, which implement dynamically
2692 bound locations for values. The functions below are available from
2695 (use-modules (srfi srfi-39))
2698 A parameter object is a procedure. Called with no arguments it
2699 returns its value, called with one argument it sets the value.
2702 (define my-param (make-parameter 123))
2703 (my-param) @result{} 123
2705 (my-param) @result{} 456
2708 The @code{parameterize} special form establishes new locations for
2709 parameters, those new locations having effect within the dynamic scope
2710 of the @code{parameterize} body. Leaving restores the previous
2711 locations, or re-entering through a saved continuation will again use
2715 (parameterize ((my-param 789))
2716 (my-param) @result{} 789
2718 (my-param) @result{} 456
2721 Parameters are like dynamically bound variables in other Lisp dialets.
2722 They allow an application to establish parameter settings (as the name
2723 suggests) just for the execution of a particular bit of code,
2724 restoring when done. Examples of such parameters might be
2725 case-sensitivity for a search, or a prompt for user input.
2727 Global variables are not as good as parameter objects for this sort of
2728 thing. Changes to them are visible to all threads, but in Guile
2729 parameter object locations are per-thread, thereby truely limiting the
2730 effect of @code{parameterize} to just its dynamic execution.
2732 Passing arguments to functions is thread-safe, but that soon becomes
2733 tedious when there's more than a few or when they need to pass down
2734 through several layers of calls before reaching the point they should
2735 affect. And introducing a new setting to existing code is often
2736 easier with a parameter object than adding arguments.
2740 @defun make-parameter init [converter]
2741 Return a new parameter object, with initial value @var{init}.
2743 A parameter object is a procedure. When called @code{(param)} it
2744 returns its value, or a call @code{(param val)} sets its value. For
2748 (define my-param (make-parameter 123))
2749 (my-param) @result{} 123
2752 (my-param) @result{} 456
2755 If a @var{converter} is given, then a call @code{(@var{converter}
2756 val)} is made for each value set, its return is the value stored.
2757 Such a call is made for the @var{init} initial value too.
2759 A @var{converter} allows values to be validated, or put into a
2760 canonical form. For example,
2763 (define my-param (make-parameter 123
2765 (if (not (number? val))
2766 (error "must be a number"))
2767 (inexact->exact val))))
2769 (my-param) @result{} 3/4
2773 @deffn {library syntax} parameterize ((param value) @dots{}) body @dots{}
2774 Establish a new dynamic scope with the given @var{param}s bound to new
2775 locations and set to the given @var{value}s. @var{body} is evaluated
2776 in that environment, the result is the return from the last form in
2779 Each @var{param} is an expression which is evaluated to get the
2780 parameter object. Often this will just be the name of a variable
2781 holding the object, but it can be anything that evaluates to a
2784 The @var{param} expressions and @var{value} expressions are all
2785 evaluated before establishing the new dynamic bindings, and they're
2786 evaluated in an unspecified order.
2791 (define prompt (make-parameter "Type something: "))
2796 (parameterize ((prompt "Type a number: "))
2802 @deffn {Parameter object} current-input-port [new-port]
2803 @deffnx {Parameter object} current-output-port [new-port]
2804 @deffnx {Parameter object} current-error-port [new-port]
2805 This SRFI extends the core @code{current-input-port} and
2806 @code{current-output-port}, making them parameter objects. The
2807 Guile-specific @code{current-error-port} is extended too, for
2808 consistency. (@pxref{Default Ports}.)
2810 This is an upwardly compatible extension, a plain call like
2811 @code{(current-input-port)} still returns the current input port, and
2812 @code{set-current-input-port} can still be used. But the port can now
2813 also be set with @code{(current-input-port my-port)} and bound
2814 dynamically with @code{parameterize}.
2817 @defun with-parameters* param-list value-list thunk
2818 Establish a new dynamic scope, as per @code{parameterize} above,
2819 taking parameters from @var{param-list} and corresponding values from
2820 @var{values-list}. A call @code{(@var{thunk})} is made in the new
2821 scope and the result from that @var{thunk} is the return from
2822 @code{with-parameters*}.
2824 This function is a Guile-specific addition to the SRFI, it's similar
2825 to the core @code{with-fluids*} (@pxref{Fluids and Dynamic States}).
2830 Parameter objects are implemented using fluids (@pxref{Fluids and
2831 Dynamic States}), so each dynamic state has it's own parameter
2832 locations. That includes the separate locations when outside any
2833 @code{parameterize} form. When a parameter is created it gets a
2834 separate initial location in each dynamic state, all initialized to
2835 the given @var{init} value.
2837 As alluded to above, because each thread usually has a separate
2838 dynamic state, each thread has it's own locations behind parameter
2839 objects, and changes in one thread are not visible to any other. When
2840 a new dynamic state or thread is created, the values of parameters in
2841 the originating context are copied, into new locations.
2843 SRFI-39 doesn't specify the interaction between parameter objects and
2844 threads, so the threading behaviour described here should be regarded
2849 @subsection SRFI-55 - Requiring Features
2852 SRFI-55 provides @code{require-extension} which is a portable
2853 mechanism to load selected SRFI modules. This is implemented in the
2854 Guile core, there's no module needed to get SRFI-55 itself.
2856 @deffn {library syntax} require-extension clause@dots{}
2857 Require each of the given @var{clause} features, throwing an error if
2858 any are unavailable.
2860 A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
2861 only @var{identifier} currently supported is @code{srfi} and the
2862 arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
2865 (require-extension (srfi 1 6))
2868 @code{require-extension} can only be used at the top-level.
2870 A Guile-specific program can simply @code{use-modules} to load SRFIs
2871 not already in the core, @code{require-extension} is for programs
2872 designed to be portable to other Scheme implementations.
2877 @subsection SRFI-60 - Integers as Bits
2879 @cindex integers as bits
2880 @cindex bitwise logical
2882 This SRFI provides various functions for treating integers as bits and
2883 for bitwise manipulations. These functions can be obtained with,
2886 (use-modules (srfi srfi-60))
2889 Integers are treated as infinite precision twos-complement, the same
2890 as in the core logical functions (@pxref{Bitwise Operations}). And
2891 likewise bit indexes start from 0 for the least significant bit. The
2892 following functions in this SRFI are already in the Guile core,
2901 @code{integer-length},
2907 @defun bitwise-and n1 ...
2908 @defunx bitwise-ior n1 ...
2909 @defunx bitwise-xor n1 ...
2910 @defunx bitwise-not n
2911 @defunx any-bits-set? j k
2912 @defunx bit-set? index n
2913 @defunx arithmetic-shift n count
2914 @defunx bit-field n start end
2916 Aliases for @code{logand}, @code{logior}, @code{logxor},
2917 @code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
2918 @code{bit-extract} and @code{logcount} respectively.
2920 Note that the name @code{bit-count} conflicts with @code{bit-count} in
2921 the core (@pxref{Bit Vectors}).
2924 @defun bitwise-if mask n1 n0
2925 @defunx bitwise-merge mask n1 n0
2926 Return an integer with bits selected from @var{n1} and @var{n0}
2927 according to @var{mask}. Those bits where @var{mask} has 1s are taken
2928 from @var{n1}, and those where @var{mask} has 0s are taken from
2932 (bitwise-if 3 #b0101 #b1010) @result{} 9
2936 @defun log2-binary-factors n
2937 @defunx first-set-bit n
2938 Return a count of how many factors of 2 are present in @var{n}. This
2939 is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
2940 0, the return is @math{-1}.
2943 (log2-binary-factors 6) @result{} 1
2944 (log2-binary-factors -8) @result{} 3
2948 @defun copy-bit index n newbit
2949 Return @var{n} with the bit at @var{index} set according to
2950 @var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
2951 or @code{#f} to set it to 0. Bits other than at @var{index} are
2952 unchanged in the return.
2955 (copy-bit 1 #b0101 #t) @result{} 7
2959 @defun copy-bit-field n newbits start end
2960 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2961 (exclusive) changed to the value @var{newbits}.
2963 The least significant bit in @var{newbits} goes to @var{start}, the
2964 next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
2965 @var{end} given is ignored.
2968 (copy-bit-field #b10000 #b11 1 3) @result{} #b10110
2972 @defun rotate-bit-field n count start end
2973 Return @var{n} with the bit field from @var{start} (inclusive) to
2974 @var{end} (exclusive) rotated upwards by @var{count} bits.
2976 @var{count} can be positive or negative, and it can be more than the
2977 field width (it'll be reduced modulo the width).
2980 (rotate-bit-field #b0110 2 1 4) @result{} #b1010
2984 @defun reverse-bit-field n start end
2985 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2986 (exclusive) reversed.
2989 (reverse-bit-field #b101001 2 4) @result{} #b100101
2993 @defun integer->list n [len]
2994 Return bits from @var{n} in the form of a list of @code{#t} for 1 and
2995 @code{#f} for 0. The least significant @var{len} bits are returned,
2996 and the first list element is the most significant of those bits. If
2997 @var{len} is not given, the default is @code{(integer-length @var{n})}
2998 (@pxref{Bitwise Operations}).
3001 (integer->list 6) @result{} (#t #t #f)
3002 (integer->list 1 4) @result{} (#f #f #f #t)
3006 @defun list->integer lst
3007 @defunx booleans->integer bool@dots{}
3008 Return an integer formed bitwise from the given @var{lst} list of
3009 booleans, or for @code{booleans->integer} from the @var{bool}
3012 Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
3013 element becomes the most significant bit in the return.
3016 (list->integer '(#t #f #t #f)) @result{} 10
3022 @subsection SRFI-61 - A more general @code{cond} clause
3024 This SRFI extends RnRS @code{cond} to support test expressions that
3025 return multiple values, as well as arbitrary definitions of test
3026 success. SRFI 61 is implemented in the Guile core; there's no module
3027 needed to get SRFI-61 itself. Extended @code{cond} is documented in
3028 @ref{if cond case,, Simple Conditional Evaluation}.
3032 @subsection SRFI-69 - Basic hash tables
3035 This is a portable wrapper around Guile's built-in hash table and weak
3036 table support. @xref{Hash Tables}, for information on that built-in
3037 support. Above that, this hash-table interface provides association
3038 of equality and hash functions with tables at creation time, so
3039 variants of each function are not required, as well as a procedure
3040 that takes care of most uses for Guile hash table handles, which this
3041 SRFI does not provide as such.
3046 (use-modules (srfi srfi-69))
3050 * SRFI-69 Creating hash tables::
3051 * SRFI-69 Accessing table items::
3052 * SRFI-69 Table properties::
3053 * SRFI-69 Hash table algorithms::
3056 @node SRFI-69 Creating hash tables
3057 @subsubsection Creating hash tables
3059 @deffn {Scheme Procedure} make-hash-table [equal-proc hash-proc #:weak weakness start-size]
3060 Create and answer a new hash table with @var{equal-proc} as the
3061 equality function and @var{hash-proc} as the hashing function.
3063 By default, @var{equal-proc} is @code{equal?}. It can be any
3064 two-argument procedure, and should answer whether two keys are the
3065 same for this table's purposes.
3067 My default @var{hash-proc} assumes that @code{equal-proc} is no
3068 coarser than @code{equal?} unless it is literally @code{string-ci=?}.
3069 If provided, @var{hash-proc} should be a two-argument procedure that
3070 takes a key and the current table size, and answers a reasonably good
3071 hash integer between 0 (inclusive) and the size (exclusive).
3073 @var{weakness} should be @code{#f} or a symbol indicating how ``weak''
3078 An ordinary non-weak hash table. This is the default.
3081 When the key has no more non-weak references at GC, remove that entry.
3084 When the value has no more non-weak references at GC, remove that
3088 When either has no more non-weak references at GC, remove the
3092 As a legacy of the time when Guile couldn't grow hash tables,
3093 @var{start-size} is an optional integer argument that specifies the
3094 approximate starting size for the hash table, which will be rounded to
3095 an algorithmically-sounder number.
3098 By @dfn{coarser} than @code{equal?}, we mean that for all @var{x} and
3099 @var{y} values where @code{(@var{equal-proc} @var{x} @var{y})},
3100 @code{(equal? @var{x} @var{y})} as well. If that does not hold for
3101 your @var{equal-proc}, you must provide a @var{hash-proc}.
3103 In the case of weak tables, remember that @dfn{references} above
3104 always refers to @code{eq?}-wise references. Just because you have a
3105 reference to some string @code{"foo"} doesn't mean that an association
3106 with key @code{"foo"} in a weak-key table @emph{won't} be collected;
3107 it only counts as a reference if the two @code{"foo"}s are @code{eq?},
3108 regardless of @var{equal-proc}. As such, it is usually only sensible
3109 to use @code{eq?} and @code{hashq} as the equivalence and hash
3110 functions for a weak table. @xref{Weak References}, for more
3111 information on Guile's built-in weak table support.
3113 @deffn {Scheme Procedure} alist->hash-table alist [equal-proc hash-proc #:weak weakness start-size]
3114 As with @code{make-hash-table}, but initialize it with the
3115 associations in @var{alist}. Where keys are repeated in @var{alist},
3116 the leftmost association takes precedence.
3119 @node SRFI-69 Accessing table items
3120 @subsubsection Accessing table items
3122 @deffn {Scheme Procedure} hash-table-ref table key [default-thunk]
3123 @deffnx {Scheme Procedure} hash-table-ref/default table key default
3124 Answer the value associated with @var{key} in @var{table}. If
3125 @var{key} is not present, answer the result of invoking the thunk
3126 @var{default-thunk}, which signals an error instead by default.
3128 @code{hash-table-ref/default} is a variant that requires a third
3129 argument, @var{default}, and answers @var{default} itself instead of
3133 @deffn {Scheme Procedure} hash-table-set! table key new-value
3134 Set @var{key} to @var{new-value} in @var{table}.
3137 @deffn {Scheme Procedure} hash-table-delete! table key
3138 Remove the association of @var{key} in @var{table}, if present. If
3142 @deffn {Scheme Procedure} hash-table-exists? table key
3143 Answer whether @var{key} has an association in @var{table}.
3146 @deffn {Scheme Procedure} hash-table-update! table key modifier [default-thunk]
3147 @deffnx {Scheme Procedure} hash-table-update!/default table key modifier default
3148 Replace @var{key}'s associated value in @var{table} by invoking
3149 @var{modifier} with one argument, the old value.
3151 If @var{key} is not present, and @var{default-thunk} is provided,
3152 invoke it with no arguments to get the ``old value'' to be passed to
3153 @var{modifier} as above. If @var{default-thunk} is not provided in
3154 such a case, signal an error.
3156 @code{hash-table-update!/default} is a variant that requires the
3157 fourth argument, which is used directly as the ``old value'' rather
3158 than as a thunk to be invoked to retrieve the ``old value''.
3161 @node SRFI-69 Table properties
3162 @subsubsection Table properties
3164 @deffn {Scheme Procedure} hash-table-size table
3165 Answer the number of associations in @var{table}. This is guaranteed
3166 to run in constant time for non-weak tables.
3169 @deffn {Scheme Procedure} hash-table-keys table
3170 Answer an unordered list of the keys in @var{table}.
3173 @deffn {Scheme Procedure} hash-table-values table
3174 Answer an unordered list of the values in @var{table}.
3177 @deffn {Scheme Procedure} hash-table-walk table proc
3178 Invoke @var{proc} once for each association in @var{table}, passing
3179 the key and value as arguments.
3182 @deffn {Scheme Procedure} hash-table-fold table proc init
3183 Invoke @code{(@var{proc} @var{key} @var{value} @var{previous})} for
3184 each @var{key} and @var{value} in @var{table}, where @var{previous} is
3185 the result of the previous invocation, using @var{init} as the first
3186 @var{previous} value. Answer the final @var{proc} result.
3189 @deffn {Scheme Procedure} hash-table->alist table
3190 Answer an alist where each association in @var{table} is an
3191 association in the result.
3194 @node SRFI-69 Hash table algorithms
3195 @subsubsection Hash table algorithms
3197 Each hash table carries an @dfn{equivalence function} and a @dfn{hash
3198 function}, used to implement key lookups. Beginning users should
3199 follow the rules for consistency of the default @var{hash-proc}
3200 specified above. Advanced users can use these to implement their own
3201 equivalence and hash functions for specialized lookup semantics.
3203 @deffn {Scheme Procedure} hash-table-equivalence-function hash-table
3204 @deffnx {Scheme Procedure} hash-table-hash-function hash-table
3205 Answer the equivalence and hash function of @var{hash-table}, respectively.
3208 @deffn {Scheme Procedure} hash obj [size]
3209 @deffnx {Scheme Procedure} string-hash obj [size]
3210 @deffnx {Scheme Procedure} string-ci-hash obj [size]
3211 @deffnx {Scheme Procedure} hash-by-identity obj [size]
3212 Answer a hash value appropriate for equality predicate @code{equal?},
3213 @code{string=?}, @code{string-ci=?}, and @code{eq?}, respectively.
3216 @code{hash} is a backwards-compatible replacement for Guile's built-in
3220 @subsection SRFI-88 Keyword Objects
3222 @cindex keyword objects
3224 @uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI-88} provides
3225 @dfn{keyword objects}, which are equivalent to Guile's keywords
3226 (@pxref{Keywords}). SRFI-88 keywords can be entered using the
3227 @dfn{postfix keyword syntax}, which consists of an identifier followed
3228 by @code{:} (@pxref{Reader options, @code{postfix} keyword syntax}).
3229 SRFI-88 can be made available with:
3232 (use-modules (srfi srfi-88))
3235 Doing so installs the right reader option for keyword syntax, using
3236 @code{(read-set! keywords 'postfix)}. It also provides the procedures
3239 @deffn {Scheme Procedure} keyword? obj
3240 Return @code{#t} if @var{obj} is a keyword. This is the same procedure
3241 as the same-named built-in procedure (@pxref{Keyword Procedures,
3245 (keyword? foo:) @result{} #t
3246 (keyword? 'foo:) @result{} #t
3247 (keyword? "foo") @result{} #f
3251 @deffn {Scheme Procedure} keyword->string kw
3252 Return the name of @var{kw} as a string, i.e., without the trailing
3253 colon. The returned string may not be modified, e.g., with
3257 (keyword->string foo:) @result{} "foo"
3261 @deffn {Scheme Procedure} string->keyword str
3262 Return the keyword object whose name is @var{str}.
3265 (keyword->string (string->keyword "a b c")) @result{} "a b c"
3270 @c srfi-modules.texi ends here
3273 @c TeX-master: "guile.texi"