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