More deprecated entries.
[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.
3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Simple Data Types
9@section Simple Generic Data Types
10
11This chapter describes those of Guile's simple data types which are
12primarily used for their role as items of generic data. By
13@dfn{simple} we mean data types that are not primarily used as
14containers to hold other data --- i.e.@: pairs, lists, vectors and so on.
15For the documentation of such @dfn{compound} data types, see
16@ref{Compound Data Types}.
17
18@c One of the great strengths of Scheme is that there is no straightforward
19@c distinction between ``data'' and ``functionality''. For example,
20@c Guile's support for dynamic linking could be described:
21
22@c @itemize @bullet
23@c @item
24@c either in a ``data-centric'' way, as the behaviour and properties of the
25@c ``dynamically linked object'' data type, and the operations that may be
26@c applied to instances of this type
27
28@c @item
29@c or in a ``functionality-centric'' way, as the set of procedures that
30@c constitute Guile's support for dynamic linking, in the context of the
31@c module system.
32@c @end itemize
33
34@c The contents of this chapter are, therefore, a matter of judgment. By
35@c @dfn{generic}, we mean to select those data types whose typical use as
36@c @emph{data} in a wide variety of programming contexts is more important
37@c than their use in the implementation of a particular piece of
38@c @emph{functionality}. The last section of this chapter provides
39@c references for all the data types that are documented not here but in a
40@c ``functionality-centric'' way elsewhere in the manual.
41
42@menu
43* Booleans:: True/false values.
44* Numbers:: Numerical data types.
45* Characters:: New character names.
46* Strings:: Special things about strings.
47* Regular Expressions:: Pattern matching and substitution.
48* Symbols:: Symbols.
49* Keywords:: Self-quoting, customizable display keywords.
50* Other Types:: "Functionality-centric" data types.
51@end menu
52
53
54@node Booleans
55@subsection Booleans
56@tpindex Booleans
57
58The two boolean values are @code{#t} for true and @code{#f} for false.
59
60Boolean values are returned by predicate procedures, such as the general
61equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
62(@pxref{Equality}) and numerical and string comparison operators like
63@code{string=?} (@pxref{String Comparison}) and @code{<=}
64(@pxref{Comparison}).
65
66@lisp
67(<= 3 8)
68@result{} #t
69
70(<= 3 -3)
71@result{} #f
72
73(equal? "house" "houses")
74@result{} #f
75
76(eq? #f #f)
77@result{}
78#t
79@end lisp
80
81In test condition contexts like @code{if} and @code{cond} (@pxref{if
82cond case}), where a group of subexpressions will be evaluated only if a
83@var{condition} expression evaluates to ``true'', ``true'' means any
84value at all except @code{#f}.
85
86@lisp
87(if #t "yes" "no")
88@result{} "yes"
89
90(if 0 "yes" "no")
91@result{} "yes"
92
93(if #f "yes" "no")
94@result{} "no"
95@end lisp
96
97A result of this asymmetry is that typical Scheme source code more often
98uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
99represent an @code{if} or @code{cond} false value, whereas @code{#t} is
100not necessary to represent an @code{if} or @code{cond} true value.
101
102It is important to note that @code{#f} is @strong{not} equivalent to any
103other Scheme value. In particular, @code{#f} is not the same as the
104number 0 (like in C and C++), and not the same as the ``empty list''
105(like in some Lisp dialects).
106
107In C, the two Scheme boolean values are available as the two constants
108@code{SCM_BOOL_T} for @code{#t} and @code{SCM_BOOL_F} for @code{#f}.
109Care must be taken with the false value @code{SCM_BOOL_F}: it is not
110false when used in C conditionals. In order to test for it, use
111@code{scm_is_false} or @code{scm_is_true}.
112
113@rnindex not
114@deffn {Scheme Procedure} not x
115@deffnx {C Function} scm_not (x)
116Return @code{#t} if @var{x} is @code{#f}, else return @code{#f}.
117@end deffn
118
119@rnindex boolean?
120@deffn {Scheme Procedure} boolean? obj
121@deffnx {C Function} scm_boolean_p (obj)
122Return @code{#t} if @var{obj} is either @code{#t} or @code{#f}, else
123return @code{#f}.
124@end deffn
125
126@deftypevr {C Macro} SCM SCM_BOOL_T
127The @code{SCM} representation of the Scheme object @code{#t}.
128@end deftypevr
129
130@deftypevr {C Macro} SCM SCM_BOOL_F
131The @code{SCM} representation of the Scheme object @code{#f}.
132@end deftypevr
133
134@deftypefn {C Function} int scm_is_true (SCM obj)
135Return @code{0} if @var{obj} is @code{#f}, else return @code{1}.
136@end deftypefn
137
138@deftypefn {C Function} int scm_is_false (SCM obj)
139Return @code{1} if @var{obj} is @code{#f}, else return @code{0}.
140@end deftypefn
141
142@deftypefn {C Function} int scm_is_bool (SCM obj)
143Return @code{1} if @var{obj} is either @code{#t} or @code{#f}, else
144return @code{0}.
145@end deftypefn
146
147@deftypefn {C Function} SCM scm_from_bool (int val)
148Return @code{#f} if @var{val} is @code{0}, else return @code{#t}.
149@end deftypefn
150
151@deftypefn {C Function} int scm_to_bool (SCM val)
152Return @code{1} if @var{val} is @code{SCM_BOOL_T}, return @code{0}
153when @var{val} is @code{SCM_BOOL_F}, else signal a `wrong type' error.
154
155You should probably use @code{scm_is_true} instead of this function
156when you just want to test a @code{SCM} value for trueness.
157@end deftypefn
158
159@node Numbers
160@subsection Numerical data types
161@tpindex Numbers
162
163Guile supports a rich ``tower'' of numerical types --- integer,
164rational, real and complex --- and provides an extensive set of
165mathematical and scientific functions for operating on numerical
166data. This section of the manual documents those types and functions.
167
168You may also find it illuminating to read R5RS's presentation of numbers
169in Scheme, which is particularly clear and accessible: see
170@ref{Numbers,,,r5rs,R5RS}.
171
172@menu
173* Numerical Tower:: Scheme's numerical "tower".
174* Integers:: Whole numbers.
175* Reals and Rationals:: Real and rational numbers.
176* Complex Numbers:: Complex numbers.
177* Exactness:: Exactness and inexactness.
178* Number Syntax:: Read syntax for numerical data.
179* Integer Operations:: Operations on integer values.
180* Comparison:: Comparison predicates.
181* Conversion:: Converting numbers to and from strings.
182* Complex:: Complex number operations.
183* Arithmetic:: Arithmetic functions.
184* Scientific:: Scientific functions.
185* Primitive Numerics:: Primitive numeric functions.
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
229@m{2\sin(\pi/4),sin(pi/4)} is exactly @m{\sqrt{2},2^(1/2)} but Guile
230can neither represent @m{\pi/4,pi/4} nor @m{\sqrt{2},2^(1/2)} exactly.
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
307The infinities @samp{+inf.0} and @samp{-inf.0} are considered to be
308inexact integers. They are explained in detail in the next section,
309together with reals and rationals.
310
311C has a host of different integer types, and Guile offers a host of
312functions to convert between them and the @code{SCM} representation.
313For example, a C @code{int} can be handled with @code{scm_to_int} and
314@code{scm_from_int}. Guile also defines a few C integer types of its
315own, to help with differences between systems.
316
317C integer types that are not covered can be handled with the generic
318@code{scm_to_signed_integer} and @code{scm_from_signed_integer} for
319signed types, or with @code{scm_to_unsigned_integer} and
320@code{scm_from_unsigned_integer} for unsigned types.
321
322Scheme integers can be exact and inexact. For example, a number
323written as @code{3.0} with an explicit decimal-point is inexact, but
324it is also an integer. The functions @code{integer?} and
325@code{scm_is_integer} report true for such a number, but the functions
326@code{scm_is_signed_integer} and @code{scm_is_unsigned_integer} only
327allow exact integers and thus report false. Likewise, the conversion
328functions like @code{scm_to_signed_integer} only accept exact
329integers.
330
331The motivation for this behavior is that the inexactness of a number
332should not be lost silently. If you want to allow inexact integers,
333you can explicitely insert a call to @code{inexact->exact} or to its C
334equivalent @code{scm_inexact_to_exact}. (Only inexact integers will
335be converted by this call into exact integers; inexact non-integers
336will become exact fractions.)
337
338@deffn {Scheme Procedure} integer? x
339@deffnx {C Function} scm_integer_p (x)
340Return @code{#t} if @var{x} is an exactor inexact integer number, else
341@code{#f}.
342
343@lisp
344(integer? 487)
345@result{} #t
346
347(integer? 3.0)
348@result{} #t
349
350(integer? -3.4)
351@result{} #f
352
353(integer? +inf.0)
354@result{} #t
355@end lisp
356@end deffn
357
358@deftypefn {C Function} int scm_is_integer (SCM x)
359This is equivalent to @code{scm_is_true (scm_integer_p (x))}.
360@end deftypefn
361
362@defvr {C Type} scm_t_int8
363@defvrx {C Type} scm_t_uint8
364@defvrx {C Type} scm_t_int16
365@defvrx {C Type} scm_t_uint16
366@defvrx {C Type} scm_t_int32
367@defvrx {C Type} scm_t_uint32
368@defvrx {C Type} scm_t_int64
369@defvrx {C Type} scm_t_uint64
370@defvrx {C Type} scm_t_intmax
371@defvrx {C Type} scm_t_uintmax
372The C types are equivalent to the corresponding ISO C types but are
373defined on all platforms, with the exception of @code{scm_t_int64} and
374@code{scm_t_uint64}, which are only defined when a 64-bit type is
375available. For example, @code{scm_t_int8} is equivalent to
376@code{int8_t}.
377
378You can regard these definitions as a stop-gap measure until all
379platforms provide these types. If you know that all the platforms
380that you are interested in already provide these types, it is better
381to use them directly instead of the types provided by Guile.
382@end defvr
383
384@deftypefn {C Function} int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
385@deftypefnx {C Function} int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
386Return @code{1} when @var{x} represents an exact integer that is
387between @var{min} and @var{max}, inclusive.
388
389These functions can be used to check whether a @code{SCM} value will
390fit into a given range, such as the range of a given C integer type.
391If you just want to convert a @code{SCM} value to a given C integer
392type, use one of the conversion functions directly.
393@end deftypefn
394
395@deftypefn {C Function} scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
396@deftypefnx {C Function} scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
397When @var{x} represents an exact integer that is between @var{min} and
398@var{max} inclusive, return that integer. Else signal an error,
399either a `wrong-type' error when @var{x} is not an exact integer, or
400an `out-of-range' error when it doesn't fit the given range.
401@end deftypefn
402
403@deftypefn {C Function} SCM scm_from_signed_integer (scm_t_intmax x)
404@deftypefnx {C Function} SCM scm_from_unsigned_integer (scm_t_uintmax x)
405Return the @code{SCM} value that represents the integer @var{x}. This
406function will always succeed and will always return an exact number.
407@end deftypefn
408
409@deftypefn {C Function} char scm_to_char (SCM x)
410@deftypefnx {C Function} {signed char} scm_to_schar (SCM x)
411@deftypefnx {C Function} {unsigned char} scm_to_uchar (SCM x)
412@deftypefnx {C Function} short scm_to_short (SCM x)
413@deftypefnx {C Function} {unsigned short} scm_to_ushort (SCM x)
414@deftypefnx {C Function} int scm_to_int (SCM x)
415@deftypefnx {C Function} {unsigned int} scm_to_uint (SCM x)
416@deftypefnx {C Function} long scm_to_long (SCM x)
417@deftypefnx {C Function} {unsigned long} scm_to_ulong (SCM x)
418@deftypefnx {C Function} {long long} scm_to_long_long (SCM x)
419@deftypefnx {C Function} {unsigned long long} scm_to_ulong_long (SCM x)
420@deftypefnx {C Function} size_t scm_to_size_t (SCM x)
421@deftypefnx {C Function} ssize_t scm_to_ssize_t (SCM x)
422@deftypefnx {C Function} scm_t_int8 scm_to_int8 (SCM x)
423@deftypefnx {C Function} scm_t_uint8 scm_to_uint8 (SCM x)
424@deftypefnx {C Function} scm_t_int16 scm_to_int16 (SCM x)
425@deftypefnx {C Function} scm_t_uint16 scm_to_uint16 (SCM x)
426@deftypefnx {C Function} scm_t_int32 scm_to_int32 (SCM x)
427@deftypefnx {C Function} scm_t_uint32 scm_to_uint32 (SCM x)
428@deftypefnx {C Function} scm_t_int64 scm_to_int64 (SCM x)
429@deftypefnx {C Function} scm_t_uint64 scm_to_uint64 (SCM x)
430@deftypefnx {C Function} scm_t_intmax scm_to_intmax (SCM x)
431@deftypefnx {C Function} scm_t_uintmax scm_to_uintmax (SCM x)
432When @var{x} represents an exact integer that fits into the indicated
433C type, return that integer. Else signal an error, either a
434`wrong-type' error when @var{x} is not an exact integer, or an
435`out-of-range' error when it doesn't fit the given range.
436
437The functions @code{scm_to_long_long}, @code{scm_to_ulong_long},
438@code{scm_to_int64}, and @code{scm_to_uint64} are only available when
439the corresponding types are.
440@end deftypefn
441
442@deftypefn {C Function} SCM scm_from_char (char x)
443@deftypefnx {C Function} SCM scm_from_schar (signed char x)
444@deftypefnx {C Function} SCM scm_from_uchar (unsigned char x)
445@deftypefnx {C Function} SCM scm_from_short (short x)
446@deftypefnx {C Function} SCM scm_from_ushort (unsigned short x)
447@deftypefnx {C Function} SCM scm_from_int (int x)
448@deftypefnx {C Function} SCM scm_from_uint (unsigned int x)
449@deftypefnx {C Function} SCM scm_from_long (long x)
450@deftypefnx {C Function} SCM scm_from_ulong (unsigned long x)
451@deftypefnx {C Function} SCM scm_from_long_long (long long x)
452@deftypefnx {C Function} SCM scm_from_ulong_long (unsigned long long x)
453@deftypefnx {C Function} SCM scm_from_size_t (size_t x)
454@deftypefnx {C Function} SCM scm_from_ssize_t (ssize_t x)
455@deftypefnx {C Function} SCM scm_from_int8 (scm_t_int8 x)
456@deftypefnx {C Function} SCM scm_from_uint8 (scm_t_uint8 x)
457@deftypefnx {C Function} SCM scm_from_int16 (scm_t_int16 x)
458@deftypefnx {C Function} SCM scm_from_uint16 (scm_t_uint16 x)
459@deftypefnx {C Function} SCM scm_from_int32 (scm_t_int32 x)
460@deftypefnx {C Function} SCM scm_from_uint32 (scm_t_uint32 x)
461@deftypefnx {C Function} SCM scm_from_int64 (scm_t_int64 x)
462@deftypefnx {C Function} SCM scm_from_uint64 (scm_t_uint64 x)
463@deftypefnx {C Function} SCM scm_from_intmax (scm_t_intmax x)
464@deftypefnx {C Function} SCM scm_from_uintmax (scm_t_uintmax x)
465Return the @code{SCM} value that represents the integer @var{x}.
466These functions will always succeed and will always return an exact
467number.
468@end deftypefn
469
470@node Reals and Rationals
471@subsubsection Real and Rational Numbers
472@tpindex Real numbers
473@tpindex Rational numbers
474
475@rnindex real?
476@rnindex rational?
477
478Mathematically, the real numbers are the set of numbers that describe
479all possible points along a continuous, infinite, one-dimensional line.
480The rational numbers are the set of all numbers that can be written as
481fractions @var{p}/@var{q}, where @var{p} and @var{q} are integers.
482All rational numbers are also real, but there are real numbers that
483are not rational, for example the square root of 2, and pi.
484
485Guile can represent both exact and inexact rational numbers, but it
486can not represent irrational numbers. Exact rationals are represented
487by storing the numerator and denominator as two exact integers.
488Inexact rationals are stored as floating point numbers using the C
489type @code{double}.
490
491Exact rationals are written as a fraction of integers. There must be
492no whitespace around the slash:
493
494@lisp
4951/2
496-22/7
497@end lisp
498
499Even though the actual encoding of inexact rationals is in binary, it
500may be helpful to think of it as a decimal number with a limited
501number of significant figures and a decimal point somewhere, since
502this corresponds to the standard notation for non-whole numbers. For
503example:
504
505@lisp
5060.34
507-0.00000142857931198
508-5648394822220000000000.0
5094.0
510@end lisp
511
512The limited precision of Guile's encoding means that any ``real'' number
513in Guile can be written in a rational form, by multiplying and then dividing
514by sufficient powers of 10 (or in fact, 2). For example,
515@samp{-0.00000142857931198} is the same as @minus{}142857931198 divided by
516100000000000000000. In Guile's current incarnation, therefore, the
517@code{rational?} and @code{real?} predicates are equivalent.
518
519
520Dividing by an exact zero leads to a error message, as one might
521expect. However, dividing by an inexact zero does not produce an
522error. Instead, the result of the division is either plus or minus
523infinity, depending on the sign of the divided number.
524
525The infinities are written @samp{+inf.0} and @samp{-inf.0},
526respectivly. This syntax is also recognized by @code{read} as an
527extension to the usual Scheme syntax.
528
529Dividing zero by zero yields something that is not a number at all:
530@samp{+nan.0}. This is the special `not a number' value.
531
532On platforms that follow @acronym{IEEE} 754 for their floating point
533arithmetic, the @samp{+inf.0}, @samp{-inf.0}, and @samp{+nan.0} values
534are implemented using the corresponding @acronym{IEEE} 754 values.
535They behave in arithmetic operations like @acronym{IEEE} 754 describes
536it, i.e., @code{(= +nan.0 +nan.0)} @result{} @code{#f}.
537
538The infinities are inexact integers and are considered to be both even
539and odd. While @samp{+nan.0} is not @code{=} to itself, it is
540@code{eqv?} to itself.
541
542To test for the special values, use the functions @code{inf?} and
543@code{nan?}.
544
545@deffn {Scheme Procedure} real? obj
546@deffnx {C Function} scm_real_p (obj)
547Return @code{#t} if @var{obj} is a real number, else @code{#f}. Note
548that the sets of integer and rational values form subsets of the set
549of real numbers, so the predicate will also be fulfilled if @var{obj}
550is an integer number or a rational number.
551@end deffn
552
553@deffn {Scheme Procedure} rational? x
554@deffnx {C Function} scm_rational_p (x)
555Return @code{#t} if @var{x} is a rational number, @code{#f} otherwise.
556Note that the set of integer values forms a subset of the set of
557rational numbers, i. e. the predicate will also be fulfilled if
558@var{x} is an integer number.
559
560Since Guile can not represent irrational numbers, every number
561satisfying @code{real?} also satisfies @code{rational?} in Guile.
562@end deffn
563
564@deffn {Scheme Procedure} rationalize x eps
565@deffnx {C Function} scm_rationalize (x, eps)
566Returns the @emph{simplest} rational number differing
567from @var{x} by no more than @var{eps}.
568
569As required by @acronym{R5RS}, @code{rationalize} only returns an
570exact result when both its arguments are exact. Thus, you might need
571to use @code{inexact->exact} on the arguments.
572
573@lisp
574(rationalize (inexact->exact 1.2) 1/100)
575@result{} 6/5
576@end lisp
577
578@end deffn
579
d3df9759
MV
580@deffn {Scheme Procedure} inf? x
581@deffnx {C Function} scm_inf_p (x)
07d83abe
MV
582Return @code{#t} if @var{x} is either @samp{+inf.0} or @samp{-inf.0},
583@code{#f} otherwise.
584@end deffn
585
586@deffn {Scheme Procedure} nan? x
d3df9759 587@deffnx {C Function} scm_nan_p (x)
07d83abe
MV
588Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise.
589@end deffn
590
cdf1ad3b
MV
591@deffn {Scheme Procedure} nan
592@deffnx {C Function} scm_nan ()
593Return NaN.
594@end deffn
595
596@deffn {Scheme Procedure} inf
597@deffnx {C Function} scm_inf ()
598Return Inf.
599@end deffn
600
d3df9759
MV
601@deffn {Scheme Procedure} numerator x
602@deffnx {C Function} scm_numerator (x)
603Return the numerator of the rational number @var{x}.
604@end deffn
605
606@deffn {Scheme Procedure} denominator x
607@deffnx {C Function} scm_denominator (x)
608Return the denominator of the rational number @var{x}.
609@end deffn
610
611@deftypefn {C Function} int scm_is_real (SCM val)
612@deftypefnx {C Function} int scm_is_rational (SCM val)
613Equivalent to @code{scm_is_true (scm_real_p (val))} and
614@code{scm_is_true (scm_rational_p (val))}, respectively.
615@end deftypefn
616
617@deftypefn {C Function} double scm_to_double (SCM val)
618Returns the number closest to @var{val} that is representable as a
619@code{double}. Returns infinity for a @var{val} that is too large in
620magnitude. The argument @var{val} must be a real number.
621@end deftypefn
622
623@deftypefn {C Function} SCM scm_from_double (double val)
624Return the @code{SCM} value that representats @var{val}. The returned
625value is inexact according to the predicate @code{inexact?}, but it
626will be exactly equal to @var{val}.
627@end deftypefn
628
07d83abe
MV
629@node Complex Numbers
630@subsubsection Complex Numbers
631@tpindex Complex numbers
632
633@rnindex complex?
634
635Complex numbers are the set of numbers that describe all possible points
636in a two-dimensional space. The two coordinates of a particular point
637in this space are known as the @dfn{real} and @dfn{imaginary} parts of
638the complex number that describes that point.
639
640In Guile, complex numbers are written in rectangular form as the sum of
641their real and imaginary parts, using the symbol @code{i} to indicate
642the imaginary part.
643
644@lisp
6453+4i
646@result{}
6473.0+4.0i
648
649(* 3-8i 2.3+0.3i)
650@result{}
6519.3-17.5i
652@end lisp
653
654Guile represents a complex number with a non-zero imaginary part as a
655pair of inexact rationals, so the real and imaginary parts of a
656complex number have the same properties of inexactness and limited
657precision as single inexact rational numbers. Guile can not represent
658exact complex numbers with non-zero imaginary parts.
659
5615f696
MV
660@deffn {Scheme Procedure} complex? z
661@deffnx {C Function} scm_complex_p (z)
07d83abe
MV
662Return @code{#t} if @var{x} is a complex number, @code{#f}
663otherwise. Note that the sets of real, rational and integer
664values form subsets of the set of complex numbers, i. e. the
665predicate will also be fulfilled if @var{x} is a real,
666rational or integer number.
667@end deffn
668
07d83abe
MV
669@node Exactness
670@subsubsection Exact and Inexact Numbers
671@tpindex Exact numbers
672@tpindex Inexact numbers
673
674@rnindex exact?
675@rnindex inexact?
676@rnindex exact->inexact
677@rnindex inexact->exact
678
679R5RS requires that a calculation involving inexact numbers always
680produces an inexact result. To meet this requirement, Guile
681distinguishes between an exact integer value such as @samp{5} and the
682corresponding inexact real value which, to the limited precision
683available, has no fractional part, and is printed as @samp{5.0}. Guile
684will only convert the latter value to the former when forced to do so by
685an invocation of the @code{inexact->exact} procedure.
686
687@deffn {Scheme Procedure} exact? z
688@deffnx {C Function} scm_exact_p (z)
689Return @code{#t} if the number @var{z} is exact, @code{#f}
690otherwise.
691
692@lisp
693(exact? 2)
694@result{} #t
695
696(exact? 0.5)
697@result{} #f
698
699(exact? (/ 2))
700@result{} #t
701@end lisp
702
703@end deffn
704
705@deffn {Scheme Procedure} inexact? z
706@deffnx {C Function} scm_inexact_p (z)
707Return @code{#t} if the number @var{z} is inexact, @code{#f}
708else.
709@end deffn
710
711@deffn {Scheme Procedure} inexact->exact z
712@deffnx {C Function} scm_inexact_to_exact (z)
713Return an exact number that is numerically closest to @var{z}, when
714there is one. For inexact rationals, Guile returns the exact rational
715that is numerically equal to the inexact rational. Inexact complex
716numbers with a non-zero imaginary part can not be made exact.
717
718@lisp
719(inexact->exact 0.5)
720@result{} 1/2
721@end lisp
722
723The following happens because 12/10 is not exactly representable as a
724@code{double} (on most platforms). However, when reading a decimal
725number that has been marked exact with the ``#e'' prefix, Guile is
726able to represent it correctly.
727
728@lisp
729(inexact->exact 1.2)
730@result{} 5404319552844595/4503599627370496
731
732#e1.2
733@result{} 6/5
734@end lisp
735
736@end deffn
737
738@c begin (texi-doc-string "guile" "exact->inexact")
739@deffn {Scheme Procedure} exact->inexact z
740@deffnx {C Function} scm_exact_to_inexact (z)
741Convert the number @var{z} to its inexact representation.
742@end deffn
743
744
745@node Number Syntax
746@subsubsection Read Syntax for Numerical Data
747
748The read syntax for integers is a string of digits, optionally
749preceded by a minus or plus character, a code indicating the
750base in which the integer is encoded, and a code indicating whether
751the number is exact or inexact. The supported base codes are:
752
753@table @code
754@item #b
755@itemx #B
756the integer is written in binary (base 2)
757
758@item #o
759@itemx #O
760the integer is written in octal (base 8)
761
762@item #d
763@itemx #D
764the integer is written in decimal (base 10)
765
766@item #x
767@itemx #X
768the integer is written in hexadecimal (base 16)
769@end table
770
771If the base code is omitted, the integer is assumed to be decimal. The
772following examples show how these base codes are used.
773
774@lisp
775-13
776@result{} -13
777
778#d-13
779@result{} -13
780
781#x-13
782@result{} -19
783
784#b+1101
785@result{} 13
786
787#o377
788@result{} 255
789@end lisp
790
791The codes for indicating exactness (which can, incidentally, be applied
792to all numerical values) are:
793
794@table @code
795@item #e
796@itemx #E
797the number is exact
798
799@item #i
800@itemx #I
801the number is inexact.
802@end table
803
804If the exactness indicator is omitted, the number is exact unless it
805contains a radix point. Since Guile can not represent exact complex
806numbers, an error is signalled when asking for them.
807
808@lisp
809(exact? 1.2)
810@result{} #f
811
812(exact? #e1.2)
813@result{} #t
814
815(exact? #e+1i)
816ERROR: Wrong type argument
817@end lisp
818
819Guile also understands the syntax @samp{+inf.0} and @samp{-inf.0} for
820plus and minus infinity, respectively. The value must be written
821exactly as shown, that is, they always must have a sign and exactly
822one zero digit after the decimal point. It also understands
823@samp{+nan.0} and @samp{-nan.0} for the special `not-a-number' value.
824The sign is ignored for `not-a-number' and the value is always printed
825as @samp{+nan.0}.
826
827@node Integer Operations
828@subsubsection Operations on Integer Values
829@rnindex odd?
830@rnindex even?
831@rnindex quotient
832@rnindex remainder
833@rnindex modulo
834@rnindex gcd
835@rnindex lcm
836
837@deffn {Scheme Procedure} odd? n
838@deffnx {C Function} scm_odd_p (n)
839Return @code{#t} if @var{n} is an odd number, @code{#f}
840otherwise.
841@end deffn
842
843@deffn {Scheme Procedure} even? n
844@deffnx {C Function} scm_even_p (n)
845Return @code{#t} if @var{n} is an even number, @code{#f}
846otherwise.
847@end deffn
848
849@c begin (texi-doc-string "guile" "quotient")
850@c begin (texi-doc-string "guile" "remainder")
851@deffn {Scheme Procedure} quotient n d
852@deffnx {Scheme Procedure} remainder n d
853@deffnx {C Function} scm_quotient (n, d)
854@deffnx {C Function} scm_remainder (n, d)
855Return the quotient or remainder from @var{n} divided by @var{d}. The
856quotient is rounded towards zero, and the remainder will have the same
857sign as @var{n}. In all cases quotient and remainder satisfy
858@math{@var{n} = @var{q}*@var{d} + @var{r}}.
859
860@lisp
861(remainder 13 4) @result{} 1
862(remainder -13 4) @result{} -1
863@end lisp
864@end deffn
865
866@c begin (texi-doc-string "guile" "modulo")
867@deffn {Scheme Procedure} modulo n d
868@deffnx {C Function} scm_modulo (n, d)
869Return the remainder from @var{n} divided by @var{d}, with the same
870sign as @var{d}.
871
872@lisp
873(modulo 13 4) @result{} 1
874(modulo -13 4) @result{} 3
875(modulo 13 -4) @result{} -3
876(modulo -13 -4) @result{} -1
877@end lisp
878@end deffn
879
880@c begin (texi-doc-string "guile" "gcd")
881@deffn {Scheme Procedure} gcd
882@deffnx {C Function} scm_gcd (x, y)
883Return the greatest common divisor of all arguments.
884If called without arguments, 0 is returned.
885
886The C function @code{scm_gcd} always takes two arguments, while the
887Scheme function can take an arbitrary number.
888@end deffn
889
890@c begin (texi-doc-string "guile" "lcm")
891@deffn {Scheme Procedure} lcm
892@deffnx {C Function} scm_lcm (x, y)
893Return the least common multiple of the arguments.
894If called without arguments, 1 is returned.
895
896The C function @code{scm_lcm} always takes two arguments, while the
897Scheme function can take an arbitrary number.
898@end deffn
899
cdf1ad3b
MV
900@deffn {Scheme Procedure} modulo-expt n k m
901@deffnx {C Function} scm_modulo_expt (n, k, m)
902Return @var{n} raised to the integer exponent
903@var{k}, modulo @var{m}.
904
905@lisp
906(modulo-expt 2 3 5)
907 @result{} 3
908@end lisp
909@end deffn
07d83abe
MV
910
911@node Comparison
912@subsubsection Comparison Predicates
913@rnindex zero?
914@rnindex positive?
915@rnindex negative?
916
917The C comparison functions below always takes two arguments, while the
918Scheme functions can take an arbitrary number. Also keep in mind that
919the C functions return one of the Scheme boolean values
920@code{SCM_BOOL_T} or @code{SCM_BOOL_F} which are both true as far as C
921is concerned. Thus, always write @code{scm_is_true (scm_num_eq_p (x,
922y))} when testing the two Scheme numbers @code{x} and @code{y} for
923equality, for example.
924
925@c begin (texi-doc-string "guile" "=")
926@deffn {Scheme Procedure} =
927@deffnx {C Function} scm_num_eq_p (x, y)
928Return @code{#t} if all parameters are numerically equal.
929@end deffn
930
931@c begin (texi-doc-string "guile" "<")
932@deffn {Scheme Procedure} <
933@deffnx {C Function} scm_less_p (x, y)
934Return @code{#t} if the list of parameters is monotonically
935increasing.
936@end deffn
937
938@c begin (texi-doc-string "guile" ">")
939@deffn {Scheme Procedure} >
940@deffnx {C Function} scm_gr_p (x, y)
941Return @code{#t} if the list of parameters is monotonically
942decreasing.
943@end deffn
944
945@c begin (texi-doc-string "guile" "<=")
946@deffn {Scheme Procedure} <=
947@deffnx {C Function} scm_leq_p (x, y)
948Return @code{#t} if the list of parameters is monotonically
949non-decreasing.
950@end deffn
951
952@c begin (texi-doc-string "guile" ">=")
953@deffn {Scheme Procedure} >=
954@deffnx {C Function} scm_geq_p (x, y)
955Return @code{#t} if the list of parameters is monotonically
956non-increasing.
957@end deffn
958
959@c begin (texi-doc-string "guile" "zero?")
960@deffn {Scheme Procedure} zero? z
961@deffnx {C Function} scm_zero_p (z)
962Return @code{#t} if @var{z} is an exact or inexact number equal to
963zero.
964@end deffn
965
966@c begin (texi-doc-string "guile" "positive?")
967@deffn {Scheme Procedure} positive? x
968@deffnx {C Function} scm_positive_p (x)
969Return @code{#t} if @var{x} is an exact or inexact number greater than
970zero.
971@end deffn
972
973@c begin (texi-doc-string "guile" "negative?")
974@deffn {Scheme Procedure} negative? x
975@deffnx {C Function} scm_negative_p (x)
976Return @code{#t} if @var{x} is an exact or inexact number less than
977zero.
978@end deffn
979
980
981@node Conversion
982@subsubsection Converting Numbers To and From Strings
983@rnindex number->string
984@rnindex string->number
985
986@deffn {Scheme Procedure} number->string n [radix]
987@deffnx {C Function} scm_number_to_string (n, radix)
988Return a string holding the external representation of the
989number @var{n} in the given @var{radix}. If @var{n} is
990inexact, a radix of 10 will be used.
991@end deffn
992
993@deffn {Scheme Procedure} string->number string [radix]
994@deffnx {C Function} scm_string_to_number (string, radix)
995Return a number of the maximally precise representation
996expressed by the given @var{string}. @var{radix} must be an
997exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
998is a default radix that may be overridden by an explicit radix
999prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
1000supplied, then the default radix is 10. If string is not a
1001syntactically valid notation for a number, then
1002@code{string->number} returns @code{#f}.
1003@end deffn
1004
1005
1006@node Complex
1007@subsubsection Complex Number Operations
1008@rnindex make-rectangular
1009@rnindex make-polar
1010@rnindex real-part
1011@rnindex imag-part
1012@rnindex magnitude
1013@rnindex angle
1014
1015@deffn {Scheme Procedure} make-rectangular real imaginary
1016@deffnx {C Function} scm_make_rectangular (real, imaginary)
1017Return a complex number constructed of the given @var{real} and
1018@var{imaginary} parts.
1019@end deffn
1020
1021@deffn {Scheme Procedure} make-polar x y
1022@deffnx {C Function} scm_make_polar (x, y)
1023Return the complex number @var{x} * e^(i * @var{y}).
1024@end deffn
1025
1026@c begin (texi-doc-string "guile" "real-part")
1027@deffn {Scheme Procedure} real-part z
1028@deffnx {C Function} scm_real_part (z)
1029Return the real part of the number @var{z}.
1030@end deffn
1031
1032@c begin (texi-doc-string "guile" "imag-part")
1033@deffn {Scheme Procedure} imag-part z
1034@deffnx {C Function} scm_imag_part (z)
1035Return the imaginary part of the number @var{z}.
1036@end deffn
1037
1038@c begin (texi-doc-string "guile" "magnitude")
1039@deffn {Scheme Procedure} magnitude z
1040@deffnx {C Function} scm_magnitude (z)
1041Return the magnitude of the number @var{z}. This is the same as
1042@code{abs} for real arguments, but also allows complex numbers.
1043@end deffn
1044
1045@c begin (texi-doc-string "guile" "angle")
1046@deffn {Scheme Procedure} angle z
1047@deffnx {C Function} scm_angle (z)
1048Return the angle of the complex number @var{z}.
1049@end deffn
1050
5615f696
MV
1051@deftypefn {C Function} SCM scm_c_make_rectangular (double re, double im)
1052@deftypefnx {C Function} SCM scm_c_make_polar (double x, double y)
1053Like @code{scm_make_rectangular} or @code{scm_make_polar},
1054respectively, but these functions take @code{double}s as their
1055arguments.
1056@end deftypefn
1057
1058@deftypefn {C Function} double scm_c_real_part (z)
1059@deftypefnx {C Function} double scm_c_imag_part (z)
1060Returns the real or imaginary part of @var{z} as a @code{double}.
1061@end deftypefn
1062
1063@deftypefn {C Function} double scm_c_magnitude (z)
1064@deftypefnx {C Function} double scm_c_angle (z)
1065Returns the magnitude or angle of @var{z} as a @code{double}.
1066@end deftypefn
1067
07d83abe
MV
1068
1069@node Arithmetic
1070@subsubsection Arithmetic Functions
1071@rnindex max
1072@rnindex min
1073@rnindex +
1074@rnindex *
1075@rnindex -
1076@rnindex /
1077@rnindex abs
1078@rnindex floor
1079@rnindex ceiling
1080@rnindex truncate
1081@rnindex round
1082
1083The C arithmetic functions below always takes two arguments, while the
1084Scheme functions can take an arbitrary number. When you need to
1085invoke them with just one argument, for example to compute the
1086equivalent od @code{(- x)}, pass @code{SCM_UNDEFINED} as the second
1087one: @code{scm_difference (x, SCM_UNDEFINED)}.
1088
1089@c begin (texi-doc-string "guile" "+")
1090@deffn {Scheme Procedure} + z1 @dots{}
1091@deffnx {C Function} scm_sum (z1, z2)
1092Return the sum of all parameter values. Return 0 if called without any
1093parameters.
1094@end deffn
1095
1096@c begin (texi-doc-string "guile" "-")
1097@deffn {Scheme Procedure} - z1 z2 @dots{}
1098@deffnx {C Function} scm_difference (z1, z2)
1099If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
1100the sum of all but the first argument are subtracted from the first
1101argument.
1102@end deffn
1103
1104@c begin (texi-doc-string "guile" "*")
1105@deffn {Scheme Procedure} * z1 @dots{}
1106@deffnx {C Function} scm_product (z1, z2)
1107Return the product of all arguments. If called without arguments, 1 is
1108returned.
1109@end deffn
1110
1111@c begin (texi-doc-string "guile" "/")
1112@deffn {Scheme Procedure} / z1 z2 @dots{}
1113@deffnx {C Function} scm_divide (z1, z2)
1114Divide the first argument by the product of the remaining arguments. If
1115called with one argument @var{z1}, 1/@var{z1} is returned.
1116@end deffn
1117
1118@c begin (texi-doc-string "guile" "abs")
1119@deffn {Scheme Procedure} abs x
1120@deffnx {C Function} scm_abs (x)
1121Return the absolute value of @var{x}.
1122
1123@var{x} must be a number with zero imaginary part. To calculate the
1124magnitude of a complex number, use @code{magnitude} instead.
1125@end deffn
1126
1127@c begin (texi-doc-string "guile" "max")
1128@deffn {Scheme Procedure} max x1 x2 @dots{}
1129@deffnx {C Function} scm_max (x1, x2)
1130Return the maximum of all parameter values.
1131@end deffn
1132
1133@c begin (texi-doc-string "guile" "min")
1134@deffn {Scheme Procedure} min x1 x2 @dots{}
1135@deffnx {C Function} scm_min (x1, x2)
1136Return the minimum of all parameter values.
1137@end deffn
1138
1139@c begin (texi-doc-string "guile" "truncate")
1140@deffn {Scheme Procedure} truncate
1141@deffnx {C Function} scm_truncate_number (x)
1142Round the inexact number @var{x} towards zero.
1143@end deffn
1144
1145@c begin (texi-doc-string "guile" "round")
1146@deffn {Scheme Procedure} round x
1147@deffnx {C Function} scm_round_number (x)
1148Round the inexact number @var{x} to the nearest integer. When exactly
1149halfway between two integers, round to the even one.
1150@end deffn
1151
1152@c begin (texi-doc-string "guile" "floor")
1153@deffn {Scheme Procedure} floor x
1154@deffnx {C Function} scm_floor (x)
1155Round the number @var{x} towards minus infinity.
1156@end deffn
1157
1158@c begin (texi-doc-string "guile" "ceiling")
1159@deffn {Scheme Procedure} ceiling x
1160@deffnx {C Function} scm_ceiling (x)
1161Round the number @var{x} towards infinity.
1162@end deffn
1163
35da08ee
MV
1164@deftypefn {C Function} double scm_c_truncate (double x)
1165@deftypefnx {C Function} double scm_c_round (double x)
1166Like @code{scm_truncate_number} or @code{scm_round_number},
1167respectively, but these functions take and return @code{double}
1168values.
1169@end deftypefn
07d83abe
MV
1170
1171@node Scientific
1172@subsubsection Scientific Functions
1173
1174The following procedures accept any kind of number as arguments,
1175including complex numbers.
1176
1177@rnindex sqrt
1178@c begin (texi-doc-string "guile" "sqrt")
1179@deffn {Scheme Procedure} sqrt z
1180Return the square root of @var{z}.
1181@end deffn
1182
1183@rnindex expt
1184@c begin (texi-doc-string "guile" "expt")
1185@deffn {Scheme Procedure} expt z1 z2
1186Return @var{z1} raised to the power of @var{z2}.
1187@end deffn
1188
1189@rnindex sin
1190@c begin (texi-doc-string "guile" "sin")
1191@deffn {Scheme Procedure} sin z
1192Return the sine of @var{z}.
1193@end deffn
1194
1195@rnindex cos
1196@c begin (texi-doc-string "guile" "cos")
1197@deffn {Scheme Procedure} cos z
1198Return the cosine of @var{z}.
1199@end deffn
1200
1201@rnindex tan
1202@c begin (texi-doc-string "guile" "tan")
1203@deffn {Scheme Procedure} tan z
1204Return the tangent of @var{z}.
1205@end deffn
1206
1207@rnindex asin
1208@c begin (texi-doc-string "guile" "asin")
1209@deffn {Scheme Procedure} asin z
1210Return the arcsine of @var{z}.
1211@end deffn
1212
1213@rnindex acos
1214@c begin (texi-doc-string "guile" "acos")
1215@deffn {Scheme Procedure} acos z
1216Return the arccosine of @var{z}.
1217@end deffn
1218
1219@rnindex atan
1220@c begin (texi-doc-string "guile" "atan")
1221@deffn {Scheme Procedure} atan z
1222@deffnx {Scheme Procedure} atan y x
1223Return the arctangent of @var{z}, or of @math{@var{y}/@var{x}}.
1224@end deffn
1225
1226@rnindex exp
1227@c begin (texi-doc-string "guile" "exp")
1228@deffn {Scheme Procedure} exp z
1229Return e to the power of @var{z}, where e is the base of natural
1230logarithms (2.71828@dots{}).
1231@end deffn
1232
1233@rnindex log
1234@c begin (texi-doc-string "guile" "log")
1235@deffn {Scheme Procedure} log z
1236Return the natural logarithm of @var{z}.
1237@end deffn
1238
1239@c begin (texi-doc-string "guile" "log10")
1240@deffn {Scheme Procedure} log10 z
1241Return the base 10 logarithm of @var{z}.
1242@end deffn
1243
1244@c begin (texi-doc-string "guile" "sinh")
1245@deffn {Scheme Procedure} sinh z
1246Return the hyperbolic sine of @var{z}.
1247@end deffn
1248
1249@c begin (texi-doc-string "guile" "cosh")
1250@deffn {Scheme Procedure} cosh z
1251Return the hyperbolic cosine of @var{z}.
1252@end deffn
1253
1254@c begin (texi-doc-string "guile" "tanh")
1255@deffn {Scheme Procedure} tanh z
1256Return the hyperbolic tangent of @var{z}.
1257@end deffn
1258
1259@c begin (texi-doc-string "guile" "asinh")
1260@deffn {Scheme Procedure} asinh z
1261Return the hyperbolic arcsine of @var{z}.
1262@end deffn
1263
1264@c begin (texi-doc-string "guile" "acosh")
1265@deffn {Scheme Procedure} acosh z
1266Return the hyperbolic arccosine of @var{z}.
1267@end deffn
1268
1269@c begin (texi-doc-string "guile" "atanh")
1270@deffn {Scheme Procedure} atanh z
1271Return the hyperbolic arctangent of @var{z}.
1272@end deffn
1273
1274
1275@node Primitive Numerics
1276@subsubsection Primitive Numeric Functions
1277
1278Many of Guile's numeric procedures which accept any kind of numbers as
1279arguments, including complex numbers, are implemented as Scheme
1280procedures that use the following real number-based primitives. These
1281primitives signal an error if they are called with complex arguments.
1282
1283@c begin (texi-doc-string "guile" "$abs")
1284@deffn {Scheme Procedure} $abs x
1285Return the absolute value of @var{x}.
1286@end deffn
1287
1288@c begin (texi-doc-string "guile" "$sqrt")
1289@deffn {Scheme Procedure} $sqrt x
1290Return the square root of @var{x}.
1291@end deffn
1292
1293@deffn {Scheme Procedure} $expt x y
1294@deffnx {C Function} scm_sys_expt (x, y)
1295Return @var{x} raised to the power of @var{y}. This
1296procedure does not accept complex arguments.
1297@end deffn
1298
1299@c begin (texi-doc-string "guile" "$sin")
1300@deffn {Scheme Procedure} $sin x
1301Return the sine of @var{x}.
1302@end deffn
1303
1304@c begin (texi-doc-string "guile" "$cos")
1305@deffn {Scheme Procedure} $cos x
1306Return the cosine of @var{x}.
1307@end deffn
1308
1309@c begin (texi-doc-string "guile" "$tan")
1310@deffn {Scheme Procedure} $tan x
1311Return the tangent of @var{x}.
1312@end deffn
1313
1314@c begin (texi-doc-string "guile" "$asin")
1315@deffn {Scheme Procedure} $asin x
1316Return the arcsine of @var{x}.
1317@end deffn
1318
1319@c begin (texi-doc-string "guile" "$acos")
1320@deffn {Scheme Procedure} $acos x
1321Return the arccosine of @var{x}.
1322@end deffn
1323
1324@c begin (texi-doc-string "guile" "$atan")
1325@deffn {Scheme Procedure} $atan x
1326Return the arctangent of @var{x} in the range @minus{}@math{PI/2} to
1327@math{PI/2}.
1328@end deffn
1329
1330@deffn {Scheme Procedure} $atan2 x y
1331@deffnx {C Function} scm_sys_atan2 (x, y)
1332Return the arc tangent of the two arguments @var{x} and
1333@var{y}. This is similar to calculating the arc tangent of
1334@var{x} / @var{y}, except that the signs of both arguments
1335are used to determine the quadrant of the result. This
1336procedure does not accept complex arguments.
1337@end deffn
1338
1339@c begin (texi-doc-string "guile" "$exp")
1340@deffn {Scheme Procedure} $exp x
1341Return e to the power of @var{x}, where e is the base of natural
1342logarithms (2.71828@dots{}).
1343@end deffn
1344
1345@c begin (texi-doc-string "guile" "$log")
1346@deffn {Scheme Procedure} $log x
1347Return the natural logarithm of @var{x}.
1348@end deffn
1349
1350@c begin (texi-doc-string "guile" "$sinh")
1351@deffn {Scheme Procedure} $sinh x
1352Return the hyperbolic sine of @var{x}.
1353@end deffn
1354
1355@c begin (texi-doc-string "guile" "$cosh")
1356@deffn {Scheme Procedure} $cosh x
1357Return the hyperbolic cosine of @var{x}.
1358@end deffn
1359
1360@c begin (texi-doc-string "guile" "$tanh")
1361@deffn {Scheme Procedure} $tanh x
1362Return the hyperbolic tangent of @var{x}.
1363@end deffn
1364
1365@c begin (texi-doc-string "guile" "$asinh")
1366@deffn {Scheme Procedure} $asinh x
1367Return the hyperbolic arcsine of @var{x}.
1368@end deffn
1369
1370@c begin (texi-doc-string "guile" "$acosh")
1371@deffn {Scheme Procedure} $acosh x
1372Return the hyperbolic arccosine of @var{x}.
1373@end deffn
1374
1375@c begin (texi-doc-string "guile" "$atanh")
1376@deffn {Scheme Procedure} $atanh x
1377Return the hyperbolic arctangent of @var{x}.
1378@end deffn
1379
1380C functions for the above are provided by the standard mathematics
1381library. Naturally these expect and return @code{double} arguments
1382(@pxref{Mathematics,,, libc, GNU C Library Reference Manual}).
1383
1384@multitable {xx} {Scheme Procedure} {C Function}
1385@item @tab Scheme Procedure @tab C Function
1386
1387@item @tab @code{$abs} @tab @code{fabs}
1388@item @tab @code{$sqrt} @tab @code{sqrt}
1389@item @tab @code{$sin} @tab @code{sin}
1390@item @tab @code{$cos} @tab @code{cos}
1391@item @tab @code{$tan} @tab @code{tan}
1392@item @tab @code{$asin} @tab @code{asin}
1393@item @tab @code{$acos} @tab @code{acos}
1394@item @tab @code{$atan} @tab @code{atan}
1395@item @tab @code{$atan2} @tab @code{atan2}
1396@item @tab @code{$exp} @tab @code{exp}
1397@item @tab @code{$expt} @tab @code{pow}
1398@item @tab @code{$log} @tab @code{log}
1399@item @tab @code{$sinh} @tab @code{sinh}
1400@item @tab @code{$cosh} @tab @code{cosh}
1401@item @tab @code{$tanh} @tab @code{tanh}
1402@item @tab @code{$asinh} @tab @code{asinh}
1403@item @tab @code{$acosh} @tab @code{acosh}
1404@item @tab @code{$atanh} @tab @code{atanh}
1405@end multitable
1406
1407@code{asinh}, @code{acosh} and @code{atanh} are C99 standard but might
1408not be available on older systems. Guile provides the following
1409equivalents (on all systems).
1410
1411@deftypefn {C Function} double scm_asinh (double x)
1412@deftypefnx {C Function} double scm_acosh (double x)
1413@deftypefnx {C Function} double scm_atanh (double x)
1414Return the hyperbolic arcsine, arccosine or arctangent of @var{x}
1415respectively.
1416@end deftypefn
1417
1418
1419@node Bitwise Operations
1420@subsubsection Bitwise Operations
1421
1422For the following bitwise functions, negative numbers are treated as
1423infinite precision twos-complements. For instance @math{-6} is bits
1424@math{@dots{}111010}, with infinitely many ones on the left. It can
1425be seen that adding 6 (binary 110) to such a bit pattern gives all
1426zeros.
1427
1428@deffn {Scheme Procedure} logand n1 n2 @dots{}
1429@deffnx {C Function} scm_logand (n1, n2)
1430Return the bitwise @sc{and} of the integer arguments.
1431
1432@lisp
1433(logand) @result{} -1
1434(logand 7) @result{} 7
1435(logand #b111 #b011 #b001) @result{} 1
1436@end lisp
1437@end deffn
1438
1439@deffn {Scheme Procedure} logior n1 n2 @dots{}
1440@deffnx {C Function} scm_logior (n1, n2)
1441Return the bitwise @sc{or} of the integer arguments.
1442
1443@lisp
1444(logior) @result{} 0
1445(logior 7) @result{} 7
1446(logior #b000 #b001 #b011) @result{} 3
1447@end lisp
1448@end deffn
1449
1450@deffn {Scheme Procedure} logxor n1 n2 @dots{}
1451@deffnx {C Function} scm_loxor (n1, n2)
1452Return the bitwise @sc{xor} of the integer arguments. A bit is
1453set in the result if it is set in an odd number of arguments.
1454
1455@lisp
1456(logxor) @result{} 0
1457(logxor 7) @result{} 7
1458(logxor #b000 #b001 #b011) @result{} 2
1459(logxor #b000 #b001 #b011 #b011) @result{} 1
1460@end lisp
1461@end deffn
1462
1463@deffn {Scheme Procedure} lognot n
1464@deffnx {C Function} scm_lognot (n)
1465Return the integer which is the ones-complement of the integer
1466argument, ie.@: each 0 bit is changed to 1 and each 1 bit to 0.
1467
1468@lisp
1469(number->string (lognot #b10000000) 2)
1470 @result{} "-10000001"
1471(number->string (lognot #b0) 2)
1472 @result{} "-1"
1473@end lisp
1474@end deffn
1475
1476@deffn {Scheme Procedure} logtest j k
1477@deffnx {C Function} scm_logtest (j, k)
1478@lisp
1479(logtest j k) @equiv{} (not (zero? (logand j k)))
1480
1481(logtest #b0100 #b1011) @result{} #f
1482(logtest #b0100 #b0111) @result{} #t
1483@end lisp
1484@end deffn
1485
1486@deffn {Scheme Procedure} logbit? index j
1487@deffnx {C Function} scm_logbit_p (index, j)
1488@lisp
1489(logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
1490
1491(logbit? 0 #b1101) @result{} #t
1492(logbit? 1 #b1101) @result{} #f
1493(logbit? 2 #b1101) @result{} #t
1494(logbit? 3 #b1101) @result{} #t
1495(logbit? 4 #b1101) @result{} #f
1496@end lisp
1497@end deffn
1498
1499@deffn {Scheme Procedure} ash n cnt
1500@deffnx {C Function} scm_ash (n, cnt)
1501Return @var{n} shifted left by @var{cnt} bits, or shifted right if
1502@var{cnt} is negative. This is an ``arithmetic'' shift.
1503
1504This is effectively a multiplication by @m{2^{cnt}, 2^@var{cnt}}, and
1505when @var{cnt} is negative it's a division, rounded towards negative
1506infinity. (Note that this is not the same rounding as @code{quotient}
1507does.)
1508
1509With @var{n} viewed as an infinite precision twos complement,
1510@code{ash} means a left shift introducing zero bits, or a right shift
1511dropping bits.
1512
1513@lisp
1514(number->string (ash #b1 3) 2) @result{} "1000"
1515(number->string (ash #b1010 -1) 2) @result{} "101"
1516
1517;; -23 is bits ...11101001, -6 is bits ...111010
1518(ash -23 -2) @result{} -6
1519@end lisp
1520@end deffn
1521
1522@deffn {Scheme Procedure} logcount n
1523@deffnx {C Function} scm_logcount (n)
1524Return the number of bits in integer @var{n}. If integer is
1525positive, the 1-bits in its binary representation are counted.
1526If negative, the 0-bits in its two's-complement binary
1527representation are counted. If 0, 0 is returned.
1528
1529@lisp
1530(logcount #b10101010)
1531 @result{} 4
1532(logcount 0)
1533 @result{} 0
1534(logcount -2)
1535 @result{} 1
1536@end lisp
1537@end deffn
1538
1539@deffn {Scheme Procedure} integer-length n
1540@deffnx {C Function} scm_integer_length (n)
1541Return the number of bits necessary to represent @var{n}.
1542
1543For positive @var{n} this is how many bits to the most significant one
1544bit. For negative @var{n} it's how many bits to the most significant
1545zero bit in twos complement form.
1546
1547@lisp
1548(integer-length #b10101010) @result{} 8
1549(integer-length #b1111) @result{} 4
1550(integer-length 0) @result{} 0
1551(integer-length -1) @result{} 0
1552(integer-length -256) @result{} 8
1553(integer-length -257) @result{} 9
1554@end lisp
1555@end deffn
1556
1557@deffn {Scheme Procedure} integer-expt n k
1558@deffnx {C Function} scm_integer_expt (n, k)
1559Return @var{n} raised to the non-negative integer exponent
1560@var{k}.
1561
1562@lisp
1563(integer-expt 2 5)
1564 @result{} 32
1565(integer-expt -3 3)
1566 @result{} -27
1567@end lisp
1568@end deffn
1569
1570@deffn {Scheme Procedure} bit-extract n start end
1571@deffnx {C Function} scm_bit_extract (n, start, end)
1572Return the integer composed of the @var{start} (inclusive)
1573through @var{end} (exclusive) bits of @var{n}. The
1574@var{start}th bit becomes the 0-th bit in the result.
1575
1576@lisp
1577(number->string (bit-extract #b1101101010 0 4) 2)
1578 @result{} "1010"
1579(number->string (bit-extract #b1101101010 4 9) 2)
1580 @result{} "10110"
1581@end lisp
1582@end deffn
1583
1584
1585@node Random
1586@subsubsection Random Number Generation
1587
1588Pseudo-random numbers are generated from a random state object, which
1589can be created with @code{seed->random-state}. The @var{state}
1590parameter to the various functions below is optional, it defaults to
1591the state object in the @code{*random-state*} variable.
1592
1593@deffn {Scheme Procedure} copy-random-state [state]
1594@deffnx {C Function} scm_copy_random_state (state)
1595Return a copy of the random state @var{state}.
1596@end deffn
1597
1598@deffn {Scheme Procedure} random n [state]
1599@deffnx {C Function} scm_random (n, state)
1600Return a number in [0, @var{n}).
1601
1602Accepts a positive integer or real n and returns a
1603number of the same type between zero (inclusive) and
1604@var{n} (exclusive). The values returned have a uniform
1605distribution.
1606@end deffn
1607
1608@deffn {Scheme Procedure} random:exp [state]
1609@deffnx {C Function} scm_random_exp (state)
1610Return an inexact real in an exponential distribution with mean
16111. For an exponential distribution with mean @var{u} use @code{(*
1612@var{u} (random:exp))}.
1613@end deffn
1614
1615@deffn {Scheme Procedure} random:hollow-sphere! vect [state]
1616@deffnx {C Function} scm_random_hollow_sphere_x (vect, state)
1617Fills @var{vect} with inexact real random numbers the sum of whose
1618squares is equal to 1.0. Thinking of @var{vect} as coordinates in
1619space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1620the coordinates are uniformly distributed over the surface of the unit
1621n-sphere.
1622@end deffn
1623
1624@deffn {Scheme Procedure} random:normal [state]
1625@deffnx {C Function} scm_random_normal (state)
1626Return an inexact real in a normal distribution. The distribution
1627used has mean 0 and standard deviation 1. For a normal distribution
1628with mean @var{m} and standard deviation @var{d} use @code{(+ @var{m}
1629(* @var{d} (random:normal)))}.
1630@end deffn
1631
1632@deffn {Scheme Procedure} random:normal-vector! vect [state]
1633@deffnx {C Function} scm_random_normal_vector_x (vect, state)
1634Fills @var{vect} with inexact real random numbers that are
1635independent and standard normally distributed
1636(i.e., with mean 0 and variance 1).
1637@end deffn
1638
1639@deffn {Scheme Procedure} random:solid-sphere! vect [state]
1640@deffnx {C Function} scm_random_solid_sphere_x (vect, state)
1641Fills @var{vect} with inexact real random numbers the sum of whose
1642squares is less than 1.0. Thinking of @var{vect} as coordinates in
1643space of dimension @var{n} @math{=} @code{(vector-length @var{vect})},
1644the coordinates are uniformly distributed within the unit
1645@var{n}-sphere. The sum of the squares of the numbers is returned.
1646@c FIXME: What does this mean, particularly the n-sphere part?
1647@end deffn
1648
1649@deffn {Scheme Procedure} random:uniform [state]
1650@deffnx {C Function} scm_random_uniform (state)
1651Return a uniformly distributed inexact real random number in
1652[0,1).
1653@end deffn
1654
1655@deffn {Scheme Procedure} seed->random-state seed
1656@deffnx {C Function} scm_seed_to_random_state (seed)
1657Return a new random state using @var{seed}.
1658@end deffn
1659
1660@defvar *random-state*
1661The global random state used by the above functions when the
1662@var{state} parameter is not given.
1663@end defvar
1664
1665
1666@node Characters
1667@subsection Characters
1668@tpindex Characters
1669
1670@noindent
1671[@strong{FIXME}: how do you specify regular (non-control) characters?]
1672
1673Most of the ``control characters'' (those below codepoint 32) in the
1674@acronym{ASCII} character set, as well as the space, may be referred
1675to by name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and
1676so on. The following table describes the @acronym{ASCII} names for
1677each character.
1678
1679@multitable @columnfractions .25 .25 .25 .25
1680@item 0 = @code{#\nul}
1681 @tab 1 = @code{#\soh}
1682 @tab 2 = @code{#\stx}
1683 @tab 3 = @code{#\etx}
1684@item 4 = @code{#\eot}
1685 @tab 5 = @code{#\enq}
1686 @tab 6 = @code{#\ack}
1687 @tab 7 = @code{#\bel}
1688@item 8 = @code{#\bs}
1689 @tab 9 = @code{#\ht}
1690 @tab 10 = @code{#\nl}
1691 @tab 11 = @code{#\vt}
1692@item 12 = @code{#\np}
1693 @tab 13 = @code{#\cr}
1694 @tab 14 = @code{#\so}
1695 @tab 15 = @code{#\si}
1696@item 16 = @code{#\dle}
1697 @tab 17 = @code{#\dc1}
1698 @tab 18 = @code{#\dc2}
1699 @tab 19 = @code{#\dc3}
1700@item 20 = @code{#\dc4}
1701 @tab 21 = @code{#\nak}
1702 @tab 22 = @code{#\syn}
1703 @tab 23 = @code{#\etb}
1704@item 24 = @code{#\can}
1705 @tab 25 = @code{#\em}
1706 @tab 26 = @code{#\sub}
1707 @tab 27 = @code{#\esc}
1708@item 28 = @code{#\fs}
1709 @tab 29 = @code{#\gs}
1710 @tab 30 = @code{#\rs}
1711 @tab 31 = @code{#\us}
1712@item 32 = @code{#\sp}
1713@end multitable
1714
1715The ``delete'' character (octal 177) may be referred to with the name
1716@code{#\del}.
1717
1718Several characters have more than one name:
1719
1720@multitable {@code{#\backspace}} {Original}
1721@item Alias @tab Original
1722@item @code{#\space} @tab @code{#\sp}
1723@item @code{#\newline} @tab @code{#\nl}
1724@item @code{#\tab} @tab @code{#\ht}
1725@item @code{#\backspace} @tab @code{#\bs}
1726@item @code{#\return} @tab @code{#\cr}
1727@item @code{#\page} @tab @code{#\np}
1728@item @code{#\null} @tab @code{#\nul}
1729@end multitable
1730
1731@rnindex char?
1732@deffn {Scheme Procedure} char? x
1733@deffnx {C Function} scm_char_p (x)
1734Return @code{#t} iff @var{x} is a character, else @code{#f}.
1735@end deffn
1736
1737@rnindex char=?
1738@deffn {Scheme Procedure} char=? x y
1739Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
1740@end deffn
1741
1742@rnindex char<?
1743@deffn {Scheme Procedure} char<? x y
1744Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence,
1745else @code{#f}.
1746@end deffn
1747
1748@rnindex char<=?
1749@deffn {Scheme Procedure} char<=? x y
1750Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1751@acronym{ASCII} sequence, else @code{#f}.
1752@end deffn
1753
1754@rnindex char>?
1755@deffn {Scheme Procedure} char>? x y
1756Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1757sequence, else @code{#f}.
1758@end deffn
1759
1760@rnindex char>=?
1761@deffn {Scheme Procedure} char>=? x y
1762Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1763@acronym{ASCII} sequence, else @code{#f}.
1764@end deffn
1765
1766@rnindex char-ci=?
1767@deffn {Scheme Procedure} char-ci=? x y
1768Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
1769case, else @code{#f}.
1770@end deffn
1771
1772@rnindex char-ci<?
1773@deffn {Scheme Procedure} char-ci<? x y
1774Return @code{#t} iff @var{x} is less than @var{y} in the @acronym{ASCII} sequence
1775ignoring case, else @code{#f}.
1776@end deffn
1777
1778@rnindex char-ci<=?
1779@deffn {Scheme Procedure} char-ci<=? x y
1780Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
1781@acronym{ASCII} sequence ignoring case, else @code{#f}.
1782@end deffn
1783
1784@rnindex char-ci>?
1785@deffn {Scheme Procedure} char-ci>? x y
1786Return @code{#t} iff @var{x} is greater than @var{y} in the @acronym{ASCII}
1787sequence ignoring case, else @code{#f}.
1788@end deffn
1789
1790@rnindex char-ci>=?
1791@deffn {Scheme Procedure} char-ci>=? x y
1792Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
1793@acronym{ASCII} sequence ignoring case, else @code{#f}.
1794@end deffn
1795
1796@rnindex char-alphabetic?
1797@deffn {Scheme Procedure} char-alphabetic? chr
1798@deffnx {C Function} scm_char_alphabetic_p (chr)
1799Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
1800Alphabetic means the same thing as the @code{isalpha} C library function.
1801@end deffn
1802
1803@rnindex char-numeric?
1804@deffn {Scheme Procedure} char-numeric? chr
1805@deffnx {C Function} scm_char_numeric_p (chr)
1806Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
1807Numeric means the same thing as the @code{isdigit} C library function.
1808@end deffn
1809
1810@rnindex char-whitespace?
1811@deffn {Scheme Procedure} char-whitespace? chr
1812@deffnx {C Function} scm_char_whitespace_p (chr)
1813Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
1814Whitespace means the same thing as the @code{isspace} C library function.
1815@end deffn
1816
1817@rnindex char-upper-case?
1818@deffn {Scheme Procedure} char-upper-case? chr
1819@deffnx {C Function} scm_char_upper_case_p (chr)
1820Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
1821Uppercase means the same thing as the @code{isupper} C library function.
1822@end deffn
1823
1824@rnindex char-lower-case?
1825@deffn {Scheme Procedure} char-lower-case? chr
1826@deffnx {C Function} scm_char_lower_case_p (chr)
1827Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
1828Lowercase means the same thing as the @code{islower} C library function.
1829@end deffn
1830
1831@deffn {Scheme Procedure} char-is-both? chr
1832@deffnx {C Function} scm_char_is_both_p (chr)
1833Return @code{#t} iff @var{chr} is either uppercase or lowercase, else
1834@code{#f}. Uppercase and lowercase are as defined by the
1835@code{isupper} and @code{islower} C library functions.
1836@end deffn
1837
1838@rnindex char->integer
1839@deffn {Scheme Procedure} char->integer chr
1840@deffnx {C Function} scm_char_to_integer (chr)
1841Return the number corresponding to ordinal position of @var{chr} in the
1842@acronym{ASCII} sequence.
1843@end deffn
1844
1845@rnindex integer->char
1846@deffn {Scheme Procedure} integer->char n
1847@deffnx {C Function} scm_integer_to_char (n)
1848Return the character at position @var{n} in the @acronym{ASCII} sequence.
1849@end deffn
1850
1851@rnindex char-upcase
1852@deffn {Scheme Procedure} char-upcase chr
1853@deffnx {C Function} scm_char_upcase (chr)
1854Return the uppercase character version of @var{chr}.
1855@end deffn
1856
1857@rnindex char-downcase
1858@deffn {Scheme Procedure} char-downcase chr
1859@deffnx {C Function} scm_char_downcase (chr)
1860Return the lowercase character version of @var{chr}.
1861@end deffn
1862
1863@xref{Classification of Characters,,,libc,GNU C Library Reference
1864Manual}, for information about the @code{is*} Standard C functions
1865mentioned above.
1866
1867
1868@node Strings
1869@subsection Strings
1870@tpindex Strings
1871
1872Strings are fixed-length sequences of characters. They can be created
1873by calling constructor procedures, but they can also literally get
1874entered at the @acronym{REPL} or in Scheme source files.
1875
1876@c Guile provides a rich set of string processing procedures, because text
1877@c handling is very important when Guile is used as a scripting language.
1878
1879Strings always carry the information about how many characters they are
1880composed of with them, so there is no special end-of-string character,
1881like in C. That means that Scheme strings can contain any character,
c48c62d0
MV
1882even the @samp{#\nul} character @samp{\0}.
1883
1884To use strings efficiently, you need to know a bit about how Guile
1885implements them. In Guile, a string consists of two parts, a head and
1886the actual memory where the characters are stored. When a string (or
1887a substring of it) is copied, only a new head gets created, the memory
1888is usually not copied. The two heads start out pointing to the same
1889memory.
1890
1891When one of these two strings is modified, as with @code{string-set!},
1892their common memory does get copied so that each string has its own
1893memory and modifying one does not accidently modify the other as well.
1894Thus, Guile's strings are `copy on write'; the actual copying of their
1895memory is delayed until one string is written to.
1896
1897This implementation makes functions like @code{substring} very
1898efficient in the common case that no modifications are done to the
1899involved strings.
1900
1901If you do know that your strings are getting modified right away, you
1902can use @code{substring/copy} instead of @code{substring}. This
1903function performs the copy immediately at the time of creation. This
1904is more efficient, especially in a multi-threaded program. Also,
1905@code{substring/copy} can avoid the problem that a short substring
1906holds on to the memory of a very large original string that could
1907otherwise be recycled.
1908
1909If you want to avoid the copy altogether, so that modifications of one
1910string show up in the other, you can use @code{substring/shared}. The
1911strings created by this procedure are called @dfn{mutation sharing
1912substrings} since the substring and the original string share
1913modifications to each other.
07d83abe
MV
1914
1915@menu
1916* String Syntax:: Read syntax for strings.
1917* String Predicates:: Testing strings for certain properties.
1918* String Constructors:: Creating new string objects.
1919* List/String Conversion:: Converting from/to lists of characters.
1920* String Selection:: Select portions from strings.
1921* String Modification:: Modify parts or whole strings.
1922* String Comparison:: Lexicographic ordering predicates.
1923* String Searching:: Searching in strings.
1924* Alphabetic Case Mapping:: Convert the alphabetic case of strings.
1925* Appending Strings:: Appending strings to form a new string.
91210d62 1926* Conversion to/from C::
07d83abe
MV
1927@end menu
1928
1929@node String Syntax
1930@subsubsection String Read Syntax
1931
1932@c In the following @code is used to get a good font in TeX etc, but
1933@c is omitted for Info format, so as not to risk any confusion over
1934@c whether surrounding ` ' quotes are part of the escape or are
1935@c special in a string (they're not).
1936
1937The read syntax for strings is an arbitrarily long sequence of
c48c62d0 1938characters enclosed in double quotes (@nicode{"}).
07d83abe
MV
1939
1940Backslash is an escape character and can be used to insert the
1941following special characters. @nicode{\"} and @nicode{\\} are R5RS
1942standard, the rest are Guile extensions, notice they follow C string
1943syntax.
1944
1945@table @asis
1946@item @nicode{\\}
1947Backslash character.
1948
1949@item @nicode{\"}
1950Double quote character (an unescaped @nicode{"} is otherwise the end
1951of the string).
1952
1953@item @nicode{\0}
1954NUL character (ASCII 0).
1955
1956@item @nicode{\a}
1957Bell character (ASCII 7).
1958
1959@item @nicode{\f}
1960Formfeed character (ASCII 12).
1961
1962@item @nicode{\n}
1963Newline character (ASCII 10).
1964
1965@item @nicode{\r}
1966Carriage return character (ASCII 13).
1967
1968@item @nicode{\t}
1969Tab character (ASCII 9).
1970
1971@item @nicode{\v}
1972Vertical tab character (ASCII 11).
1973
1974@item @nicode{\xHH}
1975Character code given by two hexadecimal digits. For example
1976@nicode{\x7f} for an ASCII DEL (127).
1977@end table
1978
1979@noindent
1980The following are examples of string literals:
1981
1982@lisp
1983"foo"
1984"bar plonk"
1985"Hello World"
1986"\"Hi\", he said."
1987@end lisp
1988
1989
1990@node String Predicates
1991@subsubsection String Predicates
1992
1993The following procedures can be used to check whether a given string
1994fulfills some specified property.
1995
1996@rnindex string?
1997@deffn {Scheme Procedure} string? obj
1998@deffnx {C Function} scm_string_p (obj)
1999Return @code{#t} if @var{obj} is a string, else @code{#f}.
2000@end deffn
2001
91210d62
MV
2002@deftypefn {C Function} int scm_is_string (SCM obj)
2003Returns @code{1} if @var{obj} is a string, @code{0} otherwise.
2004@end deftypefn
2005
07d83abe
MV
2006@deffn {Scheme Procedure} string-null? str
2007@deffnx {C Function} scm_string_null_p (str)
2008Return @code{#t} if @var{str}'s length is zero, and
2009@code{#f} otherwise.
2010@lisp
2011(string-null? "") @result{} #t
2012y @result{} "foo"
2013(string-null? y) @result{} #f
2014@end lisp
2015@end deffn
2016
2017@node String Constructors
2018@subsubsection String Constructors
2019
2020The string constructor procedures create new string objects, possibly
c48c62d0
MV
2021initializing them with some specified character data. See also
2022@xref{String Selection}, for ways to create strings from existing
2023strings.
07d83abe
MV
2024
2025@c FIXME::martin: list->string belongs into `List/String Conversion'
2026
2027@rnindex string
2028@rnindex list->string
2029@deffn {Scheme Procedure} string . chrs
2030@deffnx {Scheme Procedure} list->string chrs
2031@deffnx {C Function} scm_string (chrs)
2032Return a newly allocated string composed of the arguments,
2033@var{chrs}.
2034@end deffn
2035
2036@rnindex make-string
2037@deffn {Scheme Procedure} make-string k [chr]
2038@deffnx {C Function} scm_make_string (k, chr)
2039Return a newly allocated string of
2040length @var{k}. If @var{chr} is given, then all elements of
2041the string are initialized to @var{chr}, otherwise the contents
2042of the @var{string} are unspecified.
2043@end deffn
2044
c48c62d0
MV
2045@deftypefn {C Function} SCM scm_c_make_string (size_t len, SCM chr)
2046Like @code{scm_make_string}, but expects the length as a
2047@code{size_t}.
2048@end deftypefn
2049
07d83abe
MV
2050@node List/String Conversion
2051@subsubsection List/String conversion
2052
2053When processing strings, it is often convenient to first convert them
2054into a list representation by using the procedure @code{string->list},
2055work with the resulting list, and then convert it back into a string.
2056These procedures are useful for similar tasks.
2057
2058@rnindex string->list
2059@deffn {Scheme Procedure} string->list str
2060@deffnx {C Function} scm_string_to_list (str)
2061Return a newly allocated list of the characters that make up
2062the given string @var{str}. @code{string->list} and
2063@code{list->string} are inverses as far as @samp{equal?} is
2064concerned.
2065@end deffn
2066
2067@deffn {Scheme Procedure} string-split str chr
2068@deffnx {C Function} scm_string_split (str, chr)
2069Split the string @var{str} into the a list of the substrings delimited
2070by appearances of the character @var{chr}. Note that an empty substring
2071between separator characters will result in an empty string in the
2072result list.
2073
2074@lisp
2075(string-split "root:x:0:0:root:/root:/bin/bash" #\:)
2076@result{}
2077("root" "x" "0" "0" "root" "/root" "/bin/bash")
2078
2079(string-split "::" #\:)
2080@result{}
2081("" "" "")
2082
2083(string-split "" #\:)
2084@result{}
2085("")
2086@end lisp
2087@end deffn
2088
2089
2090@node String Selection
2091@subsubsection String Selection
2092
2093Portions of strings can be extracted by these procedures.
2094@code{string-ref} delivers individual characters whereas
2095@code{substring} can be used to extract substrings from longer strings.
2096
2097@rnindex string-length
2098@deffn {Scheme Procedure} string-length string
2099@deffnx {C Function} scm_string_length (string)
2100Return the number of characters in @var{string}.
2101@end deffn
2102
c48c62d0
MV
2103@deftypefn {C Function} size_t scm_c_string_length (SCM str)
2104Return the number of characters in @var{str} as a @code{size_t}.
2105@end deftypefn
2106
07d83abe
MV
2107@rnindex string-ref
2108@deffn {Scheme Procedure} string-ref str k
2109@deffnx {C Function} scm_string_ref (str, k)
2110Return character @var{k} of @var{str} using zero-origin
2111indexing. @var{k} must be a valid index of @var{str}.
2112@end deffn
2113
c48c62d0
MV
2114@deftypefn {C Function} SCM scm_c_string_ref (SCM str, size_t k)
2115Return character @var{k} of @var{str} using zero-origin
2116indexing. @var{k} must be a valid index of @var{str}.
2117@end deftypefn
2118
07d83abe
MV
2119@rnindex string-copy
2120@deffn {Scheme Procedure} string-copy str
2121@deffnx {C Function} scm_string_copy (str)
c48c62d0
MV
2122Return a copy of the given @var{string}.
2123
2124The returned string shares storage with @var{str} initially, but it is
2125copied as soon as one of the two strings is modified.
07d83abe
MV
2126@end deffn
2127
2128@rnindex substring
2129@deffn {Scheme Procedure} substring str start [end]
2130@deffnx {C Function} scm_substring (str, start, end)
c48c62d0 2131Return a new string formed from the characters
07d83abe
MV
2132of @var{str} beginning with index @var{start} (inclusive) and
2133ending with index @var{end} (exclusive).
2134@var{str} must be a string, @var{start} and @var{end} must be
2135exact integers satisfying:
2136
21370 <= @var{start} <= @var{end} <= @code{(string-length @var{str})}.
c48c62d0
MV
2138
2139The returned string shares storage with @var{str} initially, but it is
2140copied as soon as one of the two strings is modified.
2141@end deffn
2142
2143@deffn {Scheme Procedure} substring/shared str start [end]
2144@deffnx {C Function} scm_substring_shared (str, start, end)
2145Like @code{substring}, but the strings continue to share their storage
2146even if they are modified. Thus, modifications to @var{str} show up
2147in the new string, and vice versa.
2148@end deffn
2149
2150@deffn {Scheme Procedure} substring/copy str start [end]
2151@deffnx {C Function} scm_substring_copy (str, start, end)
2152Like @code{substring}, but the storage for the new string is copied
2153immediately.
07d83abe
MV
2154@end deffn
2155
c48c62d0
MV
2156@deftypefn {C Function} SCM scm_c_substring (SCM str, size_t start, size_t end)
2157@deftypefnx {C Function} SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
2158@deftypefnx {C Function} SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
2159Like @code{scm_substring}, etc. but the bounds are given as a @code{size_t}.
2160@end deftypefn
2161
07d83abe
MV
2162@node String Modification
2163@subsubsection String Modification
2164
2165These procedures are for modifying strings in-place. This means that the
2166result of the operation is not a new string; instead, the original string's
2167memory representation is modified.
2168
2169@rnindex string-set!
2170@deffn {Scheme Procedure} string-set! str k chr
2171@deffnx {C Function} scm_string_set_x (str, k, chr)
2172Store @var{chr} in element @var{k} of @var{str} and return
2173an unspecified value. @var{k} must be a valid index of
2174@var{str}.
2175@end deffn
2176
c48c62d0
MV
2177@deftypefn {C Function} void scm_c_string_set_x (SCM str, size_t k, SCM chr)
2178Like @code{scm_string_set_x}, but the index is given as a @code{size_t}.
2179@end deftypefn
2180
07d83abe
MV
2181@rnindex string-fill!
2182@deffn {Scheme Procedure} string-fill! str chr
2183@deffnx {C Function} scm_string_fill_x (str, chr)
2184Store @var{char} in every element of the given @var{string} and
2185return an unspecified value.
2186@end deffn
2187
2188@deffn {Scheme Procedure} substring-fill! str start end fill
2189@deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
2190Change every character in @var{str} between @var{start} and
2191@var{end} to @var{fill}.
2192
2193@lisp
2194(define y "abcdefg")
2195(substring-fill! y 1 3 #\r)
2196y
2197@result{} "arrdefg"
2198@end lisp
2199@end deffn
2200
2201@deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
2202@deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
2203Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
2204into @var{str2} beginning at position @var{start2}.
2205@var{str1} and @var{str2} can be the same string.
2206@end deffn
2207
2208
2209@node String Comparison
2210@subsubsection String Comparison
2211
2212The procedures in this section are similar to the character ordering
2213predicates (@pxref{Characters}), but are defined on character sequences.
2214They all return @code{#t} on success and @code{#f} on failure. The
2215predicates ending in @code{-ci} ignore the character case when comparing
2216strings.
2217
2218
2219@rnindex string=?
2220@deffn {Scheme Procedure} string=? s1 s2
2221Lexicographic equality predicate; return @code{#t} if the two
2222strings are the same length and contain the same characters in
2223the same positions, otherwise return @code{#f}.
2224
2225The procedure @code{string-ci=?} treats upper and lower case
2226letters as though they were the same character, but
2227@code{string=?} treats upper and lower case as distinct
2228characters.
2229@end deffn
2230
2231@rnindex string<?
2232@deffn {Scheme Procedure} string<? s1 s2
2233Lexicographic ordering predicate; return @code{#t} if @var{s1}
2234is lexicographically less than @var{s2}.
2235@end deffn
2236
2237@rnindex string<=?
2238@deffn {Scheme Procedure} string<=? s1 s2
2239Lexicographic ordering predicate; return @code{#t} if @var{s1}
2240is lexicographically less than or equal to @var{s2}.
2241@end deffn
2242
2243@rnindex string>?
2244@deffn {Scheme Procedure} string>? s1 s2
2245Lexicographic ordering predicate; return @code{#t} if @var{s1}
2246is lexicographically greater than @var{s2}.
2247@end deffn
2248
2249@rnindex string>=?
2250@deffn {Scheme Procedure} string>=? s1 s2
2251Lexicographic ordering predicate; return @code{#t} if @var{s1}
2252is lexicographically greater than or equal to @var{s2}.
2253@end deffn
2254
2255@rnindex string-ci=?
2256@deffn {Scheme Procedure} string-ci=? s1 s2
2257Case-insensitive string equality predicate; return @code{#t} if
2258the two strings are the same length and their component
2259characters match (ignoring case) at each position; otherwise
2260return @code{#f}.
2261@end deffn
2262
2263@rnindex string-ci<
2264@deffn {Scheme Procedure} string-ci<? s1 s2
2265Case insensitive lexicographic ordering predicate; return
2266@code{#t} if @var{s1} is lexicographically less than @var{s2}
2267regardless of case.
2268@end deffn
2269
2270@rnindex string<=?
2271@deffn {Scheme Procedure} string-ci<=? s1 s2
2272Case insensitive lexicographic ordering predicate; return
2273@code{#t} if @var{s1} is lexicographically less than or equal
2274to @var{s2} regardless of case.
2275@end deffn
2276
2277@rnindex string-ci>?
2278@deffn {Scheme Procedure} string-ci>? s1 s2
2279Case insensitive lexicographic ordering predicate; return
2280@code{#t} if @var{s1} is lexicographically greater than
2281@var{s2} regardless of case.
2282@end deffn
2283
2284@rnindex string-ci>=?
2285@deffn {Scheme Procedure} string-ci>=? s1 s2
2286Case insensitive lexicographic ordering predicate; return
2287@code{#t} if @var{s1} is lexicographically greater than or
2288equal to @var{s2} regardless of case.
2289@end deffn
2290
2291
2292@node String Searching
2293@subsubsection String Searching
2294
2295When searching for the index of a character in a string, these
2296procedures can be used.
2297
2298@deffn {Scheme Procedure} string-index str chr [frm [to]]
2299@deffnx {C Function} scm_string_index (str, chr, frm, to)
2300Return the index of the first occurrence of @var{chr} in
2301@var{str}. The optional integer arguments @var{frm} and
2302@var{to} limit the search to a portion of the string. This
2303procedure essentially implements the @code{index} or
2304@code{strchr} functions from the C library.
2305
2306@lisp
2307(string-index "weiner" #\e)
2308@result{} 1
2309
2310(string-index "weiner" #\e 2)
2311@result{} 4
2312
2313(string-index "weiner" #\e 2 4)
2314@result{} #f
2315@end lisp
2316@end deffn
2317
2318@deffn {Scheme Procedure} string-rindex str chr [frm [to]]
2319@deffnx {C Function} scm_string_rindex (str, chr, frm, to)
2320Like @code{string-index}, but search from the right of the
2321string rather than from the left. This procedure essentially
2322implements the @code{rindex} or @code{strrchr} functions from
2323the C library.
2324
2325@lisp
2326(string-rindex "weiner" #\e)
2327@result{} 4
2328
2329(string-rindex "weiner" #\e 2 4)
2330@result{} #f
2331
2332(string-rindex "weiner" #\e 2 5)
2333@result{} 4
2334@end lisp
2335@end deffn
2336
2337@node Alphabetic Case Mapping
2338@subsubsection Alphabetic Case Mapping
2339
2340These are procedures for mapping strings to their upper- or lower-case
2341equivalents, respectively, or for capitalizing strings.
2342
2343@deffn {Scheme Procedure} string-upcase str
2344@deffnx {C Function} scm_string_upcase (str)
2345Return a freshly allocated string containing the characters of
2346@var{str} in upper case.
2347@end deffn
2348
2349@deffn {Scheme Procedure} string-upcase! str
2350@deffnx {C Function} scm_string_upcase_x (str)
2351Destructively upcase every character in @var{str} and return
2352@var{str}.
2353@lisp
2354y @result{} "arrdefg"
2355(string-upcase! y) @result{} "ARRDEFG"
2356y @result{} "ARRDEFG"
2357@end lisp
2358@end deffn
2359
2360@deffn {Scheme Procedure} string-downcase str
2361@deffnx {C Function} scm_string_downcase (str)
2362Return a freshly allocation string containing the characters in
2363@var{str} in lower case.
2364@end deffn
2365
2366@deffn {Scheme Procedure} string-downcase! str
2367@deffnx {C Function} scm_string_downcase_x (str)
2368Destructively downcase every character in @var{str} and return
2369@var{str}.
2370@lisp
2371y @result{} "ARRDEFG"
2372(string-downcase! y) @result{} "arrdefg"
2373y @result{} "arrdefg"
2374@end lisp
2375@end deffn
2376
2377@deffn {Scheme Procedure} string-capitalize str
2378@deffnx {C Function} scm_string_capitalize (str)
2379Return a freshly allocated string with the characters in
2380@var{str}, where the first character of every word is
2381capitalized.
2382@end deffn
2383
2384@deffn {Scheme Procedure} string-capitalize! str
2385@deffnx {C Function} scm_string_capitalize_x (str)
2386Upcase the first character of every word in @var{str}
2387destructively and return @var{str}.
2388
2389@lisp
2390y @result{} "hello world"
2391(string-capitalize! y) @result{} "Hello World"
2392y @result{} "Hello World"
2393@end lisp
2394@end deffn
2395
2396
2397@node Appending Strings
2398@subsubsection Appending Strings
2399
2400The procedure @code{string-append} appends several strings together to
2401form a longer result string.
2402
2403@rnindex string-append
2404@deffn {Scheme Procedure} string-append . args
2405@deffnx {C Function} scm_string_append (args)
2406Return a newly allocated string whose characters form the
2407concatenation of the given strings, @var{args}.
2408
2409@example
2410(let ((h "hello "))
2411 (string-append h "world"))
2412@result{} "hello world"
2413@end example
2414@end deffn
2415
91210d62
MV
2416@node Conversion to/from C
2417@subsubsection Conversion to/from C
2418
2419When creating a Scheme string from a C string or when converting a
2420Scheme string to a C string, the concept of character encoding becomes
2421important.
2422
2423In C, a string is just a sequence of bytes, and the character encoding
2424describes the relation between these bytes and the actual characters
c88453e8
MV
2425that make up the string. For Scheme strings, character encoding is
2426not an issue (most of the time), since in Scheme you never get to see
2427the bytes, only the characters.
91210d62
MV
2428
2429Well, ideally, anyway. Right now, Guile simply equates Scheme
2430characters and bytes, ignoring the possibility of multi-byte encodings
2431completely. This will change in the future, where Guile will use
c48c62d0
MV
2432Unicode codepoints as its characters and UTF-8 or some other encoding
2433as its internal encoding. When you exclusively use the functions
2434listed in this section, you are `future-proof'.
91210d62 2435
c88453e8
MV
2436Converting a Scheme string to a C string will often allocate fresh
2437memory to hold the result. You must take care that this memory is
2438properly freed eventually. In many cases, this can be achieved by
2439using @code{scm_frame_free} inside an appropriate frame,
2440@xref{Frames}.
91210d62
MV
2441
2442@deftypefn {C Function} SCM scm_from_locale_string (const char *str)
2443@deftypefnx {C Function} SCM scm_from_locale_stringn (const char *str, size_t len)
2444Creates a new Scheme string that has the same contents as @var{str}
2445when interpreted in the current locale character encoding.
2446
2447For @code{scm_from_locale_string}, @var{str} must be null-terminated.
2448
2449For @code{scm_from_locale_stringn}, @var{len} specifies the length of
2450@var{str} in bytes, and @var{str} does not need to be null-terminated.
2451If @var{len} is @code{(size_t)-1}, then @var{str} does need to be
2452null-terminated and the real length will be found with @code{strlen}.
2453@end deftypefn
2454
2455@deftypefn {C Function} SCM scm_take_locale_string (char *str)
2456@deftypefnx {C Function} SCM scm_take_locale_stringn (char *str, size_t len)
2457Like @code{scm_from_locale_string} and @code{scm_from_locale_stringn},
2458respectively, but also frees @var{str} with @code{free} eventually.
2459Thus, you can use this function when you would free @var{str} anyway
2460immediately after creating the Scheme string. In certain cases, Guile
2461can then use @var{str} directly as its internal representation.
2462@end deftypefn
2463
2464@deftypefn {C Function} char *scm_to_locale_string (SCM str)
2465@deftypefnx {C Function} char *scm_to_locale_stringn (SCM str, size_t *lenp)
2466Returns a C string in the current locale encoding with the same
2467contents as @var{str}. The C string must be freed with @code{free}
2468eventually, maybe by using @code{scm_frame_free}, @xref{Frames}.
2469
2470For @code{scm_to_locale_string}, the returned string is
2471null-terminated and an error is signalled when @var{str} contains
2472@code{#\nul} characters.
2473
2474For @code{scm_to_locale_stringn} and @var{lenp} not @code{NULL},
2475@var{str} might contain @code{#\nul} characters and the length of the
2476returned string in bytes is stored in @code{*@var{lenp}}. The
2477returned string will not be null-terminated in this case. If
2478@var{lenp} is @code{NULL}, @code{scm_to_locale_stringn} behaves like
2479@code{scm_to_locale_string}.
2480@end deftypefn
2481
2482@deftypefn {C Function} size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
2483Puts @var{str} as a C string in the current locale encoding into the
2484memory pointed to by @var{buf}. The buffer at @var{buf} has room for
2485@var{max_len} bytes and @code{scm_to_local_stringbuf} will never store
2486more than that. No terminating @code{'\0'} will be stored.
2487
2488The return value of @code{scm_to_locale_stringbuf} is the number of
2489bytes that are needed for all of @var{str}, regardless of whether
2490@var{buf} was large enough to hold them. Thus, when the return value
2491is larger than @var{max_len}, only @var{max_len} bytes have been
2492stored and you probably need to try again with a larger buffer.
2493@end deftypefn
07d83abe
MV
2494
2495@node Regular Expressions
2496@subsection Regular Expressions
2497@tpindex Regular expressions
2498
2499@cindex regular expressions
2500@cindex regex
2501@cindex emacs regexp
2502
2503A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
2504describes a whole class of strings. A full description of regular
2505expressions and their syntax is beyond the scope of this manual;
2506an introduction can be found in the Emacs manual (@pxref{Regexps,
2507, Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
2508in many general Unix reference books.
2509
2510If your system does not include a POSIX regular expression library,
2511and you have not linked Guile with a third-party regexp library such
2512as Rx, these functions will not be available. You can tell whether
2513your Guile installation includes regular expression support by
2514checking whether @code{(provided? 'regex)} returns true.
2515
2516The following regexp and string matching features are provided by the
2517@code{(ice-9 regex)} module. Before using the described functions,
2518you should load this module by executing @code{(use-modules (ice-9
2519regex))}.
2520
2521@menu
2522* Regexp Functions:: Functions that create and match regexps.
2523* Match Structures:: Finding what was matched by a regexp.
2524* Backslash Escapes:: Removing the special meaning of regexp
2525 meta-characters.
2526@end menu
2527
2528
2529@node Regexp Functions
2530@subsubsection Regexp Functions
2531
2532By default, Guile supports POSIX extended regular expressions.
2533That means that the characters @samp{(}, @samp{)}, @samp{+} and
2534@samp{?} are special, and must be escaped if you wish to match the
2535literal characters.
2536
2537This regular expression interface was modeled after that
2538implemented by SCSH, the Scheme Shell. It is intended to be
2539upwardly compatible with SCSH regular expressions.
2540
2541@deffn {Scheme Procedure} string-match pattern str [start]
2542Compile the string @var{pattern} into a regular expression and compare
2543it with @var{str}. The optional numeric argument @var{start} specifies
2544the position of @var{str} at which to begin matching.
2545
2546@code{string-match} returns a @dfn{match structure} which
2547describes what, if anything, was matched by the regular
2548expression. @xref{Match Structures}. If @var{str} does not match
2549@var{pattern} at all, @code{string-match} returns @code{#f}.
2550@end deffn
2551
2552Two examples of a match follow. In the first example, the pattern
2553matches the four digits in the match string. In the second, the pattern
2554matches nothing.
2555
2556@example
2557(string-match "[0-9][0-9][0-9][0-9]" "blah2002")
2558@result{} #("blah2002" (4 . 8))
2559
2560(string-match "[A-Za-z]" "123456")
2561@result{} #f
2562@end example
2563
2564Each time @code{string-match} is called, it must compile its
2565@var{pattern} argument into a regular expression structure. This
2566operation is expensive, which makes @code{string-match} inefficient if
2567the same regular expression is used several times (for example, in a
2568loop). For better performance, you can compile a regular expression in
2569advance and then match strings against the compiled regexp.
2570
2571@deffn {Scheme Procedure} make-regexp pat flag@dots{}
2572@deffnx {C Function} scm_make_regexp (pat, flaglst)
2573Compile the regular expression described by @var{pat}, and
2574return the compiled regexp structure. If @var{pat} does not
2575describe a legal regular expression, @code{make-regexp} throws
2576a @code{regular-expression-syntax} error.
2577
2578The @var{flag} arguments change the behavior of the compiled
2579regular expression. The following values may be supplied:
2580
2581@defvar regexp/icase
2582Consider uppercase and lowercase letters to be the same when
2583matching.
2584@end defvar
2585
2586@defvar regexp/newline
2587If a newline appears in the target string, then permit the
2588@samp{^} and @samp{$} operators to match immediately after or
2589immediately before the newline, respectively. Also, the
2590@samp{.} and @samp{[^...]} operators will never match a newline
2591character. The intent of this flag is to treat the target
2592string as a buffer containing many lines of text, and the
2593regular expression as a pattern that may match a single one of
2594those lines.
2595@end defvar
2596
2597@defvar regexp/basic
2598Compile a basic (``obsolete'') regexp instead of the extended
2599(``modern'') regexps that are the default. Basic regexps do
2600not consider @samp{|}, @samp{+} or @samp{?} to be special
2601characters, and require the @samp{@{...@}} and @samp{(...)}
2602metacharacters to be backslash-escaped (@pxref{Backslash
2603Escapes}). There are several other differences between basic
2604and extended regular expressions, but these are the most
2605significant.
2606@end defvar
2607
2608@defvar regexp/extended
2609Compile an extended regular expression rather than a basic
2610regexp. This is the default behavior; this flag will not
2611usually be needed. If a call to @code{make-regexp} includes
2612both @code{regexp/basic} and @code{regexp/extended} flags, the
2613one which comes last will override the earlier one.
2614@end defvar
2615@end deffn
2616
2617@deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
2618@deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
2619Match the compiled regular expression @var{rx} against
2620@code{str}. If the optional integer @var{start} argument is
2621provided, begin matching from that position in the string.
2622Return a match structure describing the results of the match,
2623or @code{#f} if no match could be found.
2624
2625The @var{flags} arguments change the matching behavior.
2626The following flags may be supplied:
2627
2628@defvar regexp/notbol
2629Operator @samp{^} always fails (unless @code{regexp/newline}
2630is used). Use this when the beginning of the string should
2631not be considered the beginning of a line.
2632@end defvar
2633
2634@defvar regexp/noteol
2635Operator @samp{$} always fails (unless @code{regexp/newline}
2636is used). Use this when the end of the string should not be
2637considered the end of a line.
2638@end defvar
2639@end deffn
2640
2641@lisp
2642;; Regexp to match uppercase letters
2643(define r (make-regexp "[A-Z]*"))
2644
2645;; Regexp to match letters, ignoring case
2646(define ri (make-regexp "[A-Z]*" regexp/icase))
2647
2648;; Search for bob using regexp r
2649(match:substring (regexp-exec r "bob"))
2650@result{} "" ; no match
2651
2652;; Search for bob using regexp ri
2653(match:substring (regexp-exec ri "Bob"))
2654@result{} "Bob" ; matched case insensitive
2655@end lisp
2656
2657@deffn {Scheme Procedure} regexp? obj
2658@deffnx {C Function} scm_regexp_p (obj)
2659Return @code{#t} if @var{obj} is a compiled regular expression,
2660or @code{#f} otherwise.
2661@end deffn
2662
2663Regular expressions are commonly used to find patterns in one string and
2664replace them with the contents of another string.
2665
2666@c begin (scm-doc-string "regex.scm" "regexp-substitute")
2667@deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
2668Write to the output port @var{port} selected contents of the match
2669structure @var{match}. Each @var{item} specifies what should be
2670written, and may be one of the following arguments:
2671
2672@itemize @bullet
2673@item
2674A string. String arguments are written out verbatim.
2675
2676@item
2677An integer. The submatch with that number is written.
2678
2679@item
2680The symbol @samp{pre}. The portion of the matched string preceding
2681the regexp match is written.
2682
2683@item
2684The symbol @samp{post}. The portion of the matched string following
2685the regexp match is written.
2686@end itemize
2687
2688The @var{port} argument may be @code{#f}, in which case nothing is
2689written; instead, @code{regexp-substitute} constructs a string from the
2690specified @var{item}s and returns that.
2691@end deffn
2692
2693The following example takes a regular expression that matches a standard
2694@sc{yyyymmdd}-format date such as @code{"20020828"}. The
2695@code{regexp-substitute} call returns a string computed from the
2696information in the match structure, consisting of the fields and text
2697from the original string reordered and reformatted.
2698
2699@lisp
2700(define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2701(define s "Date 20020429 12am.")
2702(define sm (string-match date-regex s))
2703(regexp-substitute #f sm 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2704@result{} "Date 04-29-2002 12am. (20020429)"
2705@end lisp
2706
2707@c begin (scm-doc-string "regex.scm" "regexp-substitute")
2708@deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
2709Similar to @code{regexp-substitute}, but can be used to perform global
2710substitutions on @var{str}. Instead of taking a match structure as an
2711argument, @code{regexp-substitute/global} takes two string arguments: a
2712@var{regexp} string describing a regular expression, and a @var{target}
2713string which should be matched against this regular expression.
2714
2715Each @var{item} behaves as in @code{regexp-substitute}, with the
2716following exceptions:
2717
2718@itemize @bullet
2719@item
2720A function may be supplied. When this function is called, it will be
2721passed one argument: a match structure for a given regular expression
2722match. It should return a string to be written out to @var{port}.
2723
2724@item
2725The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
2726on the unmatched portion of @var{str}. This @emph{must} be supplied in
2727order to perform global search-and-replace on @var{str}; if it is not
2728present among the @var{item}s, then @code{regexp-substitute/global} will
2729return after processing a single match.
2730@end itemize
2731@end deffn
2732
2733The example above for @code{regexp-substitute} could be rewritten as
2734follows to remove the @code{string-match} stage:
2735
2736@lisp
2737(define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
2738(define s "Date 20020429 12am.")
2739(regexp-substitute/global #f date-regex s
2740 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
2741@result{} "Date 04-29-2002 12am. (20020429)"
2742@end lisp
2743
2744
2745@node Match Structures
2746@subsubsection Match Structures
2747
2748@cindex match structures
2749
2750A @dfn{match structure} is the object returned by @code{string-match} and
2751@code{regexp-exec}. It describes which portion of a string, if any,
2752matched the given regular expression. Match structures include: a
2753reference to the string that was checked for matches; the starting and
2754ending positions of the regexp match; and, if the regexp included any
2755parenthesized subexpressions, the starting and ending positions of each
2756submatch.
2757
2758In each of the regexp match functions described below, the @code{match}
2759argument must be a match structure returned by a previous call to
2760@code{string-match} or @code{regexp-exec}. Most of these functions
2761return some information about the original target string that was
2762matched against a regular expression; we will call that string
2763@var{target} for easy reference.
2764
2765@c begin (scm-doc-string "regex.scm" "regexp-match?")
2766@deffn {Scheme Procedure} regexp-match? obj
2767Return @code{#t} if @var{obj} is a match structure returned by a
2768previous call to @code{regexp-exec}, or @code{#f} otherwise.
2769@end deffn
2770
2771@c begin (scm-doc-string "regex.scm" "match:substring")
2772@deffn {Scheme Procedure} match:substring match [n]
2773Return the portion of @var{target} matched by subexpression number
2774@var{n}. Submatch 0 (the default) represents the entire regexp match.
2775If the regular expression as a whole matched, but the subexpression
2776number @var{n} did not match, return @code{#f}.
2777@end deffn
2778
2779@lisp
2780(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2781(match:substring s)
2782@result{} "2002"
2783
2784;; match starting at offset 6 in the string
2785(match:substring
2786 (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
2787@result{} "7654"
2788@end lisp
2789
2790@c begin (scm-doc-string "regex.scm" "match:start")
2791@deffn {Scheme Procedure} match:start match [n]
2792Return the starting position of submatch number @var{n}.
2793@end deffn
2794
2795In the following example, the result is 4, since the match starts at
2796character index 4:
2797
2798@lisp
2799(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2800(match:start s)
2801@result{} 4
2802@end lisp
2803
2804@c begin (scm-doc-string "regex.scm" "match:end")
2805@deffn {Scheme Procedure} match:end match [n]
2806Return the ending position of submatch number @var{n}.
2807@end deffn
2808
2809In the following example, the result is 8, since the match runs between
2810characters 4 and 8 (i.e. the ``2002'').
2811
2812@lisp
2813(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2814(match:end s)
2815@result{} 8
2816@end lisp
2817
2818@c begin (scm-doc-string "regex.scm" "match:prefix")
2819@deffn {Scheme Procedure} match:prefix match
2820Return the unmatched portion of @var{target} preceding the regexp match.
2821
2822@lisp
2823(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2824(match:prefix s)
2825@result{} "blah"
2826@end lisp
2827@end deffn
2828
2829@c begin (scm-doc-string "regex.scm" "match:suffix")
2830@deffn {Scheme Procedure} match:suffix match
2831Return the unmatched portion of @var{target} following the regexp match.
2832@end deffn
2833
2834@lisp
2835(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2836(match:suffix s)
2837@result{} "foo"
2838@end lisp
2839
2840@c begin (scm-doc-string "regex.scm" "match:count")
2841@deffn {Scheme Procedure} match:count match
2842Return the number of parenthesized subexpressions from @var{match}.
2843Note that the entire regular expression match itself counts as a
2844subexpression, and failed submatches are included in the count.
2845@end deffn
2846
2847@c begin (scm-doc-string "regex.scm" "match:string")
2848@deffn {Scheme Procedure} match:string match
2849Return the original @var{target} string.
2850@end deffn
2851
2852@lisp
2853(define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
2854(match:string s)
2855@result{} "blah2002foo"
2856@end lisp
2857
2858
2859@node Backslash Escapes
2860@subsubsection Backslash Escapes
2861
2862Sometimes you will want a regexp to match characters like @samp{*} or
2863@samp{$} exactly. For example, to check whether a particular string
2864represents a menu entry from an Info node, it would be useful to match
2865it against a regexp like @samp{^* [^:]*::}. However, this won't work;
2866because the asterisk is a metacharacter, it won't match the @samp{*} at
2867the beginning of the string. In this case, we want to make the first
2868asterisk un-magic.
2869
2870You can do this by preceding the metacharacter with a backslash
2871character @samp{\}. (This is also called @dfn{quoting} the
2872metacharacter, and is known as a @dfn{backslash escape}.) When Guile
2873sees a backslash in a regular expression, it considers the following
2874glyph to be an ordinary character, no matter what special meaning it
2875would ordinarily have. Therefore, we can make the above example work by
2876changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
2877the regular expression engine to match only a single asterisk in the
2878target string.
2879
2880Since the backslash is itself a metacharacter, you may force a regexp to
2881match a backslash in the target string by preceding the backslash with
2882itself. For example, to find variable references in a @TeX{} program,
2883you might want to find occurrences of the string @samp{\let\} followed
2884by any number of alphabetic characters. The regular expression
2885@samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
2886regexp each match a single backslash in the target string.
2887
2888@c begin (scm-doc-string "regex.scm" "regexp-quote")
2889@deffn {Scheme Procedure} regexp-quote str
2890Quote each special character found in @var{str} with a backslash, and
2891return the resulting string.
2892@end deffn
2893
2894@strong{Very important:} Using backslash escapes in Guile source code
2895(as in Emacs Lisp or C) can be tricky, because the backslash character
2896has special meaning for the Guile reader. For example, if Guile
2897encounters the character sequence @samp{\n} in the middle of a string
2898while processing Scheme code, it replaces those characters with a
2899newline character. Similarly, the character sequence @samp{\t} is
2900replaced by a horizontal tab. Several of these @dfn{escape sequences}
2901are processed by the Guile reader before your code is executed.
2902Unrecognized escape sequences are ignored: if the characters @samp{\*}
2903appear in a string, they will be translated to the single character
2904@samp{*}.
2905
2906This translation is obviously undesirable for regular expressions, since
2907we want to be able to include backslashes in a string in order to
2908escape regexp metacharacters. Therefore, to make sure that a backslash
2909is preserved in a string in your Guile program, you must use @emph{two}
2910consecutive backslashes:
2911
2912@lisp
2913(define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
2914@end lisp
2915
2916The string in this example is preprocessed by the Guile reader before
2917any code is executed. The resulting argument to @code{make-regexp} is
2918the string @samp{^\* [^:]*}, which is what we really want.
2919
2920This also means that in order to write a regular expression that matches
2921a single backslash character, the regular expression string in the
2922source code must include @emph{four} backslashes. Each consecutive pair
2923of backslashes gets translated by the Guile reader to a single
2924backslash, and the resulting double-backslash is interpreted by the
2925regexp engine as matching a single backslash character. Hence:
2926
2927@lisp
2928(define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
2929@end lisp
2930
2931The reason for the unwieldiness of this syntax is historical. Both
2932regular expression pattern matchers and Unix string processing systems
2933have traditionally used backslashes with the special meanings
2934described above. The POSIX regular expression specification and ANSI C
2935standard both require these semantics. Attempting to abandon either
2936convention would cause other kinds of compatibility problems, possibly
2937more severe ones. Therefore, without extending the Scheme reader to
2938support strings with different quoting conventions (an ungainly and
2939confusing extension when implemented in other languages), we must adhere
2940to this cumbersome escape syntax.
2941
2942
2943@node Symbols
2944@subsection Symbols
2945@tpindex Symbols
2946
2947Symbols in Scheme are widely used in three ways: as items of discrete
2948data, as lookup keys for alists and hash tables, and to denote variable
2949references.
2950
2951A @dfn{symbol} is similar to a string in that it is defined by a
2952sequence of characters. The sequence of characters is known as the
2953symbol's @dfn{name}. In the usual case --- that is, where the symbol's
2954name doesn't include any characters that could be confused with other
2955elements of Scheme syntax --- a symbol is written in a Scheme program by
2956writing the sequence of characters that make up the name, @emph{without}
2957any quotation marks or other special syntax. For example, the symbol
2958whose name is ``multiply-by-2'' is written, simply:
2959
2960@lisp
2961multiply-by-2
2962@end lisp
2963
2964Notice how this differs from a @emph{string} with contents
2965``multiply-by-2'', which is written with double quotation marks, like
2966this:
2967
2968@lisp
2969"multiply-by-2"
2970@end lisp
2971
2972Looking beyond how they are written, symbols are different from strings
2973in two important respects.
2974
2975The first important difference is uniqueness. If the same-looking
2976string is read twice from two different places in a program, the result
2977is two @emph{different} string objects whose contents just happen to be
2978the same. If, on the other hand, the same-looking symbol is read twice
2979from two different places in a program, the result is the @emph{same}
2980symbol object both times.
2981
2982Given two read symbols, you can use @code{eq?} to test whether they are
2983the same (that is, have the same name). @code{eq?} is the most
2984efficient comparison operator in Scheme, and comparing two symbols like
2985this is as fast as comparing, for example, two numbers. Given two
2986strings, on the other hand, you must use @code{equal?} or
2987@code{string=?}, which are much slower comparison operators, to
2988determine whether the strings have the same contents.
2989
2990@lisp
2991(define sym1 (quote hello))
2992(define sym2 (quote hello))
2993(eq? sym1 sym2) @result{} #t
2994
2995(define str1 "hello")
2996(define str2 "hello")
2997(eq? str1 str2) @result{} #f
2998(equal? str1 str2) @result{} #t
2999@end lisp
3000
3001The second important difference is that symbols, unlike strings, are not
3002self-evaluating. This is why we need the @code{(quote @dots{})}s in the
3003example above: @code{(quote hello)} evaluates to the symbol named
3004"hello" itself, whereas an unquoted @code{hello} is @emph{read} as the
3005symbol named "hello" and evaluated as a variable reference @dots{} about
3006which more below (@pxref{Symbol Variables}).
3007
3008@menu
3009* Symbol Data:: Symbols as discrete data.
3010* Symbol Keys:: Symbols as lookup keys.
3011* Symbol Variables:: Symbols as denoting variables.
3012* Symbol Primitives:: Operations related to symbols.
3013* Symbol Props:: Function slots and property lists.
3014* Symbol Read Syntax:: Extended read syntax for symbols.
3015* Symbol Uninterned:: Uninterned symbols.
3016@end menu
3017
3018
3019@node Symbol Data
3020@subsubsection Symbols as Discrete Data
3021
3022Numbers and symbols are similar to the extent that they both lend
3023themselves to @code{eq?} comparison. But symbols are more descriptive
3024than numbers, because a symbol's name can be used directly to describe
3025the concept for which that symbol stands.
3026
3027For example, imagine that you need to represent some colours in a
3028computer program. Using numbers, you would have to choose arbitrarily
3029some mapping between numbers and colours, and then take care to use that
3030mapping consistently:
3031
3032@lisp
3033;; 1=red, 2=green, 3=purple
3034
3035(if (eq? (colour-of car) 1)
3036 ...)
3037@end lisp
3038
3039@noindent
3040You can make the mapping more explicit and the code more readable by
3041defining constants:
3042
3043@lisp
3044(define red 1)
3045(define green 2)
3046(define purple 3)
3047
3048(if (eq? (colour-of car) red)
3049 ...)
3050@end lisp
3051
3052@noindent
3053But the simplest and clearest approach is not to use numbers at all, but
3054symbols whose names specify the colours that they refer to:
3055
3056@lisp
3057(if (eq? (colour-of car) 'red)
3058 ...)
3059@end lisp
3060
3061The descriptive advantages of symbols over numbers increase as the set
3062of concepts that you want to describe grows. Suppose that a car object
3063can have other properties as well, such as whether it has or uses:
3064
3065@itemize @bullet
3066@item
3067automatic or manual transmission
3068@item
3069leaded or unleaded fuel
3070@item
3071power steering (or not).
3072@end itemize
3073
3074@noindent
3075Then a car's combined property set could be naturally represented and
3076manipulated as a list of symbols:
3077
3078@lisp
3079(properties-of car1)
3080@result{}
3081(red manual unleaded power-steering)
3082
3083(if (memq 'power-steering (properties-of car1))
3084 (display "Unfit people can drive this car.\n")
3085 (display "You'll need strong arms to drive this car!\n"))
3086@print{}
3087Unfit people can drive this car.
3088@end lisp
3089
3090Remember, the fundamental property of symbols that we are relying on
3091here is that an occurrence of @code{'red} in one part of a program is an
3092@emph{indistinguishable} symbol from an occurrence of @code{'red} in
3093another part of a program; this means that symbols can usefully be
3094compared using @code{eq?}. At the same time, symbols have naturally
3095descriptive names. This combination of efficiency and descriptive power
3096makes them ideal for use as discrete data.
3097
3098
3099@node Symbol Keys
3100@subsubsection Symbols as Lookup Keys
3101
3102Given their efficiency and descriptive power, it is natural to use
3103symbols as the keys in an association list or hash table.
3104
3105To illustrate this, consider a more structured representation of the car
3106properties example from the preceding subsection. Rather than
3107mixing all the properties up together in a flat list, we could use an
3108association list like this:
3109
3110@lisp
3111(define car1-properties '((colour . red)
3112 (transmission . manual)
3113 (fuel . unleaded)
3114 (steering . power-assisted)))
3115@end lisp
3116
3117Notice how this structure is more explicit and extensible than the flat
3118list. For example it makes clear that @code{manual} refers to the
3119transmission rather than, say, the windows or the locking of the car.
3120It also allows further properties to use the same symbols among their
3121possible values without becoming ambiguous:
3122
3123@lisp
3124(define car1-properties '((colour . red)
3125 (transmission . manual)
3126 (fuel . unleaded)
3127 (steering . power-assisted)
3128 (seat-colour . red)
3129 (locking . manual)))
3130@end lisp
3131
3132With a representation like this, it is easy to use the efficient
3133@code{assq-XXX} family of procedures (@pxref{Association Lists}) to
3134extract or change individual pieces of information:
3135
3136@lisp
3137(assq-ref car1-properties 'fuel) @result{} unleaded
3138(assq-ref car1-properties 'transmission) @result{} manual
3139
3140(assq-set! car1-properties 'seat-colour 'black)
3141@result{}
3142((colour . red)
3143 (transmission . manual)
3144 (fuel . unleaded)
3145 (steering . power-assisted)
3146 (seat-colour . black)
3147 (locking . manual)))
3148@end lisp
3149
3150Hash tables also have keys, and exactly the same arguments apply to the
3151use of symbols in hash tables as in association lists. The hash value
3152that Guile uses to decide where to add a symbol-keyed entry to a hash
3153table can be obtained by calling the @code{symbol-hash} procedure:
3154
3155@deffn {Scheme Procedure} symbol-hash symbol
3156@deffnx {C Function} scm_symbol_hash (symbol)
3157Return a hash value for @var{symbol}.
3158@end deffn
3159
3160See @ref{Hash Tables} for information about hash tables in general, and
3161for why you might choose to use a hash table rather than an association
3162list.
3163
3164
3165@node Symbol Variables
3166@subsubsection Symbols as Denoting Variables
3167
3168When an unquoted symbol in a Scheme program is evaluated, it is
3169interpreted as a variable reference, and the result of the evaluation is
3170the appropriate variable's value.
3171
3172For example, when the expression @code{(string-length "abcd")} is read
3173and evaluated, the sequence of characters @code{string-length} is read
3174as the symbol whose name is "string-length". This symbol is associated
3175with a variable whose value is the procedure that implements string
3176length calculation. Therefore evaluation of the @code{string-length}
3177symbol results in that procedure.
3178
3179The details of the connection between an unquoted symbol and the
3180variable to which it refers are explained elsewhere. See @ref{Binding
3181Constructs}, for how associations between symbols and variables are
3182created, and @ref{Modules}, for how those associations are affected by
3183Guile's module system.
3184
3185
3186@node Symbol Primitives
3187@subsubsection Operations Related to Symbols
3188
3189Given any Scheme value, you can determine whether it is a symbol using
3190the @code{symbol?} primitive:
3191
3192@rnindex symbol?
3193@deffn {Scheme Procedure} symbol? obj
3194@deffnx {C Function} scm_symbol_p (obj)
3195Return @code{#t} if @var{obj} is a symbol, otherwise return
3196@code{#f}.
3197@end deffn
3198
3199Once you know that you have a symbol, you can obtain its name as a
3200string by calling @code{symbol->string}. Note that Guile differs by
3201default from R5RS on the details of @code{symbol->string} as regards
3202case-sensitivity:
3203
3204@rnindex symbol->string
3205@deffn {Scheme Procedure} symbol->string s
3206@deffnx {C Function} scm_symbol_to_string (s)
3207Return the name of symbol @var{s} as a string. By default, Guile reads
3208symbols case-sensitively, so the string returned will have the same case
3209variation as the sequence of characters that caused @var{s} to be
3210created.
3211
3212If Guile is set to read symbols case-insensitively (as specified by
3213R5RS), and @var{s} comes into being as part of a literal expression
3214(@pxref{Literal expressions,,,r5rs, The Revised^5 Report on Scheme}) or
3215by a call to the @code{read} or @code{string-ci->symbol} procedures,
3216Guile converts any alphabetic characters in the symbol's name to
3217lower case before creating the symbol object, so the string returned
3218here will be in lower case.
3219
3220If @var{s} was created by @code{string->symbol}, the case of characters
3221in the string returned will be the same as that in the string that was
3222passed to @code{string->symbol}, regardless of Guile's case-sensitivity
3223setting at the time @var{s} was created.
3224
3225It is an error to apply mutation procedures like @code{string-set!} to
3226strings returned by this procedure.
3227@end deffn
3228
3229Most symbols are created by writing them literally in code. However it
3230is also possible to create symbols programmatically using the following
3231@code{string->symbol} and @code{string-ci->symbol} procedures:
3232
3233@rnindex string->symbol
3234@deffn {Scheme Procedure} string->symbol string
3235@deffnx {C Function} scm_string_to_symbol (string)
3236Return the symbol whose name is @var{string}. This procedure can create
3237symbols with names containing special characters or letters in the
3238non-standard case, but it is usually a bad idea to create such symbols
3239because in some implementations of Scheme they cannot be read as
3240themselves.
3241@end deffn
3242
3243@deffn {Scheme Procedure} string-ci->symbol str
3244@deffnx {C Function} scm_string_ci_to_symbol (str)
3245Return the symbol whose name is @var{str}. If Guile is currently
3246reading symbols case-insensitively, @var{str} is converted to lowercase
3247before the returned symbol is looked up or created.
3248@end deffn
3249
3250The following examples illustrate Guile's detailed behaviour as regards
3251the case-sensitivity of symbols:
3252
3253@lisp
3254(read-enable 'case-insensitive) ; R5RS compliant behaviour
3255
3256(symbol->string 'flying-fish) @result{} "flying-fish"
3257(symbol->string 'Martin) @result{} "martin"
3258(symbol->string
3259 (string->symbol "Malvina")) @result{} "Malvina"
3260
3261(eq? 'mISSISSIppi 'mississippi) @result{} #t
3262(string->symbol "mISSISSIppi") @result{} mISSISSIppi
3263(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
3264(eq? 'LolliPop
3265 (string->symbol (symbol->string 'LolliPop))) @result{} #t
3266(string=? "K. Harper, M.D."
3267 (symbol->string
3268 (string->symbol "K. Harper, M.D."))) @result{} #t
3269
3270(read-disable 'case-insensitive) ; Guile default behaviour
3271
3272(symbol->string 'flying-fish) @result{} "flying-fish"
3273(symbol->string 'Martin) @result{} "Martin"
3274(symbol->string
3275 (string->symbol "Malvina")) @result{} "Malvina"
3276
3277(eq? 'mISSISSIppi 'mississippi) @result{} #f
3278(string->symbol "mISSISSIppi") @result{} mISSISSIppi
3279(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #t
3280(eq? 'LolliPop
3281 (string->symbol (symbol->string 'LolliPop))) @result{} #t
3282(string=? "K. Harper, M.D."
3283 (symbol->string
3284 (string->symbol "K. Harper, M.D."))) @result{} #t
3285@end lisp
3286
3287From C, there are lower level functions that construct a Scheme symbol
c48c62d0
MV
3288from a C string in the current locale encoding.
3289
3290When you want to do more from C, you should convert between symbols
3291and strings using @code{scm_symbol_to_string} and
3292@code{scm_string_to_symbol} and work with the strings.
07d83abe 3293
c48c62d0
MV
3294@deffn {C Function} scm_from_locale_symbol (const char *name)
3295@deffnx {C Function} scm_from_locale_symboln (const char *name, size_t len)
07d83abe 3296Construct and return a Scheme symbol whose name is specified by
c48c62d0
MV
3297@var{name}. For @code{scm_from_locale_symbol}, @var{name} must be null
3298terminated; for @code{scm_from_locale_symboln} the length of @var{name} is
07d83abe
MV
3299specified explicitly by @var{len}.
3300@end deffn
3301
3302Finally, some applications, especially those that generate new Scheme
3303code dynamically, need to generate symbols for use in the generated
3304code. The @code{gensym} primitive meets this need:
3305
3306@deffn {Scheme Procedure} gensym [prefix]
3307@deffnx {C Function} scm_gensym (prefix)
3308Create a new symbol with a name constructed from a prefix and a counter
3309value. The string @var{prefix} can be specified as an optional
3310argument. Default prefix is @samp{@w{ g}}. The counter is increased by 1
3311at each call. There is no provision for resetting the counter.
3312@end deffn
3313
3314The symbols generated by @code{gensym} are @emph{likely} to be unique,
3315since their names begin with a space and it is only otherwise possible
3316to generate such symbols if a programmer goes out of their way to do
3317so. Uniqueness can be guaranteed by instead using uninterned symbols
3318(@pxref{Symbol Uninterned}), though they can't be usefully written out
3319and read back in.
3320
3321
3322@node Symbol Props
3323@subsubsection Function Slots and Property Lists
3324
3325In traditional Lisp dialects, symbols are often understood as having
3326three kinds of value at once:
3327
3328@itemize @bullet
3329@item
3330a @dfn{variable} value, which is used when the symbol appears in
3331code in a variable reference context
3332
3333@item
3334a @dfn{function} value, which is used when the symbol appears in
3335code in a function name position (i.e. as the first element in an
3336unquoted list)
3337
3338@item
3339a @dfn{property list} value, which is used when the symbol is given as
3340the first argument to Lisp's @code{put} or @code{get} functions.
3341@end itemize
3342
3343Although Scheme (as one of its simplifications with respect to Lisp)
3344does away with the distinction between variable and function namespaces,
3345Guile currently retains some elements of the traditional structure in
3346case they turn out to be useful when implementing translators for other
3347languages, in particular Emacs Lisp.
3348
3349Specifically, Guile symbols have two extra slots. for a symbol's
3350property list, and for its ``function value.'' The following procedures
3351are provided to access these slots.
3352
3353@deffn {Scheme Procedure} symbol-fref symbol
3354@deffnx {C Function} scm_symbol_fref (symbol)
3355Return the contents of @var{symbol}'s @dfn{function slot}.
3356@end deffn
3357
3358@deffn {Scheme Procedure} symbol-fset! symbol value
3359@deffnx {C Function} scm_symbol_fset_x (symbol, value)
3360Set the contents of @var{symbol}'s function slot to @var{value}.
3361@end deffn
3362
3363@deffn {Scheme Procedure} symbol-pref symbol
3364@deffnx {C Function} scm_symbol_pref (symbol)
3365Return the @dfn{property list} currently associated with @var{symbol}.
3366@end deffn
3367
3368@deffn {Scheme Procedure} symbol-pset! symbol value
3369@deffnx {C Function} scm_symbol_pset_x (symbol, value)
3370Set @var{symbol}'s property list to @var{value}.
3371@end deffn
3372
3373@deffn {Scheme Procedure} symbol-property sym prop
3374From @var{sym}'s property list, return the value for property
3375@var{prop}. The assumption is that @var{sym}'s property list is an
3376association list whose keys are distinguished from each other using
3377@code{equal?}; @var{prop} should be one of the keys in that list. If
3378the property list has no entry for @var{prop}, @code{symbol-property}
3379returns @code{#f}.
3380@end deffn
3381
3382@deffn {Scheme Procedure} set-symbol-property! sym prop val
3383In @var{sym}'s property list, set the value for property @var{prop} to
3384@var{val}, or add a new entry for @var{prop}, with value @var{val}, if
3385none already exists. For the structure of the property list, see
3386@code{symbol-property}.
3387@end deffn
3388
3389@deffn {Scheme Procedure} symbol-property-remove! sym prop
3390From @var{sym}'s property list, remove the entry for property
3391@var{prop}, if there is one. For the structure of the property list,
3392see @code{symbol-property}.
3393@end deffn
3394
3395Support for these extra slots may be removed in a future release, and it
3396is probably better to avoid using them. (In release 1.6, Guile itself
3397uses the property list slot sparingly, and the function slot not at
3398all.) For a more modern and Schemely approach to properties, see
3399@ref{Object Properties}.
3400
3401
3402@node Symbol Read Syntax
3403@subsubsection Extended Read Syntax for Symbols
3404
3405The read syntax for a symbol is a sequence of letters, digits, and
3406@dfn{extended alphabetic characters}, beginning with a character that
3407cannot begin a number. In addition, the special cases of @code{+},
3408@code{-}, and @code{...} are read as symbols even though numbers can
3409begin with @code{+}, @code{-} or @code{.}.
3410
3411Extended alphabetic characters may be used within identifiers as if
3412they were letters. The set of extended alphabetic characters is:
3413
3414@example
3415! $ % & * + - . / : < = > ? @@ ^ _ ~
3416@end example
3417
3418In addition to the standard read syntax defined above (which is taken
3419from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
3420Scheme})), Guile provides an extended symbol read syntax that allows the
3421inclusion of unusual characters such as space characters, newlines and
3422parentheses. If (for whatever reason) you need to write a symbol
3423containing characters not mentioned above, you can do so as follows.
3424
3425@itemize @bullet
3426@item
3427Begin the symbol with the characters @code{#@{},
3428
3429@item
3430write the characters of the symbol and
3431
3432@item
3433finish the symbol with the characters @code{@}#}.
3434@end itemize
3435
3436Here are a few examples of this form of read syntax. The first symbol
3437needs to use extended syntax because it contains a space character, the
3438second because it contains a line break, and the last because it looks
3439like a number.
3440
3441@lisp
3442#@{foo bar@}#
3443
3444#@{what
3445ever@}#
3446
3447#@{4242@}#
3448@end lisp
3449
3450Although Guile provides this extended read syntax for symbols,
3451widespread usage of it is discouraged because it is not portable and not
3452very readable.
3453
3454
3455@node Symbol Uninterned
3456@subsubsection Uninterned Symbols
3457
3458What makes symbols useful is that they are automatically kept unique.
3459There are no two symbols that are distinct objects but have the same
3460name. But of course, there is no rule without exception. In addition
3461to the normal symbols that have been discussed up to now, you can also
3462create special @dfn{uninterned} symbols that behave slightly
3463differently.
3464
3465To understand what is different about them and why they might be useful,
3466we look at how normal symbols are actually kept unique.
3467
3468Whenever Guile wants to find the symbol with a specific name, for
3469example during @code{read} or when executing @code{string->symbol}, it
3470first looks into a table of all existing symbols to find out whether a
3471symbol with the given name already exists. When this is the case, Guile
3472just returns that symbol. When not, a new symbol with the name is
3473created and entered into the table so that it can be found later.
3474
3475Sometimes you might want to create a symbol that is guaranteed `fresh',
3476i.e. a symbol that did not exist previously. You might also want to
3477somehow guarantee that no one else will ever unintentionally stumble
3478across your symbol in the future. These properties of a symbol are
3479often needed when generating code during macro expansion. When
3480introducing new temporary variables, you want to guarantee that they
3481don't conflict with variables in other people's code.
3482
3483The simplest way to arrange for this is to create a new symbol but
3484not enter it into the global table of all symbols. That way, no one
3485will ever get access to your symbol by chance. Symbols that are not in
3486the table are called @dfn{uninterned}. Of course, symbols that
3487@emph{are} in the table are called @dfn{interned}.
3488
3489You create new uninterned symbols with the function @code{make-symbol}.
3490You can test whether a symbol is interned or not with
3491@code{symbol-interned?}.
3492
3493Uninterned symbols break the rule that the name of a symbol uniquely
3494identifies the symbol object. Because of this, they can not be written
3495out and read back in like interned symbols. Currently, Guile has no
3496support for reading uninterned symbols. Note that the function
3497@code{gensym} does not return uninterned symbols for this reason.
3498
3499@deffn {Scheme Procedure} make-symbol name
3500@deffnx {C Function} scm_make_symbol (name)
3501Return a new uninterned symbol with the name @var{name}. The returned
3502symbol is guaranteed to be unique and future calls to
3503@code{string->symbol} will not return it.
3504@end deffn
3505
3506@deffn {Scheme Procedure} symbol-interned? symbol
3507@deffnx {C Function} scm_symbol_interned_p (symbol)
3508Return @code{#t} if @var{symbol} is interned, otherwise return
3509@code{#f}.
3510@end deffn
3511
3512For example:
3513
3514@lisp
3515(define foo-1 (string->symbol "foo"))
3516(define foo-2 (string->symbol "foo"))
3517(define foo-3 (make-symbol "foo"))
3518(define foo-4 (make-symbol "foo"))
3519
3520(eq? foo-1 foo-2)
3521@result{} #t
3522; Two interned symbols with the same name are the same object,
3523
3524(eq? foo-1 foo-3)
3525@result{} #f
3526; but a call to make-symbol with the same name returns a
3527; distinct object.
3528
3529(eq? foo-3 foo-4)
3530@result{} #f
3531; A call to make-symbol always returns a new object, even for
3532; the same name.
3533
3534foo-3
3535@result{} #<uninterned-symbol foo 8085290>
3536; Uninterned symbols print differently from interned symbols,
3537
3538(symbol? foo-3)
3539@result{} #t
3540; but they are still symbols,
3541
3542(symbol-interned? foo-3)
3543@result{} #f
3544; just not interned.
3545@end lisp
3546
3547
3548@node Keywords
3549@subsection Keywords
3550@tpindex Keywords
3551
3552Keywords are self-evaluating objects with a convenient read syntax that
3553makes them easy to type.
3554
3555Guile's keyword support conforms to R5RS, and adds a (switchable) read
3556syntax extension to permit keywords to begin with @code{:} as well as
3557@code{#:}.
3558
3559@menu
3560* Why Use Keywords?:: Motivation for keyword usage.
3561* Coding With Keywords:: How to use keywords.
3562* Keyword Read Syntax:: Read syntax for keywords.
3563* Keyword Procedures:: Procedures for dealing with keywords.
3564* Keyword Primitives:: The underlying primitive procedures.
3565@end menu
3566
3567@node Why Use Keywords?
3568@subsubsection Why Use Keywords?
3569
3570Keywords are useful in contexts where a program or procedure wants to be
3571able to accept a large number of optional arguments without making its
3572interface unmanageable.
3573
3574To illustrate this, consider a hypothetical @code{make-window}
3575procedure, which creates a new window on the screen for drawing into
3576using some graphical toolkit. There are many parameters that the caller
3577might like to specify, but which could also be sensibly defaulted, for
3578example:
3579
3580@itemize @bullet
3581@item
3582color depth -- Default: the color depth for the screen
3583
3584@item
3585background color -- Default: white
3586
3587@item
3588width -- Default: 600
3589
3590@item
3591height -- Default: 400
3592@end itemize
3593
3594If @code{make-window} did not use keywords, the caller would have to
3595pass in a value for each possible argument, remembering the correct
3596argument order and using a special value to indicate the default value
3597for that argument:
3598
3599@lisp
3600(make-window 'default ;; Color depth
3601 'default ;; Background color
3602 800 ;; Width
3603 100 ;; Height
3604 @dots{}) ;; More make-window arguments
3605@end lisp
3606
3607With keywords, on the other hand, defaulted arguments are omitted, and
3608non-default arguments are clearly tagged by the appropriate keyword. As
3609a result, the invocation becomes much clearer:
3610
3611@lisp
3612(make-window #:width 800 #:height 100)
3613@end lisp
3614
3615On the other hand, for a simpler procedure with few arguments, the use
3616of keywords would be a hindrance rather than a help. The primitive
3617procedure @code{cons}, for example, would not be improved if it had to
3618be invoked as
3619
3620@lisp
3621(cons #:car x #:cdr y)
3622@end lisp
3623
3624So the decision whether to use keywords or not is purely pragmatic: use
3625them if they will clarify the procedure invocation at point of call.
3626
3627@node Coding With Keywords
3628@subsubsection Coding With Keywords
3629
3630If a procedure wants to support keywords, it should take a rest argument
3631and then use whatever means is convenient to extract keywords and their
3632corresponding arguments from the contents of that rest argument.
3633
3634The following example illustrates the principle: the code for
3635@code{make-window} uses a helper procedure called
3636@code{get-keyword-value} to extract individual keyword arguments from
3637the rest argument.
3638
3639@lisp
3640(define (get-keyword-value args keyword default)
3641 (let ((kv (memq keyword args)))
3642 (if (and kv (>= (length kv) 2))
3643 (cadr kv)
3644 default)))
3645
3646(define (make-window . args)
3647 (let ((depth (get-keyword-value args #:depth screen-depth))
3648 (bg (get-keyword-value args #:bg "white"))
3649 (width (get-keyword-value args #:width 800))
3650 (height (get-keyword-value args #:height 100))
3651 @dots{})
3652 @dots{}))
3653@end lisp
3654
3655But you don't need to write @code{get-keyword-value}. The @code{(ice-9
3656optargs)} module provides a set of powerful macros that you can use to
3657implement keyword-supporting procedures like this:
3658
3659@lisp
3660(use-modules (ice-9 optargs))
3661
3662(define (make-window . args)
3663 (let-keywords args #f ((depth screen-depth)
3664 (bg "white")
3665 (width 800)
3666 (height 100))
3667 ...))
3668@end lisp
3669
3670@noindent
3671Or, even more economically, like this:
3672
3673@lisp
3674(use-modules (ice-9 optargs))
3675
3676(define* (make-window #:key (depth screen-depth)
3677 (bg "white")
3678 (width 800)
3679 (height 100))
3680 ...)
3681@end lisp
3682
3683For further details on @code{let-keywords}, @code{define*} and other
3684facilities provided by the @code{(ice-9 optargs)} module, see
3685@ref{Optional Arguments}.
3686
3687
3688@node Keyword Read Syntax
3689@subsubsection Keyword Read Syntax
3690
3691Guile, by default, only recognizes the keyword syntax specified by R5RS.
3692A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
3693as a Scheme symbol (@pxref{Symbol Read Syntax}), is the external
3694representation of the keyword named @code{NAME}. Keyword objects print
3695using this syntax as well, so values containing keyword objects can be
3696read back into Guile. When used in an expression, keywords are
3697self-quoting objects.
3698
3699If the @code{keyword} read option is set to @code{'prefix}, Guile also
3700recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
3701of the form @code{:NAME} are read as symbols, as required by R5RS.
3702
3703To enable and disable the alternative non-R5RS keyword syntax, you use
3704the @code{read-set!} procedure documented in @ref{User level options
3705interfaces} and @ref{Reader options}.
3706
3707@smalllisp
3708(read-set! keywords 'prefix)
3709
3710#:type
3711@result{}
3712#:type
3713
3714:type
3715@result{}
3716#:type
3717
3718(read-set! keywords #f)
3719
3720#:type
3721@result{}
3722#:type
3723
3724:type
3725@print{}
3726ERROR: In expression :type:
3727ERROR: Unbound variable: :type
3728ABORT: (unbound-variable)
3729@end smalllisp
3730
3731@node Keyword Procedures
3732@subsubsection Keyword Procedures
3733
3734The following procedures can be used for converting symbols to keywords
3735and back.
3736
3737@deffn {Scheme Procedure} symbol->keyword sym
3738Return a keyword with the same characters as in @var{sym}.
3739@end deffn
3740
3741@deffn {Scheme Procedure} keyword->symbol kw
3742Return a symbol with the same characters as in @var{kw}.
3743@end deffn
3744
3745
3746@node Keyword Primitives
3747@subsubsection Keyword Primitives
3748
3749Internally, a keyword is implemented as something like a tagged symbol,
3750where the tag identifies the keyword as being self-evaluating, and the
3751symbol, known as the keyword's @dfn{dash symbol} has the same name as
3752the keyword name but prefixed by a single dash. For example, the
3753keyword @code{#:name} has the corresponding dash symbol @code{-name}.
3754
3755Most keyword objects are constructed automatically by the reader when it
3756reads a token beginning with @code{#:}. However, if you need to
3757construct a keyword object programmatically, you can do so by calling
3758@code{make-keyword-from-dash-symbol} with the corresponding dash symbol
3759(as the reader does). The dash symbol for a keyword object can be
3760retrieved using the @code{keyword-dash-symbol} procedure.
3761
3762@deffn {Scheme Procedure} make-keyword-from-dash-symbol symbol
3763@deffnx {C Function} scm_make_keyword_from_dash_symbol (symbol)
3764Make a keyword object from a @var{symbol} that starts with a dash.
3765For example,
3766
3767@example
3768(make-keyword-from-dash-symbol '-foo)
3769@result{} #:foo
3770@end example
3771@end deffn
3772
3773@deffn {Scheme Procedure} keyword? obj
3774@deffnx {C Function} scm_keyword_p (obj)
3775Return @code{#t} if the argument @var{obj} is a keyword, else
3776@code{#f}.
3777@end deffn
3778
3779@deffn {Scheme Procedure} keyword-dash-symbol keyword
3780@deffnx {C Function} scm_keyword_dash_symbol (keyword)
3781Return the dash symbol for @var{keyword}.
3782This is the inverse of @code{make-keyword-from-dash-symbol}.
3783For example,
3784
3785@example
3786(keyword-dash-symbol #:foo)
3787@result{} -foo
3788@end example
3789@end deffn
3790
3791@deftypefn {C Function} SCM scm_c_make_keyword (char *@var{str})
3792Make a keyword object from a string. For example,
3793
3794@example
3795scm_c_make_keyword ("foo")
3796@result{} #:foo
3797@end example
3798@c
3799@c FIXME: What can be said about the string argument? Currently it's
3800@c not used after creation, but should that be documented?
3801@end deftypefn
3802
3803
3804@node Other Types
3805@subsection ``Functionality-Centric'' Data Types
3806
3807Procedures and macros are documented in their own chapter: see
3808@ref{Procedures and Macros}.
3809
3810Variable objects are documented as part of the description of Guile's
3811module system: see @ref{Variables}.
3812
3813Asyncs, dynamic roots and fluids are described in the chapter on
3814scheduling: see @ref{Scheduling}.
3815
3816Hooks are documented in the chapter on general utility functions: see
3817@ref{Hooks}.
3818
3819Ports are described in the chapter on I/O: see @ref{Input and Output}.
3820
3821
3822@c Local Variables:
3823@c TeX-master: "guile.texi"
3824@c End: