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