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