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