add truncated-print to (ice-9 pretty-print)
[bpt/guile.git] / doc / ref / misc-modules.texi
CommitLineData
2da09c3f
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
40296bab 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006
2da09c3f
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
a0e07ba4
NJ
7@page
8@node Pretty Printing
3229f68b 9@section Pretty Printing
a0e07ba4
NJ
10
11@c FIXME::martin: Review me!
12
13@cindex pretty printing
14The module @code{(ice-9 pretty-print)} provides the procedure
15@code{pretty-print}, which provides nicely formatted output of Scheme
16objects. This is especially useful for deeply nested or complex data
17structures, such as lists and vectors.
18
19The module is loaded by simply saying.
20
21@lisp
22(use-modules (ice-9 pretty-print))
23@end lisp
24
25This makes the procedure @code{pretty-print} available. As an example
26how @code{pretty-print} will format the output, see the following:
27
28@lisp
29(pretty-print '(define (foo) (lambda (x)
385dbc8b
KR
30(cond ((zero? x) #t) ((negative? x) -x) (else
31(if (= x 1) 2 (* x x x)))))))
a0e07ba4
NJ
32@print{}
33(define (foo)
34 (lambda (x)
35 (cond ((zero? x) #t)
36 ((negative? x) -x)
37 (else (if (= x 1) 2 (* x x x))))))
38@end lisp
39
385dbc8b 40@deffn {Scheme Procedure} pretty-print obj [port] [keyword-options]
a0e07ba4
NJ
41Print the textual representation of the Scheme object @var{obj} to
42@var{port}. @var{port} defaults to the current output port, if not
43given.
385dbc8b
KR
44
45The further @var{keyword-options} are keywords and parameters as
46follows,
47
48@table @asis
49@item @nicode{#:display?} @var{flag}
50If @var{flag} is true then print using @code{display}. The default is
51@code{#f} which means use @code{write} style. (@pxref{Writing})
52
53@item @nicode{#:per-line-prefix} @var{string}
54Print the given @var{string} as a prefix on each line. The default is
55no prefix.
56
57@item @nicode{#:width} @var{columns}
58Print within the given @var{columns}. The default is 79.
59@end table
a0e07ba4
NJ
60@end deffn
61
2a946b44 62
a0e07ba4
NJ
63@page
64@node Formatted Output
3229f68b 65@section Formatted Output
a0e07ba4 66@cindex formatted output
a0e07ba4 67
76d3f3d4
KR
68@c For reference, in this section escapes like ~a are given in
69@c @nicode, to give code font in TeX etc, but leave them unadorned in
70@c Info.
71@c
72@c The idea is to reduce clutter around what's shown, and avoid any
73@c possible confusion over whether the ` ' quotes are part of what
74@c should be entered. (In particular for instance of course ' is
75@c meaningful in a format string, introducing a char parameter).
76
77The @code{format} function is a powerful way to print numbers, strings
78and other objects together with literal text under the control of a
79format string. This function is available from
80
81@example
82(use-modules (ice-9 format))
83@end example
84
85A format string is generally more compact and easier than using just
86the standard procedures like @code{display}, @code{write} and
87@code{newline}. Parameters in the output string allow various output
88styles, and parameters can be taken from the arguments for runtime
89flexibility.
90
91@code{format} is similar to the Common Lisp procedure of the same
92name, but it's not identical and doesn't have quite all the features
93found in Common Lisp.
94
95C programmers will note the similarity between @code{format} and
96@code{printf}, though escape sequences are marked with @nicode{~}
97instead of @nicode{%}, and are more powerful.
98
99@sp 1
100@deffn {Scheme Procedure} format dest fmt [args@dots{}]
101Write output specified by the @var{fmt} string to @var{dest}.
102@var{dest} can be an output port, @code{#t} for
103@code{current-output-port} (@pxref{Default Ports}), a number for
104@code{current-error-port}, or @code{#f} to return the output as a
105string.
106
107@var{fmt} can contain literal text to be output, and @nicode{~}
108escapes. Each escape has the form
109
110@example
111~ [param [, param@dots{}] [:] [@@] code
112@end example
113
114@nicode{code} is a character determining the escape sequence. The
115@nicode{:} and @nicode{@@} characters are optional modifiers, one or
116both of which change the way various codes operate. Optional
117parameters are accepted by some codes too. Parameters have the
118following forms,
a0e07ba4 119
76d3f3d4 120@table @asis
80a894c9 121@item @nicode{[+/-]number}
76d3f3d4
KR
122An integer, with optional @nicode{+} or @nicode{-}.
123@item @nicode{'} (apostrophe)
124The following character in the format string, for instance @nicode{'z}
125for @nicode{z}.
126@item @nicode{v}
127The next function argument as the parameter. @nicode{v} stands for
128``variable'', a parameter can be calculated at runtime and included in
129the arguments. Upper case @nicode{V} can be used too.
130@item @nicode{#}
131The number of arguments remaining. (See @nicode{~*} below for some
132usages.)
a0e07ba4
NJ
133@end table
134
76d3f3d4
KR
135Parameters are separated by commas (@nicode{,}). A parameter can be
136left empty to keep its default value when supplying later parameters.
a0e07ba4 137
76d3f3d4
KR
138@sp 1
139The following escapes are available. The code letters are not
140case-sensitive, upper and lower case are the same.
a0e07ba4 141
76d3f3d4
KR
142@table @asis
143@item @nicode{~a}
144@itemx @nicode{~s}
145Object output. Parameters: @var{minwidth}, @var{padinc},
146@var{minpad}, @var{padchar}.
147
148@nicode{~a} outputs an argument like @code{display}, @nicode{~s}
149outputs an argument like @code{write} (@pxref{Writing}).
150
151@example
152(format #t "~a" "foo") @print{} foo
153(format #t "~s" "foo") @print{} "foo"
154@end example
155
80a894c9
KR
156@nicode{~:a} and @nicode{~:s} put objects that don't have an external
157representation in quotes like a string.
76d3f3d4
KR
158
159@example
160(format #t "~:a" car) @print{} "#<primitive-procedure car>"
161@end example
162
163If the output is less than @var{minwidth} characters (default 0), it's
80a894c9
KR
164padded on the right with @var{padchar} (default space). @nicode{~@@a}
165and @nicode{~@@s} put the padding on the left instead.
76d3f3d4
KR
166
167@example
168(format #f "~5a" 'abc) @result{} "abc "
169(format #f "~5,,,'-@@a" 'abc) @result{} "--abc"
170@end example
171
172@var{minpad} is a minimum for the padding then plus a multiple of
173@var{padinc}. Ie.@: the padding is @math{@var{minpad} + @var{N} *
174@var{padinc}}, where @var{n} is the smallest integer making the total
175object plus padding greater than or equal to @var{minwidth}. The
176default @var{minpad} is 0 and the default @var{padinc} is 1 (imposing
177no minimum or multiple).
178
179@example
180(format #f "~5,1,4a" 'abc) @result{} "abc "
181@end example
182
183@item @nicode{~c}
184Character. Parameter: @var{charnum}.
185
186Output a character. The default is to simply output, as per
80a894c9
KR
187@code{write-char} (@pxref{Writing}). @nicode{~@@c} prints in
188@code{write} style. @nicode{~:c} prints control characters (ASCII 0
189to 31) in @nicode{^X} form.
76d3f3d4
KR
190
191@example
192(format #t "~c" #\z) @print{} z
193(format #t "~@@c" #\z) @print{} #\z
194(format #t "~:c" #\newline) @print{} ^J
195@end example
196
197If the @var{charnum} parameter is given then an argument is not taken
198but instead the character is @code{(integer->char @var{charnum})}
199(@pxref{Characters}). This can be used for instance to output
200characters given by their ASCII code.
201
202@example
203(format #t "~65c") @print{} A
204@end example
205
206@item @nicode{~d}
207@itemx @nicode{~x}
208@itemx @nicode{~o}
209@itemx @nicode{~b}
210Integer. Parameters: @var{minwidth}, @var{padchar}, @var{commachar},
211@var{commawidth}.
212
213Output an integer argument as a decimal, hexadecimal, octal or binary
214integer (respectively).
215
216@example
217(format #t "~d" 123) @print{} 123
218@end example
219
80a894c9 220@nicode{~@@d} etc shows a @nicode{+} sign is shown on positive
76d3f3d4
KR
221numbers.
222
223@c FIXME: "+" is not shown on zero, unlike in Common Lisp. Should
224@c that be changed in the code, or is it too late and should just be
225@c documented that way?
226
227@example
228(format #t "~@@b" 12) @print{} +1100
229@end example
230
231If the output is less than the @var{minwidth} parameter (default no
232minimum), it's padded on the left with the @var{padchar} parameter
233(default space).
234
235@example
236(format #t "~5,'*d" 12) @print{} ***12
237(format #t "~5,'0d" 12) @print{} 00012
238(format #t "~3d" 1234) @print{} 1234
239@end example
240
80a894c9
KR
241@nicode{~:d} adds commas (or the @var{commachar} parameter) every
242three digits (or the @var{commawidth} parameter many).
76d3f3d4
KR
243
244@example
245(format #t "~:d" 1234567) @print{} 1,234,567
246(format #t "~10,'*,'/,2:d" 12345) @print{} ***1/23/45
247@end example
248
249Hexadecimal @nicode{~x} output is in lower case, but the @nicode{~(}
250and @nicode{~)} case conversion directives described below can be used
251to get upper case.
252
253@example
254(format #t "~x" 65261) @print{} feed
255(format #t "~:@@(~x~)" 65261) @print{} FEED
256@end example
257
258@item @nicode{~r}
259Integer in words, roman numerals, or a specified radix. Parameters:
260@var{radix}, @var{minwidth}, @var{padchar}, @var{commachar},
261@var{commawidth}.
262
263With no parameters output is in words as a cardinal like ``ten'', or
80a894c9 264@nicode{~:r} prints an ordinal like ``tenth''.
76d3f3d4
KR
265
266@example
267(format #t "~r" 9) @print{} nine ;; cardinal
268(format #t "~r" -9) @print{} minus nine ;; cardinal
269(format #t "~:r" 9) @print{} ninth ;; ordinal
270@end example
271
80a894c9 272And also with no parameters, @nicode{~@@r} gives roman numerals and
40296bab 273@nicode{~:@@r} gives old roman numerals. In old roman numerals
80a894c9
KR
274there's no ``subtraction'', so 9 is @nicode{VIIII} instead of
275@nicode{IX}. In both cases only positive numbers can be output.
76d3f3d4
KR
276
277@example
278(format #t "~@@r" 89) @print{} LXXXIX ;; roman
40296bab 279(format #t "~:@@r" 89) @print{} LXXXVIIII ;; old roman
76d3f3d4
KR
280@end example
281
282When a parameter is given it means numeric output in the specified
283@var{radix}. The modifiers and parameters following the radix are the
284same as described for @nicode{~d} etc above.
285
286@example
287(format #f "~3r" 27) @result{} "1000" ;; base 3
288(format #f "~3,5r" 26) @result{} " 222" ;; base 3 width 5
289@end example
290
291@item @nicode{~f}
292Fixed-point float. Parameters: @var{width}, @var{decimals},
293@var{scale}, @var{overflowchar}, @var{padchar}.
294
295Output a number or number string in fixed-point format, ie.@: with a
296decimal point.
297
298@example
299(format #t "~f" 5) @print{} 5.0
300(format #t "~f" "123") @print{} 123.0
301(format #t "~f" "1e-1") @print{} 0.1
302@end example
303
80a894c9
KR
304@nicode{~@@f} prints a @nicode{+} sign on positive numbers (including
305zero).
76d3f3d4
KR
306
307@example
308(format #t "~@@f" 0) @print{} +0.0
309@end example
310
311If the output is less than @var{width} characters it's padded on the
312left with @var{padchar} (space by default). If the output equals or
313exceeds @var{width} then there's no padding. The default for
314@var{width} is no padding.
315
316@example
317(format #f "~6f" -1.5) @result{} " -1.5"
318(format #f "~6,,,,'*f" 23) @result{} "**23.0"
319(format #f "~6f" 1234567.0) @result{} "1234567.0"
320@end example
321
322@var{decimals} is how many digits to print after the decimal point,
323with the value rounded or padded with zeros as necessary. (The
324default is to output as many decimals as required.)
325
326@example
327(format #t "~1,2f" 3.125) @print{} 3.13
328(format #t "~1,2f" 1.5) @print{} 1.50
329@end example
330
331@var{scale} is a power of 10 applied to the value, moving the decimal
332point that many places. A positive @var{scale} increases the value
333shown, a negative decreases it.
334
335@example
336(format #t "~,,2f" 1234) @print{} 123400.0
337(format #t "~,,-2f" 1234) @print{} 12.34
338@end example
339
340If @var{overflowchar} and @var{width} are both given and if the output
341would exceed @var{width}, then that many @var{overflowchar}s are
342printed instead of the value.
343
344@example
345(format #t "~5,,,'xf" 12345) @print{} 12345
346(format #t "~4,,,'xf" 12345) @print{} xxxx
347@end example
348
349@item @nicode{~e}
350Exponential float. Parameters: @var{width}, @var{mantdigits},
351@var{expdigits}, @var{intdigits}, @var{overflowchar}, @var{padchar},
352@var{expchar}.
353
354Output a number or number string in exponential notation.
355
356@example
357(format #t "~e" 5000.25) @print{} 5.00025E+3
358(format #t "~e" "123.4") @print{} 1.234E+2
359(format #t "~e" "1e4") @print{} 1.0E+4
360@end example
361
80a894c9
KR
362@nicode{~@@e} prints a @nicode{+} sign on positive numbers (including
363zero). (This is for the mantissa, a @nicode{+} or @nicode{-} sign is
364always shown on the exponent.)
76d3f3d4
KR
365
366@example
367(format #t "~@@e" 5000.0) @print{} +5.0E+3
368@end example
369
370If the output is less than @var{width} characters it's padded on the
371left with @var{padchar} (space by default). The default for
372@var{width} is to output with no padding.
373
374@example
375(format #f "~10e" 1234.0) @result{} " 1.234E+3"
376(format #f "~10,,,,,'*e" 0.5) @result{} "****5.0E-1"
377@end example
378
379@c FIXME: Describe what happens when the number is bigger than WIDTH.
380@c There seems to be a bit of dodginess about this, or some deviation
381@c from Common Lisp.
382
383@var{mantdigits} is the number of digits shown in the mantissa after
384the decimal point. The value is rounded or trailing zeros are added
385as necessary. The default @var{mantdigits} is to show as much as
386needed by the value.
387
388@example
389(format #f "~,3e" 11111.0) @result{} "1.111E+4"
390(format #f "~,8e" 123.0) @result{} "1.23000000E+2"
391@end example
392
393@var{expdigits} is the minimum number of digits shown for the
394exponent, with leading zeros added if necessary. The default for
395@var{expdigits} is to show only as many digits as required. At least
3961 digit is always shown.
397
398@example
399(format #f "~,,1e" 1.0e99) @result{} "1.0E+99"
400(format #f "~,,6e" 1.0e99) @result{} "1.0E+000099"
401@end example
402
403@var{intdigits} (default 1) is the number of digits to show before the
404decimal point in the mantissa. @var{intdigits} can be zero, in which
405case the integer part is a single @nicode{0}, or it can be negative,
406in which case leading zeros are shown after the decimal point.
407
408@c FIXME: When INTDIGITS is 0, Common Lisp format apparently only
409@c shows the single 0 digit if it fits in WIDTH. format.scm seems to
410@c show it always. Is it meant to?
411
412@example
413(format #t "~,,,3e" 12345.0) @print{} 123.45E+2
414(format #t "~,,,0e" 12345.0) @print{} 0.12345E+5
415(format #t "~,,,-3e" 12345.0) @print{} 0.00012345E+8
416@end example
417
418@c FIXME: MANTDIGITS with negative INTDIGITS doesn't match CL spec,
419@c believe the spec says it ought to still show mantdigits+1 sig
420@c figures, ie. leading zeros don't count towards MANTDIGITS, but it
421@c seems to just treat MANTDIGITS as how many digits after the
422@c decimal point.
423
424If @var{overflowchar} is given then @var{width} is a hard limit. If
425the output would exceed @var{width} then instead that many
426@var{overflowchar}s are printed.
427
428@example
429(format #f "~6,,,,'xe" 100.0) @result{} "1.0E+2"
430(format #f "~3,,,,'xe" 100.0) @result{} "xxx"
431@end example
432
433@var{expchar} is the exponent marker character (default @nicode{E}).
434
435@example
436(format #t "~,,,,,,'ee" 100.0) @print{} 1.0e+2
437@end example
438
439@item @nicode{~g}
440General float. Parameters: @var{width}, @var{mantdigits},
441@var{expdigits}, @var{intdigits}, @var{overflowchar}, @var{padchar},
442@var{expchar}.
443
444Output a number or number string in either exponential format the same
445as @nicode{~e}, or fixed-point format like @nicode{~f} but aligned
446where the mantissa would have been and followed by padding where the
447exponent would have been.
448
449@c FIXME: The default MANTDIGITS is apparently max(needed,min(n,7))
450@c where 10^(n-1)<=abs(x)<=10^n. But the Common Lisp spec seems to
451@c ask for "needed" to be without leading or trailing zeros, whereas
452@c format.scm seems to include trailing zeros, ending up with it
453@c using fixed format for bigger values than it should.
454
455Fixed-point is used when the absolute value is 0.1 or more and it
456takes no more space than the mantissa in exponential format, ie.@:
457basically up to @var{mantdigits} digits.
458
459@example
460(format #f "~12,4,2g" 999.0) @result{} " 999.0 "
461(format #f "~12,4,2g" "100000") @result{} " 1.0000E+05"
462@end example
463
464The parameters are interpreted as per @nicode{~e} above. When
465fixed-point is used, the @var{decimals} parameter to @nicode{~f} is
466established from @var{mantdigits}, so as to give a total
467@math{@var{mantdigits}+1} figures.
468
469@item @nicode{~$}
470Monetary style fixed-point float. Parameters: @var{decimals},
471@var{intdigits}, @var{width}, @var{padchar}.
472
473@c For reference, fmtdoc.txi from past versions of slib showed the
474@c INTDIGITS parameter as SCALE. That looks like a typo, in the code
475@c and in the Common Lisp spec it's a minimum digits for the integer
476@c part, it isn't a power of 10 like in ~f.
477
478Output a number or number string in fixed-point format, ie.@: with a
479decimal point. @var{decimals} is the number of decimal places to
480show, default 2.
481
482@example
483(format #t "~$" 5) @print{} 5.00
484(format #t "~4$" "2.25") @print{} 2.2500
485(format #t "~4$" "1e-2") @print{} 0.0100
486@end example
487
80a894c9
KR
488@nicode{~@@$} prints a @nicode{+} sign on positive numbers (including
489zero).
76d3f3d4
KR
490
491@example
492(format #t "~@@$" 0) @print{} +0.00
493@end example
494
495@var{intdigits} is a minimum number of digits to show in the integer
496part of the value (default 1).
497
498@example
499(format #t "~,3$" 9.5) @print{} 009.50
500(format #t "~,0$" 0.125) @print{} .13
501@end example
502
503If the output is less than @var{width} characters (default 0), it's
80a894c9
KR
504padded on the left with @var{padchar} (default space). @nicode{~:$}
505puts the padding after the sign.
76d3f3d4
KR
506
507@example
508(format #f "~,,8$" -1.5) @result{} " -1.50"
509(format #f "~,,8:$" -1.5) @result{} "- 1.50"
40296bab 510(format #f "~,,8,'.:@@$" 3) @result{} "+...3.00"
76d3f3d4
KR
511@end example
512
513Note that floating point for dollar amounts is generally not a good
514idea, because a cent @math{0.01} cannot be represented exactly in the
515binary floating point Guile uses, which leads to slowly accumulating
516rounding errors. Keeping values as cents (or fractions of a cent) in
517integers then printing with the scale option in @nicode{~f} may be a
518better approach.
519
520@c For reference, fractions don't work with ~$ (or any of the float
521@c conversions) currently. If they did work then we could perhaps
522@c suggest keeping dollar amounts as rationals, which would of course
523@c give exact cents. An integer as cents is probably still a better
524@c recommendation though, since it forces one to think about where
525@c and when rounding can or should occur.
526
527@item @nicode{~i}
528Complex fixed-point float. Parameters: @var{width}, @var{decimals},
529@var{scale}, @var{overflowchar}, @var{padchar}.
530
531@c For reference, in Common Lisp ~i is an indent, but slib fmtdoc.txi
532@c described it as complex number output, so we keep that.
533
534Output the argument as a complex number, with both real and imaginary
535part shown (even if one or both are zero).
536
537The parameters and modifiers are the same as for fixed-point
538@nicode{~f} described above. The real and imaginary parts are both
539output with the same given parameters and modifiers, except that for
540the imaginary part the @nicode{@@} modifier is always enabled, so as
541to print a @nicode{+} sign between the real and imaginary parts.
542
543@example
544(format #t "~i" 1) @print{} 1.0+0.0i
545@end example
546
547@item @nicode{~p}
548Plural. No parameters.
549
550Output nothing if the argument is 1, or @samp{s} for any other
551value.
552
553@example
554(format #t "enter name~p" 1) @print{} enter name
555(format #t "enter name~p" 2) @print{} enter names
556@end example
557
80a894c9 558@nicode{~@@p} prints @samp{y} for 1 or @samp{ies} otherwise.
76d3f3d4
KR
559
560@example
561(format #t "pupp~@@p" 1) @print{} puppy
562(format #t "pupp~@@p" 2) @print{} puppies
563@end example
564
80a894c9
KR
565@nicode{~:p} re-uses the preceding argument instead of taking a new
566one, which can be convenient when printing some sort of count.
76d3f3d4
KR
567
568@example
80a894c9 569(format #t "~d cat~:p" 9) @print{} 9 cats
40296bab 570(format #t "~d pupp~:@@p" 5) @print{} 5 puppies
76d3f3d4
KR
571@end example
572
80a894c9
KR
573@nicode{~p} is designed for English plurals and there's no attempt to
574support other languages. @nicode{~[} conditionals (below) may be able
575to help. When using @code{gettext} to translate messages
576@code{ngettext} is probably best though
577(@pxref{Internationalization}).
578
76d3f3d4
KR
579@item @nicode{~y}
580Pretty print. No parameters.
581
582Output an argument with @code{pretty-print} (@pxref{Pretty Printing}).
583
584@item @nicode{~?}
585@itemx @nicode{~k}
586Sub-format. No parameters.
587
588Take a format string argument and a second argument which is a list of
80a894c9
KR
589arguments for that string, and output the result.
590
591@example
592(format #t "~?" "~d ~d" '(1 2)) @print{} 1 2
593@end example
594
595@nicode{~@@?} takes arguments for the sub-format directly rather than
596in a list.
76d3f3d4
KR
597
598@example
76d3f3d4
KR
599(format #t "~@@? ~s" "~d ~d" 1 2 "foo") @print{} 1 2 "foo"
600@end example
601
602@nicode{~?} and @nicode{~k} are the same, @nicode{~k} is provided for
603T-Scheme compatibility.
604
605@item @nicode{~*}
606Argument jumping. Parameter: @var{N}.
607
80a894c9
KR
608Move forward @var{N} arguments (default 1) in the argument list.
609@nicode{~:*} moves backwards. (@var{N} cannot be negative.)
a0e07ba4 610
76d3f3d4 611@example
471d2c6d
KR
612(format #f "~d ~2*~d" 1 2 3 4) @result{} "1 4"
613(format #f "~d ~:*~d" 6) @result{} "6 6"
76d3f3d4 614@end example
a0e07ba4 615
80a894c9
KR
616@nicode{~@@*} moves to argument number @var{N}. The first argument is
617number 0 (and that's the default for @var{N}).
a0e07ba4 618
76d3f3d4
KR
619@example
620(format #f "~d~d again ~@@*~d~d" 1 2) @result{} "12 again 12"
621(format #f "~d~d~d ~1@@*~d~d" 1 2 3) @result{} "123 23"
622@end example
a0e07ba4 623
471d2c6d
KR
624A @nicode{#} move to the end followed by a @nicode{:} modifier move
625back can be used for an absolute position relative to the end of the
626argument list, a reverse of what the @nicode{@@} modifier does.
a0e07ba4 627
76d3f3d4 628@example
471d2c6d 629(format #t "~#*~2:*~a" 'a 'b 'c 'd) @print{} c
76d3f3d4 630@end example
a0e07ba4 631
72b3aa56 632At the end of the format string the current argument position doesn't
471d2c6d 633matter, any further arguments are ignored.
a0e07ba4 634
76d3f3d4
KR
635@item @nicode{~t}
636Advance to a column position. Parameters: @var{colnum}, @var{colinc},
637@var{padchar}.
a0e07ba4 638
76d3f3d4
KR
639Output @var{padchar} (space by default) to move to the given
640@var{colnum} column. The start of the line is column 0, the default
641for @var{colnum} is 1.
a0e07ba4 642
76d3f3d4
KR
643@example
644(format #f "~tX") @result{} " X"
645(format #f "~3tX") @result{} " X"
646@end example
a0e07ba4 647
76d3f3d4
KR
648If the current column is already past @var{colnum}, then the move is
649to there plus a multiple of @var{colinc}, ie.@: column
650@math{@var{colnum} + @var{N} * @var{colinc}} for the smallest @var{N}
651which makes that value greater than or equal to the current column.
652The default @var{colinc} is 1 (which means no further move).
a0e07ba4 653
76d3f3d4
KR
654@example
655(format #f "abcd~2,5,'.tx") @result{} "abcd...x"
656@end example
a0e07ba4 657
80a894c9
KR
658@nicode{~@@t} takes @var{colnum} as an offset from the current column.
659@var{colnum} many pad characters are output, then further padding to
660make the current column a multiple of @var{colinc}, if it isn't
661already so.
76d3f3d4
KR
662
663@example
664(format #f "a~3,5'*@@tx") @result{} "a****x"
665@end example
666
471d2c6d
KR
667@nicode{~t} is implemented using @code{port-column} (@pxref{Reading}),
668so it works even there has been other output before @code{format}.
669
76d3f3d4
KR
670@item @nicode{~~}
671Tilde character. Parameter: @var{n}.
672
673Output a tilde character @nicode{~}, or @var{n} many if a parameter is
674given. Normally @nicode{~} introduces an escape sequence, @nicode{~~}
675is the way to output a literal tilde.
676
677@item @nicode{~%}
678Newline. Parameter: @var{n}.
679
680Output a newline character, or @var{n} many if a parameter is given.
681A newline (or a few newlines) can of course be output just by
682including them in the format string.
683
684@item @nicode{~&}
685Start a new line. Parameter: @var{n}.
686
687Output a newline if not already at the start of a line. With a
688parameter, output that many newlines, but with the first only if not
689already at the start of a line. So for instance 3 would be a newline
690if not already at the start of a line, and 2 further newlines.
691
692@item @nicode{~_}
693Space character. Parameter: @var{n}.
694
695@c For reference, in Common Lisp ~_ is a conditional newline, but
696@c slib fmtdoc.txi described it as a space, so we keep that.
697
698Output a space character, or @var{n} many if a parameter is given.
699
700With a variable parameter this is one way to insert runtime calculated
701padding (@nicode{~t} or the various field widths can do similar
702things).
703
704@example
705(format #f "~v_foo" 4) @result{} " foo"
706@end example
707
708@item @nicode{~/}
709Tab character. Parameter: @var{n}.
710
711Output a tab character, or @var{n} many if a parameter is given.
712
713@item @nicode{~|}
714Formfeed character. Parameter: @var{n}.
715
716Output a formfeed character, or @var{n} many if a parameter is given.
717
718@item @nicode{~!}
719Force output. No parameters.
720
721At the end of output, call @code{force-output} to flush any buffers on
722the destination (@pxref{Writing}). @nicode{~!} can occur anywhere in
723the format string, but the force is done at the end of output.
724
725When output is to a string (destination @code{#f}), @nicode{~!} does
726nothing.
727
728@item @nicode{~newline} (ie.@: newline character)
729Continuation line. No parameters.
730
731Skip this newline and any following whitespace in the format string,
80a894c9
KR
732ie.@: don't send it to the output. This can be used to break up a
733long format string for readability, but not print the extra
76d3f3d4
KR
734whitespace.
735
76d3f3d4
KR
736@example
737(format #f "abc~
738 ~d def~
739 ~d" 1 2) @result{} "abc1 def2"
740@end example
741
80a894c9
KR
742@nicode{~:newline} skips the newline but leaves any further whitespace
743to be printed normally.
744
745@nicode{~@@newline} prints the newline then skips following
746whitespace.
747
76d3f3d4 748@item @nicode{~(} @nicode{~)}
f0a9ab4d
KR
749Case conversion. No parameters.
750
751Between @nicode{~(} and @nicode{~)} the case of all output is changed.
752The modifiers on @nicode{~(} control the conversion.
76d3f3d4 753
f47029a1 754@itemize @w{}
76d3f3d4 755@item
80a894c9 756@nicode{~(} --- lower case.
76d3f3d4
KR
757@c
758@c FIXME: The : and @ modifiers are not yet documented because the
759@c code applies string-capitalize and string-capitalize-first to each
760@c separate format:out-str call, which has various subtly doubtful
761@c effects. And worse they're applied to individual characters,
762@c including literal characters in the format string, which has the
763@c silly effect of being always an upcase.
764@c
765@c The Common Lisp spec is apparently for the capitalization to be
766@c applied in one hit to the whole of the output between ~( and ~).
767@c (This can no doubt be implemented without accumulating all that
768@c text, just by keeping a state or the previous char to tell whether
769@c within a word.)
770@c
771@c @item
772@c @nicode{:} --- first letter of each word upper case, the rest lower
773@c case, as per the @code{string-capitalize} function (@pxref{Alphabetic
774@c Case Mapping}).
775@c @item
776@c @nicode{@@} --- first letter of just the first word upper case, the
777@c rest lower case.
778@c
779@item
40296bab 780@nicode{~:@@(} --- upper case.
76d3f3d4
KR
781@end itemize
782
783For example,
784
785@example
786(format #t "~(Hello~)") @print{} hello
40296bab 787(format #t "~:@@(Hello~)") @print{} HELLO
76d3f3d4
KR
788@end example
789
790In the future it's intended the modifiers @nicode{:} and @nicode{@@}
791alone will capitalize the first letters of words, as per Common Lisp
792@code{format}, but the current implementation of this is flawed and
793not recommended for use.
794
795Case conversions do not nest, currently. This might change in the
796future, but if it does then it will be to Common Lisp style where the
797outermost conversion has priority, overriding inner ones (making those
798fairly pointless).
799
800@item @nicode{~@{} @nicode{~@}}
801Iteration. Parameter: @var{maxreps} (for @nicode{~@{}).
802
803The format between @nicode{~@{} and @nicode{~@}} is iterated. The
804modifiers to @nicode{~@{} determine how arguments are taken. The
805default is a list argument with each iteration successively consuming
806elements from it. This is a convenient way to output a whole list.
807
808@example
809(format #t "~@{~d~@}" '(1 2 3)) @print{} 123
810(format #t "~@{~s=~d ~@}" '("x" 1 "y" 2)) @print{} "x"=1 "y"=2
811@end example
812
80a894c9
KR
813@nicode{~:@{} takes a single argument which is a list of lists, each
814of those contained lists gives the arguments for the iterated format.
76d3f3d4 815
40296bab 816@c @print{} on a new line here to avoid overflowing page width in DVI
76d3f3d4 817@example
40296bab
KR
818(format #t "~:@{~dx~d ~@}" '((1 2) (3 4) (5 6)))
819@print{} 1x2 3x4 5x6
76d3f3d4
KR
820@end example
821
80a894c9
KR
822@nicode{~@@@{} takes arguments directly, with each iteration
823successively consuming arguments.
76d3f3d4
KR
824
825@example
826(format #t "~@@@{~d~@}" 1 2 3) @print{} 123
827(format #t "~@@@{~s=~d ~@}" "x" 1 "y" 2) @print{} "x"=1 "y"=2
828@end example
829
40296bab 830@nicode{~:@@@{} takes list arguments, one argument for each iteration,
80a894c9 831using that list for the format.
76d3f3d4 832
40296bab 833@c @print{} on a new line here to avoid overflowing page width in DVI
76d3f3d4 834@example
40296bab
KR
835(format #t "~:@@@{~dx~d ~@}" '(1 2) '(3 4) '(5 6))
836@print{} 1x2 3x4 5x6
76d3f3d4
KR
837@end example
838
839Iterating stops when there are no more arguments or when the
840@var{maxreps} parameter to @nicode{~@{} is reached (default no
841maximum).
842
843@example
844(format #t "~2@{~d~@}" '(1 2 3 4)) @print{} 12
845@end example
846
847If the format between @nicode{~@{} and @nicode{~@}} is empty, then a
848format string argument is taken (before iteration argument(s)) and
849used instead. This allows a sub-format (like @nicode{~?} above) to be
850iterated.
851
852@example
853(format #t "~@{~@}" "~d" '(1 2 3)) @print{} 123
854@end example
855
856@c FIXME: What is the @nicode{:} modifier to ~} meant to do? The
857@c Common Lisp spec says it's a minimum of 1 iteration, but the
858@c format.scm code seems to merely make it have MAXREPS default to 1.
859
860Iterations can be nested, an inner iteration operates in the same way
861as described, but of course on the arguments the outer iteration
862provides it. This can be used to work into nested list structures.
863For example in the following the inner @nicode{~@{~d~@}x} is applied
864to @code{(1 2)} then @code{(3 4 5)} etc.
865
866@example
867(format #t "~@{~@{~d~@}x~@}" '((1 2) (3 4 5))) @print{} 12x345x
868@end example
869
80a894c9
KR
870See also @nicode{~^} below for escaping from iteration.
871
76d3f3d4
KR
872@item @nicode{~[} @nicode{~;} @nicode{~]}
873Conditional. Parameter: @var{selector}.
874
875A conditional block is delimited by @nicode{~[} and @nicode{~]}, and
876@nicode{~;} separates clauses within the block. @nicode{~[} takes an
877integer argument and that number clause is used. The first clause is
878number 0.
879
880@example
881(format #f "~[peach~;banana~;mango~]" 1) @result{} "banana"
882@end example
883
884The @var{selector} parameter can be used for the clause number,
885instead of taking an argument.
886
887@example
888(format #f "~2[peach~;banana~;mango~]") @result{} "mango"
889@end example
890
891If the clause number is out of range then nothing is output. Or the
80a894c9 892last clause can be @nicode{~:;} to use that for a number out of range.
76d3f3d4
KR
893
894@example
895(format #f "~[banana~;mango~]" 99) @result{} ""
896(format #f "~[banana~;mango~:;fruit~]" 99) @result{} "fruit"
897@end example
898
80a894c9
KR
899@nicode{~:[} treats the argument as a flag, and expects two clauses.
900The first is used if the argument is @code{#f} or the second
901otherwise.
76d3f3d4
KR
902
903@example
904(format #f "~:[false~;not false~]" #f) @result{} "false"
905(format #f "~:[false~;not false~]" 'abc) @result{} "not false"
906
907(let ((n 3))
908 (format #t "~d gnu~:[s are~; is~] here" n (= 1 n)))
909@print{} 3 gnus are here
910@end example
911
80a894c9
KR
912@nicode{~@@[} also treats the argument as a flag, and expects one
913clause. If the argument is @code{#f} then no output is produced and
914the argument is consumed, otherwise the clause is used and the
915argument is not consumed, it's left for the clause. This can be used
916for instance to suppress output if @code{#f} means something not
917available.
76d3f3d4
KR
918
919@example
920(format #f "~@@[temperature=~d~]" 27) @result{} "temperature=27"
921(format #f "~@@[temperature=~d~]" #f) @result{} ""
922@end example
923
924@item @nicode{~^}
925Escape. Parameters: @var{val1}, @var{val2}, @var{val3}.
926
927Stop formatting if there are no more arguments. This can be used for
80a894c9 928instance to have a format string adapt to a variable number of
76d3f3d4
KR
929arguments.
930
931@example
932(format #t "~d~^ ~d" 1) @print{} 1
933(format #t "~d~^ ~d" 1 2) @print{} 1 2
934@end example
935
936Within a @nicode{~@{} @nicode{~@}} iteration, @nicode{~^} stops the
937current iteration step if there are no more arguments to that step,
80a894c9
KR
938but continuing with possible further steps and the rest of the format.
939This can be used for instance to avoid a separator on the last
940iteration, or to adapt to variable length argument lists.
76d3f3d4
KR
941
942@example
943(format #f "~@{~d~^/~@} go" '(1 2 3)) @result{} "1/2/3 go"
944(format #f "~:@{ ~d~^~d~@} go" '((1) (2 3))) @result{} " 1 23 go"
945@end example
946
947@c For reference, format.scm doesn't implement that Common Lisp ~:^
948@c modifier which stops the entire iterating of ~:{ or ~@:{.
949
950@c FIXME: Believe the Common Lisp spec is for ~^ within ~[ ~]
951@c conditional to terminate the whole format (or iteration step if in
952@c an iteration). But format.scm seems to terminate just the
953@c conditional form.
954@c
955@c (format #f "~[abc~^def~;ghi~] blah" 0)
956@c @result{} "abc blah" ;; looks wrong
957
958@c FIXME: Believe the Common Lisp spec is for ~^ within ~( ~) to end
959@c that case conversion and then also terminate the whole format (or
960@c iteration step if in an iteration). But format.scm doesn't seem
961@c to do that quite right.
962@c
963@c (format #f "~d ~^ ~d" 1) @result{} "1 "
964@c (format #f "~(~d ~^ ~d~)" 1) @result{} ERROR
965
966Within a @nicode{~?} sub-format, @nicode{~^} operates just on that
967sub-format. If it terminates the sub-format then the originating
968format will still continue.
969
970@example
971(format #t "~? items" "~d~^ ~d" '(1)) @print{} 1 items
972(format #t "~? items" "~d~^ ~d" '(1 2)) @print{} 1 2 items
973@end example
974
975The parameters to @nicode{~^} (which are numbers) change the condition
976used to terminate. For a single parameter, termination is when that
977value is zero (notice this makes plain @nicode{~^} equivalent to
978@nicode{~#^}). For two parameters, termination is when those two are
979equal. For three parameters, termination is when @math{@var{val1}
980@le{} @var{val2}} and @math{@var{val2} @le{} @var{val3}}.
981
982@c FIXME: Good examples of these?
983
984@item @nicode{~q}
80a894c9
KR
985Inquiry message. Insert a copyright message into the output.
986
987@nicode{~:q} inserts the format implementation version.
a0e07ba4
NJ
988@end table
989
76d3f3d4 990@sp 1
471d2c6d
KR
991It's an error if there are not enough arguments for the escapes in the
992format string, but any excess arguments are ignored.
76d3f3d4
KR
993
994Iterations @nicode{~@{} @nicode{~@}} and conditionals @nicode{~[}
995@nicode{~;} @nicode{~]} can be nested, but must be properly nested,
996meaning the inner form must be entirely within the outer form. So
997it's not possible, for instance, to try to conditionalize the endpoint
998of an iteration.
999
1000@example
1001(format #t "~@{ ~[ ... ~] ~@}" ...) ;; good
1002(format #t "~@{ ~[ ... ~@} ... ~]" ...) ;; bad
1003@end example
1004
1005The same applies to case conversions @nicode{~(} @nicode{~)}, they
1006must properly nest with respect to iterations and conditionals (though
1007currently a case conversion cannot nest within another case
1008conversion).
1009
1010When a sub-format (@nicode{~?}) is used, that sub-format string must
1011be self-contained. It cannot for instance give a @nicode{~@{} to
1012begin an iteration form and have the @nicode{~@}} up in the
1013originating format, or similar.
a0e07ba4
NJ
1014@end deffn
1015
76d3f3d4
KR
1016@sp 1
1017Guile contains a @code{format} procedure even when the module
1018@code{(ice-9 format)} is not loaded. The default @code{format} is
1019@code{simple-format} (@pxref{Writing}), it doesn't support all escape
1020sequences documented in this section, and will signal an error if you
1021try to use one of them. The reason for two versions is that the full
1022@code{format} is fairly large and requires some time to load.
1023@code{simple-format} is often adequate too.
a0e07ba4
NJ
1024
1025
6da1534c 1026@node File Tree Walk
3229f68b 1027@section File Tree Walk
6da1534c
KR
1028@cindex file tree walk
1029
1030The functions in this section traverse a tree of files and
1031directories, in a fashion similar to the C @code{ftw} and @code{nftw}
1032routines (@pxref{Working with Directory Trees,,, libc, GNU C Library
1033Reference Manual}).
1034
1035@example
1036(use-modules (ice-9 ftw))
1037@end example
1038@sp 1
1039
1040@defun ftw startname proc ['hash-size n]
c4e84357 1041Walk the file system tree descending from @var{startname}, calling
6da1534c
KR
1042@var{proc} for each file and directory.
1043
1044Hard links and symbolic links are followed. A file or directory is
1045reported to @var{proc} only once, and skipped if seen again in another
1046place. One consequence of this is that @code{ftw} is safe against
1047circularly linked directory structures.
1048
1049Each @var{proc} call is @code{(@var{proc} filename statinfo flag)} and
1050it should return @code{#t} to continue, or any other value to stop.
1051
1052@var{filename} is the item visited, being @var{startname} plus a
1053further path and the name of the item. @var{statinfo} is the return
1054from @code{stat} (@pxref{File System}) on @var{filename}. @var{flag}
1055is one of the following symbols,
1056
1057@table @code
1058@item regular
1059@var{filename} is a file, this includes special files like devices,
1060named pipes, etc.
1061
1062@item directory
1063@var{filename} is a directory.
1064
1065@item invalid-stat
1066An error occurred when calling @code{stat}, so nothing is known.
1067@var{statinfo} is @code{#f} in this case.
1068
1069@item directory-not-readable
1070@var{filename} is a directory, but one which cannot be read and hence
1071won't be recursed into.
1072
1073@item symlink
1074@var{filename} is a dangling symbolic link. Symbolic links are
1075normally followed and their target reported, the link itself is
1076reported if the target does not exist.
1077@end table
1078
1079The return value from @code{ftw} is @code{#t} if it ran to completion,
1080or otherwise the non-@code{#t} value from @var{proc} which caused the
1081stop.
1082
1083Optional argument symbol @code{hash-size} and an integer can be given
1084to set the size of the hash table used to track items already visited.
1085(@pxref{Hash Table Reference})
1086
1087@c Actually, it's probably safe to escape from ftw, just need to
1088@c check it.
1089@c
1090In the current implementation, returning non-@code{#t} from @var{proc}
1091is the only valid way to terminate @code{ftw}. @var{proc} must not
1092use @code{throw} or similar to escape.
1093@end defun
1094
1095
1096@defun nftw startname proc ['chdir] ['depth] ['hash-size n] ['mount] ['physical]
c4e84357 1097Walk the file system tree starting at @var{startname}, calling
6da1534c
KR
1098@var{proc} for each file and directory. @code{nftw} has extra
1099features over the basic @code{ftw} described above.
1100
40296bab
KR
1101Like @code{ftw}, hard links and symbolic links are followed. A file
1102or directory is reported to @var{proc} only once, and skipped if seen
1103again in another place. One consequence of this is that @code{nftw}
1104is safe against circular linked directory structures.
6da1534c
KR
1105
1106Each @var{proc} call is @code{(@var{proc} filename statinfo flag
40296bab 1107base level)} and it should return @code{#t} to continue, or any
6da1534c
KR
1108other value to stop.
1109
1110@var{filename} is the item visited, being @var{startname} plus a
1111further path and the name of the item. @var{statinfo} is the return
40296bab
KR
1112from @code{stat} on @var{filename} (@pxref{File System}). @var{base}
1113is an integer offset into @var{filename} which is where the basename
1114for this item begins. @var{level} is an integer giving the directory
1115nesting level, starting from 0 for the contents of @var{startname} (or
1116that item itself if it's a file). @var{flag} is one of the following
1117symbols,
6da1534c
KR
1118
1119@table @code
1120@item regular
40296bab
KR
1121@var{filename} is a file, including special files like devices, named
1122pipes, etc.
6da1534c
KR
1123
1124@item directory
1125@var{filename} is a directory.
1126
1127@item directory-processed
1128@var{filename} is a directory, and its contents have all been visited.
1129This flag is given instead of @code{directory} when the @code{depth}
1130option below is used.
1131
1132@item invalid-stat
1133An error occurred when applying @code{stat} to @var{filename}, so
1134nothing is known about it. @var{statinfo} is @code{#f} in this case.
1135
1136@item directory-not-readable
1137@var{filename} is a directory, but one which cannot be read and hence
1138won't be recursed into.
1139
6da1534c 1140@item stale-symlink
40296bab
KR
1141@var{filename} is a dangling symbolic link. Links are normally
1142followed and their target reported, the link itself is reported if its
1143target does not exist.
1144
1145@item symlink
1146When the @code{physical} option described below is used, this
1147indicates @var{filename} is a symbolic link whose target exists (and
1148is not being followed).
6da1534c
KR
1149@end table
1150
1151The following optional arguments can be given to modify the way
1152@code{nftw} works. Each is passed as a symbol (and @code{hash-size}
1153takes a following integer value).
1154
1155@table @asis
1156@item @code{chdir}
1157Change to the directory containing the item before calling @var{proc}.
1158When @code{nftw} returns the original current directory is restored.
1159
40296bab
KR
1160Under this option, generally the @var{base} parameter to each
1161@var{proc} call should be used to pick out the base part of the
1162@var{filename}. The @var{filename} is still a path but with a changed
1163directory it won't be valid (unless the @var{startname} directory was
1164absolute).
6da1534c
KR
1165
1166@item @code{depth}
1167Visit files ``depth first'', meaning @var{proc} is called for the
1168contents of each directory before it's called for the directory
1169itself. Normally a directory is reported first, then its contents.
1170
1171Under this option, the @var{flag} to @var{proc} for a directory is
1172@code{directory-processed} instead of @code{directory}.
1173
1174@item @code{hash-size @var{n}}
1175Set the size of the hash table used to track items already visited.
1176(@pxref{Hash Table Reference})
1177
1178@item @code{mount}
1179Don't cross a mount point, meaning only visit items on the same
c4e84357 1180file system as @var{startname} (ie.@: the same @code{stat:dev}).
6da1534c
KR
1181
1182@item @code{physical}
1183Don't follow symbolic links, instead report them to @var{proc} as
40296bab
KR
1184@code{symlink}. Dangling links (those whose target doesn't exist) are
1185still reported as @code{stale-symlink}.
6da1534c
KR
1186@end table
1187
1188The return value from @code{nftw} is @code{#t} if it ran to
1189completion, or otherwise the non-@code{#t} value from @var{proc} which
1190caused the stop.
1191
1192@c For reference, one reason not to esacpe is that the current
1193@c directory is not saved and restored with dynamic-wind. Maybe
1194@c changing that would be enough to allow escaping.
1195@c
1196In the current implementation, returning non-@code{#t} from @var{proc}
1197is the only valid way to terminate @code{ftw}. @var{proc} must not
1198use @code{throw} or similar to escape.
1199@end defun
1200
1201
2370f809 1202@node Queues
3229f68b 1203@section Queues
d10196fc 1204@cindex queues
2370f809
KR
1205@tindex Queues
1206
1207@noindent
1208The functions in this section are provided by
1209
1210@example
1211(use-modules (ice-9 q))
1212@end example
1213
1214This module implements queues holding arbitrary scheme objects and
1215designed for efficient first-in / first-out operations.
1216
1217@code{make-q} creates a queue, and objects are entered and removed
23f2b9a3 1218with @code{enq!} and @code{deq!}. @code{q-push!} and @code{q-pop!}
2370f809
KR
1219can be used too, treating the front of the queue like a stack.
1220
1221@sp 1
1222
1223@deffn {Scheme Procedure} make-q
1224Return a new queue.
1225@end deffn
1226
1227@deffn {Scheme Procedure} q? obj
1228Return @code{#t} if @var{obj} is a queue, or @code{#f} if not.
1229
1230Note that queues are not a distinct class of objects but are
1231implemented with cons cells. For that reason certain list structures
1232can get @code{#t} from @code{q?}.
1233@end deffn
1234
1235@deffn {Scheme Procedure} enq! q obj
1236Add @var{obj} to the rear of @var{q}, and return @var{q}.
1237@end deffn
1238
1239@deffn {Scheme Procedure} deq! q
1240@deffnx {Scheme Procedure} q-pop! q
1241Remove and return the front element from @var{q}. If @var{q} is
1242empty, a @code{q-empty} exception is thrown.
1243
1244@code{deq!} and @code{q-pop!} are the same operation, the two names
1245just let an application match @code{enq!} with @code{deq!}, or
1246@code{q-push!} with @code{q-pop!}.
1247@end deffn
1248
1249@deffn {Scheme Procedure} q-push! q obj
1250Add @var{obj} to the front of @var{q}, and return @var{q}.
1251@end deffn
1252
1253@deffn {Scheme Procedure} q-length q
1254Return the number of elements in @var{q}.
1255@end deffn
1256
1257@deffn {Scheme Procedure} q-empty? q
1258Return true if @var{q} is empty.
1259@end deffn
1260
1261@deffn {Scheme Procedure} q-empty-check q
1262Throw a @code{q-empty} exception if @var{q} is empty.
1263@end deffn
1264
1265@deffn {Scheme Procedure} q-front q
1266Return the first element of @var{q} (without removing it). If @var{q}
1267is empty, a @code{q-empty} exception is thrown.
1268@end deffn
1269
1270@deffn {Scheme Procedure} q-rear q
1271Return the last element of @var{q} (without removing it). If @var{q}
1272is empty, a @code{q-empty} exception is thrown.
1273@end deffn
1274
1275@deffn {Scheme Procedure} q-remove! q obj
72b3aa56 1276Remove all occurrences of @var{obj} from @var{q}, and return @var{q}.
2370f809
KR
1277@var{obj} is compared to queue elements using @code{eq?}.
1278@end deffn
1279
1280@sp 1
1281@cindex @code{q-empty}
1282The @code{q-empty} exceptions described above are thrown just as
1283@code{(throw 'q-empty)}, there's no message etc like an error throw.
1284
1285A queue is implemented as a cons cell, the @code{car} containing a
1286list of queued elements, and the @code{cdr} being the last cell in
1287that list (for ease of enqueuing).
1288
1289@example
1290(@var{list} . @var{last-cell})
1291@end example
1292
1293@noindent
1294If the queue is empty, @var{list} is the empty list and
1295@var{last-cell} is @code{#f}.
1296
1297An application can directly access the queue list if desired, for
1298instance to search the elements or to insert at a specific point.
1299
1300@deffn {Scheme Procedure} sync-q! q
1301Recompute the @var{last-cell} field in @var{q}.
1302
1303All the operations above maintain @var{last-cell} as described, so
1304normally there's no need for @code{sync-q!}. But if an application
1305modifies the queue @var{list} then it must either maintain
1306@var{last-cell} similarly, or call @code{sync-q!} to recompute it.
1307@end deffn
1308
1309
458dd501
KR
1310@node Streams
1311@section Streams
1312@cindex streams
1313
1314A stream represents a sequence of values, each of which is calculated
1315only when required. This allows large or even infinite sequences to
1316be represented and manipulated with familiar operations like ``car'',
1317``cdr'', ``map'' or ``fold''. In such manipulations only as much as
1318needed is actually held in memory at any one time. The functions in
1319this section are available from
1320
1321@example
1322(use-modules (ice-9 streams))
1323@end example
1324
1325Streams are implemented using promises (@pxref{Delayed Evaluation}),
1326which is how the underlying calculation of values is made only when
1327needed, and the values then retained so the calculation is not
1328repeated.
1329
1330@noindent
1331Here is a simple example producing a stream of all odd numbers,
1332
1333@example
1334(define odds (make-stream (lambda (state)
1335 (cons state (+ state 2)))
1336 1))
1337(stream-car odds) @result{} 1
1338(stream-car (stream-cdr odds)) @result{} 3
1339@end example
1340
1341@noindent
1342@code{stream-map} could be used to derive a stream of odd squares,
1343
1344@example
1345(define (square n) (* n n))
1346(define oddsquares (stream-map square odds))
1347@end example
1348
1349These are infinite sequences, so it's not possible to convert them to
1350a list, but they could be printed (infinitely) with for example
1351
1352@example
1353(stream-for-each (lambda (n sq)
1354 (format #t "~a squared is ~a\n" n sq))
1355 odds oddsquares)
1356@print{}
13571 squared is 1
13583 squared is 9
13595 squared is 25
13607 squared is 49
1361@dots{}
1362@end example
1363
1364@sp 1
1365@defun make-stream proc initial-state
1366Return a new stream, formed by calling @var{proc} successively.
1367
1368Each call is @code{(@var{proc} @var{state})}, it should return a pair,
1369the @code{car} being the value for the stream, and the @code{cdr}
1370being the new @var{state} for the next call. For the first call
1371@var{state} is the given @var{initial-state}. At the end of the
1372stream, @var{proc} should return some non-pair object.
1373@end defun
1374
1375@defun stream-car stream
1376Return the first element from @var{stream}. @var{stream} must not be
1377empty.
1378@end defun
1379
1380@defun stream-cdr stream
1381Return a stream which is the second and subsequent elements of
1382@var{stream}. @var{stream} must not be empty.
1383@end defun
1384
1385@defun stream-null? stream
1386Return true if @var{stream} is empty.
1387@end defun
1388
1389@defun list->stream list
1390@defunx vector->stream vector
1391Return a stream with the contents of @var{list} or @var{vector}.
1392
1393@var{list} or @var{vector} should not be modified subsequently, since
1394it's unspecified whether changes there will be reflected in the stream
1395returned.
1396@end defun
1397
1398@defun port->stream port readproc
1399Return a stream which is the values obtained by reading from
1400@var{port} using @var{readproc}. Each read call is
1401@code{(@var{readproc} @var{port})}, and it should return an EOF object
1402(@pxref{Reading}) at the end of input.
1403
1404For example a stream of characters from a file,
1405
1406@example
1407(port->stream (open-input-file "/foo/bar.txt") read-char)
1408@end example
1409@end defun
1410
1411@defun stream->list stream
1412Return a list which is the entire contents of @var{stream}.
1413@end defun
1414
1415@defun stream->reversed-list stream
1416Return a list which is the entire contents of @var{stream}, but in
1417reverse order.
1418@end defun
1419
1420@defun stream->list&length stream
5179b0e2
KR
1421Return two values (@pxref{Multiple Values}), being firstly a list
1422which is the entire contents of @var{stream}, and secondly the number
1423of elements in that list.
458dd501
KR
1424@end defun
1425
1426@defun stream->reversed-list&length stream
5179b0e2
KR
1427Return two values (@pxref{Multiple Values}) being firstly a list which
1428is the entire contents of @var{stream}, but in reverse order, and
1429secondly the number of elements in that list.
458dd501
KR
1430@end defun
1431
1432@defun stream->vector stream
1433Return a vector which is the entire contents of @var{stream}.
1434@end defun
1435
1436@defun stream-fold proc init stream0 @dots{} streamN
1437Apply @var{proc} successively over the elements of the given streams,
1438from first to last until the end of the shortest stream is reached.
1439Return the result from the last @var{proc} call.
1440
1441Each call is @code{(@var{proc} elem0 @dots{} elemN prev)}, where each
1442@var{elem} is from the corresponding @var{stream}. @var{prev} is the
1443return from the previous @var{proc} call, or the given @var{init} for
1444the first call.
1445@end defun
1446
1447@defun stream-for-each proc stream0 @dots{} streamN
1448Call @var{proc} on the elements from the given @var{stream}s. The
1449return value is unspecified.
1450
1451Each call is @code{(@var{proc} elem0 @dots{} elemN)}, where each
1452@var{elem} is from the corresponding @var{stream}.
1453@code{stream-for-each} stops when it reaches the end of the shortest
1454@var{stream}.
1455@end defun
1456
1457@defun stream-map proc stream0 @dots{} streamN
1458Return a new stream which is the results of applying @var{proc} to the
1459elements of the given @var{stream}s.
1460
1461Each call is @code{(@var{proc} elem0 @dots{} elemN)}, where each
1462@var{elem} is from the corresponding @var{stream}. The new stream
5179b0e2 1463ends when the end of the shortest given @var{stream} is reached.
458dd501
KR
1464@end defun
1465
1466
40296bab
KR
1467@node Buffered Input
1468@section Buffered Input
1469@cindex Buffered input
1470@cindex Line continuation
1471
1472The following functions are provided by
1473
1474@example
1475(use-modules (ice-9 buffered-input))
1476@end example
1477
1478A buffered input port allows a reader function to return chunks of
1479characters which are to be handed out on reading the port. A notion
1480of further input for an application level logical expression is
1481maintained too, and passed through to the reader.
1482
1483@defun make-buffered-input-port reader
1484Create an input port which returns characters obtained from the given
1485@var{reader} function. @var{reader} is called (@var{reader} cont),
1486and should return a string or an EOF object.
1487
1488The new port gives precisely the characters returned by @var{reader},
1489nothing is added, so if any newline characters or other separators are
1490desired they must come from the reader function.
1491
1492The @var{cont} parameter to @var{reader} is @code{#f} for initial
1493input, or @code{#t} when continuing an expression. This is an
1494application level notion, set with
1495@code{set-buffered-input-continuation?!} below. If the user has
1496entered a partial expression then it allows @var{reader} for instance
1497to give a different prompt to show more is required.
1498@end defun
1499
1500@defun make-line-buffered-input-port reader
1501@cindex Line buffered input
1502Create an input port which returns characters obtained from the
1503specified @var{reader} function, similar to
1504@code{make-buffered-input-port} above, but where @var{reader} is
1505expected to be a line-oriented.
1506
1507@var{reader} is called (@var{reader} cont), and should return a string
1508or an EOF object as above. Each string is a line of input without a
1509newline character, the port code inserts a newline after each string.
1510@end defun
1511
1512@defun set-buffered-input-continuation?! port cont
1513Set the input continuation flag for a given buffered input
1514@var{port}.
1515
1516An application uses this by calling with a @var{cont} flag of
1517@code{#f} when beginning to read a new logical expression. For
1518example with the Scheme @code{read} function (@pxref{Scheme Read}),
1519
1520@example
1521(define my-port (make-buffered-input-port my-reader))
1522
1523(set-buffered-input-continuation?! my-port #f)
1524(let ((obj (read my-port)))
1525 ...
1526@end example
1527@end defun
1528
1529
a0e07ba4
NJ
1530@c Local Variables:
1531@c TeX-master: "guile.texi"
1532@c End: