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