* srfi-modules.texi (SRFI-1 Set Operations): use @cross iso. @times.
[bpt/guile.git] / doc / ref / srfi-modules.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node SRFI Support
9 @section SRFI Support Modules
10 @cindex SRFI
11
12 SRFI is an acronym for Scheme Request For Implementation. The SRFI
13 documents define a lot of syntactic and procedure extensions to standard
14 Scheme as defined in R5RS.
15
16 Guile has support for a number of SRFIs. This chapter gives an overview
17 over the available SRFIs and some usage hints. For complete
18 documentation, design rationales and further examples, we advise you to
19 get the relevant SRFI documents from the SRFI home page
20 @url{http://srfi.schemers.org}.
21
22 @menu
23 * About SRFI Usage:: What to know about Guile's SRFI support.
24 * SRFI-0:: cond-expand
25 * SRFI-1:: List library.
26 * SRFI-2:: and-let*.
27 * SRFI-4:: Homogeneous numeric vector datatypes.
28 * SRFI-6:: Basic String Ports.
29 * SRFI-8:: receive.
30 * SRFI-9:: define-record-type.
31 * SRFI-10:: Hash-Comma Reader Extension.
32 * SRFI-11:: let-values and let-values*.
33 * SRFI-13:: String library.
34 * SRFI-14:: Character-set library.
35 * SRFI-16:: case-lambda
36 * SRFI-17:: Generalized set!
37 * SRFI-19:: Time/Date library.
38 * SRFI-26:: Specializing parameters
39 * SRFI-31:: A special form `rec' for recursive evaluation
40 * SRFI-39:: Parameter objects
41 * SRFI-55:: Requiring Features.
42 * SRFI-60:: Integers as bits.
43 @end menu
44
45
46 @node About SRFI Usage
47 @subsection About SRFI Usage
48
49 @c FIXME::martin: Review me!
50
51 SRFI support in Guile is currently implemented partly in the core
52 library, and partly as add-on modules. That means that some SRFIs are
53 automatically available when the interpreter is started, whereas the
54 other SRFIs require you to use the appropriate support module
55 explicitly.
56
57 There are several reasons for this inconsistency. First, the feature
58 checking syntactic form @code{cond-expand} (@pxref{SRFI-0}) must be
59 available immediately, because it must be there when the user wants to
60 check for the Scheme implementation, that is, before she can know that
61 it is safe to use @code{use-modules} to load SRFI support modules. The
62 second reason is that some features defined in SRFIs had been
63 implemented in Guile before the developers started to add SRFI
64 implementations as modules (for example SRFI-6 (@pxref{SRFI-6})). In
65 the future, it is possible that SRFIs in the core library might be
66 factored out into separate modules, requiring explicit module loading
67 when they are needed. So you should be prepared to have to use
68 @code{use-modules} someday in the future to access SRFI-6 bindings. If
69 you want, you can do that already. We have included the module
70 @code{(srfi srfi-6)} in the distribution, which currently does nothing,
71 but ensures that you can write future-safe code.
72
73 Generally, support for a specific SRFI is made available by using
74 modules named @code{(srfi srfi-@var{number})}, where @var{number} is the
75 number of the SRFI needed. Another possibility is to use the command
76 line option @code{--use-srfi}, which will load the necessary modules
77 automatically (@pxref{Invoking Guile}).
78
79
80 @node SRFI-0
81 @subsection SRFI-0 - cond-expand
82 @cindex SRFI-0
83
84 This SRFI lets a portable Scheme program test for the presence of
85 certain features, and adapt itself by using different blocks of code,
86 or fail if the necessary features are not available. There's no
87 module to load, this is in the Guile core.
88
89 A program designed only for Guile will generally not need this
90 mechanism, such a program can of course directly use the various
91 documented parts of Guile.
92
93 @deffn syntax cond-expand (feature body@dots{}) @dots{}
94 Expand to the @var{body} of the first clause whose @var{feature}
95 specification is satisfied. It is an error if no @var{feature} is
96 satisfied.
97
98 Features are symbols such as @code{srfi-1}, and a feature
99 specification can use @code{and}, @code{or} and @code{not} forms to
100 test combinations. The last clause can be an @code{else}, to be used
101 if no other passes.
102
103 For example, define a private version of @code{alist-cons} if SRFI-1
104 is not available.
105
106 @example
107 (cond-expand (srfi-1
108 )
109 (else
110 (define (alist-cons key val alist)
111 (cons (cons key val) alist))))
112 @end example
113
114 Or demand a certain set of SRFIs (list operations, string ports,
115 @code{receive} and string operations), failing if they're not
116 available.
117
118 @example
119 (cond-expand ((and srfi-1 srfi-6 srfi-8 srfi-13)
120 ))
121 @end example
122 @end deffn
123
124 @noindent
125 The Guile core has the following features,
126
127 @example
128 guile
129 r5rs
130 srfi-0
131 srfi-4
132 srfi-6
133 srfi-13
134 srfi-14
135 @end example
136
137 Other SRFI feature symbols are defined once their code has been loaded
138 with @code{use-modules}, since only then are their bindings available.
139
140 The @samp{--use-srfi} command line option (@pxref{Invoking Guile}) is
141 a good way to load SRFIs to satisfy @code{cond-expand} when running a
142 portable program.
143
144 Testing the @code{guile} feature allows a program to adapt itself to
145 the Guile module system, but still run on other Scheme systems. For
146 example the following demands SRFI-8 (@code{receive}), but also knows
147 how to load it with the Guile mechanism.
148
149 @example
150 (cond-expand (srfi-8
151 )
152 (guile
153 (use-modules (srfi srfi-8))))
154 @end example
155
156 It should be noted that @code{cond-expand} is separate from the
157 @code{*features*} mechanism (@pxref{Feature Tracking}), feature
158 symbols in one are unrelated to those in the other.
159
160
161 @node SRFI-1
162 @subsection SRFI-1 - List library
163 @cindex SRFI-1
164 @cindex list
165
166 @c FIXME::martin: Review me!
167
168 The list library defined in SRFI-1 contains a lot of useful list
169 processing procedures for construction, examining, destructuring and
170 manipulating lists and pairs.
171
172 Since SRFI-1 also defines some procedures which are already contained
173 in R5RS and thus are supported by the Guile core library, some list
174 and pair procedures which appear in the SRFI-1 document may not appear
175 in this section. So when looking for a particular list/pair
176 processing procedure, you should also have a look at the sections
177 @ref{Lists} and @ref{Pairs}.
178
179 @menu
180 * SRFI-1 Constructors:: Constructing new lists.
181 * SRFI-1 Predicates:: Testing list for specific properties.
182 * SRFI-1 Selectors:: Selecting elements from lists.
183 * SRFI-1 Length Append etc:: Length calculation and list appending.
184 * SRFI-1 Fold and Map:: Higher-order list processing.
185 * SRFI-1 Filtering and Partitioning:: Filter lists based on predicates.
186 * SRFI-1 Searching:: Search for elements.
187 * SRFI-1 Deleting:: Delete elements from lists.
188 * SRFI-1 Association Lists:: Handle association lists.
189 * SRFI-1 Set Operations:: Use lists for representing sets.
190 @end menu
191
192 @node SRFI-1 Constructors
193 @subsubsection Constructors
194 @cindex list constructor
195
196 @c FIXME::martin: Review me!
197
198 New lists can be constructed by calling one of the following
199 procedures.
200
201 @deffn {Scheme Procedure} xcons d a
202 Like @code{cons}, but with interchanged arguments. Useful mostly when
203 passed to higher-order procedures.
204 @end deffn
205
206 @deffn {Scheme Procedure} list-tabulate n init-proc
207 Return an @var{n}-element list, where each list element is produced by
208 applying the procedure @var{init-proc} to the corresponding list
209 index. The order in which @var{init-proc} is applied to the indices
210 is not specified.
211 @end deffn
212
213 @deffn {Scheme Procedure} list-copy lst
214 Return a new list containing the elements of the list @var{lst}.
215
216 This function differs from the core @code{list-copy} (@pxref{List
217 Constructors}) in accepting improper lists too. And if @var{lst} is
218 not a pair at all then it's treated as the final tail of an improper
219 list and simply returned.
220 @end deffn
221
222 @deffn {Scheme Procedure} circular-list elt1 elt2 @dots{}
223 Return a circular list containing the given arguments @var{elt1}
224 @var{elt2} @dots{}.
225 @end deffn
226
227 @deffn {Scheme Procedure} iota count [start step]
228 Return a list containing @var{count} numbers, starting from
229 @var{start} and adding @var{step} each time. The default @var{start}
230 is 0, the default @var{step} is 1. For example,
231
232 @example
233 (iota 6) @result{} (0 1 2 3 4 5)
234 (iota 4 2.5 -2) @result{} (2.5 0.5 -1.5 -3.5)
235 @end example
236
237 This function takes its name from the corresponding primitive in the
238 APL language.
239 @end deffn
240
241
242 @node SRFI-1 Predicates
243 @subsubsection Predicates
244 @cindex list predicate
245
246 @c FIXME::martin: Review me!
247
248 The procedures in this section test specific properties of lists.
249
250 @deffn {Scheme Procedure} proper-list? obj
251 Return @code{#t} if @var{obj} is a proper list, or @code{#f}
252 otherwise. This is the same as the core @code{list?} (@pxref{List
253 Predicates}).
254
255 A proper list is a list which ends with the empty list @code{()} in
256 the usual way. The empty list @code{()} itself is a proper list too.
257
258 @example
259 (proper-list? '(1 2 3)) @result{} #t
260 (proper-list? '()) @result{} #t
261 @end example
262 @end deffn
263
264 @deffn {Scheme Procedure} circular-list? obj
265 Return @code{#t} if @var{obj} is a circular list, or @code{#f}
266 otherwise.
267
268 A circular list is a list where at some point the @code{cdr} refers
269 back to a previous pair in the list (either the start or some later
270 point), so that following the @code{cdr}s takes you around in a
271 circle, with no end.
272
273 @example
274 (define x (list 1 2 3 4))
275 (set-cdr! (last-pair x) (cddr x))
276 x @result{} (1 2 3 4 3 4 3 4 ...)
277 (circular-list? x) @result{} #t
278 @end example
279 @end deffn
280
281 @deffn {Scheme Procedure} dotted-list? obj
282 Return @code{#t} if @var{obj} is a dotted list, or @code{#f}
283 otherwise.
284
285 A dotted list is a list where the @code{cdr} of the last pair is not
286 the empty list @code{()}. Any non-pair @var{obj} is also considered a
287 dotted list, with length zero.
288
289 @example
290 (dotted-list? '(1 2 . 3)) @result{} #t
291 (dotted-list? 99) @result{} #t
292 @end example
293 @end deffn
294
295 It will be noted that any Scheme object passes exactly one of the
296 above three tests @code{proper-list?}, @code{circular-list?} and
297 @code{dotted-list?}. Non-lists are @code{dotted-list?}, finite lists
298 are either @code{proper-list?} or @code{dotted-list?}, and infinite
299 lists are @code{circular-list?}.
300
301 @sp 1
302 @deffn {Scheme Procedure} null-list? lst
303 Return @code{#t} if @var{lst} is the empty list @code{()}, @code{#f}
304 otherwise. If something else than a proper or circular list is passed
305 as @var{lst}, an error is signalled. This procedure is recommended
306 for checking for the end of a list in contexts where dotted lists are
307 not allowed.
308 @end deffn
309
310 @deffn {Scheme Procedure} not-pair? obj
311 Return @code{#t} is @var{obj} is not a pair, @code{#f} otherwise.
312 This is shorthand notation @code{(not (pair? @var{obj}))} and is
313 supposed to be used for end-of-list checking in contexts where dotted
314 lists are allowed.
315 @end deffn
316
317 @deffn {Scheme Procedure} list= elt= list1 @dots{}
318 Return @code{#t} if all argument lists are equal, @code{#f} otherwise.
319 List equality is determined by testing whether all lists have the same
320 length and the corresponding elements are equal in the sense of the
321 equality predicate @var{elt=}. If no or only one list is given,
322 @code{#t} is returned.
323 @end deffn
324
325
326 @node SRFI-1 Selectors
327 @subsubsection Selectors
328 @cindex list selector
329
330 @c FIXME::martin: Review me!
331
332 @deffn {Scheme Procedure} first pair
333 @deffnx {Scheme Procedure} second pair
334 @deffnx {Scheme Procedure} third pair
335 @deffnx {Scheme Procedure} fourth pair
336 @deffnx {Scheme Procedure} fifth pair
337 @deffnx {Scheme Procedure} sixth pair
338 @deffnx {Scheme Procedure} seventh pair
339 @deffnx {Scheme Procedure} eighth pair
340 @deffnx {Scheme Procedure} ninth pair
341 @deffnx {Scheme Procedure} tenth pair
342 These are synonyms for @code{car}, @code{cadr}, @code{caddr}, @dots{}.
343 @end deffn
344
345 @deffn {Scheme Procedure} car+cdr pair
346 Return two values, the @sc{car} and the @sc{cdr} of @var{pair}.
347 @end deffn
348
349 @deffn {Scheme Procedure} take lst i
350 @deffnx {Scheme Procedure} take! lst i
351 Return a list containing the first @var{i} elements of @var{lst}.
352
353 @code{take!} may modify the structure of the argument list @var{lst}
354 in order to produce the result.
355 @end deffn
356
357 @deffn {Scheme Procedure} drop lst i
358 Return a list containing all but the first @var{i} elements of
359 @var{lst}.
360 @end deffn
361
362 @deffn {Scheme Procedure} take-right lst i
363 Return the a list containing the @var{i} last elements of @var{lst}.
364 @end deffn
365
366 @deffn {Scheme Procedure} drop-right lst i
367 @deffnx {Scheme Procedure} drop-right! lst i
368 Return the a list containing all but the @var{i} last elements of
369 @var{lst}.
370
371 @code{drop-right!} may modify the structure of the argument list
372 @var{lst} in order to produce the result.
373 @end deffn
374
375 @deffn {Scheme Procedure} split-at lst i
376 @deffnx {Scheme Procedure} split-at! lst i
377 Return two values, a list containing the first @var{i} elements of the
378 list @var{lst} and a list containing the remaining elements.
379
380 @code{split-at!} may modify the structure of the argument list
381 @var{lst} in order to produce the result.
382 @end deffn
383
384 @deffn {Scheme Procedure} last lst
385 Return the last element of the non-empty, finite list @var{lst}.
386 @end deffn
387
388
389 @node SRFI-1 Length Append etc
390 @subsubsection Length, Append, Concatenate, etc.
391
392 @c FIXME::martin: Review me!
393
394 @deffn {Scheme Procedure} length+ lst
395 Return the length of the argument list @var{lst}. When @var{lst} is a
396 circular list, @code{#f} is returned.
397 @end deffn
398
399 @deffn {Scheme Procedure} concatenate list-of-lists
400 @deffnx {Scheme Procedure} concatenate! list-of-lists
401 Construct a list by appending all lists in @var{list-of-lists}.
402
403 @code{concatenate!} may modify the structure of the given lists in
404 order to produce the result.
405
406 @code{concatenate} is the same as @code{(apply append
407 @var{list-of-lists})}. It exists because some Scheme implementations
408 have a limit on the number of arguments a function takes, which the
409 @code{apply} might exceed. In Guile there is no such limit.
410 @end deffn
411
412 @deffn {Scheme Procedure} append-reverse rev-head tail
413 @deffnx {Scheme Procedure} append-reverse! rev-head tail
414 Reverse @var{rev-head}, append @var{tail} and return the result. This
415 is equivalent to @code{(append (reverse @var{rev-head}) @var{tail})},
416 but more efficient.
417
418 @code{append-reverse!} may modify @var{rev-head} in order to produce
419 the result.
420 @end deffn
421
422 @deffn {Scheme Procedure} zip lst1 lst2 @dots{}
423 Return a list as long as the shortest of the argument lists, where
424 each element is a list. The first list contains the first elements of
425 the argument lists, the second list contains the second elements, and
426 so on.
427 @end deffn
428
429 @deffn {Scheme Procedure} unzip1 lst
430 @deffnx {Scheme Procedure} unzip2 lst
431 @deffnx {Scheme Procedure} unzip3 lst
432 @deffnx {Scheme Procedure} unzip4 lst
433 @deffnx {Scheme Procedure} unzip5 lst
434 @code{unzip1} takes a list of lists, and returns a list containing the
435 first elements of each list, @code{unzip2} returns two lists, the
436 first containing the first elements of each lists and the second
437 containing the second elements of each lists, and so on.
438 @end deffn
439
440 @deffn {Scheme Procedure} count pred lst1 @dots{} lstN
441 Return a count of the number of times @var{pred} returns true when
442 called on elements from the given lists.
443
444 @var{pred} is called with @var{N} parameters @code{(@var{pred}
445 @var{elem1} @dots{} @var{elemN})}, each element being from the
446 corresponding @var{lst1} @dots{} @var{lstN}. The first call is with
447 the first element of each list, the second with the second element
448 from each, and so on.
449
450 Counting stops when the end of the shortest list is reached. At least
451 one list must be non-circular.
452 @end deffn
453
454
455 @node SRFI-1 Fold and Map
456 @subsubsection Fold, Unfold & Map
457 @cindex list fold
458 @cindex list map
459
460 @c FIXME::martin: Review me!
461
462 @deffn {Scheme Procedure} fold proc init lst1 @dots{} lstN
463 @deffnx {Scheme Procedure} fold-right proc init lst1 @dots{} lstN
464 Apply @var{proc} to the elements of @var{lst1} @dots{} @var{lstN} to
465 build a result, and return that result.
466
467 Each @var{proc} call is @code{(@var{proc} @var{elem1} @dots{}
468 @var{elemN} @var{previous})}, where @var{elem1} is from @var{lst1},
469 through @var{elemN} from @var{lstN}. @var{previous} is the return
470 from the previous call to @var{proc}, or the given @var{init} for the
471 first call. If any list is empty, just @var{init} is returned.
472
473 @code{fold} works through the list elements from first to last. The
474 following shows a list reversal and the calls it makes,
475
476 @example
477 (fold cons '() '(1 2 3))
478
479 (cons 1 '())
480 (cons 2 '(1))
481 (cons 3 '(2 1)
482 @result{} (3 2 1)
483 @end example
484
485 @code{fold-right} works through the list elements from last to first,
486 ie.@: from the right. So for example the following finds the longest
487 string, and the last among equal longest,
488
489 @example
490 (fold-right (lambda (str prev)
491 (if (> (string-length str) (string-length prev))
492 str
493 prev))
494 ""
495 '("x" "abc" "xyz" "jk"))
496 @result{} "xyz"
497 @end example
498
499 If @var{lst1} through @var{lstN} have different lengths, @code{fold}
500 stops when the end of the shortest is reached; @code{fold-right}
501 commences at the last element of the shortest. Ie.@: elements past
502 the length of the shortest are ignored in the other @var{lst}s. At
503 least one @var{lst} must be non-circular.
504
505 @code{fold} should be preferred over @code{fold-right} if the order of
506 processing doesn't matter, or can be arranged either way, since
507 @code{fold} is a little more efficient.
508
509 The way @code{fold} builds a result from iterating is quite general,
510 it can do more than other iterations like say @code{map} or
511 @code{filter}. The following for example removes adjacent duplicate
512 elements from a list,
513
514 @example
515 (define (delete-adjacent-duplicates lst)
516 (fold-right (lambda (elem ret)
517 (if (equal? elem (first ret))
518 ret
519 (cons elem ret)))
520 (list (last lst))
521 lst))
522 (delete-adjacent-duplicates '(1 2 3 3 4 4 4 5))
523 @result{} (1 2 3 4 5)
524 @end example
525
526 Clearly the same sort of thing can be done with a @code{for-each} and
527 a variable in which to build the result, but a self-contained
528 @var{proc} can be re-used in multiple contexts, where a
529 @code{for-each} would have to be written out each time.
530 @end deffn
531
532 @deffn {Scheme Procedure} pair-fold proc init lst1 @dots{} lstN
533 @deffnx {Scheme Procedure} pair-fold-right proc init lst1 @dots{} lstN
534 The same as @code{fold} and @code{fold-right}, but apply @var{proc} to
535 the pairs of the lists instead of the list elements.
536 @end deffn
537
538 @deffn {Scheme Procedure} reduce proc default lst
539 @deffnx {Scheme Procedure} reduce-right proc default lst
540 @code{reduce} is a variant of @code{fold}, where the first call to
541 @var{proc} is on two elements from @var{lst}, rather than one element
542 and a given initial value.
543
544 If @var{lst} is empty, @code{reduce} returns @var{default} (this is
545 the only use for @var{default}). If @var{lst} has just one element
546 then that's the return value. Otherwise @var{proc} is called on the
547 elements of @var{lst}.
548
549 Each @var{proc} call is @code{(@var{proc} @var{elem} @var{previous})},
550 where @var{elem} is from @var{lst} (the second and subsequent elements
551 of @var{lst}), and @var{previous} is the return from the previous call
552 to @var{proc}. The first element of @var{lst} is the @var{previous}
553 for the first call to @var{proc}.
554
555 For example, the following adds a list of numbers, the calls made to
556 @code{+} are shown. (Of course @code{+} accepts multiple arguments
557 and can add a list directly, with @code{apply}.)
558
559 @example
560 (reduce + 0 '(5 6 7)) @result{} 18
561
562 (+ 6 5) @result{} 11
563 (+ 7 11) @result{} 18
564 @end example
565
566 @code{reduce} can be used instead of @code{fold} where the @var{init}
567 value is an ``identity'', meaning a value which under @var{proc}
568 doesn't change the result, in this case 0 is an identity since
569 @code{(+ 5 0)} is just 5. @code{reduce} avoids that unnecessary call.
570
571 @code{reduce-right} is a similar variation on @code{fold-right},
572 working from the end (ie.@: the right) of @var{lst}. The last element
573 of @var{lst} is the @var{previous} for the first call to @var{proc},
574 and the @var{elem} values go from the second last.
575
576 @code{reduce} should be preferred over @code{reduce-right} if the
577 order of processing doesn't matter, or can be arranged either way,
578 since @code{reduce} is a little more efficient.
579 @end deffn
580
581 @deffn {Scheme Procedure} unfold p f g seed [tail-gen]
582 @code{unfold} is defined as follows:
583
584 @lisp
585 (unfold p f g seed) =
586 (if (p seed) (tail-gen seed)
587 (cons (f seed)
588 (unfold p f g (g seed))))
589 @end lisp
590
591 @table @var
592 @item p
593 Determines when to stop unfolding.
594
595 @item f
596 Maps each seed value to the corresponding list element.
597
598 @item g
599 Maps each seed value to next seed valu.
600
601 @item seed
602 The state value for the unfold.
603
604 @item tail-gen
605 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
606 @end table
607
608 @var{g} produces a series of seed values, which are mapped to list
609 elements by @var{f}. These elements are put into a list in
610 left-to-right order, and @var{p} tells when to stop unfolding.
611 @end deffn
612
613 @deffn {Scheme Procedure} unfold-right p f g seed [tail]
614 Construct a list with the following loop.
615
616 @lisp
617 (let lp ((seed seed) (lis tail))
618 (if (p seed) lis
619 (lp (g seed)
620 (cons (f seed) lis))))
621 @end lisp
622
623 @table @var
624 @item p
625 Determines when to stop unfolding.
626
627 @item f
628 Maps each seed value to the corresponding list element.
629
630 @item g
631 Maps each seed value to next seed valu.
632
633 @item seed
634 The state value for the unfold.
635
636 @item tail-gen
637 Creates the tail of the list; defaults to @code{(lambda (x) '())}.
638 @end table
639
640 @end deffn
641
642 @deffn {Scheme Procedure} map f lst1 lst2 @dots{}
643 Map the procedure over the list(s) @var{lst1}, @var{lst2}, @dots{} and
644 return a list containing the results of the procedure applications.
645 This procedure is extended with respect to R5RS, because the argument
646 lists may have different lengths. The result list will have the same
647 length as the shortest argument lists. The order in which @var{f}
648 will be applied to the list element(s) is not specified.
649 @end deffn
650
651 @deffn {Scheme Procedure} for-each f lst1 lst2 @dots{}
652 Apply the procedure @var{f} to each pair of corresponding elements of
653 the list(s) @var{lst1}, @var{lst2}, @dots{}. The return value is not
654 specified. This procedure is extended with respect to R5RS, because
655 the argument lists may have different lengths. The shortest argument
656 list determines the number of times @var{f} is called. @var{f} will
657 be applied to the list elements in left-to-right order.
658
659 @end deffn
660
661 @deffn {Scheme Procedure} append-map f lst1 lst2 @dots{}
662 @deffnx {Scheme Procedure} append-map! f lst1 lst2 @dots{}
663 Equivalent to
664
665 @lisp
666 (apply append (map f clist1 clist2 ...))
667 @end lisp
668
669 and
670
671 @lisp
672 (apply append! (map f clist1 clist2 ...))
673 @end lisp
674
675 Map @var{f} over the elements of the lists, just as in the @code{map}
676 function. However, the results of the applications are appended
677 together to make the final result. @code{append-map} uses
678 @code{append} to append the results together; @code{append-map!} uses
679 @code{append!}.
680
681 The dynamic order in which the various applications of @var{f} are
682 made is not specified.
683 @end deffn
684
685 @deffn {Scheme Procedure} map! f lst1 lst2 @dots{}
686 Linear-update variant of @code{map} -- @code{map!} is allowed, but not
687 required, to alter the cons cells of @var{lst1} to construct the
688 result list.
689
690 The dynamic order in which the various applications of @var{f} are
691 made is not specified. In the n-ary case, @var{lst2}, @var{lst3},
692 @dots{} must have at least as many elements as @var{lst1}.
693 @end deffn
694
695 @deffn {Scheme Procedure} pair-for-each f lst1 lst2 @dots{}
696 Like @code{for-each}, but applies the procedure @var{f} to the pairs
697 from which the argument lists are constructed, instead of the list
698 elements. The return value is not specified.
699 @end deffn
700
701 @deffn {Scheme Procedure} filter-map f lst1 lst2 @dots{}
702 Like @code{map}, but only results from the applications of @var{f}
703 which are true are saved in the result list.
704 @end deffn
705
706
707 @node SRFI-1 Filtering and Partitioning
708 @subsubsection Filtering and Partitioning
709 @cindex list filter
710 @cindex list partition
711
712 @c FIXME::martin: Review me!
713
714 Filtering means to collect all elements from a list which satisfy a
715 specific condition. Partitioning a list means to make two groups of
716 list elements, one which contains the elements satisfying a condition,
717 and the other for the elements which don't.
718
719 The @code{filter} and @code{filter!} functions are implemented in the
720 Guile core, @xref{List Modification}.
721
722 @deffn {Scheme Procedure} partition pred lst
723 @deffnx {Scheme Procedure} partition! pred lst
724 Split @var{lst} into those elements which do and don't satisfy the
725 predicate @var{pred}.
726
727 The return is two values (@pxref{Multiple Values}), the first being a
728 list of all elements from @var{lst} which satisfy @var{pred}, the
729 second a list of those which do not.
730
731 The elements in the result lists are in the same order as in @var{lst}
732 but the order in which the calls @code{(@var{pred} elem)} are made on
733 the list elements is unspecified.
734
735 @code{partition} does not change @var{lst}, but one of the returned
736 lists may share a tail with it. @code{partition!} may modify
737 @var{lst} to construct its return.
738 @end deffn
739
740 @deffn {Scheme Procedure} remove pred lst
741 @deffnx {Scheme Procedure} remove! pred lst
742 Return a list containing all elements from @var{lst} which do not
743 satisfy the predicate @var{pred}. The elements in the result list
744 have the same order as in @var{lst}. The order in which @var{pred} is
745 applied to the list elements is not specified.
746
747 @code{remove!} is allowed, but not required to modify the structure of
748 the input list.
749 @end deffn
750
751
752 @node SRFI-1 Searching
753 @subsubsection Searching
754 @cindex list search
755
756 @c FIXME::martin: Review me!
757
758 The procedures for searching elements in lists either accept a
759 predicate or a comparison object for determining which elements are to
760 be searched.
761
762 @deffn {Scheme Procedure} find pred lst
763 Return the first element of @var{lst} which satisfies the predicate
764 @var{pred} and @code{#f} if no such element is found.
765 @end deffn
766
767 @deffn {Scheme Procedure} find-tail pred lst
768 Return the first pair of @var{lst} whose @sc{car} satisfies the
769 predicate @var{pred} and @code{#f} if no such element is found.
770 @end deffn
771
772 @deffn {Scheme Procedure} take-while pred lst
773 @deffnx {Scheme Procedure} take-while! pred lst
774 Return the longest initial prefix of @var{lst} whose elements all
775 satisfy the predicate @var{pred}.
776
777 @code{take-while!} is allowed, but not required to modify the input
778 list while producing the result.
779 @end deffn
780
781 @deffn {Scheme Procedure} drop-while pred lst
782 Drop the longest initial prefix of @var{lst} whose elements all
783 satisfy the predicate @var{pred}.
784 @end deffn
785
786 @deffn {Scheme Procedure} span pred lst
787 @deffnx {Scheme Procedure} span! pred lst
788 @deffnx {Scheme Procedure} break pred lst
789 @deffnx {Scheme Procedure} break! pred lst
790 @code{span} splits the list @var{lst} into the longest initial prefix
791 whose elements all satisfy the predicate @var{pred}, and the remaining
792 tail. @code{break} inverts the sense of the predicate.
793
794 @code{span!} and @code{break!} are allowed, but not required to modify
795 the structure of the input list @var{lst} in order to produce the
796 result.
797
798 Note that the name @code{break} conflicts with the @code{break}
799 binding established by @code{while} (@pxref{while do}). Applications
800 wanting to use @code{break} from within a @code{while} loop will need
801 to make a new define under a different name.
802 @end deffn
803
804 @deffn {Scheme Procedure} any pred lst1 lst2 @dots{} lstN
805 Test whether any set of elements from @var{lst1} @dots{} lstN
806 satisfies @var{pred}. If so the return value is the return from the
807 successful @var{pred} call, or if not the return is @code{#f}.
808
809 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
810 @var{elemN})} taking an element from each @var{lst}. The calls are
811 made successively for the first, second, etc elements of the lists,
812 stopping when @var{pred} returns non-@code{#f}, or when the end of the
813 shortest list is reached.
814
815 The @var{pred} call on the last set of elements (ie.@: when the end of
816 the shortest list has been reached), if that point is reached, is a
817 tail call.
818 @end deffn
819
820 @deffn {Scheme Procedure} every pred lst1 lst2 @dots{} lstN
821 Test whether every set of elements from @var{lst1} @dots{} lstN
822 satisfies @var{pred}. If so the return value is the return from the
823 final @var{pred} call, or if not the return is @code{#f}.
824
825 Each @var{pred} call is @code{(@var{pred} @var{elem1} @dots{}
826 @var{elemN})} taking an element from each @var{lst}. The calls are
827 made successively for the first, second, etc elements of the lists,
828 stopping if @var{pred} returns @code{#f}, or when the end of any of
829 the lists is reached.
830
831 The @var{pred} call on the last set of elements (ie.@: when the end of
832 the shortest list has been reached) is a tail call.
833
834 If one of @var{lst1} @dots{} @var{lstN} is empty then no calls to
835 @var{pred} are made, and the return is @code{#t}.
836 @end deffn
837
838 @deffn {Scheme Procedure} list-index pred lst1 @dots{} lstN
839 Return the index of the first set of elements, one from each of
840 @var{lst1}@dots{}@var{lstN}, which satisfies @var{pred}.
841
842 @var{pred} is called as @code{(@var{pred} elem1 @dots{} elemN)}.
843 Searching stops when the end of the shortest @var{lst} is reached.
844 The return index starts from 0 for the first set of elements. If no
845 set of elements pass then the return is @code{#f}.
846
847 @example
848 (list-index odd? '(2 4 6 9)) @result{} 3
849 (list-index = '(1 2 3) '(3 1 2)) @result{} #f
850 @end example
851 @end deffn
852
853 @deffn {Scheme Procedure} member x lst [=]
854 Return the first sublist of @var{lst} whose @sc{car} is equal to
855 @var{x}. If @var{x} does not appear in @var{lst}, return @code{#f}.
856
857 Equality is determined by @code{equal?}, or by the equality predicate
858 @var{=} if given. @var{=} is called @code{(= @var{x} elem)},
859 ie.@: with the given @var{x} first, so for example to find the first
860 element greater than 5,
861
862 @example
863 (member 5 '(3 5 1 7 2 9) <) @result{} (7 2 9)
864 @end example
865
866 This version of @code{member} extends the core @code{member}
867 (@pxref{List Searching}) by accepting an equality predicate.
868 @end deffn
869
870
871 @node SRFI-1 Deleting
872 @subsubsection Deleting
873 @cindex list delete
874
875 @deffn {Scheme Procedure} delete x lst [=]
876 @deffnx {Scheme Procedure} delete! x lst [=]
877 Return a list containing the elements of @var{lst} but with those
878 equal to @var{x} deleted. The returned elements will be in the same
879 order as they were in @var{lst}.
880
881 Equality is determined by the @var{=} predicate, or @code{equal?} if
882 not given. An equality call is made just once for each element, but
883 the order in which the calls are made on the elements is unspecified.
884
885 The equality calls are always @code{(= x elem)}, ie.@: the given @var{x}
886 is first. This means for instance elements greater than 5 can be
887 deleted with @code{(delete 5 lst <)}.
888
889 @code{delete} does not modify @var{lst}, but the return might share a
890 common tail with @var{lst}. @code{delete!} may modify the structure
891 of @var{lst} to construct its return.
892
893 These functions extend the core @code{delete} and @code{delete!}
894 (@pxref{List Modification}) in accepting an equality predicate. See
895 also @code{lset-difference} (@pxref{SRFI-1 Set Operations}) for
896 deleting multiple elements from a list.
897 @end deffn
898
899 @deffn {Scheme Procedure} delete-duplicates lst [=]
900 @deffnx {Scheme Procedure} delete-duplicates! lst [=]
901 Return a list containing the elements of @var{lst} but without
902 duplicates.
903
904 When elements are equal, only the first in @var{lst} is retained.
905 Equal elements can be anywhere in @var{lst}, they don't have to be
906 adjacent. The returned list will have the retained elements in the
907 same order as they were in @var{lst}.
908
909 Equality is determined by the @var{=} predicate, or @code{equal?} if
910 not given. Calls @code{(= x y)} are made with element @var{x} being
911 before @var{y} in @var{lst}. A call is made at most once for each
912 combination, but the sequence of the calls across the elements is
913 unspecified.
914
915 @code{delete-duplicates} does not modify @var{lst}, but the return
916 might share a common tail with @var{lst}. @code{delete-duplicates!}
917 may modify the structure of @var{lst} to construct its return.
918
919 In the worst case, this is an @math{O(N^2)} algorithm because it must
920 check each element against all those preceding it. For long lists it
921 is more efficient to sort and then compare only adjacent elements.
922 @end deffn
923
924
925 @node SRFI-1 Association Lists
926 @subsubsection Association Lists
927 @cindex association list
928 @cindex alist
929
930 @c FIXME::martin: Review me!
931
932 Association lists are described in detail in section @ref{Association
933 Lists}. The present section only documents the additional procedures
934 for dealing with association lists defined by SRFI-1.
935
936 @deffn {Scheme Procedure} assoc key alist [=]
937 Return the pair from @var{alist} which matches @var{key}. Equality is
938 determined by @var{=}, which defaults to @code{equal?} if not given.
939 @var{alist} must be an association lists---a list of pairs.
940
941 This function extends the core @code{assoc} by accepting an equality
942 predicate. (@pxref{Association Lists})
943 @end deffn
944
945 @deffn {Scheme Procedure} alist-cons key datum alist
946 Cons a new association @var{key} and @var{datum} onto @var{alist} and
947 return the result. This is equivalent to
948
949 @lisp
950 (cons (cons @var{key} @var{datum}) @var{alist})
951 @end lisp
952
953 @code{acons} (@pxref{Adding or Setting Alist Entries}) in the Guile
954 core does the same thing.
955 @end deffn
956
957 @deffn {Scheme Procedure} alist-copy alist
958 Return a newly allocated copy of @var{alist}, that means that the
959 spine of the list as well as the pairs are copied.
960 @end deffn
961
962 @deffn {Scheme Procedure} alist-delete key alist [=]
963 @deffnx {Scheme Procedure} alist-delete! key alist [=]
964 Return a list containing the elements of @var{alist} but with those
965 elements whose keys are equal to @var{key} deleted. The returned
966 elements will be in the same order as they were in @var{alist}.
967
968 Equality is determined by the @var{=} predicate, or @code{equal?} if
969 not given. The order in which elements are tested is unspecified, but
970 each equality call is made @code{(= key alistkey)}, ie. the given
971 @var{key} parameter is first and the key from @var{alist} second.
972 This means for instance all associations with a key greater than 5 can
973 be removed with @code{(alist-delete 5 alist <)}.
974
975 @code{alist-delete} does not modify @var{alist}, but the return might
976 share a common tail with @var{alist}. @code{alist-delete!} may modify
977 the list structure of @var{alist} to construct its return.
978 @end deffn
979
980
981 @node SRFI-1 Set Operations
982 @subsubsection Set Operations on Lists
983 @cindex list set operation
984
985 Lists can be used to represent sets of objects. The procedures in
986 this section operate on such lists as sets.
987
988 Note that lists are not an efficient way to implement large sets. The
989 procedures here typically take time @math{@var{m}@cross{}@var{n}} when
990 operating on @var{m} and @var{n} element lists. Other data structures
991 like trees, bitsets (@pxref{Bit Vectors}) or hash tables (@pxref{Hash
992 Tables}) are faster.
993
994 All these procedures take an equality predicate as the first argument.
995 This predicate is used for testing the objects in the list sets for
996 sameness. This predicate must be consistent with @code{eq?}
997 (@pxref{Equality}) in the sense that if two list elements are
998 @code{eq?} then they must also be equal under the predicate. This
999 simply means a given object must be equal to itself.
1000
1001 @deffn {Scheme Procedure} lset<= = list1 list2 @dots{}
1002 Return @code{#t} if each list is a subset of the one following it.
1003 Ie.@: @var{list1} a subset of @var{list2}, @var{list2} a subset of
1004 @var{list3}, etc, for as many lists as given. If only one list or no
1005 lists are given then the return is @code{#t}.
1006
1007 A list @var{x} is a subset of @var{y} if each element of @var{x} is
1008 equal to some element in @var{y}. Elements are compared using the
1009 given @var{=} procedure, called as @code{(@var{=} xelem yelem)}.
1010
1011 @example
1012 (lset<= eq?) @result{} #t
1013 (lset<= eqv? '(1 2 3) '(1)) @result{} #f
1014 (lset<= eqv? '(1 3 2) '(4 3 1 2)) @result{} #t
1015 @end example
1016 @end deffn
1017
1018 @deffn {Scheme Procedure} lset= = list1 list2 @dots{}
1019 Return @code{#t} if all argument lists are set-equal. @var{list1} is
1020 compared to @var{list2}, @var{list2} to @var{list3}, etc, for as many
1021 lists as given. If only one list or no lists are given then the
1022 return is @code{#t}.
1023
1024 Two lists @var{x} and @var{y} are set-equal if each element of @var{x}
1025 is equal to some element of @var{y} and conversely each element of
1026 @var{y} is equal to some element of @var{x}. The order of the
1027 elements in the lists doesn't matter. Element equality is determined
1028 with the given @var{=} procedure, called as @code{(@var{=} xelem
1029 yelem)}, but exactly which calls are made is unspecified.
1030
1031 @example
1032 (lset= eq?) @result{} #t
1033 (lset= eqv? '(1 2 3) '(3 2 1)) @result{} #t
1034 (lset= string-ci=? '("a" "A" "b") '("B" "b" "a")) @result{} #t
1035 @end example
1036 @end deffn
1037
1038 @deffn {Scheme Procedure} lset-adjoin = list elem1 @dots{}
1039 Add to @var{list} any of the given @var{elem}s not already in the
1040 list. @var{elem}s are @code{cons}ed onto the start of @var{list} (so
1041 the return shares a common tail with @var{list}), but the order
1042 they're added is unspecified.
1043
1044 The given @var{=} procedure is used for comparing elements, called as
1045 @code{(@var{=} listelem elem)}, ie.@: the second argument is one of
1046 the given @var{elem} parameters.
1047
1048 @example
1049 (lset-adjoin eqv? '(1 2 3) 4 1 5) @result{} (5 4 1 2 3)
1050 @end example
1051 @end deffn
1052
1053 @deffn {Scheme Procedure} lset-union = list1 list2 @dots{}
1054 @deffnx {Scheme Procedure} lset-union! = list1 list2 @dots{}
1055 Return the union of the argument list sets. The result is built by
1056 taking the union of @var{list1} and @var{list2}, then the union of
1057 that with @var{list3}, etc, for as many lists as given. For one list
1058 argument that list itself is the result, for no list arguments the
1059 result is the empty list.
1060
1061 The union of two lists @var{x} and @var{y} is formed as follows. If
1062 @var{x} is empty then the result is @var{y}. Otherwise start with
1063 @var{x} as the result and consider each @var{y} element (from first to
1064 last). A @var{y} element not equal to something already in the result
1065 is @code{cons}ed onto the result.
1066
1067 The given @var{=} procedure is used for comparing elements, called as
1068 @code{(@var{=} relem yelem)}. The first argument is from the result
1069 accumulated so far, and the second is from the list being union-ed in.
1070 But exactly which calls are made is otherwise unspecified.
1071
1072 Notice that duplicate elements in @var{list1} (or the first non-empty
1073 list) are preserved, but that repeated elements in subsequent lists
1074 are only added once.
1075
1076 @example
1077 (lset-union eqv?) @result{} ()
1078 (lset-union eqv? '(1 2 3)) @result{} (1 2 3)
1079 (lset-union eqv? '(1 2 1 3) '(2 4 5) '(5)) @result{} (5 4 1 2 1 3)
1080 @end example
1081
1082 @code{lset-union} doesn't change the given lists but the result may
1083 share a tail with the first non-empty list. @code{lset-union!} can
1084 modify all of the given lists to form the result.
1085 @end deffn
1086
1087 @deffn {Scheme Procedure} lset-intersection = list1 list2 @dots{}
1088 @deffnx {Scheme Procedure} lset-intersection! = list1 list2 @dots{}
1089 Return the intersection of @var{list1} with the other argument lists,
1090 meaning those elements of @var{list1} which are also in all of
1091 @var{list2} etc. For one list argument, just that list is returned.
1092
1093 The test for an element of @var{list1} to be in the return is simply
1094 that it's equal to some element in each of @var{list2} etc. Notice
1095 this means an element appearing twice in @var{list1} but only once in
1096 each of @var{list2} etc will go into the return twice. The return has
1097 its elements in the same order as they were in @var{list1}.
1098
1099 The given @var{=} procedure is used for comparing elements, called as
1100 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1101 and the second is from one of the subsequent lists. But exactly which
1102 calls are made and in what order is unspecified.
1103
1104 @example
1105 (lset-intersection eqv? '(x y)) @result{} (x y)
1106 (lset-intersection eqv? '(1 2 3) '(4 3 2)) @result{} (2 3)
1107 (lset-intersection eqv? '(1 1 2 2) '(1 2) '(2 1) '(2)) @result{} (2 2)
1108 @end example
1109
1110 The return from @code{lset-intersection} may share a tail with
1111 @var{list1}. @code{lset-intersection!} may modify @var{list1} to form
1112 its result.
1113 @end deffn
1114
1115 @deffn {Scheme Procedure} lset-difference = list1 list2 @dots{}
1116 @deffnx {Scheme Procedure} lset-difference! = list1 list2 @dots{}
1117 Return @var{list1} with any elements in @var{list2}, @var{list3} etc
1118 removed (ie.@: subtracted). For one list argument, just that list is
1119 returned.
1120
1121 The given @var{=} procedure is used for comparing elements, called as
1122 @code{(@var{=} elem1 elemN)}. The first argument is from @var{list1}
1123 and the second from one of the subsequent lists. But exactly which
1124 calls are made and in what order is unspecified.
1125
1126 @example
1127 (lset-difference eqv? '(x y)) @result{} (x y)
1128 (lset-difference eqv? '(1 2 3) '(3 1)) @result{} (2)
1129 (lset-difference eqv? '(1 2 3) '(3) '(2)) @result{} (1)
1130 @end example
1131
1132 The return from @code{lset-difference} may share a tail with
1133 @var{list1}. @code{lset-difference!} may modify @var{list1} to form
1134 its result.
1135 @end deffn
1136
1137 @deffn {Scheme Procedure} lset-diff+intersection = list1 list2 @dots{}
1138 @deffnx {Scheme Procedure} lset-diff+intersection! = list1 list2 @dots{}
1139 Return two values (@pxref{Multiple Values}), the difference and
1140 intersection of the argument lists as per @code{lset-difference} and
1141 @code{lset-intersection} above.
1142
1143 For two list arguments this partitions @var{list1} into those elements
1144 of @var{list1} which are in @var{list2} and not in @var{list2}. (But
1145 for more than two arguments there can be elements of @var{list1} which
1146 are neither part of the difference nor the intersection.)
1147
1148 One of the return values from @code{lset-diff+intersection} may share
1149 a tail with @var{list1}. @code{lset-diff+intersection!} may modify
1150 @var{list1} to form its results.
1151 @end deffn
1152
1153 @deffn {Scheme Procedure} lset-xor = list1 list2 @dots{}
1154 @deffnx {Scheme Procedure} lset-xor! = list1 list2 @dots{}
1155 Return an XOR of the argument lists. For two lists this means those
1156 elements which are in exactly one of the lists. For more than two
1157 lists it means those elements which appear in an odd number of the
1158 lists.
1159
1160 To be precise, the XOR of two lists @var{x} and @var{y} is formed by
1161 taking those elements of @var{x} not equal to any element of @var{y},
1162 plus those elements of @var{y} not equal to any element of @var{x}.
1163 Equality is determined with the given @var{=} procedure, called as
1164 @code{(@var{=} e1 e2)}. One argument is from @var{x} and the other
1165 from @var{y}, but which way around is unspecified. Exactly which
1166 calls are made is also unspecified, as is the order of the elements in
1167 the result.
1168
1169 @example
1170 (lset-xor eqv? '(x y)) @result{} (x y)
1171 (lset-xor eqv? '(1 2 3) '(4 3 2)) @result{} (4 1)
1172 @end example
1173
1174 The return from @code{lset-xor} may share a tail with one of the list
1175 arguments. @code{lset-xor!} may modify @var{list1} to form its
1176 result.
1177 @end deffn
1178
1179
1180 @node SRFI-2
1181 @subsection SRFI-2 - and-let*
1182 @cindex SRFI-2
1183
1184 @noindent
1185 The following syntax can be obtained with
1186
1187 @lisp
1188 (use-modules (srfi srfi-2))
1189 @end lisp
1190
1191 @deffn {library syntax} and-let* (clause @dots{}) body @dots{}
1192 A combination of @code{and} and @code{let*}.
1193
1194 Each @var{clause} is evaluated in turn, and if @code{#f} is obtained
1195 then evaluation stops and @code{#f} is returned. If all are
1196 non-@code{#f} then @var{body} is evaluated and the last form gives the
1197 return value, or if @var{body} is empty then the result is @code{#t}.
1198 Each @var{clause} should be one of the following,
1199
1200 @table @code
1201 @item (symbol expr)
1202 Evaluate @var{expr}, check for @code{#f}, and bind it to @var{symbol}.
1203 Like @code{let*}, that binding is available to subsequent clauses.
1204 @item (expr)
1205 Evaluate @var{expr} and check for @code{#f}.
1206 @item symbol
1207 Get the value bound to @var{symbol} and check for @code{#f}.
1208 @end table
1209
1210 Notice that @code{(expr)} has an ``extra'' pair of parentheses, for
1211 instance @code{((eq? x y))}. One way to remember this is to imagine
1212 the @code{symbol} in @code{(symbol expr)} is omitted.
1213
1214 @code{and-let*} is good for calculations where a @code{#f} value means
1215 termination, but where a non-@code{#f} value is going to be needed in
1216 subsequent expressions.
1217
1218 The following illustrates this, it returns text between brackets
1219 @samp{[...]} in a string, or @code{#f} if there are no such brackets
1220 (ie.@: either @code{string-index} gives @code{#f}).
1221
1222 @example
1223 (define (extract-brackets str)
1224 (and-let* ((start (string-index str #\[))
1225 (end (string-index str #\] start)))
1226 (substring str (1+ start) end)))
1227 @end example
1228
1229 The following shows plain variables and expressions tested too.
1230 @code{diagnostic-levels} is taken to be an alist associating a
1231 diagnostic type with a level. @code{str} is printed only if the type
1232 is known and its level is high enough.
1233
1234 @example
1235 (define (show-diagnostic type str)
1236 (and-let* (want-diagnostics
1237 (level (assq-ref diagnostic-levels type))
1238 ((>= level current-diagnostic-level)))
1239 (display str)))
1240 @end example
1241
1242 The advantage of @code{and-let*} is that an extended sequence of
1243 expressions and tests doesn't require lots of nesting as would arise
1244 from separate @code{and} and @code{let*}, or from @code{cond} with
1245 @code{=>}.
1246
1247 @end deffn
1248
1249
1250 @node SRFI-4
1251 @subsection SRFI-4 - Homogeneous numeric vector datatypes
1252 @cindex SRFI-4
1253
1254 The SRFI-4 procedures and data types are always available, @xref{Uniform
1255 Numeric Vectors}.
1256
1257 @node SRFI-6
1258 @subsection SRFI-6 - Basic String Ports
1259 @cindex SRFI-6
1260
1261 SRFI-6 defines the procedures @code{open-input-string},
1262 @code{open-output-string} and @code{get-output-string}. These
1263 procedures are included in the Guile core, so using this module does not
1264 make any difference at the moment. But it is possible that support for
1265 SRFI-6 will be factored out of the core library in the future, so using
1266 this module does not hurt, after all.
1267
1268 @node SRFI-8
1269 @subsection SRFI-8 - receive
1270 @cindex SRFI-8
1271
1272 @code{receive} is a syntax for making the handling of multiple-value
1273 procedures easier. It is documented in @xref{Multiple Values}.
1274
1275
1276 @node SRFI-9
1277 @subsection SRFI-9 - define-record-type
1278 @cindex SRFI-9
1279 @cindex record
1280
1281 This SRFI is a syntax for defining new record types and creating
1282 predicate, constructor, and field getter and setter functions. In
1283 Guile this is simply an alternate interface to the core record
1284 functionality (@pxref{Records}). It can be used with,
1285
1286 @example
1287 (use-modules (srfi srfi-9))
1288 @end example
1289
1290 @deffn {library syntax} define-record-type type @* (constructor fieldname @dots{}) @* predicate @* (fieldname accessor [modifier]) @dots{}
1291 @sp 1
1292 Create a new record type, and make various @code{define}s for using
1293 it. This syntax can only occur at the top-level, not nested within
1294 some other form.
1295
1296 @var{type} is bound to the record type, which is as per the return
1297 from the core @code{make-record-type}. @var{type} also provides the
1298 name for the record, as per @code{record-type-name}.
1299
1300 @var{constructor} is bound to a function to be called as
1301 @code{(@var{constructor} fieldval @dots{})} to create a new record of
1302 this type. The arguments are initial values for the fields, one
1303 argument for each field, in the order they appear in the
1304 @code{define-record-type} form.
1305
1306 The @var{fieldname}s provide the names for the record fields, as per
1307 the core @code{record-type-fields} etc, and are referred to in the
1308 subsequent accessor/modifier forms.
1309
1310 @var{predictate} is bound to a function to be called as
1311 @code{(@var{predicate} obj)}. It returns @code{#t} or @code{#f}
1312 according to whether @var{obj} is a record of this type.
1313
1314 Each @var{accessor} is bound to a function to be called
1315 @code{(@var{accessor} record)} to retrieve the respective field from a
1316 @var{record}. Similarly each @var{modifier} is bound to a function to
1317 be called @code{(@var{modifier} record val)} to set the respective
1318 field in a @var{record}.
1319 @end deffn
1320
1321 @noindent
1322 An example will illustrate typical usage,
1323
1324 @example
1325 (define-record-type employee-type
1326 (make-employee name age salary)
1327 employee?
1328 (name get-employee-name)
1329 (age get-employee-age set-employee-age)
1330 (salary get-employee-salary set-employee-salary))
1331 @end example
1332
1333 This creates a new employee data type, with name, age and salary
1334 fields. Accessor functions are created for each field, but no
1335 modifier function for the name (the intention in this example being
1336 that it's established only when an employee object is created). These
1337 can all then be used as for example,
1338
1339 @example
1340 employee-type @result{} #<record-type employee-type>
1341
1342 (define fred (make-employee "Fred" 45 20000.00))
1343
1344 (employee? fred) @result{} #t
1345 (get-employee-age fred) @result{} 45
1346 (set-employee-salary fred 25000.00) ;; pay rise
1347 @end example
1348
1349 The functions created by @code{define-record-type} are ordinary
1350 top-level @code{define}s. They can be redefined or @code{set!} as
1351 desired, exported from a module, etc.
1352
1353
1354 @node SRFI-10
1355 @subsection SRFI-10 - Hash-Comma Reader Extension
1356 @cindex SRFI-10
1357
1358 @cindex hash-comma
1359 @cindex #,()
1360 This SRFI implements a reader extension @code{#,()} called hash-comma.
1361 It allows the reader to give new kinds of objects, for use both in
1362 data and as constants or literals in source code. This feature is
1363 available with
1364
1365 @example
1366 (use-modules (srfi srfi-10))
1367 @end example
1368
1369 @noindent
1370 The new read syntax is of the form
1371
1372 @example
1373 #,(@var{tag} @var{arg}@dots{})
1374 @end example
1375
1376 @noindent
1377 where @var{tag} is a symbol and the @var{arg}s are objects taken as
1378 parameters. @var{tag}s are registered with the following procedure.
1379
1380 @deffn {Scheme Procedure} define-reader-ctor tag proc
1381 Register @var{proc} as the constructor for a hash-comma read syntax
1382 starting with symbol @var{tag}, ie. @nicode{#,(@var{tag} arg@dots{})}.
1383 @var{proc} is called with the given arguments @code{(@var{proc}
1384 arg@dots{})} and the object it returns is the result of the read.
1385 @end deffn
1386
1387 @noindent
1388 For example, a syntax giving a list of @var{N} copies of an object.
1389
1390 @example
1391 (define-reader-ctor 'repeat
1392 (lambda (obj reps)
1393 (make-list reps obj)))
1394
1395 (display '#,(repeat 99 3))
1396 @print{} (99 99 99)
1397 @end example
1398
1399 Notice the quote @nicode{'} when the @nicode{#,( )} is used. The
1400 @code{repeat} handler returns a list and the program must quote to use
1401 it literally, the same as any other list. Ie.
1402
1403 @example
1404 (display '#,(repeat 99 3))
1405 @result{}
1406 (display '(99 99 99))
1407 @end example
1408
1409 When a handler returns an object which is self-evaluating, like a
1410 number or a string, then there's no need for quoting, just as there's
1411 no need when giving those directly as literals. For example an
1412 addition,
1413
1414 @example
1415 (define-reader-ctor 'sum
1416 (lambda (x y)
1417 (+ x y)))
1418 (display #,(sum 123 456)) @print{} 579
1419 @end example
1420
1421 A typical use for @nicode{#,()} is to get a read syntax for objects
1422 which don't otherwise have one. For example, the following allows a
1423 hash table to be given literally, with tags and values, ready for fast
1424 lookup.
1425
1426 @example
1427 (define-reader-ctor 'hash
1428 (lambda elems
1429 (let ((table (make-hash-table)))
1430 (for-each (lambda (elem)
1431 (apply hash-set! table elem))
1432 elems)
1433 table)))
1434
1435 (define (animal->family animal)
1436 (hash-ref '#,(hash ("tiger" "cat")
1437 ("lion" "cat")
1438 ("wolf" "dog"))
1439 animal))
1440
1441 (animal->family "lion") @result{} "cat"
1442 @end example
1443
1444 Or for example the following is a syntax for a compiled regular
1445 expression (@pxref{Regular Expressions}).
1446
1447 @example
1448 (use-modules (ice-9 regex))
1449
1450 (define-reader-ctor 'regexp make-regexp)
1451
1452 (define (extract-angs str)
1453 (let ((match (regexp-exec '#,(regexp "<([A-Z0-9]+)>") str)))
1454 (and match
1455 (match:substring match 1))))
1456
1457 (extract-angs "foo <BAR> quux") @result{} "BAR"
1458 @end example
1459
1460 @sp 1
1461 @nicode{#,()} is somewhat similar to @code{define-macro}
1462 (@pxref{Macros}) in that handler code is run to produce a result, but
1463 @nicode{#,()} operates at the read stage, so it can appear in data for
1464 @code{read} (@pxref{Scheme Read}), not just in code to be executed.
1465
1466 Because @nicode{#,()} is handled at read-time it has no direct access
1467 to variables etc. A symbol in the arguments is just a symbol, not a
1468 variable reference. The arguments are essentially constants, though
1469 the handler procedure can use them in any complicated way it might
1470 want.
1471
1472 Once @code{(srfi srfi-10)} has loaded, @nicode{#,()} is available
1473 globally, there's no need to use @code{(srfi srfi-10)} in later
1474 modules. Similarly the tags registered are global and can be used
1475 anywhere once registered.
1476
1477 There's no attempt to record what previous @nicode{#,()} forms have
1478 been seen, if two identical forms occur then two calls are made to the
1479 handler procedure. The handler might like to maintain a cache or
1480 similar to avoid making copies of large objects, depending on expected
1481 usage.
1482
1483 In code the best uses of @nicode{#,()} are generally when there's a
1484 lot of objects of a particular kind as literals or constants. If
1485 there's just a few then some local variables and initializers are
1486 fine, but that becomes tedious and error prone when there's a lot, and
1487 the anonymous and compact syntax of @nicode{#,()} is much better.
1488
1489
1490 @node SRFI-11
1491 @subsection SRFI-11 - let-values
1492 @cindex SRFI-11
1493
1494 @findex let-values
1495 @findex let-values*
1496 This module implements the binding forms for multiple values
1497 @code{let-values} and @code{let-values*}. These forms are similar to
1498 @code{let} and @code{let*} (@pxref{Local Bindings}), but they support
1499 binding of the values returned by multiple-valued expressions.
1500
1501 Write @code{(use-modules (srfi srfi-11))} to make the bindings
1502 available.
1503
1504 @lisp
1505 (let-values (((x y) (values 1 2))
1506 ((z f) (values 3 4)))
1507 (+ x y z f))
1508 @result{}
1509 10
1510 @end lisp
1511
1512 @code{let-values} performs all bindings simultaneously, which means that
1513 no expression in the binding clauses may refer to variables bound in the
1514 same clause list. @code{let-values*}, on the other hand, performs the
1515 bindings sequentially, just like @code{let*} does for single-valued
1516 expressions.
1517
1518
1519 @node SRFI-13
1520 @subsection SRFI-13 - String Library
1521 @cindex SRFI-13
1522
1523 The SRFI-13 procedures are always available, @xref{Strings}.
1524
1525 @node SRFI-14
1526 @subsection SRFI-14 - Character-set Library
1527 @cindex SRFI-14
1528
1529 The SRFI-14 data type and procedures are always available,
1530 @xref{Character Sets}.
1531
1532 @node SRFI-16
1533 @subsection SRFI-16 - case-lambda
1534 @cindex SRFI-16
1535 @cindex variable arity
1536 @cindex arity, variable
1537
1538 @c FIXME::martin: Review me!
1539
1540 @findex case-lambda
1541 The syntactic form @code{case-lambda} creates procedures, just like
1542 @code{lambda}, but has syntactic extensions for writing procedures of
1543 varying arity easier.
1544
1545 The syntax of the @code{case-lambda} form is defined in the following
1546 EBNF grammar.
1547
1548 @example
1549 @group
1550 <case-lambda>
1551 --> (case-lambda <case-lambda-clause>)
1552 <case-lambda-clause>
1553 --> (<formals> <definition-or-command>*)
1554 <formals>
1555 --> (<identifier>*)
1556 | (<identifier>* . <identifier>)
1557 | <identifier>
1558 @end group
1559 @end example
1560
1561 The value returned by a @code{case-lambda} form is a procedure which
1562 matches the number of actual arguments against the formals in the
1563 various clauses, in order. @dfn{Formals} means a formal argument list
1564 just like with @code{lambda} (@pxref{Lambda}). The first matching clause
1565 is selected, the corresponding values from the actual parameter list are
1566 bound to the variable names in the clauses and the body of the clause is
1567 evaluated. If no clause matches, an error is signalled.
1568
1569 The following (silly) definition creates a procedure @var{foo} which
1570 acts differently, depending on the number of actual arguments. If one
1571 argument is given, the constant @code{#t} is returned, two arguments are
1572 added and if more arguments are passed, their product is calculated.
1573
1574 @lisp
1575 (define foo (case-lambda
1576 ((x) #t)
1577 ((x y) (+ x y))
1578 (z
1579 (apply * z))))
1580 (foo 'bar)
1581 @result{}
1582 #t
1583 (foo 2 4)
1584 @result{}
1585 6
1586 (foo 3 3 3)
1587 @result{}
1588 27
1589 (foo)
1590 @result{}
1591 1
1592 @end lisp
1593
1594 The last expression evaluates to 1 because the last clause is matched,
1595 @var{z} is bound to the empty list and the following multiplication,
1596 applied to zero arguments, yields 1.
1597
1598
1599 @node SRFI-17
1600 @subsection SRFI-17 - Generalized set!
1601 @cindex SRFI-17
1602
1603 This is an implementation of SRFI-17: Generalized set!
1604
1605 @findex getter-with-setter
1606 It exports the Guile procedure @code{make-procedure-with-setter} under
1607 the SRFI name @code{getter-with-setter} and exports the standard
1608 procedures @code{car}, @code{cdr}, @dots{}, @code{cdddr},
1609 @code{string-ref} and @code{vector-ref} as procedures with setters, as
1610 required by the SRFI.
1611
1612 SRFI-17 was heavily criticized during its discussion period but it was
1613 finalized anyway. One issue was its concept of globally associating
1614 setter @dfn{properties} with (procedure) values, which is non-Schemy.
1615 For this reason, this implementation chooses not to provide a way to set
1616 the setter of a procedure. In fact, @code{(set! (setter @var{proc})
1617 @var{setter})} signals an error. The only way to attach a setter to a
1618 procedure is to create a new object (a @dfn{procedure with setter}) via
1619 the @code{getter-with-setter} procedure. This procedure is also
1620 specified in the SRFI. Using it avoids the described problems.
1621
1622
1623 @node SRFI-19
1624 @subsection SRFI-19 - Time/Date Library
1625 @cindex SRFI-19
1626 @cindex time
1627 @cindex date
1628
1629 This is an implementation of the SRFI-19 time/date library. The
1630 functions and variables described here are provided by
1631
1632 @example
1633 (use-modules (srfi srfi-19))
1634 @end example
1635
1636 @strong{Caution}: The current code in this module incorrectly extends
1637 the Gregorian calendar leap year rule back prior to the introduction
1638 of those reforms in 1582 (or the appropriate year in various
1639 countries). The Julian calendar was used prior to 1582, and there
1640 were 10 days skipped for the reform, but the code doesn't implement
1641 that.
1642
1643 This will be fixed some time. Until then calculations for 1583
1644 onwards are correct, but prior to that any day/month/year and day of
1645 the week calculations are wrong.
1646
1647 @menu
1648 * SRFI-19 Introduction::
1649 * SRFI-19 Time::
1650 * SRFI-19 Date::
1651 * SRFI-19 Time/Date conversions::
1652 * SRFI-19 Date to string::
1653 * SRFI-19 String to date::
1654 @end menu
1655
1656 @node SRFI-19 Introduction
1657 @subsubsection SRFI-19 Introduction
1658
1659 @cindex universal time
1660 @cindex atomic time
1661 @cindex UTC
1662 @cindex TAI
1663 This module implements time and date representations and calculations,
1664 in various time systems, including universal time (UTC) and atomic
1665 time (TAI).
1666
1667 For those not familiar with these time systems, TAI is based on a
1668 fixed length second derived from oscillations of certain atoms. UTC
1669 differs from TAI by an integral number of seconds, which is increased
1670 or decreased at announced times to keep UTC aligned to a mean solar
1671 day (the orbit and rotation of the earth are not quite constant).
1672
1673 @cindex leap second
1674 So far, only increases in the TAI
1675 @tex
1676 $\leftrightarrow$
1677 @end tex
1678 @ifnottex
1679 <->
1680 @end ifnottex
1681 UTC difference have been needed. Such an increase is a ``leap
1682 second'', an extra second of TAI introduced at the end of a UTC day.
1683 When working entirely within UTC this is never seen, every day simply
1684 has 86400 seconds. But when converting from TAI to a UTC date, an
1685 extra 23:59:60 is present, where normally a day would end at 23:59:59.
1686 Effectively the UTC second from 23:59:59 to 00:00:00 has taken two TAI
1687 seconds.
1688
1689 @cindex system clock
1690 In the current implementation, the system clock is assumed to be UTC,
1691 and a table of leap seconds in the code converts to TAI. See comments
1692 in @file{srfi-19.scm} for how to update this table.
1693
1694 @cindex julian day
1695 @cindex modified julian day
1696 Also, for those not familiar with the terminology, a @dfn{Julian Day}
1697 is a real number which is a count of days and fraction of a day, in
1698 UTC, starting from -4713-01-01T12:00:00Z, ie.@: midday Monday 1 Jan
1699 4713 B.C. A @dfn{Modified Julian Day} is the same, but starting from
1700 1858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. That time
1701 is julian day 2400000.5.
1702
1703 @c The SRFI-1 spec says -4714-11-24T12:00:00Z (November 24, -4714 at
1704 @c noon, UTC), but this is incorrect. It looks like it might have
1705 @c arisen from the code incorrectly treating years a multiple of 100
1706 @c but not 400 prior to 1582 as non-leap years, where instead the Julian
1707 @c calendar should be used so all multiples of 4 before 1582 are leap
1708 @c years.
1709
1710
1711 @node SRFI-19 Time
1712 @subsubsection SRFI-19 Time
1713 @cindex time
1714
1715 A @dfn{time} object has type, seconds and nanoseconds fields
1716 representing a point in time starting from some epoch. This is an
1717 arbitrary point in time, not just a time of day. Although times are
1718 represented in nanoseconds, the actual resolution may be lower.
1719
1720 The following variables hold the possible time types. For instance
1721 @code{(current-time time-process)} would give the current CPU process
1722 time.
1723
1724 @defvar time-utc
1725 Universal Coordinated Time (UTC).
1726 @cindex UTC
1727 @end defvar
1728
1729 @defvar time-tai
1730 International Atomic Time (TAI).
1731 @cindex TAI
1732 @end defvar
1733
1734 @defvar time-monotonic
1735 Monotonic time, meaning a monotonically increasing time starting from
1736 an unspecified epoch.
1737
1738 Note that in the current implementation @code{time-monotonic} is the
1739 same as @code{time-tai}, and unfortunately is therefore affected by
1740 adjustments to the system clock. Perhaps this will change in the
1741 future.
1742 @end defvar
1743
1744 @defvar time-duration
1745 A duration, meaning simply a difference between two times.
1746 @end defvar
1747
1748 @defvar time-process
1749 CPU time spent in the current process, starting from when the process
1750 began.
1751 @cindex process time
1752 @end defvar
1753
1754 @defvar time-thread
1755 CPU time spent in the current thread. Not currently implemented.
1756 @cindex thread time
1757 @end defvar
1758
1759 @sp 1
1760 @defun time? obj
1761 Return @code{#t} if @var{obj} is a time object, or @code{#f} if not.
1762 @end defun
1763
1764 @defun make-time type nanoseconds seconds
1765 Create a time object with the given @var{type}, @var{seconds} and
1766 @var{nanoseconds}.
1767 @end defun
1768
1769 @defun time-type time
1770 @defunx time-nanosecond time
1771 @defunx time-second time
1772 @defunx set-time-type! time type
1773 @defunx set-time-nanosecond! time nsec
1774 @defunx set-time-second! time sec
1775 Get or set the type, seconds or nanoseconds fields of a time object.
1776
1777 @code{set-time-type!} merely changes the field, it doesn't convert the
1778 time value. For conversions, see @ref{SRFI-19 Time/Date conversions}.
1779 @end defun
1780
1781 @defun copy-time time
1782 Return a new time object, which is a copy of the given @var{time}.
1783 @end defun
1784
1785 @defun current-time [type]
1786 Return the current time of the given @var{type}. The default
1787 @var{type} is @code{time-utc}.
1788
1789 Note that the name @code{current-time} conflicts with the Guile core
1790 @code{current-time} function (@pxref{Time}). Applications wanting to
1791 use both will need to use a different name for one of them.
1792 @end defun
1793
1794 @defun time-resolution [type]
1795 Return the resolution, in nanoseconds, of the given time @var{type}.
1796 The default @var{type} is @code{time-utc}.
1797 @end defun
1798
1799 @defun time<=? t1 t2
1800 @defunx time<? t1 t2
1801 @defunx time=? t1 t2
1802 @defunx time>=? t1 t2
1803 @defunx time>? t1 t2
1804 Return @code{#t} or @code{#f} according to the respective relation
1805 between time objects @var{t1} and @var{t2}. @var{t1} and @var{t2}
1806 must be the same time type.
1807 @end defun
1808
1809 @defun time-difference t1 t2
1810 @defunx time-difference! t1 t2
1811 Return a time object of type @code{time-duration} representing the
1812 period between @var{t1} and @var{t2}. @var{t1} and @var{t2} must be
1813 the same time type.
1814
1815 @code{time-difference} returns a new time object,
1816 @code{time-difference!} may modify @var{t1} to form its return.
1817 @end defun
1818
1819 @defun add-duration time duration
1820 @defunx add-duration! time duration
1821 @defunx subtract-duration time duration
1822 @defunx subtract-duration! time duration
1823 Return a time object which is @var{time} with the given @var{duration}
1824 added or subtracted. @var{duration} must be a time object of type
1825 @code{time-duration}.
1826
1827 @code{add-duration} and @code{subtract-duration} return a new time
1828 object. @code{add-duration!} and @code{subtract-duration!} may modify
1829 the given @var{time} to form their return.
1830 @end defun
1831
1832
1833 @node SRFI-19 Date
1834 @subsubsection SRFI-19 Date
1835 @cindex date
1836
1837 A @dfn{date} object represents a date in the Gregorian calendar and a
1838 time of day on that date in some timezone.
1839
1840 The fields are year, month, day, hour, minute, second, nanoseconds and
1841 timezone. A date object is immutable, its fields can be read but they
1842 cannot be modified once the object is created.
1843
1844 @defun date? obj
1845 Return @code{#t} if @var{obj} is a date object, or @code{#f} if not.
1846 @end defun
1847
1848 @defun make-date nsecs seconds minutes hours date month year zone-offset
1849 Create a new date object.
1850 @c
1851 @c FIXME: What can we say about the ranges of the values. The
1852 @c current code looks it doesn't normalize, but expects then in their
1853 @c usual range already.
1854 @c
1855 @end defun
1856
1857 @defun date-nanosecond date
1858 Nanoseconds, 0 to 999999999.
1859 @end defun
1860
1861 @defun date-second date
1862 Seconds, 0 to 59, or 60 for a leap second. 60 is never seen when working
1863 entirely within UTC, it's only when converting to or from TAI.
1864 @end defun
1865
1866 @defun date-minute date
1867 Minutes, 0 to 59.
1868 @end defun
1869
1870 @defun date-hour date
1871 Hour, 0 to 23.
1872 @end defun
1873
1874 @defun date-day date
1875 Day of the month, 1 to 31 (or less, according to the month).
1876 @end defun
1877
1878 @defun date-month date
1879 Month, 1 to 12.
1880 @end defun
1881
1882 @defun date-year date
1883 Year, eg.@: 2003. Dates B.C.@: are negative, eg.@: @math{-46} is 46
1884 B.C. There is no year 0, year @math{-1} is followed by year 1.
1885 @end defun
1886
1887 @defun date-zone-offset date
1888 Time zone, an integer number of seconds east of Greenwich.
1889 @end defun
1890
1891 @defun date-year-day date
1892 Day of the year, starting from 1 for 1st January.
1893 @end defun
1894
1895 @defun date-week-day date
1896 Day of the week, starting from 0 for Sunday.
1897 @end defun
1898
1899 @defun date-week-number date dstartw
1900 Week of the year, ignoring a first partial week. @var{dstartw} is the
1901 day of the week which is taken to start a week, 0 for Sunday, 1 for
1902 Monday, etc.
1903 @c
1904 @c FIXME: The spec doesn't say whether numbering starts at 0 or 1.
1905 @c The code looks like it's 0, if that's the correct intention.
1906 @c
1907 @end defun
1908
1909 @c The SRFI text doesn't actually give the default for tz-offset, but
1910 @c the reference implementation has the local timezone and the
1911 @c conversions functions all specify that, so it should be ok to
1912 @c document it here.
1913 @c
1914 @defun current-date [tz-offset]
1915 Return a date object representing the current date/time, in UTC offset
1916 by @var{tz-offset}. @var{tz-offset} is seconds east of Greenwich and
1917 defaults to the local timezone.
1918 @end defun
1919
1920 @defun current-julian-day
1921 @cindex julian day
1922 Return the current Julian Day.
1923 @end defun
1924
1925 @defun current-modified-julian-day
1926 @cindex modified julian day
1927 Return the current Modified Julian Day.
1928 @end defun
1929
1930
1931 @node SRFI-19 Time/Date conversions
1932 @subsubsection SRFI-19 Time/Date conversions
1933 @cindex time conversion
1934 @cindex date conversion
1935
1936 @defun date->julian-day date
1937 @defunx date->modified-julian-day date
1938 @defunx date->time-monotonic date
1939 @defunx date->time-tai date
1940 @defunx date->time-utc date
1941 @end defun
1942 @defun julian-day->date jdn [tz-offset]
1943 @defunx julian-day->time-monotonic jdn
1944 @defunx julian-day->time-tai jdn
1945 @defunx julian-day->time-utc jdn
1946 @end defun
1947 @defun modified-julian-day->date jdn [tz-offset]
1948 @defunx modified-julian-day->time-monotonic jdn
1949 @defunx modified-julian-day->time-tai jdn
1950 @defunx modified-julian-day->time-utc jdn
1951 @end defun
1952 @defun time-monotonic->date time [tz-offset]
1953 @defunx time-monotonic->time-tai time
1954 @defunx time-monotonic->time-tai! time
1955 @defunx time-monotonic->time-utc time
1956 @defunx time-monotonic->time-utc! time
1957 @end defun
1958 @defun time-tai->date time [tz-offset]
1959 @defunx time-tai->julian-day time
1960 @defunx time-tai->modified-julian-day time
1961 @defunx time-tai->time-monotonic time
1962 @defunx time-tai->time-monotonic! time
1963 @defunx time-tai->time-utc time
1964 @defunx time-tai->time-utc! time
1965 @end defun
1966 @defun time-utc->date time [tz-offset]
1967 @defunx time-utc->julian-day time
1968 @defunx time-utc->modified-julian-day time
1969 @defunx time-utc->time-monotonic time
1970 @defunx time-utc->time-monotonic! time
1971 @defunx time-utc->time-tai time
1972 @defunx time-utc->time-tai! time
1973 @sp 1
1974 Convert between dates, times and days of the respective types. For
1975 instance @code{time-tai->time-utc} accepts a @var{time} object of type
1976 @code{time-tai} and returns an object of type @code{time-utc}.
1977
1978 The @code{!} variants may modify their @var{time} argument to form
1979 their return. The plain functions create a new object.
1980
1981 For conversions to dates, @var{tz-offset} is seconds east of
1982 Greenwich. The default is the local timezone, at the given time, as
1983 provided by the system, using @code{localtime} (@pxref{Time}).
1984
1985 On 32-bit systems, @code{localtime} is limited to a 32-bit
1986 @code{time_t}, so a default @var{tz-offset} is only available for
1987 times between Dec 1901 and Jan 2038. For prior dates an application
1988 might like to use the value in 1902, though some locations have zone
1989 changes prior to that. For future dates an application might like to
1990 assume today's rules extend indefinitely. But for correct daylight
1991 savings transitions it will be necessary to take an offset for the
1992 same day and time but a year in range and which has the same starting
1993 weekday and same leap/non-leap (to support rules like last Sunday in
1994 October).
1995 @end defun
1996
1997 @node SRFI-19 Date to string
1998 @subsubsection SRFI-19 Date to string
1999 @cindex date to string
2000 @cindex string, from date
2001
2002 @defun date->string date [format]
2003 Convert a date to a string under the control of a format.
2004 @var{format} should be a string containing @samp{~} escapes, which
2005 will be expanded as per the following conversion table. The default
2006 @var{format} is @samp{~c}, a locale-dependent date and time.
2007
2008 Many of these conversion characters are the same as POSIX
2009 @code{strftime} (@pxref{Time}), but there are some extras and some
2010 variations.
2011
2012 @multitable {MMMM} {MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM}
2013 @item @nicode{~~} @tab literal ~
2014 @item @nicode{~a} @tab locale abbreviated weekday, eg.@: @samp{Sun}
2015 @item @nicode{~A} @tab locale full weekday, eg.@: @samp{Sunday}
2016 @item @nicode{~b} @tab locale abbreviated month, eg.@: @samp{Jan}
2017 @item @nicode{~B} @tab locale full month, eg.@: @samp{January}
2018 @item @nicode{~c} @tab locale date and time, eg.@: @*
2019 @samp{Fri Jul 14 20:28:42-0400 2000}
2020 @item @nicode{~d} @tab day of month, zero padded, @samp{01} to @samp{31}
2021
2022 @c Spec says d/m/y, reference implementation says m/d/y.
2023 @c Apparently the reference code was the intention, but would like to
2024 @c see an errata published for the spec before contradicting it here.
2025 @c
2026 @c @item @nicode{~D} @tab date @nicode{~d/~m/~y}
2027
2028 @item @nicode{~e} @tab day of month, blank padded, @samp{ 1} to @samp{31}
2029 @item @nicode{~f} @tab seconds and fractional seconds,
2030 with locale decimal point, eg.@: @samp{5.2}
2031 @item @nicode{~h} @tab same as @nicode{~b}
2032 @item @nicode{~H} @tab hour, 24-hour clock, zero padded, @samp{00} to @samp{23}
2033 @item @nicode{~I} @tab hour, 12-hour clock, zero padded, @samp{01} to @samp{12}
2034 @item @nicode{~j} @tab day of year, zero padded, @samp{001} to @samp{366}
2035 @item @nicode{~k} @tab hour, 24-hour clock, blank padded, @samp{ 0} to @samp{23}
2036 @item @nicode{~l} @tab hour, 12-hour clock, blank padded, @samp{ 1} to @samp{12}
2037 @item @nicode{~m} @tab month, zero padded, @samp{01} to @samp{12}
2038 @item @nicode{~M} @tab minute, zero padded, @samp{00} to @samp{59}
2039 @item @nicode{~n} @tab newline
2040 @item @nicode{~N} @tab nanosecond, zero padded, @samp{000000000} to @samp{999999999}
2041 @item @nicode{~p} @tab locale AM or PM
2042 @item @nicode{~r} @tab time, 12 hour clock, @samp{~I:~M:~S ~p}
2043 @item @nicode{~s} @tab number of full seconds since ``the epoch'' in UTC
2044 @item @nicode{~S} @tab second, zero padded @samp{00} to @samp{60} @*
2045 (usual limit is 59, 60 is a leap second)
2046 @item @nicode{~t} @tab horizontal tab character
2047 @item @nicode{~T} @tab time, 24 hour clock, @samp{~H:~M:~S}
2048 @item @nicode{~U} @tab week of year, Sunday first day of week,
2049 @samp{00} to @samp{52}
2050 @item @nicode{~V} @tab week of year, Monday first day of week,
2051 @samp{01} to @samp{53}
2052 @item @nicode{~w} @tab day of week, 0 for Sunday, @samp{0} to @samp{6}
2053 @item @nicode{~W} @tab week of year, Monday first day of week,
2054 @samp{00} to @samp{52}
2055
2056 @c The spec has ~x as an apparent duplicate of ~W, and ~X as a locale
2057 @c date. The reference code has ~x as the locale date and ~X as a
2058 @c locale time. The rule is apparently that the code should be
2059 @c believed, but would like to see an errata for the spec before
2060 @c contradicting it here.
2061 @c
2062 @c @item @nicode{~x} @tab week of year, Monday as first day of week,
2063 @c @samp{00} to @samp{53}
2064 @c @item @nicode{~X} @tab locale date, eg.@: @samp{07/31/00}
2065
2066 @item @nicode{~y} @tab year, two digits, @samp{00} to @samp{99}
2067 @item @nicode{~Y} @tab year, full, eg.@: @samp{2003}
2068 @item @nicode{~z} @tab time zone, RFC-822 style
2069 @item @nicode{~Z} @tab time zone symbol (not currently implemented)
2070 @item @nicode{~1} @tab ISO-8601 date, @samp{~Y-~m-~d}
2071 @item @nicode{~2} @tab ISO-8601 time+zone, @samp{~k:~M:~S~z}
2072 @item @nicode{~3} @tab ISO-8601 time, @samp{~k:~M:~S}
2073 @item @nicode{~4} @tab ISO-8601 date/time+zone, @samp{~Y-~m-~dT~k:~M:~S~z}
2074 @item @nicode{~5} @tab ISO-8601 date/time, @samp{~Y-~m-~dT~k:~M:~S}
2075 @end multitable
2076 @end defun
2077
2078 Conversions @samp{~D}, @samp{~x} and @samp{~X} are not currently
2079 described here, since the specification and reference implementation
2080 differ.
2081
2082 Currently Guile doesn't implement any localizations for the above, all
2083 outputs are in English, and the @samp{~c} conversion is POSIX
2084 @code{ctime} style @samp{~a ~b ~d ~H:~M:~S~z ~Y}. This may change in
2085 the future.
2086
2087
2088 @node SRFI-19 String to date
2089 @subsubsection SRFI-19 String to date
2090 @cindex string to date
2091 @cindex date, from string
2092
2093 @c FIXME: Can we say what happens when an incomplete date is
2094 @c converted? Ie. fields left as 0, or what? The spec seems to be
2095 @c silent on this.
2096
2097 @defun string->date input template
2098 Convert an @var{input} string to a date under the control of a
2099 @var{template} string. Return a newly created date object.
2100
2101 Literal characters in @var{template} must match characters in
2102 @var{input} and @samp{~} escapes must match the input forms described
2103 in the table below. ``Skip to'' means characters up to one of the
2104 given type are ignored, or ``no skip'' for no skipping. ``Read'' is
2105 what's then read, and ``Set'' is the field affected in the date
2106 object.
2107
2108 For example @samp{~Y} skips input characters until a digit is reached,
2109 at which point it expects a year and stores that to the year field of
2110 the date.
2111
2112 @multitable {MMMM} {@nicode{char-alphabetic?}} {MMMMMMMMMMMMMMMMMMMMMMMMM} {@nicode{date-zone-offset}}
2113 @item
2114 @tab Skip to
2115 @tab Read
2116 @tab Set
2117
2118 @item @nicode{~~}
2119 @tab no skip
2120 @tab literal ~
2121 @tab nothing
2122
2123 @item @nicode{~a}
2124 @tab @nicode{char-alphabetic?}
2125 @tab locale abbreviated weekday name
2126 @tab nothing
2127
2128 @item @nicode{~A}
2129 @tab @nicode{char-alphabetic?}
2130 @tab locale full weekday name
2131 @tab nothing
2132
2133 @c Note that the SRFI spec says that ~b and ~B don't set anything,
2134 @c but that looks like a mistake. The reference implementation sets
2135 @c the month field, which seems sensible and is what we describe
2136 @c here.
2137
2138 @item @nicode{~b}
2139 @tab @nicode{char-alphabetic?}
2140 @tab locale abbreviated month name
2141 @tab @nicode{date-month}
2142
2143 @item @nicode{~B}
2144 @tab @nicode{char-alphabetic?}
2145 @tab locale full month name
2146 @tab @nicode{date-month}
2147
2148 @item @nicode{~d}
2149 @tab @nicode{char-numeric?}
2150 @tab day of month
2151 @tab @nicode{date-day}
2152
2153 @item @nicode{~e}
2154 @tab no skip
2155 @tab day of month, blank padded
2156 @tab @nicode{date-day}
2157
2158 @item @nicode{~h}
2159 @tab same as @samp{~b}
2160
2161 @item @nicode{~H}
2162 @tab @nicode{char-numeric?}
2163 @tab hour
2164 @tab @nicode{date-hour}
2165
2166 @item @nicode{~k}
2167 @tab no skip
2168 @tab hour, blank padded
2169 @tab @nicode{date-hour}
2170
2171 @item @nicode{~m}
2172 @tab @nicode{char-numeric?}
2173 @tab month
2174 @tab @nicode{date-month}
2175
2176 @item @nicode{~M}
2177 @tab @nicode{char-numeric?}
2178 @tab minute
2179 @tab @nicode{date-minute}
2180
2181 @item @nicode{~S}
2182 @tab @nicode{char-numeric?}
2183 @tab second
2184 @tab @nicode{date-second}
2185
2186 @item @nicode{~y}
2187 @tab no skip
2188 @tab 2-digit year
2189 @tab @nicode{date-year} within 50 years
2190
2191 @item @nicode{~Y}
2192 @tab @nicode{char-numeric?}
2193 @tab year
2194 @tab @nicode{date-year}
2195
2196 @item @nicode{~z}
2197 @tab no skip
2198 @tab time zone
2199 @tab date-zone-offset
2200 @end multitable
2201
2202 Notice that the weekday matching forms don't affect the date object
2203 returned, instead the weekday will be derived from the day, month and
2204 year.
2205
2206 Currently Guile doesn't implement any localizations for the above,
2207 month and weekday names are always expected in English. This may
2208 change in the future.
2209 @end defun
2210
2211
2212 @node SRFI-26
2213 @subsection SRFI-26 - specializing parameters
2214 @cindex SRFI-26
2215 @cindex parameter specialize
2216 @cindex argument specialize
2217 @cindex specialize parameter
2218
2219 This SRFI provides a syntax for conveniently specializing selected
2220 parameters of a function. It can be used with,
2221
2222 @example
2223 (use-modules (srfi srfi-26))
2224 @end example
2225
2226 @deffn {library syntax} cut slot @dots{}
2227 @deffnx {library syntax} cute slot @dots{}
2228 Return a new procedure which will make a call (@var{slot} @dots{}) but
2229 with selected parameters specialized to given expressions.
2230
2231 An example will illustrate the idea. The following is a
2232 specialization of @code{write}, sending output to
2233 @code{my-output-port},
2234
2235 @example
2236 (cut write <> my-output-port)
2237 @result{}
2238 (lambda (obj) (write obj my-output-port))
2239 @end example
2240
2241 The special symbol @code{<>} indicates a slot to be filled by an
2242 argument to the new procedure. @code{my-output-port} on the other
2243 hand is an expression to be evaluated and passed, ie.@: it specializes
2244 the behaviour of @code{write}.
2245
2246 @table @nicode
2247 @item <>
2248 A slot to be filled by an argument from the created procedure.
2249 Arguments are assigned to @code{<>} slots in the order they appear in
2250 the @code{cut} form, there's no way to re-arrange arguments.
2251
2252 The first argument to @code{cut} is usually a procedure (or expression
2253 giving a procedure), but @code{<>} is allowed there too. For example,
2254
2255 @example
2256 (cut <> 1 2 3)
2257 @result{}
2258 (lambda (proc) (proc 1 2 3))
2259 @end example
2260
2261 @item <...>
2262 A slot to be filled by all remaining arguments from the new procedure.
2263 This can only occur at the end of a @code{cut} form.
2264
2265 For example, a procedure taking a variable number of arguments like
2266 @code{max} but in addition enforcing a lower bound,
2267
2268 @example
2269 (define my-lower-bound 123)
2270
2271 (cut max my-lower-bound <...>)
2272 @result{}
2273 (lambda arglist (apply max my-lower-bound arglist))
2274 @end example
2275 @end table
2276
2277 For @code{cut} the specializing expressions are evaluated each time
2278 the new procedure is called. For @code{cute} they're evaluated just
2279 once, when the new procedure is created. The name @code{cute} stands
2280 for ``@code{cut} with evaluated arguments''. In all cases the
2281 evaluations take place in an unspecified order.
2282
2283 The following illustrates the difference between @code{cut} and
2284 @code{cute},
2285
2286 @example
2287 (cut format <> "the time is ~s" (current-time))
2288 @result{}
2289 (lambda (port) (format port "the time is ~s" (current-time)))
2290
2291 (cute format <> "the time is ~s" (current-time))
2292 @result{}
2293 (let ((val (current-time)))
2294 (lambda (port) (format port "the time is ~s" val))
2295 @end example
2296
2297 (There's no provision for a mixture of @code{cut} and @code{cute}
2298 where some expressions would be evaluated every time but others
2299 evaluated only once.)
2300
2301 @code{cut} is really just a shorthand for the sort of @code{lambda}
2302 forms shown in the above examples. But notice @code{cut} avoids the
2303 need to name unspecialized parameters, and is more compact. Use in
2304 functional programming style or just with @code{map}, @code{for-each}
2305 or similar is typical.
2306
2307 @example
2308 (map (cut * 2 <>) '(1 2 3 4))
2309
2310 (for-each (cut write <> my-port) my-list)
2311 @end example
2312 @end deffn
2313
2314 @node SRFI-31
2315 @subsection SRFI-31 - A special form `rec' for recursive evaluation
2316 @cindex SRFI-31
2317 @cindex recursive expression
2318 @findex rec
2319
2320 SRFI-31 defines a special form that can be used to create
2321 self-referential expressions more conveniently. The syntax is as
2322 follows:
2323
2324 @example
2325 @group
2326 <rec expression> --> (rec <variable> <expression>)
2327 <rec expression> --> (rec (<variable>+) <body>)
2328 @end group
2329 @end example
2330
2331 The first syntax can be used to create self-referential expressions,
2332 for example:
2333
2334 @lisp
2335 guile> (define tmp (rec ones (cons 1 (delay ones))))
2336 @end lisp
2337
2338 The second syntax can be used to create anonymous recursive functions:
2339
2340 @lisp
2341 guile> (define tmp (rec (display-n item n)
2342 (if (positive? n)
2343 (begin (display n) (display-n (- n 1))))))
2344 guile> (tmp 42 3)
2345 424242
2346 guile>
2347 @end lisp
2348
2349
2350 @node SRFI-39
2351 @subsection SRFI-39 - Parameters
2352 @cindex SRFI-39
2353 @cindex parameter object
2354 @tindex Parameter
2355
2356 This SRFI provides parameter objects, which implement dynamically
2357 bound locations for values. The functions below are available from
2358
2359 @example
2360 (use-modules (srfi srfi-39))
2361 @end example
2362
2363 A parameter object is a procedure. Called with no arguments it
2364 returns its value, called with one argument it sets the value.
2365
2366 @example
2367 (define my-param (make-parameter 123))
2368 (my-param) @result{} 123
2369 (my-param 456)
2370 (my-param) @result{} 456
2371 @end example
2372
2373 The @code{parameterize} special form establishes new locations for
2374 parameters, those new locations having effect within the dynamic scope
2375 of the @code{parameterize} body. Leaving restores the previous
2376 locations, or re-entering through a saved continuation will again use
2377 the new locations.
2378
2379 @example
2380 (parameterize ((my-param 789))
2381 (my-param) @result{} 789
2382 )
2383 (my-param) @result{} 456
2384 @end example
2385
2386 Parameters are like dynamically bound variables in other Lisp dialets.
2387 They allow an application to establish parameter settings (as the name
2388 suggests) just for the execution of a particular bit of code,
2389 restoring when done. Examples of such parameters might be
2390 case-sensitivity for a search, or a prompt for user input.
2391
2392 Global variables are not as good as parameter objects for this sort of
2393 thing. Changes to them are visible to all threads, but in Guile
2394 parameter object locations are per-thread, thereby truely limiting the
2395 effect of @code{parameterize} to just its dynamic execution.
2396
2397 Passing arguments to functions is thread-safe, but that soon becomes
2398 tedious when there's more than a few or when they need to pass down
2399 through several layers of calls before reaching the point they should
2400 affect. And introducing a new setting to existing code is often
2401 easier with a parameter object than adding arguments.
2402
2403
2404 @sp 1
2405 @defun make-parameter init [converter]
2406 Return a new parameter object, with initial value @var{init}.
2407
2408 A parameter object is a procedure. When called @code{(param)} it
2409 returns its value, or a call @code{(param val)} sets its value. For
2410 example,
2411
2412 @example
2413 (define my-param (make-parameter 123))
2414 (my-param) @result{} 123
2415
2416 (my-param 456)
2417 (my-param) @result{} 456
2418 @end example
2419
2420 If a @var{converter} is given, then a call @code{(@var{converter}
2421 val)} is made for each value set, its return is the value stored.
2422 Such a call is made for the @var{init} initial value too.
2423
2424 A @var{converter} allows values to be validated, or put into a
2425 canonical form. For example,
2426
2427 @example
2428 (define my-param (make-parameter 123
2429 (lambda (val)
2430 (if (not (number? val))
2431 (error "must be a number"))
2432 (inexact->exact val))))
2433 (my-param 0.75)
2434 (my-param) @result{} 3/4
2435 @end example
2436 @end defun
2437
2438 @deffn {library syntax} parameterize ((param value) @dots{}) body @dots{}
2439 Establish a new dynamic scope with the given @var{param}s bound to new
2440 locations and set to the given @var{value}s. @var{body} is evaluated
2441 in that environment, the result is the return from the last form in
2442 @var{body}.
2443
2444 Each @var{param} is an expression which is evaluated to get the
2445 parameter object. Often this will just be the name of a variable
2446 holding the object, but it can be anything that evaluates to a
2447 parameter.
2448
2449 The @var{param} expressions and @var{value} expressions are all
2450 evaluated before establishing the new dynamic bindings, and they're
2451 evaluated in an unspecified order.
2452
2453 For example,
2454
2455 @example
2456 (define prompt (make-parameter "Type something: "))
2457 (define (get-input)
2458 (display (prompt))
2459 ...)
2460
2461 (parameterize ((prompt "Type a number: "))
2462 (get-input)
2463 ...)
2464 @end example
2465 @end deffn
2466
2467 @deffn {Parameter object} current-input-port [new-port]
2468 @deffnx {Parameter object} current-output-port [new-port]
2469 @deffnx {Parameter object} current-error-port [new-port]
2470 This SRFI extends the core @code{current-input-port} and
2471 @code{current-output-port}, making them parameter objects. The
2472 Guile-specific @code{current-error-port} is extended too, for
2473 consistency. (@pxref{Default Ports}.)
2474
2475 This is an upwardly compatible extension, a plain call like
2476 @code{(current-input-port)} still returns the current input port, and
2477 @code{set-current-input-port} can still be used. But the port can now
2478 also be set with @code{(current-input-port my-port)} and bound
2479 dynamically with @code{parameterize}.
2480 @end deffn
2481
2482 @defun with-parameters* param-list value-list thunk
2483 Establish a new dynamic scope, as per @code{parameterize} above,
2484 taking parameters from @var{param-list} and corresponding values from
2485 @var{values-list}. A call @code{(@var{thunk})} is made in the new
2486 scope and the result from that @var{thunk} is the return from
2487 @code{with-parameters*}.
2488
2489 This function is a Guile-specific addition to the SRFI, it's similar
2490 to the core @code{with-fluids*} (@pxref{Fluids and Dynamic States}).
2491 @end defun
2492
2493
2494 @sp 1
2495 Parameter objects are implemented using fluids (@pxref{Fluids and
2496 Dynamic States}), so each dynamic state has it's own parameter
2497 locations. That includes the separate locations when outside any
2498 @code{parameterize} form. When a parameter is created it gets a
2499 separate initial location in each dynamic state, all initialized to
2500 the given @var{init} value.
2501
2502 As alluded to above, because each thread usually has a separate
2503 dynamic state, each thread has it's own locations behind parameter
2504 objects, and changes in one thread are not visible to any other. When
2505 a new dynamic state or thread is created, the values of parameters in
2506 the originating context are copied, into new locations.
2507
2508 SRFI-39 doesn't specify the interaction between parameter objects and
2509 threads, so the threading behaviour described here should be regarded
2510 as Guile-specific.
2511
2512
2513 @node SRFI-55
2514 @subsection SRFI-55 - Requiring Features
2515 @cindex SRFI-55
2516
2517 SRFI-55 provides @code{require-extension} which is a portable
2518 mechanism to load selected SRFI modules. This is implemented in the
2519 Guile core, there's no module needed to get SRFI-55 itself.
2520
2521 @deffn {library syntax} require-extension clause@dots{}
2522 Require each of the given @var{clause} features, throwing an error if
2523 any are unavailable.
2524
2525 A @var{clause} is of the form @code{(@var{identifier} arg...)}. The
2526 only @var{identifier} currently supported is @code{srfi} and the
2527 arguments are SRFI numbers. For example to get SRFI-1 and SRFI-6,
2528
2529 @example
2530 (require-extension (srfi 1 6))
2531 @end example
2532
2533 @code{require-extension} can only be used at the top-level.
2534
2535 A Guile-specific program can simply @code{use-modules} to load SRFIs
2536 not already in the core, @code{require-extension} is for programs
2537 designed to be portable to other Scheme implementations.
2538 @end deffn
2539
2540
2541 @node SRFI-60
2542 @subsection SRFI-60 - Integers as Bits
2543 @cindex SRFI-60
2544 @cindex integers as bits
2545 @cindex bitwise logical
2546
2547 This SRFI provides various functions for treating integers as bits and
2548 for bitwise manipulations. These functions can be obtained with,
2549
2550 @example
2551 (use-modules (srfi srfi-60))
2552 @end example
2553
2554 Integers are treated as infinite precision twos-complement, the same
2555 as in the core logical functions (@pxref{Bitwise Operations}). And
2556 likewise bit indexes start from 0 for the least significant bit. The
2557 following functions in this SRFI are already in the Guile core,
2558
2559 @quotation
2560 @code{logand},
2561 @code{logior},
2562 @code{logxor},
2563 @code{lognot},
2564 @code{logtest},
2565 @code{logcount},
2566 @code{integer-length},
2567 @code{logbit?},
2568 @code{ash}
2569 @end quotation
2570
2571 @sp 1
2572 @defun bitwise-and n1 ...
2573 @defunx bitwise-ior n1 ...
2574 @defunx bitwise-xor n1 ...
2575 @defunx bitwise-not n
2576 @defunx any-bits-set? j k
2577 @defunx bit-set? index n
2578 @defunx arithmetic-shift n count
2579 @defunx bit-field n start end
2580 @defunx bit-count n
2581 Aliases for @code{logand}, @code{logior}, @code{logxor},
2582 @code{lognot}, @code{logtest}, @code{logbit?}, @code{ash},
2583 @code{bit-extract} and @code{logcount} respectively.
2584
2585 Note that the name @code{bit-count} conflicts with @code{bit-count} in
2586 the core (@pxref{Bit Vectors}).
2587 @end defun
2588
2589 @defun bitwise-if mask n1 n0
2590 @defunx bitwise-merge mask n1 n0
2591 Return an integer with bits selected from @var{n1} and @var{n0}
2592 according to @var{mask}. Those bits where @var{mask} has 1s are taken
2593 from @var{n1}, and those where @var{mask} has 0s are taken from
2594 @var{n0}.
2595
2596 @example
2597 (bitwise-if 3 #b0101 #b1010) @result{} 9
2598 @end example
2599 @end defun
2600
2601 @defun log2-binary-factors n
2602 @defunx first-set-bit n
2603 Return a count of how many factors of 2 are present in @var{n}. This
2604 is also the bit index of the lowest 1 bit in @var{n}. If @var{n} is
2605 0, the return is @math{-1}.
2606
2607 @example
2608 (log2-binary-factors 6) @result{} 1
2609 (log2-binary-factors -8) @result{} 3
2610 @end example
2611 @end defun
2612
2613 @defun copy-bit index n newbit
2614 Return @var{n} with the bit at @var{index} set according to
2615 @var{newbit}. @var{newbit} should be @code{#t} to set the bit to 1,
2616 or @code{#f} to set it to 0. Bits other than at @var{index} are
2617 unchanged in the return.
2618
2619 @example
2620 (copy-bit 1 #b0101 #t) @result{} 7
2621 @end example
2622 @end defun
2623
2624 @defun copy-bit-field n newbits start end
2625 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2626 (exclusive) changed to the value @var{newbits}.
2627
2628 The least significant bit in @var{newbits} goes to @var{start}, the
2629 next to @math{@var{start}+1}, etc. Anything in @var{newbits} past the
2630 @var{end} given is ignored.
2631
2632 @example
2633 (copy-bit-field #b10000 #b11 1 3) @result{} #b10110
2634 @end example
2635 @end defun
2636
2637 @defun rotate-bit-field n count start end
2638 Return @var{n} with the bit field from @var{start} (inclusive) to
2639 @var{end} (exclusive) rotated upwards by @var{count} bits.
2640
2641 @var{count} can be positive or negative, and it can be more than the
2642 field width (it'll be reduced modulo the width).
2643
2644 @example
2645 (rotate-bit-field #b0110 2 1 4) @result{} #b1010
2646 @end example
2647 @end defun
2648
2649 @defun reverse-bit-field n start end
2650 Return @var{n} with the bits from @var{start} (inclusive) to @var{end}
2651 (exclusive) reversed.
2652
2653 @example
2654 (reverse-bit-field #b101001 2 4) @result{} #b100101
2655 @end example
2656 @end defun
2657
2658 @defun integer->list n [len]
2659 Return bits from @var{n} in the form of a list of @code{#t} for 1 and
2660 @code{#f} for 0. The least significant @var{len} bits are returned,
2661 and the first list element is the most significant of those bits. If
2662 @var{len} is not given, the default is @code{(integer-length @var{n})}
2663 (@pxref{Bitwise Operations}).
2664
2665 @example
2666 (integer->list 6) @result{} (#t #t #f)
2667 (integer->list 1 4) @result{} (#f #f #f #t)
2668 @end example
2669 @end defun
2670
2671 @defun list->integer lst
2672 @defunx booleans->integer bool@dots{}
2673 Return an integer formed bitwise from the given @var{lst} list of
2674 booleans, or for @code{booleans->integer} from the @var{bool}
2675 arguments.
2676
2677 Each boolean is @code{#t} for a 1 and @code{#f} for a 0. The first
2678 element becomes the most significant bit in the return.
2679
2680 @example
2681 (list->integer '(#t #f #t #f)) @result{} 10
2682 @end example
2683 @end defun
2684
2685
2686 @c srfi-modules.texi ends here
2687
2688 @c Local Variables:
2689 @c TeX-master: "guile.texi"
2690 @c End: