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