Changes from arch/CVS synchronization
[bpt/guile.git] / doc / ref / api-data.texi
CommitLineData
07d83abe
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
7@page
8@node Simple Data Types
9@section Simple Generic Data Types
10
11This chapter describes those of Guile's simple data types which are
12primarily used for their role as items of generic data. By
13@dfn{simple} we mean data types that are not primarily used as
14containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
15For the documentation of such @dfn{compound} data types, see
16@ref{Compound Data Types}.
17
18@c One of the great strengths of Scheme is that there is no straightforward
19@c distinction between ``data'' and ``functionality''. For example,
20@c Guile's support for dynamic linking could be described:
21
22@c @itemize @bullet
23@c @item
24@c either in a ``data-centric'' way, as the behaviour and properties of the
25@c ``dynamically linked object'' data type, and the operations that may be
26@c applied to instances of this type
27
28@c @item
29@c or in a ``functionality-centric'' way, as the set of procedures that
30@c constitute Guile's support for dynamic linking, in the context of the
31@c module system.
32@c @end itemize
33
34@c The contents of this chapter are, therefore, a matter of judgment. By
35@c @dfn{generic}, we mean to select those data types whose typical use as
36@c @emph{data} in a wide variety of programming contexts is more important
37@c than their use in the implementation of a particular piece of
38@c @emph{functionality}. The last section of this chapter provides
39@c references for all the data types that are documented not here but in a
40@c ``functionality-centric'' way elsewhere in the manual.
41
42@menu
43* Booleans:: True/false values.
44* Numbers:: Numerical data types.
050ab45f
MV
45* Characters:: Single characters.
46* Character Sets:: Sets of characters.
47* Strings:: Sequences of characters.
07d83abe
MV
48* Regular Expressions:: Pattern matching and substitution.
49* Symbols:: Symbols.
50* Keywords:: Self-quoting, customizable display keywords.
51* Other Types:: "Functionality-centric" data types.
52@end menu
53
54
55@node Booleans
56@subsection Booleans
57@tpindex Booleans
58
59The two boolean values are @code{#t} for true and @code{#f} for false.
60
61Boolean values are returned by predicate procedures, such as the general
62equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
63(@pxref{Equality}) and numerical and string comparison operators like
64@code{string=?} (@pxref{String Comparison}) and @code{<=}
65(@pxref{Comparison}).
66
67@lisp
68(<= 3 8)
69@result{} #t
70
71(<= 3 -3)
72@result{} #f
73
74(equal? "house" "houses")
75@result{} #f
76
77(eq? #f #f)
78@result{}
79#t
80@end lisp
81
82In test condition contexts like @code{if} and @code{cond} (@pxref{if
83cond case}), where a group of subexpressions will be evaluated only if a
84@var{condition} expression evaluates to ``true'', ``true'' means any
85value at all except @code{#f}.
86
87@lisp
88(if #t "yes" "no")
89@result{} "yes"
90
91(if 0 "yes" "no")
92@result{} "yes"
93
94(if #f "yes" "no")
95@result{} "no"
96@end lisp
97
98A result of this asymmetry is that typical Scheme source code more often
99uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
100represent an @code{if} or @code{cond} false value, whereas @code{#t} is
101not necessary to represent an @code{if} or @code{cond} true value.
102
103It is important to note that @code{#f} is @strong{not} equivalent to any
104other Scheme value. In particular, @code{#f} is not the same as the
105number 0 (like in C and C++), and not the same as the ``empty list''
106(like in some Lisp dialects).
107
108In C, the two Scheme boolean values are available as the two constants
109@code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
110Care must be taken with the false value @code{SCM_BOOL_F}: it is not
111false when used in C conditionals. In order to test for it, use
112@code{scm_is_false} or @code{scm_is_true}.
113
114@rnindex not
115@deffn {Scheme Procedure} not x
116@deffnx {C Function} scm_not (x)
117Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
118@end deffn
119
120@rnindex boolean?
121@deffn {Scheme Procedure} boolean? obj
122@deffnx {C Function} scm_boolean_p (obj)
123Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
124return @code{#f}.
125@end deffn
126
127@deftypevr {C Macro} SCM SCM_BOOL_T
128The @code{SCM} representation of the Scheme object @code{#t}.
129@end deftypevr
130
131@deftypevr {C Macro} SCM SCM_BOOL_F
132The @code{SCM} representation of the Scheme object @code{#f}.
133@end deftypevr
134
135@deftypefn {C Function} int scm_is_true (SCM obj)
136Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
137@end deftypefn
138
139@deftypefn {C Function} int scm_is_false (SCM obj)
140Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
141@end deftypefn
142
143@deftypefn {C Function} int scm_is_bool (SCM obj)
144Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
145return @code{0}.
146@end deftypefn
147
148@deftypefn {C Function} SCM scm_from_bool (int val)
149Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
150@end deftypefn
151
152@deftypefn {C Function} int scm_to_bool (SCM val)
153Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
154when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
155
156You should probably use @code{scm_is_true} instead of this function
157when you just want to test a @code{SCM} value for trueness.
158@end deftypefn
159
160@node Numbers
161@subsection Numerical data types
162@tpindex Numbers
163
164Guile supports a rich ``tower'' of numerical types --- integer,
165rational, real and complex --- and provides an extensive set of
166mathematical and scientific functions for operating on numerical
167data. This section of the manual documents those types and functions.
168
169You may also find it illuminating to read R5RS's presentation of numbers
170in Scheme, which is particularly clear and accessible: see
171@ref{Numbers,,,r5rs,R5RS}.
172
173@menu
174* Numerical Tower:: Scheme's numerical "tower".
175* Integers:: Whole numbers.
176* Reals and Rationals:: Real and rational numbers.
177* Complex Numbers:: Complex numbers.
178* Exactness:: Exactness and inexactness.
179* Number Syntax:: Read syntax for numerical data.
180* Integer Operations:: Operations on integer values.
181* Comparison:: Comparison predicates.
182* Conversion:: Converting numbers to and from strings.
183* Complex:: Complex number operations.
184* Arithmetic:: Arithmetic functions.
185* Scientific:: Scientific functions.
186* Primitive Numerics:: Primitive numeric functions.
187* Bitwise Operations:: Logical AND, OR, NOT, and so on.
188* Random:: Random number generation.
189@end menu
190
191
192@node Numerical Tower
193@subsubsection Scheme's Numerical ``Tower''
194@rnindex number?
195
196Scheme's numerical ``tower'' consists of the following categories of
197numbers:
198
199@table @dfn
200@item integers
201Whole numbers, positive or negative; e.g.@: --5, 0, 18.
202
203@item rationals
204The set of numbers that can be expressed as @math{@var{p}/@var{q}}
205where @var{p} and @var{q} are integers; e.g.@: @math{9/16} works, but
206pi (an irrational number) doesn't. These include integers
207(@math{@var{n}/1}).
208
209@item real numbers
210The set of numbers that describes all possible positions along a
211one-dimensional line. This includes rationals as well as irrational
212numbers.
213
214@item complex numbers
215The set of numbers that describes all possible positions in a two
216dimensional space. This includes real as well as imaginary numbers
217(@math{@var{a}+@var{b}i}, where @var{a} is the @dfn{real part},
218@var{b} is the @dfn{imaginary part}, and @math{i} is the square root of
219@minus{}1.)
220@end table
221
222It is called a tower because each category ``sits on'' the one that
223follows it, in the sense that every integer is also a rational, every
224rational is also real, and every real number is also a complex number
225(but with zero imaginary part).
226
227In addition to the classification into integers, rationals, reals and
228complex numbers, Scheme also distinguishes between whether a number is
229represented exactly or not. For example, the result of
9f1ba6a9
NJ
230@m{2\sin(\pi/4),2*sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)}, but Guile
231can represent neither @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
07d83abe
MV
232Instead, it stores an inexact approximation, using the C type
233@code{double}.
234
235Guile can represent exact rationals of any magnitude, inexact
236rationals that fit into a C @code{double}, and inexact complex numbers
237with @code{double} real and imaginary parts.
238
239The @code{number?} predicate may be applied to any Scheme value to
240discover whether the value is any of the supported numerical types.
241
242@deffn {Scheme Procedure} number? obj
243@deffnx {C Function} scm_number_p (obj)
244Return @code{#t} if @var{obj} is any kind of number, else @code{#f}.
245@end deffn
246
247For example:
248
249@lisp
250(number? 3)
251@result{} #t
252
253(number? "hello there!")
254@result{} #f
255
256(define pi 3.141592654)
257(number? pi)
258@result{} #t
259@end lisp
260
5615f696
MV
261@deftypefn {C Function} int scm_is_number (SCM obj)
262This is equivalent to @code{scm_is_true (scm_number_p (obj))}.
263@end deftypefn
264
07d83abe
MV
265The next few subsections document each of Guile's numerical data types
266in detail.
267
268@node Integers
269@subsubsection Integers
270
271@tpindex Integer numbers
272
273@rnindex integer?
274
275Integers are whole numbers, that is numbers with no fractional part,
276such as 2, 83, and @minus{}3789.
277
278Integers in Guile can be arbitrarily big, as shown by the following
279example.
280
281@lisp
282(define (factorial n)
283 (let loop ((n n) (product 1))
284 (if (= n 0)
285 product
286 (loop (- n 1) (* product n)))))
287
288(factorial 3)
289@result{} 6
290
291(factorial 20)
292@result{} 2432902008176640000
293
294(- (factorial 45))
295@result{} -119622220865480194561963161495657715064383733760000000000
296@end lisp
297
298Readers whose background is in programming languages where integers are
299limited by the need to fit into just 4 or 8 bytes of memory may find
300this surprising, or suspect that Guile's representation of integers is
301inefficient. In fact, Guile achieves a near optimal balance of
302convenience and efficiency by using the host computer's native
303representation of integers where possible, and a more general
304representation where the required number does not fit in the native
305form. Conversion between these two representations is automatic and
306completely invisible to the Scheme level programmer.
307
308The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
309inexact integers. They are explained in detail in the next section,
310together with reals and rationals.
311
312C has a host of different integer types, and Guile offers a host of
313functions to convert between them and the @code{SCM} representation.
314For example, a C @code{int} can be handled with @code{scm_to_int} and
315@code{scm_from_int}. Guile also defines a few C integer types of its
316own, to help with differences between systems.
317
318C integer types that are not covered can be handled with the generic
319@code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
320signed types, or with @code{scm_to_unsigned_integer} and
321@code{scm_from_unsigned_integer} for unsigned types.
322
323Scheme integers can be exact and inexact. For example, a number
324written as @code{3.0} with an explicit decimal-point is inexact, but
325it is also an integer. The functions @code{integer?} and
326@code{scm_is_integer} report true for such a number, but the functions
327@code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
328allow exact integers and thus report false. Likewise, the conversion
329functions like @code{scm_to_signed_integer} only accept exact
330integers.
331
332The motivation for this behavior is that the inexactness of a number
333should not be lost silently. If you want to allow inexact integers,
334you can explicitely insert a call to @code{inexact->exact} or to its C
335equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
336be converted by this call into exact integers; inexact non-integers
337will become exact fractions.)
338
339@deffn {Scheme Procedure} integer? x
340@deffnx {C Function} scm_integer_p (x)
909fcc97 341Return @code{#t} if @var{x} is an exact or inexact integer number, else
07d83abe
MV
342@code{#f}.
343
344@lisp
345(integer? 487)
346@result{} #t
347
348(integer? 3.0)
349@result{} #t
350
351(integer? -3.4)
352@result{} #f
353
354(integer? +inf.0)
355@result{} #t
356@end lisp
357@end deffn
358
359@deftypefn {C Function} int scm_is_integer (SCM x)
360This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
361@end deftypefn
362
363@defvr {C Type} scm_t_int8
364@defvrx {C Type} scm_t_uint8
365@defvrx {C Type} scm_t_int16
366@defvrx {C Type} scm_t_uint16
367@defvrx {C Type} scm_t_int32
368@defvrx {C Type} scm_t_uint32
369@defvrx {C Type} scm_t_int64
370@defvrx {C Type} scm_t_uint64
371@defvrx {C Type} scm_t_intmax
372@defvrx {C Type} scm_t_uintmax
373The C types are equivalent to the corresponding ISO C types but are
374defined on all platforms, with the exception of @code{scm_t_int64} and
375@code{scm_t_uint64}, which are only defined when a 64-bit type is
376available. For example, @code{scm_t_int8} is equivalent to
377@code{int8_t}.
378
379You can regard these definitions as a stop-gap measure until all
380platforms provide these types. If you know that all the platforms
381that you are interested in already provide these types, it is better
382to use them directly instead of the types provided by Guile.
383@end defvr
384
385@deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
386@deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
387Return @code{1} when @var{x} represents an exact integer that is
388between @var{min} and @var{max}, inclusive.
389
390These functions can be used to check whether a @code{SCM} value will
391fit into a given range, such as the range of a given C integer type.
392If you just want to convert a @code{SCM} value to a given C integer
393type, use one of the conversion functions directly.
394@end deftypefn
395
396@deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
397@deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
398When @var{x} represents an exact integer that is between @var{min} and
399@var{max} inclusive, return that integer. Else signal an error,
400either a `wrong-type' error when @var{x} is not an exact integer, or
401an `out-of-range' error when it doesn't fit the given range.
402@end deftypefn
403
404@deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
405@deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
406Return the @code{SCM} value that represents the integer @var{x}. This
407function will always succeed and will always return an exact number.
408@end deftypefn
409
410@deftypefn {C Function} char scm_to_char (SCM x)
411@deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
412@deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
413@deftypefnx {C Function} short scm_to_short (SCM x)
414@deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
415@deftypefnx {C Function} int scm_to_int (SCM x)
416@deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
417@deftypefnx {C Function} long scm_to_long (SCM x)
418@deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
419@deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
420@deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
421@deftypefnx {C Function} size_t scm_to_size_t (SCM x)
422@deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
423@deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
424@deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
425@deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
426@deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
427@deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
428@deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
429@deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
430@deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
431@deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
432@deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
433When @var{x} represents an exact integer that fits into the indicated
434C type, return that integer. Else signal an error, either a
435`wrong-type' error when @var{x} is not an exact integer, or an
436`out-of-range' error when it doesn't fit the given range.
437
438The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
439@code{scm_to_int64}, and @code{scm_to_uint64} are only available when
440the corresponding types are.
441@end deftypefn
442
443@deftypefn {C Function} SCM scm_from_char (char x)
444@deftypefnx {C Function} SCM scm_from_schar (signed char x)
445@deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
446@deftypefnx {C Function} SCM scm_from_short (short x)
447@deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
448@deftypefnx {C Function} SCM scm_from_int (int x)
449@deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
450@deftypefnx {C Function} SCM scm_from_long (long x)
451@deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
452@deftypefnx {C Function} SCM scm_from_long_long (long long x)
453@deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
454@deftypefnx {C Function} SCM scm_from_size_t (size_t x)
455@deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
456@deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
457@deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
458@deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
459@deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
460@deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
461@deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
462@deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
463@deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
464@deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
465@deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
466Return the @code{SCM} value that represents the integer @var{x}.
467These functions will always succeed and will always return an exact
468number.
469@end deftypefn
470
08962922
MV
471@deftypefn {C Function} void scm_to_mpz (SCM val, mpz_t rop)
472Assign @var{val} to the multiple precision integer @var{rop}.
473@var{val} must be an exact integer, otherwise an error will be
474signalled. @var{rop} must have been initialized with @code{mpz_init}
475before this function is called. When @var{rop} is no longer needed
476the occupied space must be freed with @code{mpz_clear}.
477@xref{Initializing Integers,,, gmp, GNU MP Manual}, for details.
478@end deftypefn
479
9f1ba6a9 480@deftypefn {C Function} SCM scm_from_mpz (mpz_t val)
08962922
MV
481Return the @code{SCM} value that represents @var{val}.
482@end deftypefn
483
07d83abe
MV
484@node Reals and Rationals
485@subsubsection Real and Rational Numbers
486@tpindex Real numbers
487@tpindex Rational numbers
488
489@rnindex real?
490@rnindex rational?
491
492Mathematically, the real numbers are the set of numbers that describe
493all possible points along a continuous, infinite, one-dimensional line.
494The rational numbers are the set of all numbers that can be written as
495fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
496All rational numbers are also real, but there are real numbers that
34942993
KR
497are not rational, for example @m{\sqrt2, the square root of 2}, and
498@m{\pi,pi}.
07d83abe
MV
499
500Guile can represent both exact and inexact rational numbers, but it
501can not represent irrational numbers. Exact rationals are represented
502by storing the numerator and denominator as two exact integers.
503Inexact rationals are stored as floating point numbers using the C
504type @code{double}.
505
506Exact rationals are written as a fraction of integers. There must be
507no whitespace around the slash:
508
509@lisp
5101/2
511-22/7
512@end lisp
513
514Even though the actual encoding of inexact rationals is in binary, it
515may be helpful to think of it as a decimal number with a limited
516number of significant figures and a decimal point somewhere, since
517this corresponds to the standard notation for non-whole numbers. For
518example:
519
520@lisp
5210.34
522-0.00000142857931198
523-5648394822220000000000.0
5244.0
525@end lisp
526
527The limited precision of Guile's encoding means that any ``real'' number
528in Guile can be written in a rational form, by multiplying and then dividing
529by sufficient powers of 10 (or in fact, 2). For example,
530@samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
531100000000000000000. In Guile's current incarnation, therefore, the
532@code{rational?} and @code{real?} predicates are equivalent.
533
534
535Dividing by an exact zero leads to a error message, as one might
536expect. However, dividing by an inexact zero does not produce an
537error. Instead, the result of the division is either plus or minus
538infinity, depending on the sign of the divided number.
539
540The infinities are written @samp{+inf.0} and @samp{-inf.0},
541respectivly. This syntax is also recognized by @code{read} as an
542extension to the usual Scheme syntax.
543
544Dividing zero by zero yields something that is not a number at all:
545@samp{+nan.0}. This is the special `not a number' value.
546
547On platforms that follow @acronym{IEEE} 754 for their floating point
548arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
549are implemented using the corresponding @acronym{IEEE} 754 values.
550They behave in arithmetic operations like @acronym{IEEE} 754 describes
551it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
552
553The infinities are inexact integers and are considered to be both even
554and odd. While @samp{+nan.0} is not @code{=} to itself, it is
555@code{eqv?} to itself.
556
557To test for the special values, use the functions @code{inf?} and
558@code{nan?}.
559
560@deffn {Scheme Procedure} real? obj
561@deffnx {C Function} scm_real_p (obj)
562Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
563that the sets of integer and rational values form subsets of the set
564of real numbers, so the predicate will also be fulfilled if @var{obj}
565is an integer number or a rational number.
566@end deffn
567
568@deffn {Scheme Procedure} rational? x
569@deffnx {C Function} scm_rational_p (x)
570Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
571Note that the set of integer values forms a subset of the set of
572rational numbers, i. e. the predicate will also be fulfilled if
573@var{x} is an integer number.
574
575Since Guile can not represent irrational numbers, every number
576satisfying @code{real?} also satisfies @code{rational?} in Guile.
577@end deffn
578
579@deffn {Scheme Procedure} rationalize x eps
580@deffnx {C Function} scm_rationalize (x, eps)
581Returns the @emph{simplest} rational number differing
582from @var{x} by no more than @var{eps}.
583
584As required by @acronym{R5RS}, @code{rationalize} only returns an
585exact result when both its arguments are exact. Thus, you might need
586to use @code{inexact->exact} on the arguments.
587
588@lisp
589(rationalize (inexact->exact 1.2) 1/100)
590@result{} 6/5
591@end lisp
592
593@end deffn
594
d3df9759
MV
595@deffn {Scheme Procedure} inf? x
596@deffnx {C Function} scm_inf_p (x)
07d83abe
MV
597Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
598@code{#f} otherwise.
599@end deffn
600
601@deffn {Scheme Procedure} nan? x
d3df9759 602@deffnx {C Function} scm_nan_p (x)
07d83abe
MV
603Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
604@end deffn
605
cdf1ad3b
MV
606@deffn {Scheme Procedure} nan
607@deffnx {C Function} scm_nan ()
608Return NaN.
609@end deffn
610
611@deffn {Scheme Procedure} inf
612@deffnx {C Function} scm_inf ()
613Return Inf.
614@end deffn
615
d3df9759
MV
616@deffn {Scheme Procedure} numerator x
617@deffnx {C Function} scm_numerator (x)
618Return the numerator of the rational number @var{x}.
619@end deffn
620
621@deffn {Scheme Procedure} denominator x
622@deffnx {C Function} scm_denominator (x)
623Return the denominator of the rational number @var{x}.
624@end deffn
625
626@deftypefn {C Function} int scm_is_real (SCM val)
627@deftypefnx {C Function} int scm_is_rational (SCM val)
628Equivalent to @code{scm_is_true (scm_real_p (val))} and
629@code{scm_is_true (scm_rational_p (val))}, respectively.
630@end deftypefn
631
632@deftypefn {C Function} double scm_to_double (SCM val)
633Returns the number closest to @var{val} that is representable as a
634@code{double}. Returns infinity for a @var{val} that is too large in
635magnitude. The argument @var{val} must be a real number.
636@end deftypefn
637
638@deftypefn {C Function} SCM scm_from_double (double val)
639Return the @code{SCM} value that representats @var{val}. The returned
640value is inexact according to the predicate @code{inexact?}, but it
641will be exactly equal to @var{val}.
642@end deftypefn
643
07d83abe
MV
644@node Complex Numbers
645@subsubsection Complex Numbers
646@tpindex Complex numbers
647
648@rnindex complex?
649
650Complex numbers are the set of numbers that describe all possible points
651in a two-dimensional space. The two coordinates of a particular point
652in this space are known as the @dfn{real} and @dfn{imaginary} parts of
653the complex number that describes that point.
654
655In Guile, complex numbers are written in rectangular form as the sum of
656their real and imaginary parts, using the symbol @code{i} to indicate
657the imaginary part.
658
659@lisp
6603+4i
661@result{}
6623.0+4.0i
663
664(* 3-8i 2.3+0.3i)
665@result{}
6669.3-17.5i
667@end lisp
668
34942993
KR
669@cindex polar form
670@noindent
671Polar form can also be used, with an @samp{@@} between magnitude and
672angle,
673
674@lisp
6751@@3.141592 @result{} -1.0 (approx)
676-1@@1.57079 @result{} 0.0-1.0i (approx)
677@end lisp
678
07d83abe
MV
679Guile represents a complex number with a non-zero imaginary part as a
680pair of inexact rationals, so the real and imaginary parts of a
681complex number have the same properties of inexactness and limited
682precision as single inexact rational numbers. Guile can not represent
683exact complex numbers with non-zero imaginary parts.
684
5615f696
MV
685@deffn {Scheme Procedure} complex? z
686@deffnx {C Function} scm_complex_p (z)
07d83abe
MV
687Return @code{#t} if @var{x} is a complex number, @code{#f}
688otherwise. Note that the sets of real, rational and integer
689values form subsets of the set of complex numbers, i. e. the
690predicate will also be fulfilled if @var{x} is a real,
691rational or integer number.
692@end deffn
693
c9dc8c6c
MV
694@deftypefn {C Function} int scm_is_complex (SCM val)
695Equivalent to @code{scm_is_true (scm_complex_p (val))}.
696@end deftypefn
697
07d83abe
MV
698@node Exactness
699@subsubsection Exact and Inexact Numbers
700@tpindex Exact numbers
701@tpindex Inexact numbers
702
703@rnindex exact?
704@rnindex inexact?
705@rnindex exact->inexact
706@rnindex inexact->exact
707
708R5RS requires that a calculation involving inexact numbers always
709produces an inexact result. To meet this requirement, Guile
710distinguishes between an exact integer value such as @samp{5} and the
711corresponding inexact real value which, to the limited precision
712available, has no fractional part, and is printed as @samp{5.0}. Guile
713will only convert the latter value to the former when forced to do so by
714an invocation of the @code{inexact->exact} procedure.
715
716@deffn {Scheme Procedure} exact? z
717@deffnx {C Function} scm_exact_p (z)
718Return @code{#t} if the number @var{z} is exact, @code{#f}
719otherwise.
720
721@lisp
722(exact? 2)
723@result{} #t
724
725(exact? 0.5)
726@result{} #f
727
728(exact? (/ 2))
729@result{} #t
730@end lisp
731
732@end deffn
733
734@deffn {Scheme Procedure} inexact? z
735@deffnx {C Function} scm_inexact_p (z)
736Return @code{#t} if the number @var{z} is inexact, @code{#f}
737else.
738@end deffn
739
740@deffn {Scheme Procedure} inexact->exact z
741@deffnx {C Function} scm_inexact_to_exact (z)
742Return an exact number that is numerically closest to @var{z}, when
743there is one. For inexact rationals, Guile returns the exact rational
744that is numerically equal to the inexact rational. Inexact complex
745numbers with a non-zero imaginary part can not be made exact.
746
747@lisp
748(inexact->exact 0.5)
749@result{} 1/2
750@end lisp
751
752The following happens because 12/10 is not exactly representable as a
753@code{double} (on most platforms). However, when reading a decimal
754number that has been marked exact with the ``#e'' prefix, Guile is
755able to represent it correctly.
756
757@lisp
758(inexact->exact 1.2)
759@result{} 5404319552844595/4503599627370496
760
761#e1.2
762@result{} 6/5
763@end lisp
764
765@end deffn
766
767@c begin (texi-doc-string "guile" "exact->inexact")
768@deffn {Scheme Procedure} exact->inexact z
769@deffnx {C Function} scm_exact_to_inexact (z)
770Convert the number @var{z} to its inexact representation.
771@end deffn
772
773
774@node Number Syntax
775@subsubsection Read Syntax for Numerical Data
776
777The read syntax for integers is a string of digits, optionally
778preceded by a minus or plus character, a code indicating the
779base in which the integer is encoded, and a code indicating whether
780the number is exact or inexact. The supported base codes are:
781
782@table @code
783@item #b
784@itemx #B
785the integer is written in binary (base 2)
786
787@item #o
788@itemx #O
789the integer is written in octal (base 8)
790
791@item #d
792@itemx #D
793the integer is written in decimal (base 10)
794
795@item #x
796@itemx #X
797the integer is written in hexadecimal (base 16)
798@end table
799
800If the base code is omitted, the integer is assumed to be decimal. The
801following examples show how these base codes are used.
802
803@lisp
804-13
805@result{} -13
806
807#d-13
808@result{} -13
809
810#x-13
811@result{} -19
812
813#b+1101
814@result{} 13
815
816#o377
817@result{} 255
818@end lisp
819
820The codes for indicating exactness (which can, incidentally, be applied
821to all numerical values) are:
822
823@table @code
824@item #e
825@itemx #E
826the number is exact
827
828@item #i
829@itemx #I
830the number is inexact.
831@end table
832
833If the exactness indicator is omitted, the number is exact unless it
834contains a radix point. Since Guile can not represent exact complex
835numbers, an error is signalled when asking for them.
836
837@lisp
838(exact? 1.2)
839@result{} #f
840
841(exact? #e1.2)
842@result{} #t
843
844(exact? #e+1i)
845ERROR: Wrong type argument
846@end lisp
847
848Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
849plus and minus infinity, respectively. The value must be written
850exactly as shown, that is, they always must have a sign and exactly
851one zero digit after the decimal point. It also understands
852@samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
853The sign is ignored for `not-a-number' and the value is always printed
854as @samp{+nan.0}.
855
856@node Integer Operations
857@subsubsection Operations on Integer Values
858@rnindex odd?
859@rnindex even?
860@rnindex quotient
861@rnindex remainder
862@rnindex modulo
863@rnindex gcd
864@rnindex lcm
865
866@deffn {Scheme Procedure} odd? n
867@deffnx {C Function} scm_odd_p (n)
868Return @code{#t} if @var{n} is an odd number, @code{#f}
869otherwise.
870@end deffn
871
872@deffn {Scheme Procedure} even? n
873@deffnx {C Function} scm_even_p (n)
874Return @code{#t} if @var{n} is an even number, @code{#f}
875otherwise.
876@end deffn
877
878@c begin (texi-doc-string "guile" "quotient")
879@c begin (texi-doc-string "guile" "remainder")
880@deffn {Scheme Procedure} quotient n d
881@deffnx {Scheme Procedure} remainder n d
882@deffnx {C Function} scm_quotient (n, d)
883@deffnx {C Function} scm_remainder (n, d)
884Return the quotient or remainder from @var{n} divided by @var{d}. The
885quotient is rounded towards zero, and the remainder will have the same
886sign as @var{n}. In all cases quotient and remainder satisfy
887@math{@var{n} = @var{q}*@var{d} + @var{r}}.
888
889@lisp
890(remainder 13 4) @result{} 1
891(remainder -13 4) @result{} -1
892@end lisp
893@end deffn
894
895@c begin (texi-doc-string "guile" "modulo")
896@deffn {Scheme Procedure} modulo n d
897@deffnx {C Function} scm_modulo (n, d)
898Return the remainder from @var{n} divided by @var{d}, with the same
899sign as @var{d}.
900
901@lisp
902(modulo 13 4) @result{} 1
903(modulo -13 4) @result{} 3
904(modulo 13 -4) @result{} -3
905(modulo -13 -4) @result{} -1
906@end lisp
907@end deffn
908
909@c begin (texi-doc-string "guile" "gcd")
fd8a1df5 910@deffn {Scheme Procedure} gcd x@dots{}
07d83abe
MV
911@deffnx {C Function} scm_gcd (x, y)
912Return the greatest common divisor of all arguments.
913If called without arguments, 0 is returned.
914
915The C function @code{scm_gcd} always takes two arguments, while the
916Scheme function can take an arbitrary number.
917@end deffn
918
919@c begin (texi-doc-string "guile" "lcm")
fd8a1df5 920@deffn {Scheme Procedure} lcm x@dots{}
07d83abe
MV
921@deffnx {C Function} scm_lcm (x, y)
922Return the least common multiple of the arguments.
923If called without arguments, 1 is returned.
924
925The C function @code{scm_lcm} always takes two arguments, while the
926Scheme function can take an arbitrary number.
927@end deffn
928
cdf1ad3b
MV
929@deffn {Scheme Procedure} modulo-expt n k m
930@deffnx {C Function} scm_modulo_expt (n, k, m)
931Return @var{n} raised to the integer exponent
932@var{k}, modulo @var{m}.
933
934@lisp
935(modulo-expt 2 3 5)
936 @result{} 3
937@end lisp
938@end deffn
07d83abe
MV
939
940@node Comparison
941@subsubsection Comparison Predicates
942@rnindex zero?
943@rnindex positive?
944@rnindex negative?
945
946The C comparison functions below always takes two arguments, while the
947Scheme functions can take an arbitrary number. Also keep in mind that
948the C functions return one of the Scheme boolean values
949@code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
950is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
951y))} when testing the two Scheme numbers @code{x} and @code{y} for
952equality, for example.
953
954@c begin (texi-doc-string "guile" "=")
955@deffn {Scheme Procedure} =
956@deffnx {C Function} scm_num_eq_p (x, y)
957Return @code{#t} if all parameters are numerically equal.
958@end deffn
959
960@c begin (texi-doc-string "guile" "<")
961@deffn {Scheme Procedure} <
962@deffnx {C Function} scm_less_p (x, y)
963Return @code{#t} if the list of parameters is monotonically
964increasing.
965@end deffn
966
967@c begin (texi-doc-string "guile" ">")
968@deffn {Scheme Procedure} >
969@deffnx {C Function} scm_gr_p (x, y)
970Return @code{#t} if the list of parameters is monotonically
971decreasing.
972@end deffn
973
974@c begin (texi-doc-string "guile" "<=")
975@deffn {Scheme Procedure} <=
976@deffnx {C Function} scm_leq_p (x, y)
977Return @code{#t} if the list of parameters is monotonically
978non-decreasing.
979@end deffn
980
981@c begin (texi-doc-string "guile" ">=")
982@deffn {Scheme Procedure} >=
983@deffnx {C Function} scm_geq_p (x, y)
984Return @code{#t} if the list of parameters is monotonically
985non-increasing.
986@end deffn
987
988@c begin (texi-doc-string "guile" "zero?")
989@deffn {Scheme Procedure} zero? z
990@deffnx {C Function} scm_zero_p (z)
991Return @code{#t} if @var{z} is an exact or inexact number equal to
992zero.
993@end deffn
994
995@c begin (texi-doc-string "guile" "positive?")
996@deffn {Scheme Procedure} positive? x
997@deffnx {C Function} scm_positive_p (x)
998Return @code{#t} if @var{x} is an exact or inexact number greater than
999zero.
1000@end deffn
1001
1002@c begin (texi-doc-string "guile" "negative?")
1003@deffn {Scheme Procedure} negative? x
1004@deffnx {C Function} scm_negative_p (x)
1005Return @code{#t} if @var{x} is an exact or inexact number less than
1006zero.
1007@end deffn
1008
1009
1010@node Conversion
1011@subsubsection Converting Numbers To and From Strings
1012@rnindex number->string
1013@rnindex string->number
1014
1015@deffn {Scheme Procedure} number->string n [radix]
1016@deffnx {C Function} scm_number_to_string (n, radix)
1017Return a string holding the external representation of the
1018number @var{n} in the given @var{radix}. If @var{n} is
1019inexact, a radix of 10 will be used.
1020@end deffn
1021
1022@deffn {Scheme Procedure} string->number string [radix]
1023@deffnx {C Function} scm_string_to_number (string, radix)
1024Return a number of the maximally precise representation
1025expressed by the given @var{string}. @var{radix} must be an
1026exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
1027is a default radix that may be overridden by an explicit radix
1028prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1029supplied, then the default radix is 10. If string is not a
1030syntactically valid notation for a number, then
1031@code{string->number} returns @code{#f}.
1032@end deffn
1033
1b09b607
KR
1034@deftypefn {C Function} SCM scm_c_locale_stringn_to_number (const char *string, size_t len, unsigned radix)
1035As per @code{string->number} above, but taking a C string, as pointer
1036and length. The string characters should be in the current locale
1037encoding (@code{locale} in the name refers only to that, there's no
1038locale-dependent parsing).
1039@end deftypefn
1040
07d83abe
MV
1041
1042@node Complex
1043@subsubsection Complex Number Operations
1044@rnindex make-rectangular
1045@rnindex make-polar
1046@rnindex real-part
1047@rnindex imag-part
1048@rnindex magnitude
1049@rnindex angle
1050
1051@deffn {Scheme Procedure} make-rectangular real imaginary
1052@deffnx {C Function} scm_make_rectangular (real, imaginary)
1053Return a complex number constructed of the given @var{real} and
1054@var{imaginary} parts.
1055@end deffn
1056
1057@deffn {Scheme Procedure} make-polar x y
1058@deffnx {C Function} scm_make_polar (x, y)
34942993 1059@cindex polar form
07d83abe
MV
1060Return the complex number @var{x} * e^(i * @var{y}).
1061@end deffn
1062
1063@c begin (texi-doc-string "guile" "real-part")
1064@deffn {Scheme Procedure} real-part z
1065@deffnx {C Function} scm_real_part (z)
1066Return the real part of the number @var{z}.
1067@end deffn
1068
1069@c begin (texi-doc-string "guile" "imag-part")
1070@deffn {Scheme Procedure} imag-part z
1071@deffnx {C Function} scm_imag_part (z)
1072Return the imaginary part of the number @var{z}.
1073@end deffn
1074
1075@c begin (texi-doc-string "guile" "magnitude")
1076@deffn {Scheme Procedure} magnitude z
1077@deffnx {C Function} scm_magnitude (z)
1078Return the magnitude of the number @var{z}. This is the same as
1079@code{abs} for real arguments, but also allows complex numbers.
1080@end deffn
1081
1082@c begin (texi-doc-string "guile" "angle")
1083@deffn {Scheme Procedure} angle z
1084@deffnx {C Function} scm_angle (z)
1085Return the angle of the complex number @var{z}.
1086@end deffn
1087
5615f696
MV
1088@deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1089@deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1090Like @code{scm_make_rectangular} or @code{scm_make_polar},
1091respectively, but these functions take @code{double}s as their
1092arguments.
1093@end deftypefn
1094
1095@deftypefn {C Function} double scm_c_real_part (z)
1096@deftypefnx {C Function} double scm_c_imag_part (z)
1097Returns the real or imaginary part of @var{z} as a @code{double}.
1098@end deftypefn
1099
1100@deftypefn {C Function} double scm_c_magnitude (z)
1101@deftypefnx {C Function} double scm_c_angle (z)
1102Returns the magnitude or angle of @var{z} as a @code{double}.
1103@end deftypefn
1104
07d83abe
MV
1105
1106@node Arithmetic
1107@subsubsection Arithmetic Functions
1108@rnindex max
1109@rnindex min
1110@rnindex +
1111@rnindex *
1112@rnindex -
1113@rnindex /
1114@rnindex abs
1115@rnindex floor
1116@rnindex ceiling
1117@rnindex truncate
1118@rnindex round
1119
1120The C arithmetic functions below always takes two arguments, while the
1121Scheme functions can take an arbitrary number. When you need to
1122invoke them with just one argument, for example to compute the
1123equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1124one: @code{scm_difference (x, SCM_UNDEFINED)}.
1125
1126@c begin (texi-doc-string "guile" "+")
1127@deffn {Scheme Procedure} + z1 @dots{}
1128@deffnx {C Function} scm_sum (z1, z2)
1129Return the sum of all parameter values. Return 0 if called without any
1130parameters.
1131@end deffn
1132
1133@c begin (texi-doc-string "guile" "-")
1134@deffn {Scheme Procedure} - z1 z2 @dots{}
1135@deffnx {C Function} scm_difference (z1, z2)
1136If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1137the sum of all but the first argument are subtracted from the first
1138argument.
1139@end deffn
1140
1141@c begin (texi-doc-string "guile" "*")
1142@deffn {Scheme Procedure} * z1 @dots{}
1143@deffnx {C Function} scm_product (z1, z2)
1144Return the product of all arguments. If called without arguments, 1 is
1145returned.
1146@end deffn
1147
1148@c begin (texi-doc-string "guile" "/")
1149@deffn {Scheme Procedure} / z1 z2 @dots{}
1150@deffnx {C Function} scm_divide (z1, z2)
1151Divide the first argument by the product of the remaining arguments. If
1152called with one argument @var{z1}, 1/@var{z1} is returned.
1153@end deffn
1154
1155@c begin (texi-doc-string "guile" "abs")
1156@deffn {Scheme Procedure} abs x
1157@deffnx {C Function} scm_abs (x)
1158Return the absolute value of @var{x}.
1159
1160@var{x} must be a number with zero imaginary part. To calculate the
1161magnitude of a complex number, use @code{magnitude} instead.
1162@end deffn
1163
1164@c begin (texi-doc-string "guile" "max")
1165@deffn {Scheme Procedure} max x1 x2 @dots{}
1166@deffnx {C Function} scm_max (x1, x2)
1167Return the maximum of all parameter values.
1168@end deffn
1169
1170@c begin (texi-doc-string "guile" "min")
1171@deffn {Scheme Procedure} min x1 x2 @dots{}
1172@deffnx {C Function} scm_min (x1, x2)
1173Return the minimum of all parameter values.
1174@end deffn
1175
1176@c begin (texi-doc-string "guile" "truncate")
fd8a1df5 1177@deffn {Scheme Procedure} truncate x
07d83abe
MV
1178@deffnx {C Function} scm_truncate_number (x)
1179Round the inexact number @var{x} towards zero.
1180@end deffn
1181
1182@c begin (texi-doc-string "guile" "round")
1183@deffn {Scheme Procedure} round x
1184@deffnx {C Function} scm_round_number (x)
1185Round the inexact number @var{x} to the nearest integer. When exactly
1186halfway between two integers, round to the even one.
1187@end deffn
1188
1189@c begin (texi-doc-string "guile" "floor")
1190@deffn {Scheme Procedure} floor x
1191@deffnx {C Function} scm_floor (x)
1192Round the number @var{x} towards minus infinity.
1193@end deffn
1194
1195@c begin (texi-doc-string "guile" "ceiling")
1196@deffn {Scheme Procedure} ceiling x
1197@deffnx {C Function} scm_ceiling (x)
1198Round the number @var{x} towards infinity.
1199@end deffn
1200
35da08ee
MV
1201@deftypefn {C Function} double scm_c_truncate (double x)
1202@deftypefnx {C Function} double scm_c_round (double x)
1203Like @code{scm_truncate_number} or @code{scm_round_number},
1204respectively, but these functions take and return @code{double}
1205values.
1206@end deftypefn
07d83abe
MV
1207
1208@node Scientific
1209@subsubsection Scientific Functions
1210
1211The following procedures accept any kind of number as arguments,
1212including complex numbers.
1213
1214@rnindex sqrt
1215@c begin (texi-doc-string "guile" "sqrt")
1216@deffn {Scheme Procedure} sqrt z
1217Return the square root of @var{z}.
1218@end deffn
1219
1220@rnindex expt
1221@c begin (texi-doc-string "guile" "expt")
1222@deffn {Scheme Procedure} expt z1 z2
1223Return @var{z1} raised to the power of @var{z2}.
1224@end deffn
1225
1226@rnindex sin
1227@c begin (texi-doc-string "guile" "sin")
1228@deffn {Scheme Procedure} sin z
1229Return the sine of @var{z}.
1230@end deffn
1231
1232@rnindex cos
1233@c begin (texi-doc-string "guile" "cos")
1234@deffn {Scheme Procedure} cos z
1235Return the cosine of @var{z}.
1236@end deffn
1237
1238@rnindex tan
1239@c begin (texi-doc-string "guile" "tan")
1240@deffn {Scheme Procedure} tan z
1241Return the tangent of @var{z}.
1242@end deffn
1243
1244@rnindex asin
1245@c begin (texi-doc-string "guile" "asin")
1246@deffn {Scheme Procedure} asin z
1247Return the arcsine of @var{z}.
1248@end deffn
1249
1250@rnindex acos
1251@c begin (texi-doc-string "guile" "acos")
1252@deffn {Scheme Procedure} acos z
1253Return the arccosine of @var{z}.
1254@end deffn
1255
1256@rnindex atan
1257@c begin (texi-doc-string "guile" "atan")
1258@deffn {Scheme Procedure} atan z
1259@deffnx {Scheme Procedure} atan y x
1260Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1261@end deffn
1262
1263@rnindex exp
1264@c begin (texi-doc-string "guile" "exp")
1265@deffn {Scheme Procedure} exp z
1266Return e to the power of @var{z}, where e is the base of natural
1267logarithms (2.71828@dots{}).
1268@end deffn
1269
1270@rnindex log
1271@c begin (texi-doc-string "guile" "log")
1272@deffn {Scheme Procedure} log z
1273Return the natural logarithm of @var{z}.
1274@end deffn
1275
1276@c begin (texi-doc-string "guile" "log10")
1277@deffn {Scheme Procedure} log10 z
1278Return the base 10 logarithm of @var{z}.
1279@end deffn
1280
1281@c begin (texi-doc-string "guile" "sinh")
1282@deffn {Scheme Procedure} sinh z
1283Return the hyperbolic sine of @var{z}.
1284@end deffn
1285
1286@c begin (texi-doc-string "guile" "cosh")
1287@deffn {Scheme Procedure} cosh z
1288Return the hyperbolic cosine of @var{z}.
1289@end deffn
1290
1291@c begin (texi-doc-string "guile" "tanh")
1292@deffn {Scheme Procedure} tanh z
1293Return the hyperbolic tangent of @var{z}.
1294@end deffn
1295
1296@c begin (texi-doc-string "guile" "asinh")
1297@deffn {Scheme Procedure} asinh z
1298Return the hyperbolic arcsine of @var{z}.
1299@end deffn
1300
1301@c begin (texi-doc-string "guile" "acosh")
1302@deffn {Scheme Procedure} acosh z
1303Return the hyperbolic arccosine of @var{z}.
1304@end deffn
1305
1306@c begin (texi-doc-string "guile" "atanh")
1307@deffn {Scheme Procedure} atanh z
1308Return the hyperbolic arctangent of @var{z}.
1309@end deffn
1310
1311
1312@node Primitive Numerics
1313@subsubsection Primitive Numeric Functions
1314
1315Many of Guile's numeric procedures which accept any kind of numbers as
1316arguments, including complex numbers, are implemented as Scheme
1317procedures that use the following real number-based primitives. These
1318primitives signal an error if they are called with complex arguments.
1319
1320@c begin (texi-doc-string "guile" "$abs")
1321@deffn {Scheme Procedure} $abs x
1322Return the absolute value of @var{x}.
1323@end deffn
1324
1325@c begin (texi-doc-string "guile" "$sqrt")
1326@deffn {Scheme Procedure} $sqrt x
1327Return the square root of @var{x}.
1328@end deffn
1329
1330@deffn {Scheme Procedure} $expt x y
1331@deffnx {C Function} scm_sys_expt (x, y)
1332Return @var{x} raised to the power of @var{y}. This
1333procedure does not accept complex arguments.
1334@end deffn
1335
1336@c begin (texi-doc-string "guile" "$sin")
1337@deffn {Scheme Procedure} $sin x
1338Return the sine of @var{x}.
1339@end deffn
1340
1341@c begin (texi-doc-string "guile" "$cos")
1342@deffn {Scheme Procedure} $cos x
1343Return the cosine of @var{x}.
1344@end deffn
1345
1346@c begin (texi-doc-string "guile" "$tan")
1347@deffn {Scheme Procedure} $tan x
1348Return the tangent of @var{x}.
1349@end deffn
1350
1351@c begin (texi-doc-string "guile" "$asin")
1352@deffn {Scheme Procedure} $asin x
1353Return the arcsine of @var{x}.
1354@end deffn
1355
1356@c begin (texi-doc-string "guile" "$acos")
1357@deffn {Scheme Procedure} $acos x
1358Return the arccosine of @var{x}.
1359@end deffn
1360
1361@c begin (texi-doc-string "guile" "$atan")
1362@deffn {Scheme Procedure} $atan x
1363Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
1364@math{PI/2}.
1365@end deffn
1366
1367@deffn {Scheme Procedure} $atan2 x y
1368@deffnx {C Function} scm_sys_atan2 (x, y)
1369Return the arc tangent of the two arguments @var{x} and
1370@var{y}. This is similar to calculating the arc tangent of
1371@var{x} / @var{y}, except that the signs of both arguments
1372are used to determine the quadrant of the result. This
1373procedure does not accept complex arguments.
1374@end deffn
1375
1376@c begin (texi-doc-string "guile" "$exp")
1377@deffn {Scheme Procedure} $exp x
1378Return e to the power of @var{x}, where e is the base of natural
1379logarithms (2.71828@dots{}).
1380@end deffn
1381
1382@c begin (texi-doc-string "guile" "$log")
1383@deffn {Scheme Procedure} $log x
1384Return the natural logarithm of @var{x}.
1385@end deffn
1386
1387@c begin (texi-doc-string "guile" "$sinh")
1388@deffn {Scheme Procedure} $sinh x
1389Return the hyperbolic sine of @var{x}.
1390@end deffn
1391
1392@c begin (texi-doc-string "guile" "$cosh")
1393@deffn {Scheme Procedure} $cosh x
1394Return the hyperbolic cosine of @var{x}.
1395@end deffn
1396
1397@c begin (texi-doc-string "guile" "$tanh")
1398@deffn {Scheme Procedure} $tanh x
1399Return the hyperbolic tangent of @var{x}.
1400@end deffn
1401
1402@c begin (texi-doc-string "guile" "$asinh")
1403@deffn {Scheme Procedure} $asinh x
1404Return the hyperbolic arcsine of @var{x}.
1405@end deffn
1406
1407@c begin (texi-doc-string "guile" "$acosh")
1408@deffn {Scheme Procedure} $acosh x
1409Return the hyperbolic arccosine of @var{x}.
1410@end deffn
1411
1412@c begin (texi-doc-string "guile" "$atanh")
1413@deffn {Scheme Procedure} $atanh x
1414Return the hyperbolic arctangent of @var{x}.
1415@end deffn
1416
1417C functions for the above are provided by the standard mathematics
1418library. Naturally these expect and return @code{double} arguments
1419(@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1420
1421@multitable {xx} {Scheme Procedure} {C Function}
1422@item @tab Scheme Procedure @tab C Function
1423
1424@item @tab @code{$abs} @tab @code{fabs}
1425@item @tab @code{$sqrt} @tab @code{sqrt}
1426@item @tab @code{$sin} @tab @code{sin}
1427@item @tab @code{$cos} @tab @code{cos}
1428@item @tab @code{$tan} @tab @code{tan}
1429@item @tab @code{$asin} @tab @code{asin}
1430@item @tab @code{$acos} @tab @code{acos}
1431@item @tab @code{$atan} @tab @code{atan}
1432@item @tab @code{$atan2} @tab @code{atan2}
1433@item @tab @code{$exp} @tab @code{exp}
1434@item @tab @code{$expt} @tab @code{pow}
1435@item @tab @code{$log} @tab @code{log}
1436@item @tab @code{$sinh} @tab @code{sinh}
1437@item @tab @code{$cosh} @tab @code{cosh}
1438@item @tab @code{$tanh} @tab @code{tanh}
1439@item @tab @code{$asinh} @tab @code{asinh}
1440@item @tab @code{$acosh} @tab @code{acosh}
1441@item @tab @code{$atanh} @tab @code{atanh}
1442@end multitable
1443
1444@code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1445not be available on older systems. Guile provides the following
1446equivalents (on all systems).
1447
1448@deftypefn {C Function} double scm_asinh (double x)
1449@deftypefnx {C Function} double scm_acosh (double x)
1450@deftypefnx {C Function} double scm_atanh (double x)
1451Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1452respectively.
1453@end deftypefn
1454
1455
1456@node Bitwise Operations
1457@subsubsection Bitwise Operations
1458
1459For the following bitwise functions, negative numbers are treated as
1460infinite precision twos-complements. For instance @math{-6} is bits
1461@math{@dots{}111010}, with infinitely many ones on the left. It can
1462be seen that adding 6 (binary 110) to such a bit pattern gives all
1463zeros.
1464
1465@deffn {Scheme Procedure} logand n1 n2 @dots{}
1466@deffnx {C Function} scm_logand (n1, n2)
1467Return the bitwise @sc{and} of the integer arguments.
1468
1469@lisp
1470(logand) @result{} -1
1471(logand 7) @result{} 7
1472(logand #b111 #b011 #b001) @result{} 1
1473@end lisp
1474@end deffn
1475
1476@deffn {Scheme Procedure} logior n1 n2 @dots{}
1477@deffnx {C Function} scm_logior (n1, n2)
1478Return the bitwise @sc{or} of the integer arguments.
1479
1480@lisp
1481(logior) @result{} 0
1482(logior 7) @result{} 7
1483(logior #b000 #b001 #b011) @result{} 3
1484@end lisp
1485@end deffn
1486
1487@deffn {Scheme Procedure} logxor n1 n2 @dots{}
1488@deffnx {C Function} scm_loxor (n1, n2)
1489Return the bitwise @sc{xor} of the integer arguments. A bit is
1490set in the result if it is set in an odd number of arguments.
1491
1492@lisp
1493(logxor) @result{} 0
1494(logxor 7) @result{} 7
1495(logxor #b000 #b001 #b011) @result{} 2
1496(logxor #b000 #b001 #b011 #b011) @result{} 1
1497@end lisp
1498@end deffn
1499
1500@deffn {Scheme Procedure} lognot n
1501@deffnx {C Function} scm_lognot (n)
1502Return the integer which is the ones-complement of the integer
1503argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1504
1505@lisp
1506(number->string (lognot #b10000000) 2)
1507 @result{} "-10000001"
1508(number->string (lognot #b0) 2)
1509 @result{} "-1"
1510@end lisp
1511@end deffn
1512
1513@deffn {Scheme Procedure} logtest j k
1514@deffnx {C Function} scm_logtest (j, k)
a46648ac
KR
1515Test whether @var{j} and @var{k} have any 1 bits in common. This is
1516equivalent to @code{(not (zero? (logand j k)))}, but without actually
1517calculating the @code{logand}, just testing for non-zero.
07d83abe 1518
a46648ac 1519@lisp
07d83abe
MV
1520(logtest #b0100 #b1011) @result{} #f
1521(logtest #b0100 #b0111) @result{} #t
1522@end lisp
1523@end deffn
1524
1525@deffn {Scheme Procedure} logbit? index j
1526@deffnx {C Function} scm_logbit_p (index, j)
a46648ac
KR
1527Test whether bit number @var{index} in @var{j} is set. @var{index}
1528starts from 0 for the least significant bit.
07d83abe 1529
a46648ac 1530@lisp
07d83abe
MV
1531(logbit? 0 #b1101) @result{} #t
1532(logbit? 1 #b1101) @result{} #f
1533(logbit? 2 #b1101) @result{} #t
1534(logbit? 3 #b1101) @result{} #t
1535(logbit? 4 #b1101) @result{} #f
1536@end lisp
1537@end deffn
1538
1539@deffn {Scheme Procedure} ash n cnt
1540@deffnx {C Function} scm_ash (n, cnt)
1541Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1542@var{cnt} is negative. This is an ``arithmetic'' shift.
1543
1544This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1545when @var{cnt} is negative it's a division, rounded towards negative
1546infinity. (Note that this is not the same rounding as @code{quotient}
1547does.)
1548
1549With @var{n} viewed as an infinite precision twos complement,
1550@code{ash} means a left shift introducing zero bits, or a right shift
1551dropping bits.
1552
1553@lisp
1554(number->string (ash #b1 3) 2) @result{} "1000"
1555(number->string (ash #b1010 -1) 2) @result{} "101"
1556
1557;; -23 is bits ...11101001, -6 is bits ...111010
1558(ash -23 -2) @result{} -6
1559@end lisp
1560@end deffn
1561
1562@deffn {Scheme Procedure} logcount n
1563@deffnx {C Function} scm_logcount (n)
a46648ac 1564Return the number of bits in integer @var{n}. If @var{n} is
07d83abe
MV
1565positive, the 1-bits in its binary representation are counted.
1566If negative, the 0-bits in its two's-complement binary
a46648ac 1567representation are counted. If zero, 0 is returned.
07d83abe
MV
1568
1569@lisp
1570(logcount #b10101010)
1571 @result{} 4
1572(logcount 0)
1573 @result{} 0
1574(logcount -2)
1575 @result{} 1
1576@end lisp
1577@end deffn
1578
1579@deffn {Scheme Procedure} integer-length n
1580@deffnx {C Function} scm_integer_length (n)
1581Return the number of bits necessary to represent @var{n}.
1582
1583For positive @var{n} this is how many bits to the most significant one
1584bit. For negative @var{n} it's how many bits to the most significant
1585zero bit in twos complement form.
1586
1587@lisp
1588(integer-length #b10101010) @result{} 8
1589(integer-length #b1111) @result{} 4
1590(integer-length 0) @result{} 0
1591(integer-length -1) @result{} 0
1592(integer-length -256) @result{} 8
1593(integer-length -257) @result{} 9
1594@end lisp
1595@end deffn
1596
1597@deffn {Scheme Procedure} integer-expt n k
1598@deffnx {C Function} scm_integer_expt (n, k)
a46648ac
KR
1599Return @var{n} raised to the power @var{k}. @var{k} must be an exact
1600integer, @var{n} can be any number.
1601
1602Negative @var{k} is supported, and results in @m{1/n^|k|, 1/n^abs(k)}
1603in the usual way. @math{@var{n}^0} is 1, as usual, and that includes
1604@math{0^0} is 1.
07d83abe
MV
1605
1606@lisp
a46648ac
KR
1607(integer-expt 2 5) @result{} 32
1608(integer-expt -3 3) @result{} -27
1609(integer-expt 5 -3) @result{} 1/125
1610(integer-expt 0 0) @result{} 1
07d83abe
MV
1611@end lisp
1612@end deffn
1613
1614@deffn {Scheme Procedure} bit-extract n start end
1615@deffnx {C Function} scm_bit_extract (n, start, end)
1616Return the integer composed of the @var{start} (inclusive)
1617through @var{end} (exclusive) bits of @var{n}. The
1618@var{start}th bit becomes the 0-th bit in the result.
1619
1620@lisp
1621(number->string (bit-extract #b1101101010 0 4) 2)
1622 @result{} "1010"
1623(number->string (bit-extract #b1101101010 4 9) 2)
1624 @result{} "10110"
1625@end lisp
1626@end deffn
1627
1628
1629@node Random
1630@subsubsection Random Number Generation
1631
1632Pseudo-random numbers are generated from a random state object, which
1633can be created with @code{seed->random-state}. The @var{state}
1634parameter to the various functions below is optional, it defaults to
1635the state object in the @code{*random-state*} variable.
1636
1637@deffn {Scheme Procedure} copy-random-state [state]
1638@deffnx {C Function} scm_copy_random_state (state)
1639Return a copy of the random state @var{state}.
1640@end deffn
1641
1642@deffn {Scheme Procedure} random n [state]
1643@deffnx {C Function} scm_random (n, state)
1644Return a number in [0, @var{n}).
1645
1646Accepts a positive integer or real n and returns a
1647number of the same type between zero (inclusive) and
1648@var{n} (exclusive). The values returned have a uniform
1649distribution.
1650@end deffn
1651
1652@deffn {Scheme Procedure} random:exp [state]
1653@deffnx {C Function} scm_random_exp (state)
1654Return an inexact real in an exponential distribution with mean
16551. For an exponential distribution with mean @var{u} use @code{(*
1656@var{u} (random:exp))}.
1657@end deffn
1658
1659@deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1660@deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1661Fills @var{vect} with inexact real random numbers the sum of whose
1662squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1663space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1664the coordinates are uniformly distributed over the surface of the unit
1665n-sphere.
1666@end deffn
1667
1668@deffn {Scheme Procedure} random:normal [state]
1669@deffnx {C Function} scm_random_normal (state)
1670Return an inexact real in a normal distribution. The distribution
1671used has mean 0 and standard deviation 1. For a normal distribution
1672with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1673(* @var{d} (random:normal)))}.
1674@end deffn
1675
1676@deffn {Scheme Procedure} random:normal-vector! vect [state]
1677@deffnx {C Function} scm_random_normal_vector_x (vect, state)
1678Fills @var{vect} with inexact real random numbers that are
1679independent and standard normally distributed
1680(i.e., with mean 0 and variance 1).
1681@end deffn
1682
1683@deffn {Scheme Procedure} random:solid-sphere! vect [state]
1684@deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1685Fills @var{vect} with inexact real random numbers the sum of whose
1686squares is less than 1.0. Thinking of @var{vect} as coordinates in
1687space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1688the coordinates are uniformly distributed within the unit
4497bd2f 1689@var{n}-sphere.
07d83abe
MV
1690@c FIXME: What does this mean, particularly the n-sphere part?
1691@end deffn
1692
1693@deffn {Scheme Procedure} random:uniform [state]
1694@deffnx {C Function} scm_random_uniform (state)
1695Return a uniformly distributed inexact real random number in
1696[0,1).
1697@end deffn
1698
1699@deffn {Scheme Procedure} seed->random-state seed
1700@deffnx {C Function} scm_seed_to_random_state (seed)
1701Return a new random state using @var{seed}.
1702@end deffn
1703
1704@defvar *random-state*
1705The global random state used by the above functions when the
1706@var{state} parameter is not given.
1707@end defvar
1708
1709
1710@node Characters
1711@subsection Characters
1712@tpindex Characters
1713
050ab45f
MV
1714In Scheme, a character literal is written as @code{#\@var{name}} where
1715@var{name} is the name of the character that you want. Printable
1716characters have their usual single character name; for example,
1717@code{#\a} is a lower case @code{a}.
07d83abe
MV
1718
1719Most of the ``control characters'' (those below codepoint 32) in the
1720@acronym{ASCII} character set, as well as the space, may be referred
050ab45f
MV
1721to by longer names: for example, @code{#\tab}, @code{#\esc},
1722@code{#\stx}, and so on. The following table describes the
1723@acronym{ASCII} names for each character.
07d83abe
MV
1724
1725@multitable @columnfractions .25 .25 .25 .25
1726@item 0 = @code{#\nul}
1727 @tab 1 = @code{#\soh}
1728 @tab 2 = @code{#\stx}
1729 @tab 3 = @code{#\etx}
1730@item 4 = @code{#\eot}
1731 @tab 5 = @code{#\enq}
1732 @tab 6 = @code{#\ack}
1733 @tab 7 = @code{#\bel}
1734@item 8 = @code{#\bs}
1735 @tab 9 = @code{#\ht}
1736 @tab 10 = @code{#\nl}
1737 @tab 11 = @code{#\vt}
1738@item 12 = @code{#\np}
1739 @tab 13 = @code{#\cr}
1740 @tab 14 = @code{#\so}
1741 @tab 15 = @code{#\si}
1742@item 16 = @code{#\dle}
1743 @tab 17 = @code{#\dc1}
1744 @tab 18 = @code{#\dc2}
1745 @tab 19 = @code{#\dc3}
1746@item 20 = @code{#\dc4}
1747 @tab 21 = @code{#\nak}
1748 @tab 22 = @code{#\syn}
1749 @tab 23 = @code{#\etb}
1750@item 24 = @code{#\can}
1751 @tab 25 = @code{#\em}
1752 @tab 26 = @code{#\sub}
1753 @tab 27 = @code{#\esc}
1754@item 28 = @code{#\fs}
1755 @tab 29 = @code{#\gs}
1756 @tab 30 = @code{#\rs}
1757 @tab 31 = @code{#\us}
1758@item 32 = @code{#\sp}
1759@end multitable
1760
1761The ``delete'' character (octal 177) may be referred to with the name
1762@code{#\del}.
1763
1764Several characters have more than one name:
1765
1766@multitable {@code{#\backspace}} {Original}
1767@item Alias @tab Original
1768@item @code{#\space} @tab @code{#\sp}
1769@item @code{#\newline} @tab @code{#\nl}
1770@item @code{#\tab} @tab @code{#\ht}
1771@item @code{#\backspace} @tab @code{#\bs}
1772@item @code{#\return} @tab @code{#\cr}
1773@item @code{#\page} @tab @code{#\np}
1774@item @code{#\null} @tab @code{#\nul}
1775@end multitable
1776
1777@rnindex char?
1778@deffn {Scheme Procedure} char? x
1779@deffnx {C Function} scm_char_p (x)
1780Return @code{#t} iff @var{x} is a character, else @code{#f}.
1781@end deffn
1782
1783@rnindex char=?
1784@deffn {Scheme Procedure} char=? x y
1785Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1786@end deffn
1787
1788@rnindex char<?
1789@deffn {Scheme Procedure} char<? x y
1790Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1791else @code{#f}.
1792@end deffn
1793
1794@rnindex char<=?
1795@deffn {Scheme Procedure} char<=? x y
1796Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1797@acronym{ASCII} sequence, else @code{#f}.
1798@end deffn
1799
1800@rnindex char>?
1801@deffn {Scheme Procedure} char>? x y
1802Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1803sequence, else @code{#f}.
1804@end deffn
1805
1806@rnindex char>=?
1807@deffn {Scheme Procedure} char>=? x y
1808Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1809@acronym{ASCII} sequence, else @code{#f}.
1810@end deffn
1811
1812@rnindex char-ci=?
1813@deffn {Scheme Procedure} char-ci=? x y
1814Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1815case, else @code{#f}.
1816@end deffn
1817
1818@rnindex char-ci<?
1819@deffn {Scheme Procedure} char-ci<? x y
1820Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1821ignoring case, else @code{#f}.
1822@end deffn
1823
1824@rnindex char-ci<=?
1825@deffn {Scheme Procedure} char-ci<=? x y
1826Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1827@acronym{ASCII} sequence ignoring case, else @code{#f}.
1828@end deffn
1829
1830@rnindex char-ci>?
1831@deffn {Scheme Procedure} char-ci>? x y
1832Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1833sequence ignoring case, else @code{#f}.
1834@end deffn
1835
1836@rnindex char-ci>=?
1837@deffn {Scheme Procedure} char-ci>=? x y
1838Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1839@acronym{ASCII} sequence ignoring case, else @code{#f}.
1840@end deffn
1841
1842@rnindex char-alphabetic?
1843@deffn {Scheme Procedure} char-alphabetic? chr
1844@deffnx {C Function} scm_char_alphabetic_p (chr)
1845Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
07d83abe
MV
1846@end deffn
1847
1848@rnindex char-numeric?
1849@deffn {Scheme Procedure} char-numeric? chr
1850@deffnx {C Function} scm_char_numeric_p (chr)
1851Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
07d83abe
MV
1852@end deffn
1853
1854@rnindex char-whitespace?
1855@deffn {Scheme Procedure} char-whitespace? chr
1856@deffnx {C Function} scm_char_whitespace_p (chr)
1857Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
07d83abe
MV
1858@end deffn
1859
1860@rnindex char-upper-case?
1861@deffn {Scheme Procedure} char-upper-case? chr
1862@deffnx {C Function} scm_char_upper_case_p (chr)
1863Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
07d83abe
MV
1864@end deffn
1865
1866@rnindex char-lower-case?
1867@deffn {Scheme Procedure} char-lower-case? chr
1868@deffnx {C Function} scm_char_lower_case_p (chr)
1869Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
07d83abe
MV
1870@end deffn
1871
1872@deffn {Scheme Procedure} char-is-both? chr
1873@deffnx {C Function} scm_char_is_both_p (chr)
1874Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
5676b4fa 1875@code{#f}.
07d83abe
MV
1876@end deffn
1877
1878@rnindex char->integer
1879@deffn {Scheme Procedure} char->integer chr
1880@deffnx {C Function} scm_char_to_integer (chr)
1881Return the number corresponding to ordinal position of @var{chr} in the
1882@acronym{ASCII} sequence.
1883@end deffn
1884
1885@rnindex integer->char
1886@deffn {Scheme Procedure} integer->char n
1887@deffnx {C Function} scm_integer_to_char (n)
1888Return the character at position @var{n} in the @acronym{ASCII} sequence.
1889@end deffn
1890
1891@rnindex char-upcase
1892@deffn {Scheme Procedure} char-upcase chr
1893@deffnx {C Function} scm_char_upcase (chr)
1894Return the uppercase character version of @var{chr}.
1895@end deffn
1896
1897@rnindex char-downcase
1898@deffn {Scheme Procedure} char-downcase chr
1899@deffnx {C Function} scm_char_downcase (chr)
1900Return the lowercase character version of @var{chr}.
1901@end deffn
1902
050ab45f
MV
1903@node Character Sets
1904@subsection Character Sets
07d83abe 1905
050ab45f
MV
1906The features described in this section correspond directly to SRFI-14.
1907
1908The data type @dfn{charset} implements sets of characters
1909(@pxref{Characters}). Because the internal representation of
1910character sets is not visible to the user, a lot of procedures for
1911handling them are provided.
1912
1913Character sets can be created, extended, tested for the membership of a
1914characters and be compared to other character sets.
1915
1916The Guile implementation of character sets currently deals only with
19178-bit characters. In the future, when Guile gets support for
1918international character sets, this will change, but the functions
1919provided here will always then be able to efficiently cope with very
1920large character sets.
1921
1922@menu
1923* Character Set Predicates/Comparison::
1924* Iterating Over Character Sets:: Enumerate charset elements.
1925* Creating Character Sets:: Making new charsets.
1926* Querying Character Sets:: Test charsets for membership etc.
1927* Character-Set Algebra:: Calculating new charsets.
1928* Standard Character Sets:: Variables containing predefined charsets.
1929@end menu
1930
1931@node Character Set Predicates/Comparison
1932@subsubsection Character Set Predicates/Comparison
1933
1934Use these procedures for testing whether an object is a character set,
1935or whether several character sets are equal or subsets of each other.
1936@code{char-set-hash} can be used for calculating a hash value, maybe for
1937usage in fast lookup procedures.
1938
1939@deffn {Scheme Procedure} char-set? obj
1940@deffnx {C Function} scm_char_set_p (obj)
1941Return @code{#t} if @var{obj} is a character set, @code{#f}
1942otherwise.
1943@end deffn
1944
1945@deffn {Scheme Procedure} char-set= . char_sets
1946@deffnx {C Function} scm_char_set_eq (char_sets)
1947Return @code{#t} if all given character sets are equal.
1948@end deffn
1949
1950@deffn {Scheme Procedure} char-set<= . char_sets
1951@deffnx {C Function} scm_char_set_leq (char_sets)
1952Return @code{#t} if every character set @var{cs}i is a subset
1953of character set @var{cs}i+1.
1954@end deffn
1955
1956@deffn {Scheme Procedure} char-set-hash cs [bound]
1957@deffnx {C Function} scm_char_set_hash (cs, bound)
1958Compute a hash value for the character set @var{cs}. If
1959@var{bound} is given and non-zero, it restricts the
1960returned value to the range 0 @dots{} @var{bound - 1}.
1961@end deffn
1962
1963@c ===================================================================
1964
1965@node Iterating Over Character Sets
1966@subsubsection Iterating Over Character Sets
1967
1968Character set cursors are a means for iterating over the members of a
1969character sets. After creating a character set cursor with
1970@code{char-set-cursor}, a cursor can be dereferenced with
1971@code{char-set-ref}, advanced to the next member with
1972@code{char-set-cursor-next}. Whether a cursor has passed past the last
1973element of the set can be checked with @code{end-of-char-set?}.
1974
1975Additionally, mapping and (un-)folding procedures for character sets are
1976provided.
1977
1978@deffn {Scheme Procedure} char-set-cursor cs
1979@deffnx {C Function} scm_char_set_cursor (cs)
1980Return a cursor into the character set @var{cs}.
1981@end deffn
1982
1983@deffn {Scheme Procedure} char-set-ref cs cursor
1984@deffnx {C Function} scm_char_set_ref (cs, cursor)
1985Return the character at the current cursor position
1986@var{cursor} in the character set @var{cs}. It is an error to
1987pass a cursor for which @code{end-of-char-set?} returns true.
1988@end deffn
1989
1990@deffn {Scheme Procedure} char-set-cursor-next cs cursor
1991@deffnx {C Function} scm_char_set_cursor_next (cs, cursor)
1992Advance the character set cursor @var{cursor} to the next
1993character in the character set @var{cs}. It is an error if the
1994cursor given satisfies @code{end-of-char-set?}.
1995@end deffn
1996
1997@deffn {Scheme Procedure} end-of-char-set? cursor
1998@deffnx {C Function} scm_end_of_char_set_p (cursor)
1999Return @code{#t} if @var{cursor} has reached the end of a
2000character set, @code{#f} otherwise.
2001@end deffn
2002
2003@deffn {Scheme Procedure} char-set-fold kons knil cs
2004@deffnx {C Function} scm_char_set_fold (kons, knil, cs)
2005Fold the procedure @var{kons} over the character set @var{cs},
2006initializing it with @var{knil}.
2007@end deffn
2008
2009@deffn {Scheme Procedure} char-set-unfold p f g seed [base_cs]
2010@deffnx {C Function} scm_char_set_unfold (p, f, g, seed, base_cs)
2011This is a fundamental constructor for character sets.
2012@itemize @bullet
2013@item @var{g} is used to generate a series of ``seed'' values
2014from the initial seed: @var{seed}, (@var{g} @var{seed}),
2015(@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2016@item @var{p} tells us when to stop -- when it returns true
2017when applied to one of the seed values.
2018@item @var{f} maps each seed value to a character. These
2019characters are added to the base character set @var{base_cs} to
2020form the result; @var{base_cs} defaults to the empty set.
2021@end itemize
2022@end deffn
2023
2024@deffn {Scheme Procedure} char-set-unfold! p f g seed base_cs
2025@deffnx {C Function} scm_char_set_unfold_x (p, f, g, seed, base_cs)
2026This is a fundamental constructor for character sets.
2027@itemize @bullet
2028@item @var{g} is used to generate a series of ``seed'' values
2029from the initial seed: @var{seed}, (@var{g} @var{seed}),
2030(@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}), @dots{}
2031@item @var{p} tells us when to stop -- when it returns true
2032when applied to one of the seed values.
2033@item @var{f} maps each seed value to a character. These
2034characters are added to the base character set @var{base_cs} to
2035form the result; @var{base_cs} defaults to the empty set.
2036@end itemize
2037@end deffn
2038
2039@deffn {Scheme Procedure} char-set-for-each proc cs
2040@deffnx {C Function} scm_char_set_for_each (proc, cs)
2041Apply @var{proc} to every character in the character set
2042@var{cs}. The return value is not specified.
2043@end deffn
2044
2045@deffn {Scheme Procedure} char-set-map proc cs
2046@deffnx {C Function} scm_char_set_map (proc, cs)
2047Map the procedure @var{proc} over every character in @var{cs}.
2048@var{proc} must be a character -> character procedure.
2049@end deffn
2050
2051@c ===================================================================
2052
2053@node Creating Character Sets
2054@subsubsection Creating Character Sets
2055
2056New character sets are produced with these procedures.
2057
2058@deffn {Scheme Procedure} char-set-copy cs
2059@deffnx {C Function} scm_char_set_copy (cs)
2060Return a newly allocated character set containing all
2061characters in @var{cs}.
2062@end deffn
2063
2064@deffn {Scheme Procedure} char-set . rest
2065@deffnx {C Function} scm_char_set (rest)
2066Return a character set containing all given characters.
2067@end deffn
2068
2069@deffn {Scheme Procedure} list->char-set list [base_cs]
2070@deffnx {C Function} scm_list_to_char_set (list, base_cs)
2071Convert the character list @var{list} to a character set. If
2072the character set @var{base_cs} is given, the character in this
2073set are also included in the result.
2074@end deffn
2075
2076@deffn {Scheme Procedure} list->char-set! list base_cs
2077@deffnx {C Function} scm_list_to_char_set_x (list, base_cs)
2078Convert the character list @var{list} to a character set. The
2079characters are added to @var{base_cs} and @var{base_cs} is
2080returned.
2081@end deffn
2082
2083@deffn {Scheme Procedure} string->char-set str [base_cs]
2084@deffnx {C Function} scm_string_to_char_set (str, base_cs)
2085Convert the string @var{str} to a character set. If the
2086character set @var{base_cs} is given, the characters in this
2087set are also included in the result.
2088@end deffn
2089
2090@deffn {Scheme Procedure} string->char-set! str base_cs
2091@deffnx {C Function} scm_string_to_char_set_x (str, base_cs)
2092Convert the string @var{str} to a character set. The
2093characters from the string are added to @var{base_cs}, and
2094@var{base_cs} is returned.
2095@end deffn
2096
2097@deffn {Scheme Procedure} char-set-filter pred cs [base_cs]
2098@deffnx {C Function} scm_char_set_filter (pred, cs, base_cs)
2099Return a character set containing every character from @var{cs}
2100so that it satisfies @var{pred}. If provided, the characters
2101from @var{base_cs} are added to the result.
2102@end deffn
2103
2104@deffn {Scheme Procedure} char-set-filter! pred cs base_cs
2105@deffnx {C Function} scm_char_set_filter_x (pred, cs, base_cs)
2106Return a character set containing every character from @var{cs}
2107so that it satisfies @var{pred}. The characters are added to
2108@var{base_cs} and @var{base_cs} is returned.
2109@end deffn
2110
2111@deffn {Scheme Procedure} ucs-range->char-set lower upper [error [base_cs]]
2112@deffnx {C Function} scm_ucs_range_to_char_set (lower, upper, error, base_cs)
2113Return a character set containing all characters whose
2114character codes lie in the half-open range
2115[@var{lower},@var{upper}).
2116
2117If @var{error} is a true value, an error is signalled if the
2118specified range contains characters which are not contained in
2119the implemented character range. If @var{error} is @code{#f},
2120these characters are silently left out of the resultung
2121character set.
2122
2123The characters in @var{base_cs} are added to the result, if
2124given.
2125@end deffn
2126
2127@deffn {Scheme Procedure} ucs-range->char-set! lower upper error base_cs
2128@deffnx {C Function} scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
2129Return a character set containing all characters whose
2130character codes lie in the half-open range
2131[@var{lower},@var{upper}).
2132
2133If @var{error} is a true value, an error is signalled if the
2134specified range contains characters which are not contained in
2135the implemented character range. If @var{error} is @code{#f},
2136these characters are silently left out of the resultung
2137character set.
2138
2139The characters are added to @var{base_cs} and @var{base_cs} is
2140returned.
2141@end deffn
2142
2143@deffn {Scheme Procedure} ->char-set x
2144@deffnx {C Function} scm_to_char_set (x)
2145Coerces x into a char-set. @var{x} may be a string, character or char-set. A string is converted to the set of its constituent characters; a character is converted to a singleton set; a char-set is returned as-is.
2146@end deffn
2147
2148@c ===================================================================
2149
2150@node Querying Character Sets
2151@subsubsection Querying Character Sets
2152
2153Access the elements and other information of a character set with these
2154procedures.
2155
2156@deffn {Scheme Procedure} char-set-size cs
2157@deffnx {C Function} scm_char_set_size (cs)
2158Return the number of elements in character set @var{cs}.
2159@end deffn
2160
2161@deffn {Scheme Procedure} char-set-count pred cs
2162@deffnx {C Function} scm_char_set_count (pred, cs)
2163Return the number of the elements int the character set
2164@var{cs} which satisfy the predicate @var{pred}.
2165@end deffn
2166
2167@deffn {Scheme Procedure} char-set->list cs
2168@deffnx {C Function} scm_char_set_to_list (cs)
2169Return a list containing the elements of the character set
2170@var{cs}.
2171@end deffn
2172
2173@deffn {Scheme Procedure} char-set->string cs
2174@deffnx {C Function} scm_char_set_to_string (cs)
2175Return a string containing the elements of the character set
2176@var{cs}. The order in which the characters are placed in the
2177string is not defined.
2178@end deffn
2179
2180@deffn {Scheme Procedure} char-set-contains? cs ch
2181@deffnx {C Function} scm_char_set_contains_p (cs, ch)
2182Return @code{#t} iff the character @var{ch} is contained in the
2183character set @var{cs}.
2184@end deffn
2185
2186@deffn {Scheme Procedure} char-set-every pred cs
2187@deffnx {C Function} scm_char_set_every (pred, cs)
2188Return a true value if every character in the character set
2189@var{cs} satisfies the predicate @var{pred}.
2190@end deffn
2191
2192@deffn {Scheme Procedure} char-set-any pred cs
2193@deffnx {C Function} scm_char_set_any (pred, cs)
2194Return a true value if any character in the character set
2195@var{cs} satisfies the predicate @var{pred}.
2196@end deffn
2197
2198@c ===================================================================
2199
2200@node Character-Set Algebra
2201@subsubsection Character-Set Algebra
2202
2203Character sets can be manipulated with the common set algebra operation,
2204such as union, complement, intersection etc. All of these procedures
2205provide side-effecting variants, which modify their character set
2206argument(s).
2207
2208@deffn {Scheme Procedure} char-set-adjoin cs . rest
2209@deffnx {C Function} scm_char_set_adjoin (cs, rest)
2210Add all character arguments to the first argument, which must
2211be a character set.
2212@end deffn
2213
2214@deffn {Scheme Procedure} char-set-delete cs . rest
2215@deffnx {C Function} scm_char_set_delete (cs, rest)
2216Delete all character arguments from the first argument, which
2217must be a character set.
2218@end deffn
2219
2220@deffn {Scheme Procedure} char-set-adjoin! cs . rest
2221@deffnx {C Function} scm_char_set_adjoin_x (cs, rest)
2222Add all character arguments to the first argument, which must
2223be a character set.
2224@end deffn
2225
2226@deffn {Scheme Procedure} char-set-delete! cs . rest
2227@deffnx {C Function} scm_char_set_delete_x (cs, rest)
2228Delete all character arguments from the first argument, which
2229must be a character set.
2230@end deffn
2231
2232@deffn {Scheme Procedure} char-set-complement cs
2233@deffnx {C Function} scm_char_set_complement (cs)
2234Return the complement of the character set @var{cs}.
2235@end deffn
2236
2237@deffn {Scheme Procedure} char-set-union . rest
2238@deffnx {C Function} scm_char_set_union (rest)
2239Return the union of all argument character sets.
2240@end deffn
2241
2242@deffn {Scheme Procedure} char-set-intersection . rest
2243@deffnx {C Function} scm_char_set_intersection (rest)
2244Return the intersection of all argument character sets.
2245@end deffn
2246
2247@deffn {Scheme Procedure} char-set-difference cs1 . rest
2248@deffnx {C Function} scm_char_set_difference (cs1, rest)
2249Return the difference of all argument character sets.
2250@end deffn
2251
2252@deffn {Scheme Procedure} char-set-xor . rest
2253@deffnx {C Function} scm_char_set_xor (rest)
2254Return the exclusive-or of all argument character sets.
2255@end deffn
2256
2257@deffn {Scheme Procedure} char-set-diff+intersection cs1 . rest
2258@deffnx {C Function} scm_char_set_diff_plus_intersection (cs1, rest)
2259Return the difference and the intersection of all argument
2260character sets.
2261@end deffn
2262
2263@deffn {Scheme Procedure} char-set-complement! cs
2264@deffnx {C Function} scm_char_set_complement_x (cs)
2265Return the complement of the character set @var{cs}.
2266@end deffn
2267
2268@deffn {Scheme Procedure} char-set-union! cs1 . rest
2269@deffnx {C Function} scm_char_set_union_x (cs1, rest)
2270Return the union of all argument character sets.
2271@end deffn
2272
2273@deffn {Scheme Procedure} char-set-intersection! cs1 . rest
2274@deffnx {C Function} scm_char_set_intersection_x (cs1, rest)
2275Return the intersection of all argument character sets.
2276@end deffn
2277
2278@deffn {Scheme Procedure} char-set-difference! cs1 . rest
2279@deffnx {C Function} scm_char_set_difference_x (cs1, rest)
2280Return the difference of all argument character sets.
2281@end deffn
2282
2283@deffn {Scheme Procedure} char-set-xor! cs1 . rest
2284@deffnx {C Function} scm_char_set_xor_x (cs1, rest)
2285Return the exclusive-or of all argument character sets.
2286@end deffn
2287
2288@deffn {Scheme Procedure} char-set-diff+intersection! cs1 cs2 . rest
2289@deffnx {C Function} scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
2290Return the difference and the intersection of all argument
2291character sets.
2292@end deffn
2293
2294@c ===================================================================
2295
2296@node Standard Character Sets
2297@subsubsection Standard Character Sets
2298
2299In order to make the use of the character set data type and procedures
2300useful, several predefined character set variables exist.
2301
c9dc8c6c
MV
2302@defvr {Scheme Variable} char-set:lower-case
2303@defvrx {C Variable} scm_char_set_lower_case
050ab45f 2304All lower-case characters.
c9dc8c6c 2305@end defvr
050ab45f 2306
c9dc8c6c
MV
2307@defvr {Scheme Variable} char-set:upper-case
2308@defvrx {C Variable} scm_char_set_upper_case
050ab45f 2309All upper-case characters.
c9dc8c6c 2310@end defvr
050ab45f 2311
c9dc8c6c
MV
2312@defvr {Scheme Variable} char-set:title-case
2313@defvrx {C Variable} scm_char_set_title_case
050ab45f 2314This is empty, because ASCII has no titlecase characters.
c9dc8c6c 2315@end defvr
050ab45f 2316
c9dc8c6c
MV
2317@defvr {Scheme Variable} char-set:letter
2318@defvrx {C Variable} scm_char_set_letter
050ab45f
MV
2319All letters, e.g. the union of @code{char-set:lower-case} and
2320@code{char-set:upper-case}.
c9dc8c6c 2321@end defvr
050ab45f 2322
c9dc8c6c
MV
2323@defvr {Scheme Variable} char-set:digit
2324@defvrx {C Variable} scm_char_set_digit
050ab45f 2325All digits.
c9dc8c6c 2326@end defvr
050ab45f 2327
c9dc8c6c
MV
2328@defvr {Scheme Variable} char-set:letter+digit
2329@defvrx {C Variable} scm_char_set_letter_and_digit
050ab45f 2330The union of @code{char-set:letter} and @code{char-set:digit}.
c9dc8c6c 2331@end defvr
050ab45f 2332
c9dc8c6c
MV
2333@defvr {Scheme Variable} char-set:graphic
2334@defvrx {C Variable} scm_char_set_graphic
050ab45f 2335All characters which would put ink on the paper.
c9dc8c6c 2336@end defvr
050ab45f 2337
c9dc8c6c
MV
2338@defvr {Scheme Variable} char-set:printing
2339@defvrx {C Variable} scm_char_set_printing
050ab45f 2340The union of @code{char-set:graphic} and @code{char-set:whitespace}.
c9dc8c6c 2341@end defvr
050ab45f 2342
c9dc8c6c
MV
2343@defvr {Scheme Variable} char-set:whitespace
2344@defvrx {C Variable} scm_char_set_whitespace
050ab45f 2345All whitespace characters.
c9dc8c6c 2346@end defvr
050ab45f 2347
c9dc8c6c
MV
2348@defvr {Scheme Variable} char-set:blank
2349@defvrx {C Variable} scm_char_set_blank
050ab45f
MV
2350All horizontal whitespace characters, that is @code{#\space} and
2351@code{#\tab}.
c9dc8c6c 2352@end defvr
050ab45f 2353
c9dc8c6c
MV
2354@defvr {Scheme Variable} char-set:iso-control
2355@defvrx {C Variable} scm_char_set_iso_control
050ab45f 2356The ISO control characters with the codes 0--31 and 127.
c9dc8c6c 2357@end defvr
050ab45f 2358
c9dc8c6c
MV
2359@defvr {Scheme Variable} char-set:punctuation
2360@defvrx {C Variable} scm_char_set_punctuation
050ab45f 2361The characters @code{!"#%&'()*,-./:;?@@[\\]_@{@}}
c9dc8c6c 2362@end defvr
050ab45f 2363
c9dc8c6c
MV
2364@defvr {Scheme Variable} char-set:symbol
2365@defvrx {C Variable} scm_char_set_symbol
050ab45f 2366The characters @code{$+<=>^`|~}.
c9dc8c6c 2367@end defvr
050ab45f 2368
c9dc8c6c
MV
2369@defvr {Scheme Variable} char-set:hex-digit
2370@defvrx {C Variable} scm_char_set_hex_digit
050ab45f 2371The hexadecimal digits @code{0123456789abcdefABCDEF}.
c9dc8c6c 2372@end defvr
050ab45f 2373
c9dc8c6c
MV
2374@defvr {Scheme Variable} char-set:ascii
2375@defvrx {C Variable} scm_char_set_ascii
050ab45f 2376All ASCII characters.
c9dc8c6c 2377@end defvr
050ab45f 2378
c9dc8c6c
MV
2379@defvr {Scheme Variable} char-set:empty
2380@defvrx {C Variable} scm_char_set_empty
050ab45f 2381The empty character set.
c9dc8c6c 2382@end defvr
050ab45f 2383
c9dc8c6c
MV
2384@defvr {Scheme Variable} char-set:full
2385@defvrx {C Variable} scm_char_set_full
050ab45f 2386This character set contains all possible characters.
c9dc8c6c 2387@end defvr
07d83abe
MV
2388
2389@node Strings
2390@subsection Strings
2391@tpindex Strings
2392
2393Strings are fixed-length sequences of characters. They can be created
2394by calling constructor procedures, but they can also literally get
2395entered at the @acronym{REPL} or in Scheme source files.
2396
2397@c Guile provides a rich set of string processing procedures, because text
2398@c handling is very important when Guile is used as a scripting language.
2399
2400Strings always carry the information about how many characters they are
2401composed of with them, so there is no special end-of-string character,
2402like in C. That means that Scheme strings can contain any character,
c48c62d0
MV
2403even the @samp{#\nul} character @samp{\0}.
2404
2405To use strings efficiently, you need to know a bit about how Guile
2406implements them. In Guile, a string consists of two parts, a head and
2407the actual memory where the characters are stored. When a string (or
2408a substring of it) is copied, only a new head gets created, the memory
2409is usually not copied. The two heads start out pointing to the same
2410memory.
2411
2412When one of these two strings is modified, as with @code{string-set!},
2413their common memory does get copied so that each string has its own
2414memory and modifying one does not accidently modify the other as well.
2415Thus, Guile's strings are `copy on write'; the actual copying of their
2416memory is delayed until one string is written to.
2417
2418This implementation makes functions like @code{substring} very
2419efficient in the common case that no modifications are done to the
2420involved strings.
2421
2422If you do know that your strings are getting modified right away, you
2423can use @code{substring/copy} instead of @code{substring}. This
2424function performs the copy immediately at the time of creation. This
2425is more efficient, especially in a multi-threaded program. Also,
2426@code{substring/copy} can avoid the problem that a short substring
2427holds on to the memory of a very large original string that could
2428otherwise be recycled.
2429
2430If you want to avoid the copy altogether, so that modifications of one
2431string show up in the other, you can use @code{substring/shared}. The
2432strings created by this procedure are called @dfn{mutation sharing
2433substrings} since the substring and the original string share
2434modifications to each other.
07d83abe 2435
05256760
MV
2436If you want to prevent modifications, use @code{substring/read-only}.
2437
c9dc8c6c
MV
2438Guile provides all procedures of SRFI-13 and a few more.
2439
07d83abe 2440@menu
5676b4fa
MV
2441* String Syntax:: Read syntax for strings.
2442* String Predicates:: Testing strings for certain properties.
2443* String Constructors:: Creating new string objects.
2444* List/String Conversion:: Converting from/to lists of characters.
2445* String Selection:: Select portions from strings.
2446* String Modification:: Modify parts or whole strings.
2447* String Comparison:: Lexicographic ordering predicates.
2448* String Searching:: Searching in strings.
2449* Alphabetic Case Mapping:: Convert the alphabetic case of strings.
2450* Reversing and Appending Strings:: Appending strings to form a new string.
2451* Mapping Folding and Unfolding:: Iterating over strings.
2452* Miscellaneous String Operations:: Replicating, insertion, parsing, ...
91210d62 2453* Conversion to/from C::
07d83abe
MV
2454@end menu
2455
2456@node String Syntax
2457@subsubsection String Read Syntax
2458
2459@c In the following @code is used to get a good font in TeX etc, but
2460@c is omitted for Info format, so as not to risk any confusion over
2461@c whether surrounding ` ' quotes are part of the escape or are
2462@c special in a string (they're not).
2463
2464The read syntax for strings is an arbitrarily long sequence of
c48c62d0 2465characters enclosed in double quotes (@nicode{"}).
07d83abe
MV
2466
2467Backslash is an escape character and can be used to insert the
2468following special characters. @nicode{\"} and @nicode{\\} are R5RS
2469standard, the rest are Guile extensions, notice they follow C string
2470syntax.
2471
2472@table @asis
2473@item @nicode{\\}
2474Backslash character.
2475
2476@item @nicode{\"}
2477Double quote character (an unescaped @nicode{"} is otherwise the end
2478of the string).
2479
2480@item @nicode{\0}
2481NUL character (ASCII 0).
2482
2483@item @nicode{\a}
2484Bell character (ASCII 7).
2485
2486@item @nicode{\f}
2487Formfeed character (ASCII 12).
2488
2489@item @nicode{\n}
2490Newline character (ASCII 10).
2491
2492@item @nicode{\r}
2493Carriage return character (ASCII 13).
2494
2495@item @nicode{\t}
2496Tab character (ASCII 9).
2497
2498@item @nicode{\v}
2499Vertical tab character (ASCII 11).
2500
2501@item @nicode{\xHH}
2502Character code given by two hexadecimal digits. For example
2503@nicode{\x7f} for an ASCII DEL (127).
2504@end table
2505
2506@noindent
2507The following are examples of string literals:
2508
2509@lisp
2510"foo"
2511"bar plonk"
2512"Hello World"
2513"\"Hi\", he said."
2514@end lisp
2515
2516
2517@node String Predicates
2518@subsubsection String Predicates
2519
2520The following procedures can be used to check whether a given string
2521fulfills some specified property.
2522
2523@rnindex string?
2524@deffn {Scheme Procedure} string? obj
2525@deffnx {C Function} scm_string_p (obj)
2526Return @code{#t} if @var{obj} is a string, else @code{#f}.
2527@end deffn
2528
91210d62
MV
2529@deftypefn {C Function} int scm_is_string (SCM obj)
2530Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2531@end deftypefn
2532
07d83abe
MV
2533@deffn {Scheme Procedure} string-null? str
2534@deffnx {C Function} scm_string_null_p (str)
2535Return @code{#t} if @var{str}'s length is zero, and
2536@code{#f} otherwise.
2537@lisp
2538(string-null? "") @result{} #t
2539y @result{} "foo"
2540(string-null? y) @result{} #f
2541@end lisp
2542@end deffn
2543
5676b4fa
MV
2544@deffn {Scheme Procedure} string-any char_pred s [start [end]]
2545@deffnx {C Function} scm_string_any (char_pred, s, start, end)
c100a12c 2546Check if @var{char_pred} is true for any character in string @var{s}.
5676b4fa 2547
c100a12c
KR
2548@var{char_pred} can be a character to check for any equal to that, or
2549a character set (@pxref{Character Sets}) to check for any in that set,
2550or a predicate procedure to call.
5676b4fa 2551
c100a12c
KR
2552For a procedure, calls @code{(@var{char_pred} c)} are made
2553successively on the characters from @var{start} to @var{end}. If
2554@var{char_pred} returns true (ie.@: non-@code{#f}), @code{string-any}
2555stops and that return value is the return from @code{string-any}. The
2556call on the last character (ie.@: at @math{@var{end}-1}), if that
2557point is reached, is a tail call.
2558
2559If there are no characters in @var{s} (ie.@: @var{start} equals
2560@var{end}) then the return is @code{#f}.
5676b4fa
MV
2561@end deffn
2562
2563@deffn {Scheme Procedure} string-every char_pred s [start [end]]
2564@deffnx {C Function} scm_string_every (char_pred, s, start, end)
c100a12c
KR
2565Check if @var{char_pred} is true for every character in string
2566@var{s}.
5676b4fa 2567
c100a12c
KR
2568@var{char_pred} can be a character to check for every character equal
2569to that, or a character set (@pxref{Character Sets}) to check for
2570every character being in that set, or a predicate procedure to call.
2571
2572For a procedure, calls @code{(@var{char_pred} c)} are made
2573successively on the characters from @var{start} to @var{end}. If
2574@var{char_pred} returns @code{#f}, @code{string-every} stops and
2575returns @code{#f}. The call on the last character (ie.@: at
2576@math{@var{end}-1}), if that point is reached, is a tail call and the
2577return from that call is the return from @code{string-every}.
5676b4fa
MV
2578
2579If there are no characters in @var{s} (ie.@: @var{start} equals
2580@var{end}) then the return is @code{#t}.
5676b4fa
MV
2581@end deffn
2582
07d83abe
MV
2583@node String Constructors
2584@subsubsection String Constructors
2585
2586The string constructor procedures create new string objects, possibly
c48c62d0
MV
2587initializing them with some specified character data. See also
2588@xref{String Selection}, for ways to create strings from existing
2589strings.
07d83abe
MV
2590
2591@c FIXME::martin: list->string belongs into `List/String Conversion'
2592
bba26c32 2593@deffn {Scheme Procedure} string char@dots{}
07d83abe 2594@rnindex string
bba26c32
KR
2595Return a newly allocated string made from the given character
2596arguments.
2597
2598@example
2599(string #\x #\y #\z) @result{} "xyz"
2600(string) @result{} ""
2601@end example
2602@end deffn
2603
2604@deffn {Scheme Procedure} list->string lst
2605@deffnx {C Function} scm_string (lst)
07d83abe 2606@rnindex list->string
bba26c32
KR
2607Return a newly allocated string made from a list of characters.
2608
2609@example
2610(list->string '(#\a #\b #\c)) @result{} "abc"
2611@end example
2612@end deffn
2613
2614@deffn {Scheme Procedure} reverse-list->string lst
2615@deffnx {C Function} scm_reverse_list_to_string (lst)
2616Return a newly allocated string made from a list of characters, in
2617reverse order.
2618
2619@example
2620(reverse-list->string '(#\a #\B #\c)) @result{} "cBa"
2621@end example
07d83abe
MV
2622@end deffn
2623
2624@rnindex make-string
2625@deffn {Scheme Procedure} make-string k [chr]
2626@deffnx {C Function} scm_make_string (k, chr)
2627Return a newly allocated string of
2628length @var{k}. If @var{chr} is given, then all elements of
2629the string are initialized to @var{chr}, otherwise the contents
2630of the @var{string} are unspecified.
2631@end deffn
2632
c48c62d0
MV
2633@deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2634Like @code{scm_make_string}, but expects the length as a
2635@code{size_t}.
2636@end deftypefn
2637
5676b4fa
MV
2638@deffn {Scheme Procedure} string-tabulate proc len
2639@deffnx {C Function} scm_string_tabulate (proc, len)
2640@var{proc} is an integer->char procedure. Construct a string
2641of size @var{len} by applying @var{proc} to each index to
2642produce the corresponding string element. The order in which
2643@var{proc} is applied to the indices is not specified.
2644@end deffn
2645
5676b4fa
MV
2646@deffn {Scheme Procedure} string-join ls [delimiter [grammar]]
2647@deffnx {C Function} scm_string_join (ls, delimiter, grammar)
2648Append the string in the string list @var{ls}, using the string
2649@var{delim} as a delimiter between the elements of @var{ls}.
2650@var{grammar} is a symbol which specifies how the delimiter is
2651placed between the strings, and defaults to the symbol
2652@code{infix}.
2653
2654@table @code
2655@item infix
2656Insert the separator between list elements. An empty string
2657will produce an empty list.
2658@item string-infix
2659Like @code{infix}, but will raise an error if given the empty
2660list.
2661@item suffix
2662Insert the separator after every list element.
2663@item prefix
2664Insert the separator before each list element.
2665@end table
2666@end deffn
2667
07d83abe
MV
2668@node List/String Conversion
2669@subsubsection List/String conversion
2670
2671When processing strings, it is often convenient to first convert them
2672into a list representation by using the procedure @code{string->list},
2673work with the resulting list, and then convert it back into a string.
2674These procedures are useful for similar tasks.
2675
2676@rnindex string->list
5676b4fa
MV
2677@deffn {Scheme Procedure} string->list str [start [end]]
2678@deffnx {C Function} scm_substring_to_list (str, start, end)
07d83abe 2679@deffnx {C Function} scm_string_to_list (str)
5676b4fa 2680Convert the string @var{str} into a list of characters.
07d83abe
MV
2681@end deffn
2682
2683@deffn {Scheme Procedure} string-split str chr
2684@deffnx {C Function} scm_string_split (str, chr)
2685Split the string @var{str} into the a list of the substrings delimited
2686by appearances of the character @var{chr}. Note that an empty substring
2687between separator characters will result in an empty string in the
2688result list.
2689
2690@lisp
2691(string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2692@result{}
2693("root" "x" "0" "0" "root" "/root" "/bin/bash")
2694
2695(string-split "::" #\:)
2696@result{}
2697("" "" "")
2698
2699(string-split "" #\:)
2700@result{}
2701("")
2702@end lisp
2703@end deffn
2704
2705
2706@node String Selection
2707@subsubsection String Selection
2708
2709Portions of strings can be extracted by these procedures.
2710@code{string-ref} delivers individual characters whereas
2711@code{substring} can be used to extract substrings from longer strings.
2712
2713@rnindex string-length
2714@deffn {Scheme Procedure} string-length string
2715@deffnx {C Function} scm_string_length (string)
2716Return the number of characters in @var{string}.
2717@end deffn
2718
c48c62d0
MV
2719@deftypefn {C Function} size_t scm_c_string_length (SCM str)
2720Return the number of characters in @var{str} as a @code{size_t}.
2721@end deftypefn
2722
07d83abe
MV
2723@rnindex string-ref
2724@deffn {Scheme Procedure} string-ref str k
2725@deffnx {C Function} scm_string_ref (str, k)
2726Return character @var{k} of @var{str} using zero-origin
2727indexing. @var{k} must be a valid index of @var{str}.
2728@end deffn
2729
c48c62d0
MV
2730@deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2731Return character @var{k} of @var{str} using zero-origin
2732indexing. @var{k} must be a valid index of @var{str}.
2733@end deftypefn
2734
07d83abe 2735@rnindex string-copy
5676b4fa
MV
2736@deffn {Scheme Procedure} string-copy str [start [end]]
2737@deffnx {C Function} scm_substring_copy (str, start, end)
07d83abe 2738@deffnx {C Function} scm_string_copy (str)
5676b4fa 2739Return a copy of the given string @var{str}.
c48c62d0
MV
2740
2741The returned string shares storage with @var{str} initially, but it is
2742copied as soon as one of the two strings is modified.
07d83abe
MV
2743@end deffn
2744
2745@rnindex substring
2746@deffn {Scheme Procedure} substring str start [end]
2747@deffnx {C Function} scm_substring (str, start, end)
c48c62d0 2748Return a new string formed from the characters
07d83abe
MV
2749of @var{str} beginning with index @var{start} (inclusive) and
2750ending with index @var{end} (exclusive).
2751@var{str} must be a string, @var{start} and @var{end} must be
2752exact integers satisfying:
2753
27540 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
c48c62d0
MV
2755
2756The returned string shares storage with @var{str} initially, but it is
2757copied as soon as one of the two strings is modified.
2758@end deffn
2759
2760@deffn {Scheme Procedure} substring/shared str start [end]
2761@deffnx {C Function} scm_substring_shared (str, start, end)
2762Like @code{substring}, but the strings continue to share their storage
2763even if they are modified. Thus, modifications to @var{str} show up
2764in the new string, and vice versa.
2765@end deffn
2766
2767@deffn {Scheme Procedure} substring/copy str start [end]
2768@deffnx {C Function} scm_substring_copy (str, start, end)
2769Like @code{substring}, but the storage for the new string is copied
2770immediately.
07d83abe
MV
2771@end deffn
2772
05256760
MV
2773@deffn {Scheme Procedure} substring/read-only str start [end]
2774@deffnx {C Function} scm_substring_read_only (str, start, end)
2775Like @code{substring}, but the resulting string can not be modified.
2776@end deffn
2777
c48c62d0
MV
2778@deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2779@deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2780@deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
05256760 2781@deftypefnx {C Function} SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
c48c62d0
MV
2782Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2783@end deftypefn
2784
5676b4fa
MV
2785@deffn {Scheme Procedure} string-take s n
2786@deffnx {C Function} scm_string_take (s, n)
2787Return the @var{n} first characters of @var{s}.
2788@end deffn
2789
2790@deffn {Scheme Procedure} string-drop s n
2791@deffnx {C Function} scm_string_drop (s, n)
2792Return all but the first @var{n} characters of @var{s}.
2793@end deffn
2794
2795@deffn {Scheme Procedure} string-take-right s n
2796@deffnx {C Function} scm_string_take_right (s, n)
2797Return the @var{n} last characters of @var{s}.
2798@end deffn
2799
2800@deffn {Scheme Procedure} string-drop-right s n
2801@deffnx {C Function} scm_string_drop_right (s, n)
2802Return all but the last @var{n} characters of @var{s}.
2803@end deffn
2804
2805@deffn {Scheme Procedure} string-pad s len [chr [start [end]]]
6337e7fb 2806@deffnx {Scheme Procedure} string-pad-right s len [chr [start [end]]]
5676b4fa 2807@deffnx {C Function} scm_string_pad (s, len, chr, start, end)
5676b4fa 2808@deffnx {C Function} scm_string_pad_right (s, len, chr, start, end)
6337e7fb
KR
2809Take characters @var{start} to @var{end} from the string @var{s} and
2810either pad with @var{char} or truncate them to give @var{len}
2811characters.
2812
2813@code{string-pad} pads or truncates on the left, so for example
2814
2815@example
2816(string-pad "x" 3) @result{} " x"
2817(string-pad "abcde" 3) @result{} "cde"
2818@end example
2819
2820@code{string-pad-right} pads or truncates on the right, so for example
2821
2822@example
2823(string-pad-right "x" 3) @result{} "x "
2824(string-pad-right "abcde" 3) @result{} "abc"
2825@end example
5676b4fa
MV
2826@end deffn
2827
2828@deffn {Scheme Procedure} string-trim s [char_pred [start [end]]]
dc297bb7
KR
2829@deffnx {Scheme Procedure} string-trim-right s [char_pred [start [end]]]
2830@deffnx {Scheme Procedure} string-trim-both s [char_pred [start [end]]]
5676b4fa 2831@deffnx {C Function} scm_string_trim (s, char_pred, start, end)
5676b4fa 2832@deffnx {C Function} scm_string_trim_right (s, char_pred, start, end)
5676b4fa 2833@deffnx {C Function} scm_string_trim_both (s, char_pred, start, end)
dc297bb7 2834Trim occurrances of @var{char_pred} from the ends of @var{s}.
5676b4fa 2835
dc297bb7
KR
2836@code{string-trim} trims @var{char_pred} characters from the left
2837(start) of the string, @code{string-trim-right} trims them from the
2838right (end) of the string, @code{string-trim-both} trims from both
2839ends.
5676b4fa 2840
dc297bb7
KR
2841@var{char_pred} can be a character, a character set, or a predicate
2842procedure to call on each character. If @var{char_pred} is not given
2843the default is whitespace as per @code{char-set:whitespace}
2844(@pxref{Standard Character Sets}).
5676b4fa 2845
dc297bb7
KR
2846@example
2847(string-trim " x ") @result{} "x "
2848(string-trim-right "banana" #\a) @result{} "banan"
2849(string-trim-both ".,xy:;" char-set:punctuation)
2850 @result{} "xy"
2851(string-trim-both "xyzzy" (lambda (c)
2852 (or (eqv? c #\x)
2853 (eqv? c #\y))))
2854 @result{} "zz"
2855@end example
5676b4fa
MV
2856@end deffn
2857
07d83abe
MV
2858@node String Modification
2859@subsubsection String Modification
2860
2861These procedures are for modifying strings in-place. This means that the
2862result of the operation is not a new string; instead, the original string's
2863memory representation is modified.
2864
2865@rnindex string-set!
2866@deffn {Scheme Procedure} string-set! str k chr
2867@deffnx {C Function} scm_string_set_x (str, k, chr)
2868Store @var{chr} in element @var{k} of @var{str} and return
2869an unspecified value. @var{k} must be a valid index of
2870@var{str}.
2871@end deffn
2872
c48c62d0
MV
2873@deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
2874Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
2875@end deftypefn
2876
07d83abe 2877@rnindex string-fill!
5676b4fa
MV
2878@deffn {Scheme Procedure} string-fill! str chr [start [end]]
2879@deffnx {C Function} scm_substring_fill_x (str, chr, start, end)
07d83abe 2880@deffnx {C Function} scm_string_fill_x (str, chr)
5676b4fa
MV
2881Stores @var{chr} in every element of the given @var{str} and
2882returns an unspecified value.
07d83abe
MV
2883@end deffn
2884
2885@deffn {Scheme Procedure} substring-fill! str start end fill
2886@deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
2887Change every character in @var{str} between @var{start} and
2888@var{end} to @var{fill}.
2889
2890@lisp
2891(define y "abcdefg")
2892(substring-fill! y 1 3 #\r)
2893y
2894@result{} "arrdefg"
2895@end lisp
2896@end deffn
2897
2898@deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
2899@deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
2900Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
2901into @var{str2} beginning at position @var{start2}.
2902@var{str1} and @var{str2} can be the same string.
2903@end deffn
2904
5676b4fa
MV
2905@deffn {Scheme Procedure} string-copy! target tstart s [start [end]]
2906@deffnx {C Function} scm_string_copy_x (target, tstart, s, start, end)
2907Copy the sequence of characters from index range [@var{start},
2908@var{end}) in string @var{s} to string @var{target}, beginning
2909at index @var{tstart}. The characters are copied left-to-right
2910or right-to-left as needed -- the copy is guaranteed to work,
2911even if @var{target} and @var{s} are the same string. It is an
2912error if the copy operation runs off the end of the target
2913string.
2914@end deffn
2915
07d83abe
MV
2916
2917@node String Comparison
2918@subsubsection String Comparison
2919
2920The procedures in this section are similar to the character ordering
2921predicates (@pxref{Characters}), but are defined on character sequences.
07d83abe 2922
5676b4fa
MV
2923The first set is specified in R5RS and has names that end in @code{?}.
2924The second set is specified in SRFI-13 and the names have no ending
2925@code{?}. The predicates ending in @code{-ci} ignore the character case
2926when comparing strings.
07d83abe
MV
2927
2928@rnindex string=?
2929@deffn {Scheme Procedure} string=? s1 s2
2930Lexicographic equality predicate; return @code{#t} if the two
2931strings are the same length and contain the same characters in
2932the same positions, otherwise return @code{#f}.
2933
2934The procedure @code{string-ci=?} treats upper and lower case
2935letters as though they were the same character, but
2936@code{string=?} treats upper and lower case as distinct
2937characters.
2938@end deffn
2939
2940@rnindex string<?
2941@deffn {Scheme Procedure} string<? s1 s2
2942Lexicographic ordering predicate; return @code{#t} if @var{s1}
2943is lexicographically less than @var{s2}.
2944@end deffn
2945
2946@rnindex string<=?
2947@deffn {Scheme Procedure} string<=? s1 s2
2948Lexicographic ordering predicate; return @code{#t} if @var{s1}
2949is lexicographically less than or equal to @var{s2}.
2950@end deffn
2951
2952@rnindex string>?
2953@deffn {Scheme Procedure} string>? s1 s2
2954Lexicographic ordering predicate; return @code{#t} if @var{s1}
2955is lexicographically greater than @var{s2}.
2956@end deffn
2957
2958@rnindex string>=?
2959@deffn {Scheme Procedure} string>=? s1 s2
2960Lexicographic ordering predicate; return @code{#t} if @var{s1}
2961is lexicographically greater than or equal to @var{s2}.
2962@end deffn
2963
2964@rnindex string-ci=?
2965@deffn {Scheme Procedure} string-ci=? s1 s2
2966Case-insensitive string equality predicate; return @code{#t} if
2967the two strings are the same length and their component
2968characters match (ignoring case) at each position; otherwise
2969return @code{#f}.
2970@end deffn
2971
5676b4fa 2972@rnindex string-ci<?
07d83abe
MV
2973@deffn {Scheme Procedure} string-ci<? s1 s2
2974Case insensitive lexicographic ordering predicate; return
2975@code{#t} if @var{s1} is lexicographically less than @var{s2}
2976regardless of case.
2977@end deffn
2978
2979@rnindex string<=?
2980@deffn {Scheme Procedure} string-ci<=? s1 s2
2981Case insensitive lexicographic ordering predicate; return
2982@code{#t} if @var{s1} is lexicographically less than or equal
2983to @var{s2} regardless of case.
2984@end deffn
2985
2986@rnindex string-ci>?
2987@deffn {Scheme Procedure} string-ci>? s1 s2
2988Case insensitive lexicographic ordering predicate; return
2989@code{#t} if @var{s1} is lexicographically greater than
2990@var{s2} regardless of case.
2991@end deffn
2992
2993@rnindex string-ci>=?
2994@deffn {Scheme Procedure} string-ci>=? s1 s2
2995Case insensitive lexicographic ordering predicate; return
2996@code{#t} if @var{s1} is lexicographically greater than or
2997equal to @var{s2} regardless of case.
2998@end deffn
2999
5676b4fa
MV
3000@deffn {Scheme Procedure} string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3001@deffnx {C Function} scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3002Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3003mismatch index, depending upon whether @var{s1} is less than,
3004equal to, or greater than @var{s2}. The mismatch index is the
3005largest index @var{i} such that for every 0 <= @var{j} <
3006@var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3007@var{i} is the first position that does not match.
3008@end deffn
3009
3010@deffn {Scheme Procedure} string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
3011@deffnx {C Function} scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
3012Apply @var{proc_lt}, @var{proc_eq}, @var{proc_gt} to the
3013mismatch index, depending upon whether @var{s1} is less than,
3014equal to, or greater than @var{s2}. The mismatch index is the
3015largest index @var{i} such that for every 0 <= @var{j} <
3016@var{i}, @var{s1}[@var{j}] = @var{s2}[@var{j}] -- that is,
3017@var{i} is the first position that does not match. The
3018character comparison is done case-insensitively.
3019@end deffn
3020
3021@deffn {Scheme Procedure} string= s1 s2 [start1 [end1 [start2 [end2]]]]
3022@deffnx {C Function} scm_string_eq (s1, s2, start1, end1, start2, end2)
3023Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3024value otherwise.
3025@end deffn
3026
3027@deffn {Scheme Procedure} string<> s1 s2 [start1 [end1 [start2 [end2]]]]
3028@deffnx {C Function} scm_string_neq (s1, s2, start1, end1, start2, end2)
3029Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3030value otherwise.
3031@end deffn
3032
3033@deffn {Scheme Procedure} string< s1 s2 [start1 [end1 [start2 [end2]]]]
3034@deffnx {C Function} scm_string_lt (s1, s2, start1, end1, start2, end2)
3035Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3036true value otherwise.
3037@end deffn
3038
3039@deffn {Scheme Procedure} string> s1 s2 [start1 [end1 [start2 [end2]]]]
3040@deffnx {C Function} scm_string_gt (s1, s2, start1, end1, start2, end2)
3041Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3042true value otherwise.
3043@end deffn
3044
3045@deffn {Scheme Procedure} string<= s1 s2 [start1 [end1 [start2 [end2]]]]
3046@deffnx {C Function} scm_string_le (s1, s2, start1, end1, start2, end2)
3047Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3048value otherwise.
3049@end deffn
3050
3051@deffn {Scheme Procedure} string>= s1 s2 [start1 [end1 [start2 [end2]]]]
3052@deffnx {C Function} scm_string_ge (s1, s2, start1, end1, start2, end2)
3053Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3054otherwise.
3055@end deffn
3056
3057@deffn {Scheme Procedure} string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
3058@deffnx {C Function} scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
3059Return @code{#f} if @var{s1} and @var{s2} are not equal, a true
3060value otherwise. The character comparison is done
3061case-insensitively.
3062@end deffn
3063
3064@deffn {Scheme Procedure} string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
3065@deffnx {C Function} scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
3066Return @code{#f} if @var{s1} and @var{s2} are equal, a true
3067value otherwise. The character comparison is done
3068case-insensitively.
3069@end deffn
3070
3071@deffn {Scheme Procedure} string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
3072@deffnx {C Function} scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
3073Return @code{#f} if @var{s1} is greater or equal to @var{s2}, a
3074true value otherwise. The character comparison is done
3075case-insensitively.
3076@end deffn
3077
3078@deffn {Scheme Procedure} string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
3079@deffnx {C Function} scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
3080Return @code{#f} if @var{s1} is less or equal to @var{s2}, a
3081true value otherwise. The character comparison is done
3082case-insensitively.
3083@end deffn
3084
3085@deffn {Scheme Procedure} string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
3086@deffnx {C Function} scm_string_ci_le (s1, s2, start1, end1, start2, end2)
3087Return @code{#f} if @var{s1} is greater to @var{s2}, a true
3088value otherwise. The character comparison is done
3089case-insensitively.
3090@end deffn
3091
3092@deffn {Scheme Procedure} string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
3093@deffnx {C Function} scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
3094Return @code{#f} if @var{s1} is less to @var{s2}, a true value
3095otherwise. The character comparison is done
3096case-insensitively.
3097@end deffn
3098
3099@deffn {Scheme Procedure} string-hash s [bound [start [end]]]
3100@deffnx {C Function} scm_substring_hash (s, bound, start, end)
3101Compute a hash value for @var{S}. the optional argument @var{bound} is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).
3102@end deffn
3103
3104@deffn {Scheme Procedure} string-hash-ci s [bound [start [end]]]
3105@deffnx {C Function} scm_substring_hash_ci (s, bound, start, end)
3106Compute a hash value for @var{S}. the optional argument @var{bound} is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).
3107@end deffn
07d83abe
MV
3108
3109@node String Searching
3110@subsubsection String Searching
3111
5676b4fa
MV
3112@deffn {Scheme Procedure} string-index s char_pred [start [end]]
3113@deffnx {C Function} scm_string_index (s, char_pred, start, end)
3114Search through the string @var{s} from left to right, returning
3115the index of the first occurence of a character which
07d83abe 3116
5676b4fa
MV
3117@itemize @bullet
3118@item
3119equals @var{char_pred}, if it is character,
07d83abe 3120
5676b4fa
MV
3121@item
3122satisifies the predicate @var{char_pred}, if it is a procedure,
07d83abe 3123
5676b4fa
MV
3124@item
3125is in the set @var{char_pred}, if it is a character set.
3126@end itemize
3127@end deffn
07d83abe 3128
5676b4fa
MV
3129@deffn {Scheme Procedure} string-rindex s char_pred [start [end]]
3130@deffnx {C Function} scm_string_rindex (s, char_pred, start, end)
3131Search through the string @var{s} from right to left, returning
3132the index of the last occurence of a character which
3133
3134@itemize @bullet
3135@item
3136equals @var{char_pred}, if it is character,
3137
3138@item
3139satisifies the predicate @var{char_pred}, if it is a procedure,
3140
3141@item
3142is in the set if @var{char_pred} is a character set.
3143@end itemize
07d83abe
MV
3144@end deffn
3145
5676b4fa
MV
3146@deffn {Scheme Procedure} string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3147@deffnx {C Function} scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
3148Return the length of the longest common prefix of the two
3149strings.
3150@end deffn
07d83abe 3151
5676b4fa
MV
3152@deffn {Scheme Procedure} string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3153@deffnx {C Function} scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
3154Return the length of the longest common prefix of the two
3155strings, ignoring character case.
3156@end deffn
07d83abe 3157
5676b4fa
MV
3158@deffn {Scheme Procedure} string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
3159@deffnx {C Function} scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
3160Return the length of the longest common suffix of the two
3161strings.
3162@end deffn
07d83abe 3163
5676b4fa
MV
3164@deffn {Scheme Procedure} string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3165@deffnx {C Function} scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
3166Return the length of the longest common suffix of the two
3167strings, ignoring character case.
3168@end deffn
3169
3170@deffn {Scheme Procedure} string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
3171@deffnx {C Function} scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
3172Is @var{s1} a prefix of @var{s2}?
3173@end deffn
3174
3175@deffn {Scheme Procedure} string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3176@deffnx {C Function} scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
3177Is @var{s1} a prefix of @var{s2}, ignoring character case?
3178@end deffn
3179
3180@deffn {Scheme Procedure} string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
3181@deffnx {C Function} scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
3182Is @var{s1} a suffix of @var{s2}?
3183@end deffn
3184
3185@deffn {Scheme Procedure} string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
3186@deffnx {C Function} scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
3187Is @var{s1} a suffix of @var{s2}, ignoring character case?
3188@end deffn
3189
3190@deffn {Scheme Procedure} string-index-right s char_pred [start [end]]
3191@deffnx {C Function} scm_string_index_right (s, char_pred, start, end)
3192Search through the string @var{s} from right to left, returning
3193the index of the last occurence of a character which
3194
3195@itemize @bullet
3196@item
3197equals @var{char_pred}, if it is character,
3198
3199@item
3200satisifies the predicate @var{char_pred}, if it is a procedure,
3201
3202@item
3203is in the set if @var{char_pred} is a character set.
3204@end itemize
3205@end deffn
3206
3207@deffn {Scheme Procedure} string-skip s char_pred [start [end]]
3208@deffnx {C Function} scm_string_skip (s, char_pred, start, end)
3209Search through the string @var{s} from left to right, returning
3210the index of the first occurence of a character which
3211
3212@itemize @bullet
3213@item
3214does not equal @var{char_pred}, if it is character,
3215
3216@item
3217does not satisify the predicate @var{char_pred}, if it is a
3218procedure,
3219
3220@item
3221is not in the set if @var{char_pred} is a character set.
3222@end itemize
3223@end deffn
3224
3225@deffn {Scheme Procedure} string-skip-right s char_pred [start [end]]
3226@deffnx {C Function} scm_string_skip_right (s, char_pred, start, end)
3227Search through the string @var{s} from right to left, returning
3228the index of the last occurence of a character which
3229
3230@itemize @bullet
3231@item
3232does not equal @var{char_pred}, if it is character,
3233
3234@item
3235does not satisfy the predicate @var{char_pred}, if it is a
3236procedure,
3237
3238@item
3239is not in the set if @var{char_pred} is a character set.
3240@end itemize
3241@end deffn
3242
3243@deffn {Scheme Procedure} string-count s char_pred [start [end]]
3244@deffnx {C Function} scm_string_count (s, char_pred, start, end)
3245Return the count of the number of characters in the string
3246@var{s} which
3247
3248@itemize @bullet
3249@item
3250equals @var{char_pred}, if it is character,
3251
3252@item
3253satisifies the predicate @var{char_pred}, if it is a procedure.
3254
3255@item
3256is in the set @var{char_pred}, if it is a character set.
3257@end itemize
3258@end deffn
3259
3260@deffn {Scheme Procedure} string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
3261@deffnx {C Function} scm_string_contains (s1, s2, start1, end1, start2, end2)
3262Does string @var{s1} contain string @var{s2}? Return the index
3263in @var{s1} where @var{s2} occurs as a substring, or false.
3264The optional start/end indices restrict the operation to the
3265indicated substrings.
3266@end deffn
3267
3268@deffn {Scheme Procedure} string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
3269@deffnx {C Function} scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
3270Does string @var{s1} contain string @var{s2}? Return the index
3271in @var{s1} where @var{s2} occurs as a substring, or false.
3272The optional start/end indices restrict the operation to the
3273indicated substrings. Character comparison is done
3274case-insensitively.
07d83abe
MV
3275@end deffn
3276
3277@node Alphabetic Case Mapping
3278@subsubsection Alphabetic Case Mapping
3279
3280These are procedures for mapping strings to their upper- or lower-case
3281equivalents, respectively, or for capitalizing strings.
3282
5676b4fa
MV
3283@deffn {Scheme Procedure} string-upcase str [start [end]]
3284@deffnx {C Function} scm_substring_upcase (str, start, end)
07d83abe 3285@deffnx {C Function} scm_string_upcase (str)
5676b4fa 3286Upcase every character in @code{str}.
07d83abe
MV
3287@end deffn
3288
5676b4fa
MV
3289@deffn {Scheme Procedure} string-upcase! str [start [end]]
3290@deffnx {C Function} scm_substring_upcase_x (str, start, end)
07d83abe 3291@deffnx {C Function} scm_string_upcase_x (str)
5676b4fa
MV
3292Destructively upcase every character in @code{str}.
3293
07d83abe 3294@lisp
5676b4fa
MV
3295(string-upcase! y)
3296@result{} "ARRDEFG"
3297y
3298@result{} "ARRDEFG"
07d83abe
MV
3299@end lisp
3300@end deffn
3301
5676b4fa
MV
3302@deffn {Scheme Procedure} string-downcase str [start [end]]
3303@deffnx {C Function} scm_substring_downcase (str, start, end)
07d83abe 3304@deffnx {C Function} scm_string_downcase (str)
5676b4fa 3305Downcase every character in @var{str}.
07d83abe
MV
3306@end deffn
3307
5676b4fa
MV
3308@deffn {Scheme Procedure} string-downcase! str [start [end]]
3309@deffnx {C Function} scm_substring_downcase_x (str, start, end)
07d83abe 3310@deffnx {C Function} scm_string_downcase_x (str)
5676b4fa
MV
3311Destructively downcase every character in @var{str}.
3312
07d83abe 3313@lisp
5676b4fa
MV
3314y
3315@result{} "ARRDEFG"
3316(string-downcase! y)
3317@result{} "arrdefg"
3318y
3319@result{} "arrdefg"
07d83abe
MV
3320@end lisp
3321@end deffn
3322
3323@deffn {Scheme Procedure} string-capitalize str
3324@deffnx {C Function} scm_string_capitalize (str)
3325Return a freshly allocated string with the characters in
3326@var{str}, where the first character of every word is
3327capitalized.
3328@end deffn
3329
3330@deffn {Scheme Procedure} string-capitalize! str
3331@deffnx {C Function} scm_string_capitalize_x (str)
3332Upcase the first character of every word in @var{str}
3333destructively and return @var{str}.
3334
3335@lisp
3336y @result{} "hello world"
3337(string-capitalize! y) @result{} "Hello World"
3338y @result{} "Hello World"
3339@end lisp
3340@end deffn
3341
5676b4fa
MV
3342@deffn {Scheme Procedure} string-titlecase str [start [end]]
3343@deffnx {C Function} scm_string_titlecase (str, start, end)
3344Titlecase every first character in a word in @var{str}.
3345@end deffn
07d83abe 3346
5676b4fa
MV
3347@deffn {Scheme Procedure} string-titlecase! str [start [end]]
3348@deffnx {C Function} scm_string_titlecase_x (str, start, end)
3349Destructively titlecase every first character in a word in
3350@var{str}.
3351@end deffn
3352
3353@node Reversing and Appending Strings
3354@subsubsection Reversing and Appending Strings
07d83abe 3355
5676b4fa
MV
3356@deffn {Scheme Procedure} string-reverse str [start [end]]
3357@deffnx {C Function} scm_string_reverse (str, start, end)
3358Reverse the string @var{str}. The optional arguments
3359@var{start} and @var{end} delimit the region of @var{str} to
3360operate on.
3361@end deffn
3362
3363@deffn {Scheme Procedure} string-reverse! str [start [end]]
3364@deffnx {C Function} scm_string_reverse_x (str, start, end)
3365Reverse the string @var{str} in-place. The optional arguments
3366@var{start} and @var{end} delimit the region of @var{str} to
3367operate on. The return value is unspecified.
3368@end deffn
07d83abe
MV
3369
3370@rnindex string-append
3371@deffn {Scheme Procedure} string-append . args
3372@deffnx {C Function} scm_string_append (args)
3373Return a newly allocated string whose characters form the
3374concatenation of the given strings, @var{args}.
3375
3376@example
3377(let ((h "hello "))
3378 (string-append h "world"))
3379@result{} "hello world"
3380@end example
3381@end deffn
3382
5676b4fa
MV
3383@deffn {Scheme Procedure} string-append/shared . ls
3384@deffnx {C Function} scm_string_append_shared (ls)
3385Like @code{string-append}, but the result may share memory
3386with the argument strings.
3387@end deffn
3388
3389@deffn {Scheme Procedure} string-concatenate ls
3390@deffnx {C Function} scm_string_concatenate (ls)
3391Append the elements of @var{ls} (which must be strings)
3392together into a single string. Guaranteed to return a freshly
3393allocated string.
3394@end deffn
3395
3396@deffn {Scheme Procedure} string-concatenate-reverse ls [final_string [end]]
3397@deffnx {C Function} scm_string_concatenate_reverse (ls, final_string, end)
3398Without optional arguments, this procedure is equivalent to
3399
3400@smalllisp
3401(string-concatenate (reverse ls))
3402@end smalllisp
3403
3404If the optional argument @var{final_string} is specified, it is
3405consed onto the beginning to @var{ls} before performing the
3406list-reverse and string-concatenate operations. If @var{end}
3407is given, only the characters of @var{final_string} up to index
3408@var{end} are used.
3409
3410Guaranteed to return a freshly allocated string.
3411@end deffn
3412
3413@deffn {Scheme Procedure} string-concatenate/shared ls
3414@deffnx {C Function} scm_string_concatenate_shared (ls)
3415Like @code{string-concatenate}, but the result may share memory
3416with the strings in the list @var{ls}.
3417@end deffn
3418
3419@deffn {Scheme Procedure} string-concatenate-reverse/shared ls [final_string [end]]
3420@deffnx {C Function} scm_string_concatenate_reverse_shared (ls, final_string, end)
3421Like @code{string-concatenate-reverse}, but the result may
3422share memory with the the strings in the @var{ls} arguments.
3423@end deffn
3424
3425@node Mapping Folding and Unfolding
3426@subsubsection Mapping, Folding, and Unfolding
3427
3428@deffn {Scheme Procedure} string-map proc s [start [end]]
3429@deffnx {C Function} scm_string_map (proc, s, start, end)
3430@var{proc} is a char->char procedure, it is mapped over
3431@var{s}. The order in which the procedure is applied to the
3432string elements is not specified.
3433@end deffn
3434
3435@deffn {Scheme Procedure} string-map! proc s [start [end]]
3436@deffnx {C Function} scm_string_map_x (proc, s, start, end)
3437@var{proc} is a char->char procedure, it is mapped over
3438@var{s}. The order in which the procedure is applied to the
3439string elements is not specified. The string @var{s} is
3440modified in-place, the return value is not specified.
3441@end deffn
3442
3443@deffn {Scheme Procedure} string-for-each proc s [start [end]]
3444@deffnx {C Function} scm_string_for_each (proc, s, start, end)
3445@var{proc} is mapped over @var{s} in left-to-right order. The
3446return value is not specified.
3447@end deffn
3448
3449@deffn {Scheme Procedure} string-for-each-index proc s [start [end]]
3450@deffnx {C Function} scm_string_for_each_index (proc, s, start, end)
2a7820f2
KR
3451Call @code{(@var{proc} i)} for each index i in @var{s}, from left to
3452right.
3453
3454For example, to change characters to alternately upper and lower case,
3455
3456@example
3457(define str (string-copy "studly"))
3458(string-for-each-index (lambda (i)
3459 (string-set! str i
3460 ((if (even? i) char-upcase char-downcase)
3461 (string-ref str i))))
3462 str)
3463str @result{} "StUdLy"
3464@end example
5676b4fa
MV
3465@end deffn
3466
3467@deffn {Scheme Procedure} string-fold kons knil s [start [end]]
3468@deffnx {C Function} scm_string_fold (kons, knil, s, start, end)
3469Fold @var{kons} over the characters of @var{s}, with @var{knil}
3470as the terminating element, from left to right. @var{kons}
3471must expect two arguments: The actual character and the last
3472result of @var{kons}' application.
3473@end deffn
3474
3475@deffn {Scheme Procedure} string-fold-right kons knil s [start [end]]
3476@deffnx {C Function} scm_string_fold_right (kons, knil, s, start, end)
3477Fold @var{kons} over the characters of @var{s}, with @var{knil}
3478as the terminating element, from right to left. @var{kons}
3479must expect two arguments: The actual character and the last
3480result of @var{kons}' application.
3481@end deffn
3482
3483@deffn {Scheme Procedure} string-unfold p f g seed [base [make_final]]
3484@deffnx {C Function} scm_string_unfold (p, f, g, seed, base, make_final)
3485@itemize @bullet
3486@item @var{g} is used to generate a series of @emph{seed}
3487values from the initial @var{seed}: @var{seed}, (@var{g}
3488@var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3489@dots{}
3490@item @var{p} tells us when to stop -- when it returns true
3491when applied to one of these seed values.
3492@item @var{f} maps each seed value to the corresponding
3493character in the result string. These chars are assembled
3494into the string in a left-to-right order.
3495@item @var{base} is the optional initial/leftmost portion
3496of the constructed string; it default to the empty
3497string.
3498@item @var{make_final} is applied to the terminal seed
3499value (on which @var{p} returns true) to produce
3500the final/rightmost portion of the constructed string.
3501It defaults to @code{(lambda (x) )}.
3502@end itemize
3503@end deffn
3504
3505@deffn {Scheme Procedure} string-unfold-right p f g seed [base [make_final]]
3506@deffnx {C Function} scm_string_unfold_right (p, f, g, seed, base, make_final)
3507@itemize @bullet
3508@item @var{g} is used to generate a series of @emph{seed}
3509values from the initial @var{seed}: @var{seed}, (@var{g}
3510@var{seed}), (@var{g}^2 @var{seed}), (@var{g}^3 @var{seed}),
3511@dots{}
3512@item @var{p} tells us when to stop -- when it returns true
3513when applied to one of these seed values.
3514@item @var{f} maps each seed value to the corresponding
3515character in the result string. These chars are assembled
3516into the string in a right-to-left order.
3517@item @var{base} is the optional initial/rightmost portion
3518of the constructed string; it default to the empty
3519string.
3520@item @var{make_final} is applied to the terminal seed
3521value (on which @var{p} returns true) to produce
3522the final/leftmost portion of the constructed string.
3523It defaults to @code{(lambda (x) )}.
3524@end itemize
3525@end deffn
3526
3527@node Miscellaneous String Operations
3528@subsubsection Miscellaneous String Operations
3529
3530@deffn {Scheme Procedure} xsubstring s from [to [start [end]]]
3531@deffnx {C Function} scm_xsubstring (s, from, to, start, end)
3532This is the @emph{extended substring} procedure that implements
3533replicated copying of a substring of some string.
3534
3535@var{s} is a string, @var{start} and @var{end} are optional
3536arguments that demarcate a substring of @var{s}, defaulting to
35370 and the length of @var{s}. Replicate this substring up and
3538down index space, in both the positive and negative directions.
3539@code{xsubstring} returns the substring of this string
3540beginning at index @var{from}, and ending at @var{to}, which
3541defaults to @var{from} + (@var{end} - @var{start}).
3542@end deffn
3543
3544@deffn {Scheme Procedure} string-xcopy! target tstart s sfrom [sto [start [end]]]
3545@deffnx {C Function} scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
3546Exactly the same as @code{xsubstring}, but the extracted text
3547is written into the string @var{target} starting at index
3548@var{tstart}. The operation is not defined if @code{(eq?
3549@var{target} @var{s})} or these arguments share storage -- you
3550cannot copy a string on top of itself.
3551@end deffn
3552
3553@deffn {Scheme Procedure} string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
3554@deffnx {C Function} scm_string_replace (s1, s2, start1, end1, start2, end2)
3555Return the string @var{s1}, but with the characters
3556@var{start1} @dots{} @var{end1} replaced by the characters
3557@var{start2} @dots{} @var{end2} from @var{s2}.
3558@end deffn
3559
3560@deffn {Scheme Procedure} string-tokenize s [token_set [start [end]]]
3561@deffnx {C Function} scm_string_tokenize (s, token_set, start, end)
3562Split the string @var{s} into a list of substrings, where each
3563substring is a maximal non-empty contiguous sequence of
3564characters from the character set @var{token_set}, which
3565defaults to @code{char-set:graphic}.
3566If @var{start} or @var{end} indices are provided, they restrict
3567@code{string-tokenize} to operating on the indicated substring
3568of @var{s}.
3569@end deffn
3570
3571@deffn {Scheme Procedure} string-filter s char_pred [start [end]]
3572@deffnx {C Function} scm_string_filter (s, char_pred, start, end)
08de3e24 3573Filter the string @var{s}, retaining only those characters which
a88e2a96 3574satisfy @var{char_pred}.
08de3e24
KR
3575
3576If @var{char_pred} is a procedure, it is applied to each character as
3577a predicate, if it is a character, it is tested for equality and if it
3578is a character set, it is tested for membership.
5676b4fa
MV
3579@end deffn
3580
3581@deffn {Scheme Procedure} string-delete s char_pred [start [end]]
3582@deffnx {C Function} scm_string_delete (s, char_pred, start, end)
a88e2a96 3583Delete characters satisfying @var{char_pred} from @var{s}.
08de3e24
KR
3584
3585If @var{char_pred} is a procedure, it is applied to each character as
3586a predicate, if it is a character, it is tested for equality and if it
3587is a character set, it is tested for membership.
5676b4fa
MV
3588@end deffn
3589
91210d62
MV
3590@node Conversion to/from C
3591@subsubsection Conversion to/from C
3592
3593When creating a Scheme string from a C string or when converting a
3594Scheme string to a C string, the concept of character encoding becomes
3595important.
3596
3597In C, a string is just a sequence of bytes, and the character encoding
3598describes the relation between these bytes and the actual characters
c88453e8
MV
3599that make up the string. For Scheme strings, character encoding is
3600not an issue (most of the time), since in Scheme you never get to see
3601the bytes, only the characters.
91210d62
MV
3602
3603Well, ideally, anyway. Right now, Guile simply equates Scheme
3604characters and bytes, ignoring the possibility of multi-byte encodings
3605completely. This will change in the future, where Guile will use
c48c62d0
MV
3606Unicode codepoints as its characters and UTF-8 or some other encoding
3607as its internal encoding. When you exclusively use the functions
3608listed in this section, you are `future-proof'.
91210d62 3609
c88453e8
MV
3610Converting a Scheme string to a C string will often allocate fresh
3611memory to hold the result. You must take care that this memory is
3612properly freed eventually. In many cases, this can be achieved by
661ae7ab
MV
3613using @code{scm_dynwind_free} inside an appropriate dynwind context,
3614@xref{Dynamic Wind}.
91210d62
MV
3615
3616@deftypefn {C Function} SCM scm_from_locale_string (const char *str)
3617@deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
3618Creates a new Scheme string that has the same contents as @var{str}
3619when interpreted in the current locale character encoding.
3620
3621For @code{scm_from_locale_string}, @var{str} must be null-terminated.
3622
3623For @code{scm_from_locale_stringn}, @var{len} specifies the length of
3624@var{str} in bytes, and @var{str} does not need to be null-terminated.
3625If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
3626null-terminated and the real length will be found with @code{strlen}.
3627@end deftypefn
3628
3629@deftypefn {C Function} SCM scm_take_locale_string (char *str)
3630@deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
3631Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
3632respectively, but also frees @var{str} with @code{free} eventually.
3633Thus, you can use this function when you would free @var{str} anyway
3634immediately after creating the Scheme string. In certain cases, Guile
3635can then use @var{str} directly as its internal representation.
3636@end deftypefn
3637
4846ae2c
KR
3638@deftypefn {C Function} {char *} scm_to_locale_string (SCM str)
3639@deftypefnx {C Function} {char *} scm_to_locale_stringn (SCM str, size_t *lenp)
91210d62
MV
3640Returns a C string in the current locale encoding with the same
3641contents as @var{str}. The C string must be freed with @code{free}
661ae7ab
MV
3642eventually, maybe by using @code{scm_dynwind_free}, @xref{Dynamic
3643Wind}.
91210d62
MV
3644
3645For @code{scm_to_locale_string}, the returned string is
3646null-terminated and an error is signalled when @var{str} contains
3647@code{#\nul} characters.
3648
3649For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
3650@var{str} might contain @code{#\nul} characters and the length of the
3651returned string in bytes is stored in @code{*@var{lenp}}. The
3652returned string will not be null-terminated in this case. If
3653@var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
3654@code{scm_to_locale_string}.
3655@end deftypefn
3656
3657@deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
3658Puts @var{str} as a C string in the current locale encoding into the
3659memory pointed to by @var{buf}. The buffer at @var{buf} has room for
3660@var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
3661more than that. No terminating @code{'\0'} will be stored.
3662
3663The return value of @code{scm_to_locale_stringbuf} is the number of
3664bytes that are needed for all of @var{str}, regardless of whether
3665@var{buf} was large enough to hold them. Thus, when the return value
3666is larger than @var{max_len}, only @var{max_len} bytes have been
3667stored and you probably need to try again with a larger buffer.
3668@end deftypefn
07d83abe
MV
3669
3670@node Regular Expressions
3671@subsection Regular Expressions
3672@tpindex Regular expressions
3673
3674@cindex regular expressions
3675@cindex regex
3676@cindex emacs regexp
3677
3678A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
3679describes a whole class of strings. A full description of regular
3680expressions and their syntax is beyond the scope of this manual;
3681an introduction can be found in the Emacs manual (@pxref{Regexps,
3682, Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
3683in many general Unix reference books.
3684
3685If your system does not include a POSIX regular expression library,
3686and you have not linked Guile with a third-party regexp library such
3687as Rx, these functions will not be available. You can tell whether
3688your Guile installation includes regular expression support by
3689checking whether @code{(provided? 'regex)} returns true.
3690
3691The following regexp and string matching features are provided by the
3692@code{(ice-9 regex)} module. Before using the described functions,
3693you should load this module by executing @code{(use-modules (ice-9
3694regex))}.
3695
3696@menu
3697* Regexp Functions:: Functions that create and match regexps.
3698* Match Structures:: Finding what was matched by a regexp.
3699* Backslash Escapes:: Removing the special meaning of regexp
3700 meta-characters.
3701@end menu
3702
3703
3704@node Regexp Functions
3705@subsubsection Regexp Functions
3706
3707By default, Guile supports POSIX extended regular expressions.
3708That means that the characters @samp{(}, @samp{)}, @samp{+} and
3709@samp{?} are special, and must be escaped if you wish to match the
3710literal characters.
3711
3712This regular expression interface was modeled after that
3713implemented by SCSH, the Scheme Shell. It is intended to be
3714upwardly compatible with SCSH regular expressions.
3715
083f9d74
KR
3716Zero bytes (@code{#\nul}) cannot be used in regex patterns or input
3717strings, since the underlying C functions treat that as the end of
3718string. If there's a zero byte an error is thrown.
3719
3720Patterns and input strings are treated as being in the locale
3721character set if @code{setlocale} has been called (@pxref{Locales}),
3722and in a multibyte locale this includes treating multi-byte sequences
3723as a single character. (Guile strings are currently merely bytes,
3724though this may change in the future, @xref{Conversion to/from C}.)
3725
07d83abe
MV
3726@deffn {Scheme Procedure} string-match pattern str [start]
3727Compile the string @var{pattern} into a regular expression and compare
3728it with @var{str}. The optional numeric argument @var{start} specifies
3729the position of @var{str} at which to begin matching.
3730
3731@code{string-match} returns a @dfn{match structure} which
3732describes what, if anything, was matched by the regular
3733expression. @xref{Match Structures}. If @var{str} does not match
3734@var{pattern} at all, @code{string-match} returns @code{#f}.
3735@end deffn
3736
3737Two examples of a match follow. In the first example, the pattern
3738matches the four digits in the match string. In the second, the pattern
3739matches nothing.
3740
3741@example
3742(string-match "[0-9][0-9][0-9][0-9]" "blah2002")
3743@result{} #("blah2002" (4 . 8))
3744
3745(string-match "[A-Za-z]" "123456")
3746@result{} #f
3747@end example
3748
3749Each time @code{string-match} is called, it must compile its
3750@var{pattern} argument into a regular expression structure. This
3751operation is expensive, which makes @code{string-match} inefficient if
3752the same regular expression is used several times (for example, in a
3753loop). For better performance, you can compile a regular expression in
3754advance and then match strings against the compiled regexp.
3755
3756@deffn {Scheme Procedure} make-regexp pat flag@dots{}
3757@deffnx {C Function} scm_make_regexp (pat, flaglst)
3758Compile the regular expression described by @var{pat}, and
3759return the compiled regexp structure. If @var{pat} does not
3760describe a legal regular expression, @code{make-regexp} throws
3761a @code{regular-expression-syntax} error.
3762
3763The @var{flag} arguments change the behavior of the compiled
3764regular expression. The following values may be supplied:
3765
3766@defvar regexp/icase
3767Consider uppercase and lowercase letters to be the same when
3768matching.
3769@end defvar
3770
3771@defvar regexp/newline
3772If a newline appears in the target string, then permit the
3773@samp{^} and @samp{$} operators to match immediately after or
3774immediately before the newline, respectively. Also, the
3775@samp{.} and @samp{[^...]} operators will never match a newline
3776character. The intent of this flag is to treat the target
3777string as a buffer containing many lines of text, and the
3778regular expression as a pattern that may match a single one of
3779those lines.
3780@end defvar
3781
3782@defvar regexp/basic
3783Compile a basic (``obsolete'') regexp instead of the extended
3784(``modern'') regexps that are the default. Basic regexps do
3785not consider @samp{|}, @samp{+} or @samp{?} to be special
3786characters, and require the @samp{@{...@}} and @samp{(...)}
3787metacharacters to be backslash-escaped (@pxref{Backslash
3788Escapes}). There are several other differences between basic
3789and extended regular expressions, but these are the most
3790significant.
3791@end defvar
3792
3793@defvar regexp/extended
3794Compile an extended regular expression rather than a basic
3795regexp. This is the default behavior; this flag will not
3796usually be needed. If a call to @code{make-regexp} includes
3797both @code{regexp/basic} and @code{regexp/extended} flags, the
3798one which comes last will override the earlier one.
3799@end defvar
3800@end deffn
3801
3802@deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
3803@deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
3804Match the compiled regular expression @var{rx} against
3805@code{str}. If the optional integer @var{start} argument is
3806provided, begin matching from that position in the string.
3807Return a match structure describing the results of the match,
3808or @code{#f} if no match could be found.
3809
36c7474e
KR
3810The @var{flags} argument changes the matching behavior. The following
3811flag values may be supplied, use @code{logior} (@pxref{Bitwise
3812Operations}) to combine them,
07d83abe
MV
3813
3814@defvar regexp/notbol
36c7474e
KR
3815Consider that the @var{start} offset into @var{str} is not the
3816beginning of a line and should not match operator @samp{^}.
3817
3818If @var{rx} was created with the @code{regexp/newline} option above,
3819@samp{^} will still match after a newline in @var{str}.
07d83abe
MV
3820@end defvar
3821
3822@defvar regexp/noteol
36c7474e
KR
3823Consider that the end of @var{str} is not the end of a line and should
3824not match operator @samp{$}.
3825
3826If @var{rx} was created with the @code{regexp/newline} option above,
3827@samp{$} will still match before a newline in @var{str}.
07d83abe
MV
3828@end defvar
3829@end deffn
3830
3831@lisp
3832;; Regexp to match uppercase letters
3833(define r (make-regexp "[A-Z]*"))
3834
3835;; Regexp to match letters, ignoring case
3836(define ri (make-regexp "[A-Z]*" regexp/icase))
3837
3838;; Search for bob using regexp r
3839(match:substring (regexp-exec r "bob"))
3840@result{} "" ; no match
3841
3842;; Search for bob using regexp ri
3843(match:substring (regexp-exec ri "Bob"))
3844@result{} "Bob" ; matched case insensitive
3845@end lisp
3846
3847@deffn {Scheme Procedure} regexp? obj
3848@deffnx {C Function} scm_regexp_p (obj)
3849Return @code{#t} if @var{obj} is a compiled regular expression,
3850or @code{#f} otherwise.
3851@end deffn
3852
a285fb86
KR
3853@sp 1
3854@deffn {Scheme Procedure} list-matches regexp str [flags]
3855Return a list of match structures which are the non-overlapping
3856matches of @var{regexp} in @var{str}. @var{regexp} can be either a
3857pattern string or a compiled regexp. The @var{flags} argument is as
3858per @code{regexp-exec} above.
3859
3860@example
3861(map match:substring (list-matches "[a-z]+" "abc 42 def 78"))
3862@result{} ("abc" "def")
3863@end example
3864@end deffn
3865
3866@deffn {Scheme Procedure} fold-matches regexp str init proc [flags]
3867Apply @var{proc} to the non-overlapping matches of @var{regexp} in
3868@var{str}, to build a result. @var{regexp} can be either a pattern
3869string or a compiled regexp. The @var{flags} argument is as per
3870@code{regexp-exec} above.
3871
3872@var{proc} is called as @code{(@var{proc} match prev)} where
3873@var{match} is a match structure and @var{prev} is the previous return
3874from @var{proc}. For the first call @var{prev} is the given
3875@var{init} parameter. @code{fold-matches} returns the final value
3876from @var{proc}.
3877
3878For example to count matches,
3879
3880@example
3881(fold-matches "[a-z][0-9]" "abc x1 def y2" 0
3882 (lambda (match count)
3883 (1+ count)))
3884@result{} 2
3885@end example
3886@end deffn
3887
a13befdc
KR
3888@sp 1
3889Regular expressions are commonly used to find patterns in one string
3890and replace them with the contents of another string. The following
3891functions are convenient ways to do this.
07d83abe
MV
3892
3893@c begin (scm-doc-string "regex.scm" "regexp-substitute")
3894@deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
a13befdc
KR
3895Write to @var{port} selected parts of the match structure @var{match}.
3896Or if @var{port} is @code{#f} then form a string from those parts and
3897return that.
3898
3899Each @var{item} specifies a part to be written, and may be one of the
3900following,
07d83abe
MV
3901
3902@itemize @bullet
3903@item
3904A string. String arguments are written out verbatim.
3905
3906@item
a13befdc
KR
3907An integer. The submatch with that number is written
3908(@code{match:substring}). Zero is the entire match.
07d83abe
MV
3909
3910@item
3911The symbol @samp{pre}. The portion of the matched string preceding
a13befdc 3912the regexp match is written (@code{match:prefix}).
07d83abe
MV
3913
3914@item
3915The symbol @samp{post}. The portion of the matched string following
a13befdc 3916the regexp match is written (@code{match:suffix}).
07d83abe
MV
3917@end itemize
3918
a13befdc
KR
3919For example, changing a match and retaining the text before and after,
3920
3921@example
3922(regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
3923 'pre "37" 'post)
3924@result{} "number 37 is good"
3925@end example
07d83abe 3926
a13befdc
KR
3927Or matching a @sc{yyyymmdd} format date such as @samp{20020828} and
3928re-ordering and hyphenating the fields.
07d83abe
MV
3929
3930@lisp
3931(define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
3932(define s "Date 20020429 12am.")
a13befdc
KR
3933(regexp-substitute #f (string-match date-regex s)
3934 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
07d83abe
MV
3935@result{} "Date 04-29-2002 12am. (20020429)"
3936@end lisp
a13befdc
KR
3937@end deffn
3938
07d83abe
MV
3939
3940@c begin (scm-doc-string "regex.scm" "regexp-substitute")
3941@deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
a13befdc
KR
3942@cindex search and replace
3943Write to @var{port} selected parts of matches of @var{regexp} in
3944@var{target}. If @var{port} is @code{#f} then form a string from
3945those parts and return that. @var{regexp} can be a string or a
3946compiled regex.
07d83abe 3947
a13befdc
KR
3948This is similar to @code{regexp-substitute}, but allows global
3949substitutions on @var{target}. Each @var{item} behaves as per
3950@code{regexp-substitute}, with the following differences,
07d83abe
MV
3951
3952@itemize @bullet
3953@item
a13befdc
KR
3954A function. Called as @code{(@var{item} match)} with the match
3955structure for the @var{regexp} match, it should return a string to be
3956written to @var{port}.
07d83abe
MV
3957
3958@item
a13befdc
KR
3959The symbol @samp{post}. This doesn't output anything, but instead
3960causes @code{regexp-substitute/global} to recurse on the unmatched
3961portion of @var{target}.
3962
3963This @emph{must} be supplied to perform a global search and replace on
3964@var{target}; without it @code{regexp-substitute/global} returns after
3965a single match and output.
07d83abe 3966@end itemize
07d83abe 3967
a13befdc
KR
3968For example, to collapse runs of tabs and spaces to a single hyphen
3969each,
3970
3971@example
3972(regexp-substitute/global #f "[ \t]+" "this is the text"
3973 'pre "-" 'post)
3974@result{} "this-is-the-text"
3975@end example
3976
3977Or using a function to reverse the letters in each word,
3978
3979@example
3980(regexp-substitute/global #f "[a-z]+" "to do and not-do"
3981 'pre (lambda (m) (string-reverse (match:substring m))) 'post)
3982@result{} "ot od dna ton-od"
3983@end example
3984
3985Without the @code{post} symbol, just one regexp match is made. For
3986example the following is the date example from
3987@code{regexp-substitute} above, without the need for the separate
3988@code{string-match} call.
07d83abe
MV
3989
3990@lisp
3991(define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
3992(define s "Date 20020429 12am.")
3993(regexp-substitute/global #f date-regex s
a13befdc
KR
3994 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
3995
07d83abe
MV
3996@result{} "Date 04-29-2002 12am. (20020429)"
3997@end lisp
a13befdc 3998@end deffn
07d83abe
MV
3999
4000
4001@node Match Structures
4002@subsubsection Match Structures
4003
4004@cindex match structures
4005
4006A @dfn{match structure} is the object returned by @code{string-match} and
4007@code{regexp-exec}. It describes which portion of a string, if any,
4008matched the given regular expression. Match structures include: a
4009reference to the string that was checked for matches; the starting and
4010ending positions of the regexp match; and, if the regexp included any
4011parenthesized subexpressions, the starting and ending positions of each
4012submatch.
4013
4014In each of the regexp match functions described below, the @code{match}
4015argument must be a match structure returned by a previous call to
4016@code{string-match} or @code{regexp-exec}. Most of these functions
4017return some information about the original target string that was
4018matched against a regular expression; we will call that string
4019@var{target} for easy reference.
4020
4021@c begin (scm-doc-string "regex.scm" "regexp-match?")
4022@deffn {Scheme Procedure} regexp-match? obj
4023Return @code{#t} if @var{obj} is a match structure returned by a
4024previous call to @code{regexp-exec}, or @code{#f} otherwise.
4025@end deffn
4026
4027@c begin (scm-doc-string "regex.scm" "match:substring")
4028@deffn {Scheme Procedure} match:substring match [n]
4029Return the portion of @var{target} matched by subexpression number
4030@var{n}. Submatch 0 (the default) represents the entire regexp match.
4031If the regular expression as a whole matched, but the subexpression
4032number @var{n} did not match, return @code{#f}.
4033@end deffn
4034
4035@lisp
4036(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4037(match:substring s)
4038@result{} "2002"
4039
4040;; match starting at offset 6 in the string
4041(match:substring
4042 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
4043@result{} "7654"
4044@end lisp
4045
4046@c begin (scm-doc-string "regex.scm" "match:start")
4047@deffn {Scheme Procedure} match:start match [n]
4048Return the starting position of submatch number @var{n}.
4049@end deffn
4050
4051In the following example, the result is 4, since the match starts at
4052character index 4:
4053
4054@lisp
4055(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4056(match:start s)
4057@result{} 4
4058@end lisp
4059
4060@c begin (scm-doc-string "regex.scm" "match:end")
4061@deffn {Scheme Procedure} match:end match [n]
4062Return the ending position of submatch number @var{n}.
4063@end deffn
4064
4065In the following example, the result is 8, since the match runs between
4066characters 4 and 8 (i.e. the ``2002'').
4067
4068@lisp
4069(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4070(match:end s)
4071@result{} 8
4072@end lisp
4073
4074@c begin (scm-doc-string "regex.scm" "match:prefix")
4075@deffn {Scheme Procedure} match:prefix match
4076Return the unmatched portion of @var{target} preceding the regexp match.
4077
4078@lisp
4079(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4080(match:prefix s)
4081@result{} "blah"
4082@end lisp
4083@end deffn
4084
4085@c begin (scm-doc-string "regex.scm" "match:suffix")
4086@deffn {Scheme Procedure} match:suffix match
4087Return the unmatched portion of @var{target} following the regexp match.
4088@end deffn
4089
4090@lisp
4091(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4092(match:suffix s)
4093@result{} "foo"
4094@end lisp
4095
4096@c begin (scm-doc-string "regex.scm" "match:count")
4097@deffn {Scheme Procedure} match:count match
4098Return the number of parenthesized subexpressions from @var{match}.
4099Note that the entire regular expression match itself counts as a
4100subexpression, and failed submatches are included in the count.
4101@end deffn
4102
4103@c begin (scm-doc-string "regex.scm" "match:string")
4104@deffn {Scheme Procedure} match:string match
4105Return the original @var{target} string.
4106@end deffn
4107
4108@lisp
4109(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
4110(match:string s)
4111@result{} "blah2002foo"
4112@end lisp
4113
4114
4115@node Backslash Escapes
4116@subsubsection Backslash Escapes
4117
4118Sometimes you will want a regexp to match characters like @samp{*} or
4119@samp{$} exactly. For example, to check whether a particular string
4120represents a menu entry from an Info node, it would be useful to match
4121it against a regexp like @samp{^* [^:]*::}. However, this won't work;
4122because the asterisk is a metacharacter, it won't match the @samp{*} at
4123the beginning of the string. In this case, we want to make the first
4124asterisk un-magic.
4125
4126You can do this by preceding the metacharacter with a backslash
4127character @samp{\}. (This is also called @dfn{quoting} the
4128metacharacter, and is known as a @dfn{backslash escape}.) When Guile
4129sees a backslash in a regular expression, it considers the following
4130glyph to be an ordinary character, no matter what special meaning it
4131would ordinarily have. Therefore, we can make the above example work by
4132changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
4133the regular expression engine to match only a single asterisk in the
4134target string.
4135
4136Since the backslash is itself a metacharacter, you may force a regexp to
4137match a backslash in the target string by preceding the backslash with
4138itself. For example, to find variable references in a @TeX{} program,
4139you might want to find occurrences of the string @samp{\let\} followed
4140by any number of alphabetic characters. The regular expression
4141@samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
4142regexp each match a single backslash in the target string.
4143
4144@c begin (scm-doc-string "regex.scm" "regexp-quote")
4145@deffn {Scheme Procedure} regexp-quote str
4146Quote each special character found in @var{str} with a backslash, and
4147return the resulting string.
4148@end deffn
4149
4150@strong{Very important:} Using backslash escapes in Guile source code
4151(as in Emacs Lisp or C) can be tricky, because the backslash character
4152has special meaning for the Guile reader. For example, if Guile
4153encounters the character sequence @samp{\n} in the middle of a string
4154while processing Scheme code, it replaces those characters with a
4155newline character. Similarly, the character sequence @samp{\t} is
4156replaced by a horizontal tab. Several of these @dfn{escape sequences}
4157are processed by the Guile reader before your code is executed.
4158Unrecognized escape sequences are ignored: if the characters @samp{\*}
4159appear in a string, they will be translated to the single character
4160@samp{*}.
4161
4162This translation is obviously undesirable for regular expressions, since
4163we want to be able to include backslashes in a string in order to
4164escape regexp metacharacters. Therefore, to make sure that a backslash
4165is preserved in a string in your Guile program, you must use @emph{two}
4166consecutive backslashes:
4167
4168@lisp
4169(define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
4170@end lisp
4171
4172The string in this example is preprocessed by the Guile reader before
4173any code is executed. The resulting argument to @code{make-regexp} is
4174the string @samp{^\* [^:]*}, which is what we really want.
4175
4176This also means that in order to write a regular expression that matches
4177a single backslash character, the regular expression string in the
4178source code must include @emph{four} backslashes. Each consecutive pair
4179of backslashes gets translated by the Guile reader to a single
4180backslash, and the resulting double-backslash is interpreted by the
4181regexp engine as matching a single backslash character. Hence:
4182
4183@lisp
4184(define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
4185@end lisp
4186
4187The reason for the unwieldiness of this syntax is historical. Both
4188regular expression pattern matchers and Unix string processing systems
4189have traditionally used backslashes with the special meanings
4190described above. The POSIX regular expression specification and ANSI C
4191standard both require these semantics. Attempting to abandon either
4192convention would cause other kinds of compatibility problems, possibly
4193more severe ones. Therefore, without extending the Scheme reader to
4194support strings with different quoting conventions (an ungainly and
4195confusing extension when implemented in other languages), we must adhere
4196to this cumbersome escape syntax.
4197
4198
4199@node Symbols
4200@subsection Symbols
4201@tpindex Symbols
4202
4203Symbols in Scheme are widely used in three ways: as items of discrete
4204data, as lookup keys for alists and hash tables, and to denote variable
4205references.
4206
4207A @dfn{symbol} is similar to a string in that it is defined by a
4208sequence of characters. The sequence of characters is known as the
4209symbol's @dfn{name}. In the usual case --- that is, where the symbol's
4210name doesn't include any characters that could be confused with other
4211elements of Scheme syntax --- a symbol is written in a Scheme program by
4212writing the sequence of characters that make up the name, @emph{without}
4213any quotation marks or other special syntax. For example, the symbol
4214whose name is ``multiply-by-2'' is written, simply:
4215
4216@lisp
4217multiply-by-2
4218@end lisp
4219
4220Notice how this differs from a @emph{string} with contents
4221``multiply-by-2'', which is written with double quotation marks, like
4222this:
4223
4224@lisp
4225"multiply-by-2"
4226@end lisp
4227
4228Looking beyond how they are written, symbols are different from strings
4229in two important respects.
4230
4231The first important difference is uniqueness. If the same-looking
4232string is read twice from two different places in a program, the result
4233is two @emph{different} string objects whose contents just happen to be
4234the same. If, on the other hand, the same-looking symbol is read twice
4235from two different places in a program, the result is the @emph{same}
4236symbol object both times.
4237
4238Given two read symbols, you can use @code{eq?} to test whether they are
4239the same (that is, have the same name). @code{eq?} is the most
4240efficient comparison operator in Scheme, and comparing two symbols like
4241this is as fast as comparing, for example, two numbers. Given two
4242strings, on the other hand, you must use @code{equal?} or
4243@code{string=?}, which are much slower comparison operators, to
4244determine whether the strings have the same contents.
4245
4246@lisp
4247(define sym1 (quote hello))
4248(define sym2 (quote hello))
4249(eq? sym1 sym2) @result{} #t
4250
4251(define str1 "hello")
4252(define str2 "hello")
4253(eq? str1 str2) @result{} #f
4254(equal? str1 str2) @result{} #t
4255@end lisp
4256
4257The second important difference is that symbols, unlike strings, are not
4258self-evaluating. This is why we need the @code{(quote @dots{})}s in the
4259example above: @code{(quote hello)} evaluates to the symbol named
4260"hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
4261symbol named "hello" and evaluated as a variable reference @dots{} about
4262which more below (@pxref{Symbol Variables}).
4263
4264@menu
4265* Symbol Data:: Symbols as discrete data.
4266* Symbol Keys:: Symbols as lookup keys.
4267* Symbol Variables:: Symbols as denoting variables.
4268* Symbol Primitives:: Operations related to symbols.
4269* Symbol Props:: Function slots and property lists.
4270* Symbol Read Syntax:: Extended read syntax for symbols.
4271* Symbol Uninterned:: Uninterned symbols.
4272@end menu
4273
4274
4275@node Symbol Data
4276@subsubsection Symbols as Discrete Data
4277
4278Numbers and symbols are similar to the extent that they both lend
4279themselves to @code{eq?} comparison. But symbols are more descriptive
4280than numbers, because a symbol's name can be used directly to describe
4281the concept for which that symbol stands.
4282
4283For example, imagine that you need to represent some colours in a
4284computer program. Using numbers, you would have to choose arbitrarily
4285some mapping between numbers and colours, and then take care to use that
4286mapping consistently:
4287
4288@lisp
4289;; 1=red, 2=green, 3=purple
4290
4291(if (eq? (colour-of car) 1)
4292 ...)
4293@end lisp
4294
4295@noindent
4296You can make the mapping more explicit and the code more readable by
4297defining constants:
4298
4299@lisp
4300(define red 1)
4301(define green 2)
4302(define purple 3)
4303
4304(if (eq? (colour-of car) red)
4305 ...)
4306@end lisp
4307
4308@noindent
4309But the simplest and clearest approach is not to use numbers at all, but
4310symbols whose names specify the colours that they refer to:
4311
4312@lisp
4313(if (eq? (colour-of car) 'red)
4314 ...)
4315@end lisp
4316
4317The descriptive advantages of symbols over numbers increase as the set
4318of concepts that you want to describe grows. Suppose that a car object
4319can have other properties as well, such as whether it has or uses:
4320
4321@itemize @bullet
4322@item
4323automatic or manual transmission
4324@item
4325leaded or unleaded fuel
4326@item
4327power steering (or not).
4328@end itemize
4329
4330@noindent
4331Then a car's combined property set could be naturally represented and
4332manipulated as a list of symbols:
4333
4334@lisp
4335(properties-of car1)
4336@result{}
4337(red manual unleaded power-steering)
4338
4339(if (memq 'power-steering (properties-of car1))
4340 (display "Unfit people can drive this car.\n")
4341 (display "You'll need strong arms to drive this car!\n"))
4342@print{}
4343Unfit people can drive this car.
4344@end lisp
4345
4346Remember, the fundamental property of symbols that we are relying on
4347here is that an occurrence of @code{'red} in one part of a program is an
4348@emph{indistinguishable} symbol from an occurrence of @code{'red} in
4349another part of a program; this means that symbols can usefully be
4350compared using @code{eq?}. At the same time, symbols have naturally
4351descriptive names. This combination of efficiency and descriptive power
4352makes them ideal for use as discrete data.
4353
4354
4355@node Symbol Keys
4356@subsubsection Symbols as Lookup Keys
4357
4358Given their efficiency and descriptive power, it is natural to use
4359symbols as the keys in an association list or hash table.
4360
4361To illustrate this, consider a more structured representation of the car
4362properties example from the preceding subsection. Rather than
4363mixing all the properties up together in a flat list, we could use an
4364association list like this:
4365
4366@lisp
4367(define car1-properties '((colour . red)
4368 (transmission . manual)
4369 (fuel . unleaded)
4370 (steering . power-assisted)))
4371@end lisp
4372
4373Notice how this structure is more explicit and extensible than the flat
4374list. For example it makes clear that @code{manual} refers to the
4375transmission rather than, say, the windows or the locking of the car.
4376It also allows further properties to use the same symbols among their
4377possible values without becoming ambiguous:
4378
4379@lisp
4380(define car1-properties '((colour . red)
4381 (transmission . manual)
4382 (fuel . unleaded)
4383 (steering . power-assisted)
4384 (seat-colour . red)
4385 (locking . manual)))
4386@end lisp
4387
4388With a representation like this, it is easy to use the efficient
4389@code{assq-XXX} family of procedures (@pxref{Association Lists}) to
4390extract or change individual pieces of information:
4391
4392@lisp
4393(assq-ref car1-properties 'fuel) @result{} unleaded
4394(assq-ref car1-properties 'transmission) @result{} manual
4395
4396(assq-set! car1-properties 'seat-colour 'black)
4397@result{}
4398((colour . red)
4399 (transmission . manual)
4400 (fuel . unleaded)
4401 (steering . power-assisted)
4402 (seat-colour . black)
4403 (locking . manual)))
4404@end lisp
4405
4406Hash tables also have keys, and exactly the same arguments apply to the
4407use of symbols in hash tables as in association lists. The hash value
4408that Guile uses to decide where to add a symbol-keyed entry to a hash
4409table can be obtained by calling the @code{symbol-hash} procedure:
4410
4411@deffn {Scheme Procedure} symbol-hash symbol
4412@deffnx {C Function} scm_symbol_hash (symbol)
4413Return a hash value for @var{symbol}.
4414@end deffn
4415
4416See @ref{Hash Tables} for information about hash tables in general, and
4417for why you might choose to use a hash table rather than an association
4418list.
4419
4420
4421@node Symbol Variables
4422@subsubsection Symbols as Denoting Variables
4423
4424When an unquoted symbol in a Scheme program is evaluated, it is
4425interpreted as a variable reference, and the result of the evaluation is
4426the appropriate variable's value.
4427
4428For example, when the expression @code{(string-length "abcd")} is read
4429and evaluated, the sequence of characters @code{string-length} is read
4430as the symbol whose name is "string-length". This symbol is associated
4431with a variable whose value is the procedure that implements string
4432length calculation. Therefore evaluation of the @code{string-length}
4433symbol results in that procedure.
4434
4435The details of the connection between an unquoted symbol and the
4436variable to which it refers are explained elsewhere. See @ref{Binding
4437Constructs}, for how associations between symbols and variables are
4438created, and @ref{Modules}, for how those associations are affected by
4439Guile's module system.
4440
4441
4442@node Symbol Primitives
4443@subsubsection Operations Related to Symbols
4444
4445Given any Scheme value, you can determine whether it is a symbol using
4446the @code{symbol?} primitive:
4447
4448@rnindex symbol?
4449@deffn {Scheme Procedure} symbol? obj
4450@deffnx {C Function} scm_symbol_p (obj)
4451Return @code{#t} if @var{obj} is a symbol, otherwise return
4452@code{#f}.
4453@end deffn
4454
c9dc8c6c
MV
4455@deftypefn {C Function} int scm_is_symbol (SCM val)
4456Equivalent to @code{scm_is_true (scm_symbol_p (val))}.
4457@end deftypefn
4458
07d83abe
MV
4459Once you know that you have a symbol, you can obtain its name as a
4460string by calling @code{symbol->string}. Note that Guile differs by
4461default from R5RS on the details of @code{symbol->string} as regards
4462case-sensitivity:
4463
4464@rnindex symbol->string
4465@deffn {Scheme Procedure} symbol->string s
4466@deffnx {C Function} scm_symbol_to_string (s)
4467Return the name of symbol @var{s} as a string. By default, Guile reads
4468symbols case-sensitively, so the string returned will have the same case
4469variation as the sequence of characters that caused @var{s} to be
4470created.
4471
4472If Guile is set to read symbols case-insensitively (as specified by
4473R5RS), and @var{s} comes into being as part of a literal expression
4474(@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
4475by a call to the @code{read} or @code{string-ci->symbol} procedures,
4476Guile converts any alphabetic characters in the symbol's name to
4477lower case before creating the symbol object, so the string returned
4478here will be in lower case.
4479
4480If @var{s} was created by @code{string->symbol}, the case of characters
4481in the string returned will be the same as that in the string that was
4482passed to @code{string->symbol}, regardless of Guile's case-sensitivity
4483setting at the time @var{s} was created.
4484
4485It is an error to apply mutation procedures like @code{string-set!} to
4486strings returned by this procedure.
4487@end deffn
4488
4489Most symbols are created by writing them literally in code. However it
4490is also possible to create symbols programmatically using the following
4491@code{string->symbol} and @code{string-ci->symbol} procedures:
4492
4493@rnindex string->symbol
4494@deffn {Scheme Procedure} string->symbol string
4495@deffnx {C Function} scm_string_to_symbol (string)
4496Return the symbol whose name is @var{string}. This procedure can create
4497symbols with names containing special characters or letters in the
4498non-standard case, but it is usually a bad idea to create such symbols
4499because in some implementations of Scheme they cannot be read as
4500themselves.
4501@end deffn
4502
4503@deffn {Scheme Procedure} string-ci->symbol str
4504@deffnx {C Function} scm_string_ci_to_symbol (str)
4505Return the symbol whose name is @var{str}. If Guile is currently
4506reading symbols case-insensitively, @var{str} is converted to lowercase
4507before the returned symbol is looked up or created.
4508@end deffn
4509
4510The following examples illustrate Guile's detailed behaviour as regards
4511the case-sensitivity of symbols:
4512
4513@lisp
4514(read-enable 'case-insensitive) ; R5RS compliant behaviour
4515
4516(symbol->string 'flying-fish) @result{} "flying-fish"
4517(symbol->string 'Martin) @result{} "martin"
4518(symbol->string
4519 (string->symbol "Malvina")) @result{} "Malvina"
4520
4521(eq? 'mISSISSIppi 'mississippi) @result{} #t
4522(string->symbol "mISSISSIppi") @result{} mISSISSIppi
4523(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
4524(eq? 'LolliPop
4525 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4526(string=? "K. Harper, M.D."
4527 (symbol->string
4528 (string->symbol "K. Harper, M.D."))) @result{} #t
4529
4530(read-disable 'case-insensitive) ; Guile default behaviour
4531
4532(symbol->string 'flying-fish) @result{} "flying-fish"
4533(symbol->string 'Martin) @result{} "Martin"
4534(symbol->string
4535 (string->symbol "Malvina")) @result{} "Malvina"
4536
4537(eq? 'mISSISSIppi 'mississippi) @result{} #f
4538(string->symbol "mISSISSIppi") @result{} mISSISSIppi
4539(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
4540(eq? 'LolliPop
4541 (string->symbol (symbol->string 'LolliPop))) @result{} #t
4542(string=? "K. Harper, M.D."
4543 (symbol->string
4544 (string->symbol "K. Harper, M.D."))) @result{} #t
4545@end lisp
4546
4547From C, there are lower level functions that construct a Scheme symbol
c48c62d0
MV
4548from a C string in the current locale encoding.
4549
4550When you want to do more from C, you should convert between symbols
4551and strings using @code{scm_symbol_to_string} and
4552@code{scm_string_to_symbol} and work with the strings.
07d83abe 4553
c48c62d0
MV
4554@deffn {C Function} scm_from_locale_symbol (const char *name)
4555@deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
07d83abe 4556Construct and return a Scheme symbol whose name is specified by
c48c62d0
MV
4557@var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
4558terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
07d83abe
MV
4559specified explicitly by @var{len}.
4560@end deffn
4561
fd0a5bbc
HWN
4562@deftypefn {C Function} SCM scm_take_locale_symbol (char *str)
4563@deftypefnx {C Function} SCM scm_take_locale_symboln (char *str, size_t len)
4564Like @code{scm_from_locale_symbol} and @code{scm_from_locale_symboln},
4565respectively, but also frees @var{str} with @code{free} eventually.
4566Thus, you can use this function when you would free @var{str} anyway
4567immediately after creating the Scheme string. In certain cases, Guile
4568can then use @var{str} directly as its internal representation.
4569@end deftypefn
4570
4571
07d83abe
MV
4572Finally, some applications, especially those that generate new Scheme
4573code dynamically, need to generate symbols for use in the generated
4574code. The @code{gensym} primitive meets this need:
4575
4576@deffn {Scheme Procedure} gensym [prefix]
4577@deffnx {C Function} scm_gensym (prefix)
4578Create a new symbol with a name constructed from a prefix and a counter
4579value. The string @var{prefix} can be specified as an optional
4580argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
4581at each call. There is no provision for resetting the counter.
4582@end deffn
4583
4584The symbols generated by @code{gensym} are @emph{likely} to be unique,
4585since their names begin with a space and it is only otherwise possible
4586to generate such symbols if a programmer goes out of their way to do
4587so. Uniqueness can be guaranteed by instead using uninterned symbols
4588(@pxref{Symbol Uninterned}), though they can't be usefully written out
4589and read back in.
4590
4591
4592@node Symbol Props
4593@subsubsection Function Slots and Property Lists
4594
4595In traditional Lisp dialects, symbols are often understood as having
4596three kinds of value at once:
4597
4598@itemize @bullet
4599@item
4600a @dfn{variable} value, which is used when the symbol appears in
4601code in a variable reference context
4602
4603@item
4604a @dfn{function} value, which is used when the symbol appears in
4605code in a function name position (i.e. as the first element in an
4606unquoted list)
4607
4608@item
4609a @dfn{property list} value, which is used when the symbol is given as
4610the first argument to Lisp's @code{put} or @code{get} functions.
4611@end itemize
4612
4613Although Scheme (as one of its simplifications with respect to Lisp)
4614does away with the distinction between variable and function namespaces,
4615Guile currently retains some elements of the traditional structure in
4616case they turn out to be useful when implementing translators for other
4617languages, in particular Emacs Lisp.
4618
4619Specifically, Guile symbols have two extra slots. for a symbol's
4620property list, and for its ``function value.'' The following procedures
4621are provided to access these slots.
4622
4623@deffn {Scheme Procedure} symbol-fref symbol
4624@deffnx {C Function} scm_symbol_fref (symbol)
4625Return the contents of @var{symbol}'s @dfn{function slot}.
4626@end deffn
4627
4628@deffn {Scheme Procedure} symbol-fset! symbol value
4629@deffnx {C Function} scm_symbol_fset_x (symbol, value)
4630Set the contents of @var{symbol}'s function slot to @var{value}.
4631@end deffn
4632
4633@deffn {Scheme Procedure} symbol-pref symbol
4634@deffnx {C Function} scm_symbol_pref (symbol)
4635Return the @dfn{property list} currently associated with @var{symbol}.
4636@end deffn
4637
4638@deffn {Scheme Procedure} symbol-pset! symbol value
4639@deffnx {C Function} scm_symbol_pset_x (symbol, value)
4640Set @var{symbol}'s property list to @var{value}.
4641@end deffn
4642
4643@deffn {Scheme Procedure} symbol-property sym prop
4644From @var{sym}'s property list, return the value for property
4645@var{prop}. The assumption is that @var{sym}'s property list is an
4646association list whose keys are distinguished from each other using
4647@code{equal?}; @var{prop} should be one of the keys in that list. If
4648the property list has no entry for @var{prop}, @code{symbol-property}
4649returns @code{#f}.
4650@end deffn
4651
4652@deffn {Scheme Procedure} set-symbol-property! sym prop val
4653In @var{sym}'s property list, set the value for property @var{prop} to
4654@var{val}, or add a new entry for @var{prop}, with value @var{val}, if
4655none already exists. For the structure of the property list, see
4656@code{symbol-property}.
4657@end deffn
4658
4659@deffn {Scheme Procedure} symbol-property-remove! sym prop
4660From @var{sym}'s property list, remove the entry for property
4661@var{prop}, if there is one. For the structure of the property list,
4662see @code{symbol-property}.
4663@end deffn
4664
4665Support for these extra slots may be removed in a future release, and it
4666is probably better to avoid using them. (In release 1.6, Guile itself
4667uses the property list slot sparingly, and the function slot not at
4668all.) For a more modern and Schemely approach to properties, see
4669@ref{Object Properties}.
4670
4671
4672@node Symbol Read Syntax
4673@subsubsection Extended Read Syntax for Symbols
4674
4675The read syntax for a symbol is a sequence of letters, digits, and
4676@dfn{extended alphabetic characters}, beginning with a character that
4677cannot begin a number. In addition, the special cases of @code{+},
4678@code{-}, and @code{...} are read as symbols even though numbers can
4679begin with @code{+}, @code{-} or @code{.}.
4680
4681Extended alphabetic characters may be used within identifiers as if
4682they were letters. The set of extended alphabetic characters is:
4683
4684@example
4685! $ % & * + - . / : < = > ? @@ ^ _ ~
4686@end example
4687
4688In addition to the standard read syntax defined above (which is taken
4689from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
4690Scheme})), Guile provides an extended symbol read syntax that allows the
4691inclusion of unusual characters such as space characters, newlines and
4692parentheses. If (for whatever reason) you need to write a symbol
4693containing characters not mentioned above, you can do so as follows.
4694
4695@itemize @bullet
4696@item
4697Begin the symbol with the characters @code{#@{},
4698
4699@item
4700write the characters of the symbol and
4701
4702@item
4703finish the symbol with the characters @code{@}#}.
4704@end itemize
4705
4706Here are a few examples of this form of read syntax. The first symbol
4707needs to use extended syntax because it contains a space character, the
4708second because it contains a line break, and the last because it looks
4709like a number.
4710
4711@lisp
4712#@{foo bar@}#
4713
4714#@{what
4715ever@}#
4716
4717#@{4242@}#
4718@end lisp
4719
4720Although Guile provides this extended read syntax for symbols,
4721widespread usage of it is discouraged because it is not portable and not
4722very readable.
4723
4724
4725@node Symbol Uninterned
4726@subsubsection Uninterned Symbols
4727
4728What makes symbols useful is that they are automatically kept unique.
4729There are no two symbols that are distinct objects but have the same
4730name. But of course, there is no rule without exception. In addition
4731to the normal symbols that have been discussed up to now, you can also
4732create special @dfn{uninterned} symbols that behave slightly
4733differently.
4734
4735To understand what is different about them and why they might be useful,
4736we look at how normal symbols are actually kept unique.
4737
4738Whenever Guile wants to find the symbol with a specific name, for
4739example during @code{read} or when executing @code{string->symbol}, it
4740first looks into a table of all existing symbols to find out whether a
4741symbol with the given name already exists. When this is the case, Guile
4742just returns that symbol. When not, a new symbol with the name is
4743created and entered into the table so that it can be found later.
4744
4745Sometimes you might want to create a symbol that is guaranteed `fresh',
4746i.e. a symbol that did not exist previously. You might also want to
4747somehow guarantee that no one else will ever unintentionally stumble
4748across your symbol in the future. These properties of a symbol are
4749often needed when generating code during macro expansion. When
4750introducing new temporary variables, you want to guarantee that they
4751don't conflict with variables in other people's code.
4752
4753The simplest way to arrange for this is to create a new symbol but
4754not enter it into the global table of all symbols. That way, no one
4755will ever get access to your symbol by chance. Symbols that are not in
4756the table are called @dfn{uninterned}. Of course, symbols that
4757@emph{are} in the table are called @dfn{interned}.
4758
4759You create new uninterned symbols with the function @code{make-symbol}.
4760You can test whether a symbol is interned or not with
4761@code{symbol-interned?}.
4762
4763Uninterned symbols break the rule that the name of a symbol uniquely
4764identifies the symbol object. Because of this, they can not be written
4765out and read back in like interned symbols. Currently, Guile has no
4766support for reading uninterned symbols. Note that the function
4767@code{gensym} does not return uninterned symbols for this reason.
4768
4769@deffn {Scheme Procedure} make-symbol name
4770@deffnx {C Function} scm_make_symbol (name)
4771Return a new uninterned symbol with the name @var{name}. The returned
4772symbol is guaranteed to be unique and future calls to
4773@code{string->symbol} will not return it.
4774@end deffn
4775
4776@deffn {Scheme Procedure} symbol-interned? symbol
4777@deffnx {C Function} scm_symbol_interned_p (symbol)
4778Return @code{#t} if @var{symbol} is interned, otherwise return
4779@code{#f}.
4780@end deffn
4781
4782For example:
4783
4784@lisp
4785(define foo-1 (string->symbol "foo"))
4786(define foo-2 (string->symbol "foo"))
4787(define foo-3 (make-symbol "foo"))
4788(define foo-4 (make-symbol "foo"))
4789
4790(eq? foo-1 foo-2)
4791@result{} #t
4792; Two interned symbols with the same name are the same object,
4793
4794(eq? foo-1 foo-3)
4795@result{} #f
4796; but a call to make-symbol with the same name returns a
4797; distinct object.
4798
4799(eq? foo-3 foo-4)
4800@result{} #f
4801; A call to make-symbol always returns a new object, even for
4802; the same name.
4803
4804foo-3
4805@result{} #<uninterned-symbol foo 8085290>
4806; Uninterned symbols print differently from interned symbols,
4807
4808(symbol? foo-3)
4809@result{} #t
4810; but they are still symbols,
4811
4812(symbol-interned? foo-3)
4813@result{} #f
4814; just not interned.
4815@end lisp
4816
4817
4818@node Keywords
4819@subsection Keywords
4820@tpindex Keywords
4821
4822Keywords are self-evaluating objects with a convenient read syntax that
4823makes them easy to type.
4824
4825Guile's keyword support conforms to R5RS, and adds a (switchable) read
4826syntax extension to permit keywords to begin with @code{:} as well as
4827@code{#:}.
4828
4829@menu
4830* Why Use Keywords?:: Motivation for keyword usage.
4831* Coding With Keywords:: How to use keywords.
4832* Keyword Read Syntax:: Read syntax for keywords.
4833* Keyword Procedures:: Procedures for dealing with keywords.
07d83abe
MV
4834@end menu
4835
4836@node Why Use Keywords?
4837@subsubsection Why Use Keywords?
4838
4839Keywords are useful in contexts where a program or procedure wants to be
4840able to accept a large number of optional arguments without making its
4841interface unmanageable.
4842
4843To illustrate this, consider a hypothetical @code{make-window}
4844procedure, which creates a new window on the screen for drawing into
4845using some graphical toolkit. There are many parameters that the caller
4846might like to specify, but which could also be sensibly defaulted, for
4847example:
4848
4849@itemize @bullet
4850@item
4851color depth -- Default: the color depth for the screen
4852
4853@item
4854background color -- Default: white
4855
4856@item
4857width -- Default: 600
4858
4859@item
4860height -- Default: 400
4861@end itemize
4862
4863If @code{make-window} did not use keywords, the caller would have to
4864pass in a value for each possible argument, remembering the correct
4865argument order and using a special value to indicate the default value
4866for that argument:
4867
4868@lisp
4869(make-window 'default ;; Color depth
4870 'default ;; Background color
4871 800 ;; Width
4872 100 ;; Height
4873 @dots{}) ;; More make-window arguments
4874@end lisp
4875
4876With keywords, on the other hand, defaulted arguments are omitted, and
4877non-default arguments are clearly tagged by the appropriate keyword. As
4878a result, the invocation becomes much clearer:
4879
4880@lisp
4881(make-window #:width 800 #:height 100)
4882@end lisp
4883
4884On the other hand, for a simpler procedure with few arguments, the use
4885of keywords would be a hindrance rather than a help. The primitive
4886procedure @code{cons}, for example, would not be improved if it had to
4887be invoked as
4888
4889@lisp
4890(cons #:car x #:cdr y)
4891@end lisp
4892
4893So the decision whether to use keywords or not is purely pragmatic: use
4894them if they will clarify the procedure invocation at point of call.
4895
4896@node Coding With Keywords
4897@subsubsection Coding With Keywords
4898
4899If a procedure wants to support keywords, it should take a rest argument
4900and then use whatever means is convenient to extract keywords and their
4901corresponding arguments from the contents of that rest argument.
4902
4903The following example illustrates the principle: the code for
4904@code{make-window} uses a helper procedure called
4905@code{get-keyword-value} to extract individual keyword arguments from
4906the rest argument.
4907
4908@lisp
4909(define (get-keyword-value args keyword default)
4910 (let ((kv (memq keyword args)))
4911 (if (and kv (>= (length kv) 2))
4912 (cadr kv)
4913 default)))
4914
4915(define (make-window . args)
4916 (let ((depth (get-keyword-value args #:depth screen-depth))
4917 (bg (get-keyword-value args #:bg "white"))
4918 (width (get-keyword-value args #:width 800))
4919 (height (get-keyword-value args #:height 100))
4920 @dots{})
4921 @dots{}))
4922@end lisp
4923
4924But you don't need to write @code{get-keyword-value}. The @code{(ice-9
4925optargs)} module provides a set of powerful macros that you can use to
4926implement keyword-supporting procedures like this:
4927
4928@lisp
4929(use-modules (ice-9 optargs))
4930
4931(define (make-window . args)
4932 (let-keywords args #f ((depth screen-depth)
4933 (bg "white")
4934 (width 800)
4935 (height 100))
4936 ...))
4937@end lisp
4938
4939@noindent
4940Or, even more economically, like this:
4941
4942@lisp
4943(use-modules (ice-9 optargs))
4944
4945(define* (make-window #:key (depth screen-depth)
4946 (bg "white")
4947 (width 800)
4948 (height 100))
4949 ...)
4950@end lisp
4951
4952For further details on @code{let-keywords}, @code{define*} and other
4953facilities provided by the @code{(ice-9 optargs)} module, see
4954@ref{Optional Arguments}.
4955
4956
4957@node Keyword Read Syntax
4958@subsubsection Keyword Read Syntax
4959
7719ef22
MV
4960Guile, by default, only recognizes a keyword syntax that is compatible
4961with R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the
4962same syntax as a Scheme symbol (@pxref{Symbol Read Syntax}), is the
4963external representation of the keyword named @code{NAME}. Keyword
4964objects print using this syntax as well, so values containing keyword
4965objects can be read back into Guile. When used in an expression,
4966keywords are self-quoting objects.
07d83abe
MV
4967
4968If the @code{keyword} read option is set to @code{'prefix}, Guile also
4969recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
4970of the form @code{:NAME} are read as symbols, as required by R5RS.
4971
4972To enable and disable the alternative non-R5RS keyword syntax, you use
4973the @code{read-set!} procedure documented in @ref{User level options
4974interfaces} and @ref{Reader options}.
4975
4976@smalllisp
4977(read-set! keywords 'prefix)
4978
4979#:type
4980@result{}
4981#:type
4982
4983:type
4984@result{}
4985#:type
4986
4987(read-set! keywords #f)
4988
4989#:type
4990@result{}
4991#:type
4992
4993:type
4994@print{}
4995ERROR: In expression :type:
4996ERROR: Unbound variable: :type
4997ABORT: (unbound-variable)
4998@end smalllisp
4999
5000@node Keyword Procedures
5001@subsubsection Keyword Procedures
5002
07d83abe
MV
5003@deffn {Scheme Procedure} keyword? obj
5004@deffnx {C Function} scm_keyword_p (obj)
5005Return @code{#t} if the argument @var{obj} is a keyword, else
5006@code{#f}.
5007@end deffn
5008
7719ef22
MV
5009@deffn {Scheme Procedure} keyword->symbol keyword
5010@deffnx {C Function} scm_keyword_to_symbol (keyword)
5011Return the symbol with the same name as @var{keyword}.
07d83abe
MV
5012@end deffn
5013
7719ef22
MV
5014@deffn {Scheme Procedure} symbol->keyword symbol
5015@deffnx {C Function} scm_symbol_to_keyword (symbol)
5016Return the keyword with the same name as @var{symbol}.
5017@end deffn
07d83abe 5018
7719ef22
MV
5019@deftypefn {C Function} int scm_is_keyword (SCM obj)
5020Equivalent to @code{scm_is_true (scm_keyword_p (@var{obj}))}.
07d83abe
MV
5021@end deftypefn
5022
7719ef22
MV
5023@deftypefn {C Function} SCM scm_from_locale_keyword (const char *str)
5024@deftypefnx {C Function} SCM scm_from_locale_keywordn (const char *str, size_t len)
5025Equivalent to @code{scm_symbol_to_keyword (scm_from_locale_symbol
5026(@var{str}))} and @code{scm_symbol_to_keyword (scm_from_locale_symboln
5027(@var{str}, @var{len}))}, respectively.
5028@end deftypefn
07d83abe
MV
5029
5030@node Other Types
5031@subsection ``Functionality-Centric'' Data Types
5032
5033Procedures and macros are documented in their own chapter: see
5034@ref{Procedures and Macros}.
5035
5036Variable objects are documented as part of the description of Guile's
5037module system: see @ref{Variables}.
5038
5039Asyncs, dynamic roots and fluids are described in the chapter on
5040scheduling: see @ref{Scheduling}.
5041
5042Hooks are documented in the chapter on general utility functions: see
5043@ref{Hooks}.
5044
5045Ports are described in the chapter on I/O: see @ref{Input and Output}.
5046
5047
5048@c Local Variables:
5049@c TeX-master: "guile.texi"
5050@c End: