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