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