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