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