1
Fork 0
mirror of https://git.savannah.gnu.org/git/guile.git synced 2025-05-01 12:20:26 +02:00
guile/doc/ref/scheme-data.texi

2647 lines
83 KiB
Text
Executable file

@page
@node Simple Data Types
@chapter Simple Generic Data Types
This chapter describes those of Guile's simple data types which are
primarily are used for their role as items of generic data. By
@dfn{simple} we mean data types that are not primarily used as
containers to hold other data --- i.e. pairs, lists, vectors and so on.
For the documentation of such @dfn{compound} data types, see
@ref{Compound Data Types}.
One of the great strengths of Scheme is that there is no straightforward
distinction between ``data'' and ``functionality''. For example,
Guile's support for dynamic linking could be described
@itemize @bullet
@item
either in a ``data-centric'' way, as the behaviour and properties of the
``dynamically linked object'' data type, and the operations that may be
applied to instances of this type
@item
or in a ``functionality-centric'' way, as the set of procedures that
constitute Guile's support for dynamic linking, in the context of the
module system.
@end itemize
The contents of this chapter are, therefore, a matter of judgement. By
@dfn{generic}, we mean to select those data types whose typical use as
@emph{data} in a wide variety of programming contexts is more important
than their use in the implementation of a particular piece of
@emph{functionality}. The last section of this chapter provides
references for all the data types that are documented not here but in a
``functionality-centric'' way elsewhere in the manual.
@menu
* Booleans:: True/false values.
* Numbers:: Numerical data types.
* Characters:: New character names.
* Strings:: Special things about strings.
* Regular Expressions:: Pattern matching and substitution.
* Symbols:: Symbols.
* Keywords:: Self-quoting, customizable display keywords.
* Other Types:: "Functionality-centric" data types.
@end menu
@node Booleans
@section Booleans
@tpindex Booleans
The two boolean values are @code{#t} for true and @code{#f} for false.
Boolean values are returned by predicate procedures, such as the general
equality predicates @code{eq?}, @code{eqv?} and @code{equal?}
(@pxref{Equality}) and numerical and string comparison operators like
@code{string=?} (@pxref{String Comparison}) and @code{<=}
(@pxref{Comparison}).
@lisp
(<= 3 8)
@result{}
#t
(<= 3 -3)
@result{}
#f
(equal? "house" "houses")
@result{}
#f
(eq? #f #f)
@result{}
#t
@end lisp
In test condition contexts like @code{if} and @code{cond} (@pxref{if
cond case}), where a group of subexpressions will be evaluated only if a
@var{condition} expression evaluates to ``true'', ``true'' means any
value at all except @code{#f}.
@lisp
(if #t "yes" "no")
@result{}
"yes"
(if 0 "yes" "no")
@result{}
"yes"
(if #f "yes" "no")
@result{}
"no"
@end lisp
A result of this asymmetry is that typical Scheme source code more often
uses @code{#f} explicitly than @code{#t}: @code{#f} is necessary to
represent an @code{if} or @code{cond} false value, whereas @code{#t} is
not necessary to represent an @code{if} or @code{cond} true value.
It is important to note that @code{#f} is @strong{not} equivalent to any
other Scheme value. In particular, @code{#f} is not the same as the
number 0 (like in C and C++), and not the same as the ``empty list''
(like in some Lisp dialects).
The @code{not} procedure returns the boolean inverse of its argument:
@rnindex not
@deffn {Scheme Procedure} not x
@deffnx {C Function} scm_not (x)
Return @code{#t} iff @var{x} is @code{#f}, else return @code{#f}.
@end deffn
The @code{boolean?} procedure is a predicate that returns @code{#t} if
its argument is one of the boolean values, otherwise @code{#f}.
@rnindex boolean?
@deffn {Scheme Procedure} boolean? obj
@deffnx {C Function} scm_boolean_p (obj)
Return @code{#t} iff @var{obj} is either @code{#t} or @code{#f}.
@end deffn
@node Numbers
@section Numerical data types
@tpindex Numbers
Guile supports a rich ``tower'' of numerical types --- integer,
rational, real and complex --- and provides an extensive set of
mathematical and scientific functions for operating on numerical
data. This section of the manual documents those types and functions.
You may also find it illuminating to read R5RS's presentation of numbers
in Scheme, which is particularly clear and accessible: see
@xref{Numbers,,,r5rs}.
@menu
* Numerical Tower:: Scheme's numerical "tower".
* Integers:: Whole numbers.
* Reals and Rationals:: Real and rational numbers.
* Complex Numbers:: Complex numbers.
* Exactness:: Exactness and inexactness.
* Number Syntax:: Read syntax for numerical data.
* Integer Operations:: Operations on integer values.
* Comparison:: Comparison predicates.
* Conversion:: Converting numbers to and from strings.
* Complex:: Complex number operations.
* Arithmetic:: Arithmetic functions.
* Scientific:: Scientific functions.
* Primitive Numerics:: Primitive numeric functions.
* Bitwise Operations:: Logical AND, OR, NOT, and so on.
* Random:: Random number generation.
@end menu
@node Numerical Tower
@subsection Scheme's Numerical ``Tower''
@rnindex number?
Scheme's numerical ``tower'' consists of the following categories of
numbers:
@itemize @bullet
@item
integers (whole numbers)
@item
rationals (the set of numbers that can be expressed as P/Q where P and Q
are integers)
@item
real numbers (the set of numbers that describes all possible positions
along a one dimensional line)
@item
complex numbers (the set of numbers that describes all possible
positions in a two dimensional space)
@end itemize
It is called a tower because each category ``sits on'' the one that
follows it, in the sense that every integer is also a rational, every
rational is also real, and every real number is also a complex number
(but with zero imaginary part).
Of these, Guile implements integers, reals and complex numbers as
distinct types. Rationals are implemented as regards the read syntax
for rational numbers that is specified by R5RS, but are immediately
converted by Guile to the corresponding real number.
The @code{number?} predicate may be applied to any Scheme value to
discover whether the value is any of the supported numerical types.
@deffn {Scheme Procedure} number? obj
@deffnx {C Function} scm_number_p (obj)
Return @code{#t} if @var{obj} is any kind of number, @code{#f} else.
@findex number?
@end deffn
For example:
@lisp
(number? 3)
@result{}
#t
(number? "hello there!")
@result{}
#f
(define pi 3.141592654)
(number? pi)
@result{}
#t
@end lisp
The next few subsections document each of Guile's numerical data types
in detail.
@node Integers
@subsection Integers
@tpindex Integer numbers
@rnindex integer?
Integers are whole numbers, that is numbers with no fractional part,
such as 2, 83 and -3789.
Integers in Guile can be arbitrarily big, as shown by the following
example.
@lisp
(define (factorial n)
(let loop ((n n) (product 1))
(if (= n 0)
product
(loop (- n 1) (* product n)))))
(factorial 3)
@result{}
6
(factorial 20)
@result{}
2432902008176640000
(- (factorial 45))
@result{}
-119622220865480194561963161495657715064383733760000000000
@end lisp
Readers whose background is in programming languages where integers are
limited by the need to fit into just 4 or 8 bytes of memory may find
this surprising, or suspect that Guile's representation of integers is
inefficient. In fact, Guile achieves a near optimal balance of
convenience and efficiency by using the host computer's native
representation of integers where possible, and a more general
representation where the required number does not fit in the native
form. Conversion between these two representations is automatic and
completely invisible to the Scheme level programmer.
@c REFFIXME Maybe point here to discussion of handling immediates/bignums
@c on the C level, where the conversion is not so automatic - NJ
@deffn {Scheme Procedure} integer? x
@deffnx {C Function} scm_integer_p (x)
Return @code{#t} if @var{x} is an integer number, @code{#f} else.
@lisp
(integer? 487)
@result{}
#t
(integer? -3.4)
@result{}
#f
@end lisp
@end deffn
@node Reals and Rationals
@subsection Real and Rational Numbers
@tpindex Real numbers
@tpindex Rational numbers
@rnindex real?
@rnindex rational?
Mathematically, the real numbers are the set of numbers that describe
all possible points along a continuous, infinite, one-dimensional line.
The rational numbers are the set of all numbers that can be written as
fractions P/Q, where P and Q are integers. All rational numbers are
also real, but there are real numbers that are not rational, for example
the square root of 2, and pi.
Guile represents both real and rational numbers approximately using a
floating point encoding with limited precision. Even though the actual
encoding is in binary, it may be helpful to think of it as a decimal
number with a limited number of significant figures and a decimal point
somewhere, since this corresponds to the standard notation for non-whole
numbers. For example:
@lisp
0.34
-0.00000142857931198
-5648394822220000000000.0
4.0
@end lisp
The limited precision of Guile's encoding means that any ``real'' number
in Guile can be written in a rational form, by multiplying and then dividing
by sufficient powers of 10 (or in fact, 2). For example,
@code{-0.00000142857931198} is the same as @code{142857931198} divided by
@code{100000000000000000}. In Guile's current incarnation, therefore,
the @code{rational?} and @code{real?} predicates are equivalent.
Another aspect of this equivalence is that Guile currently does not
preserve the exactness that is possible with rational arithmetic.
If such exactness is needed, it is of course possible to implement
exact rational arithmetic at the Scheme level using Guile's arbitrary
size integers.
A planned future revision of Guile's numerical tower will make it
possible to implement exact representations and arithmetic for both
rational numbers and real irrational numbers such as square roots,
and in such a way that the new kinds of number integrate seamlessly
with those that are already implemented.
@deffn {Scheme Procedure} real? obj
@deffnx {C Function} scm_real_p (obj)
Return @code{#t} if @var{obj} is a real number, @code{#f} else.
Note that the sets of integer and rational values form subsets
of the set of real numbers, so the predicate will also be fulfilled
if @var{obj} is an integer number or a rational number.
@findex real?
@end deffn
@deffn {Scheme Procedure} rational? x
@deffnx {C Function} scm_real_p (x)
Return @code{#t} if @var{x} is a rational number, @code{#f}
else. Note that the set of integer values forms a subset of
the set of rational numbers, i. e. the predicate will also be
fulfilled if @var{x} is an integer number. Real numbers
will also satisfy this predicate, because of their limited
precision.
@end deffn
@node Complex Numbers
@subsection Complex Numbers
@tpindex Complex numbers
@rnindex complex?
Complex numbers are the set of numbers that describe all possible points
in a two-dimensional space. The two coordinates of a particular point
in this space are known as the @dfn{real} and @dfn{imaginary} parts of
the complex number that describes that point.
In Guile, complex numbers are written in rectangular form as the sum of
their real and imaginary parts, using the symbol @code{i} to indicate
the imaginary part.
@lisp
3+4i
@result{}
3.0+4.0i
(* 3-8i 2.3+0.3i)
@result{}
9.3-17.5i
@end lisp
Guile represents a complex number as a pair of numbers both of which are
real, so the real and imaginary parts of a complex number have the same
properties of inexactness and limited precision as single real numbers.
@deffn {Scheme Procedure} complex? x
@deffnx {C Function} scm_number_p (x)
Return @code{#t} if @var{x} is a complex number, @code{#f}
else. Note that the sets of real, rational and integer
values form subsets of the set of complex numbers, i. e. the
predicate will also be fulfilled if @var{x} is a real,
rational or integer number.
@end deffn
@node Exactness
@subsection Exact and Inexact Numbers
@tpindex Exact numbers
@tpindex Inexact numbers
@rnindex exact?
@rnindex inexact?
@rnindex exact->inexact
@rnindex inexact->exact
R5RS requires that a calculation involving inexact numbers always
produces an inexact result. To meet this requirement, Guile
distinguishes between an exact integer value such as @code{5} and the
corresponding inexact real value which, to the limited precision
available, has no fractional part, and is printed as @code{5.0}. Guile
will only convert the latter value to the former when forced to do so by
an invocation of the @code{inexact->exact} procedure.
@deffn {Scheme Procedure} exact? x
@deffnx {C Function} scm_exact_p (x)
Return @code{#t} if @var{x} is an exact number, @code{#f}
otherwise.
@end deffn
@deffn {Scheme Procedure} inexact? x
@deffnx {C Function} scm_inexact_p (x)
Return @code{#t} if @var{x} is an inexact number, @code{#f}
else.
@end deffn
@deffn {Scheme Procedure} inexact->exact z
@deffnx {C Function} scm_inexact_to_exact (z)
Return an exact number that is numerically closest to @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "exact->inexact")
@deffn {Scheme Procedure} exact->inexact z
Convert the number @var{z} to its inexact representation.
@end deffn
@node Number Syntax
@subsection Read Syntax for Numerical Data
The read syntax for integers is a string of digits, optionally
preceded by a minus or plus character, a code indicating the
base in which the integer is encoded, and a code indicating whether
the number is exact or inexact. The supported base codes are:
@itemize @bullet
@item
@code{#b}, @code{#B} --- the integer is written in binary (base 2)
@item
@code{#o}, @code{#O} --- the integer is written in octal (base 8)
@item
@code{#d}, @code{#D} --- the integer is written in decimal (base 10)
@item
@code{#x}, @code{#X} --- the integer is written in hexadecimal (base 16).
@end itemize
If the base code is omitted, the integer is assumed to be decimal. The
following examples show how these base codes are used.
@lisp
-13
@result{}
-13
#d-13
@result{}
-13
#x-13
@result{}
-19
#b+1101
@result{}
13
#o377
@result{}
255
@end lisp
The codes for indicating exactness (which can, incidentally, be applied
to all numerical values) are:
@itemize @bullet
@item
@code{#e}, @code{#E} --- the number is exact
@item
@code{#i}, @code{#I} --- the number is inexact.
@end itemize
If the exactness indicator is omitted, the integer is assumed to be exact,
since Guile's internal representation for integers is always exact.
Real numbers have limited precision similar to the precision of the
@code{double} type in C. A consequence of the limited precision is that
all real numbers in Guile are also rational, since any number R with a
limited number of decimal places, say N, can be made into an integer by
multiplying by 10^N.
@node Integer Operations
@subsection Operations on Integer Values
@rnindex odd?
@rnindex even?
@rnindex quotient
@rnindex remainder
@rnindex modulo
@rnindex gcd
@rnindex lcm
@deffn {Scheme Procedure} odd? n
@deffnx {C Function} scm_odd_p (n)
Return @code{#t} if @var{n} is an odd number, @code{#f}
otherwise.
@end deffn
@deffn {Scheme Procedure} even? n
@deffnx {C Function} scm_even_p (n)
Return @code{#t} if @var{n} is an even number, @code{#f}
otherwise.
@end deffn
@c begin (texi-doc-string "guile" "quotient")
@deffn {Scheme Procedure} quotient
Return the quotient of the numbers @var{x} and @var{y}.
@end deffn
@c begin (texi-doc-string "guile" "remainder")
@deffn {Scheme Procedure} remainder
Return the remainder of the numbers @var{x} and @var{y}.
@lisp
(remainder 13 4) @result{} 1
(remainder -13 4) @result{} -1
@end lisp
@end deffn
@c begin (texi-doc-string "guile" "modulo")
@deffn {Scheme Procedure} modulo
Return the modulo of the numbers @var{x} and @var{y}.
@lisp
(modulo 13 4) @result{} 1
(modulo -13 4) @result{} 3
@end lisp
@end deffn
@c begin (texi-doc-string "guile" "gcd")
@deffn {Scheme Procedure} gcd
Return the greatest common divisor of all arguments.
If called without arguments, 0 is returned.
@end deffn
@c begin (texi-doc-string "guile" "lcm")
@deffn {Scheme Procedure} lcm
Return the least common multiple of the arguments.
If called without arguments, 1 is returned.
@end deffn
@node Comparison
@subsection Comparison Predicates
@rnindex zero?
@rnindex positive?
@rnindex negative?
@c begin (texi-doc-string "guile" "=")
@deffn {Scheme Procedure} =
Return @code{#t} if all parameters are numerically equal.
@end deffn
@c begin (texi-doc-string "guile" "<")
@deffn {Scheme Procedure} <
Return @code{#t} if the list of parameters is monotonically
increasing.
@end deffn
@c begin (texi-doc-string "guile" ">")
@deffn {Scheme Procedure} >
Return @code{#t} if the list of parameters is monotonically
decreasing.
@end deffn
@c begin (texi-doc-string "guile" "<=")
@deffn {Scheme Procedure} <=
Return @code{#t} if the list of parameters is monotonically
non-decreasing.
@end deffn
@c begin (texi-doc-string "guile" ">=")
@deffn {Scheme Procedure} >=
Return @code{#t} if the list of parameters is monotonically
non-increasing.
@end deffn
@c begin (texi-doc-string "guile" "zero?")
@deffn {Scheme Procedure} zero?
Return @code{#t} if @var{z} is an exact or inexact number equal to
zero.
@end deffn
@c begin (texi-doc-string "guile" "positive?")
@deffn {Scheme Procedure} positive?
Return @code{#t} if @var{x} is an exact or inexact number greater than
zero.
@end deffn
@c begin (texi-doc-string "guile" "negative?")
@deffn {Scheme Procedure} negative?
Return @code{#t} if @var{x} is an exact or inexact number less than
zero.
@end deffn
@node Conversion
@subsection Converting Numbers To and From Strings
@rnindex number->string
@rnindex string->number
@deffn {Scheme Procedure} number->string n [radix]
@deffnx {C Function} scm_number_to_string (n, radix)
Return a string holding the external representation of the
number @var{n} in the given @var{radix}. If @var{n} is
inexact, a radix of 10 will be used.
@end deffn
@deffn {Scheme Procedure} string->number string [radix]
@deffnx {C Function} scm_string_to_number (string, radix)
Return a number of the maximally precise representation
expressed by the given @var{string}. @var{radix} must be an
exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}
is a default radix that may be overridden by an explicit radix
prefix in @var{string} (e.g. "#o177"). If @var{radix} is not
supplied, then the default radix is 10. If string is not a
syntactically valid notation for a number, then
@code{string->number} returns @code{#f}.
@end deffn
@node Complex
@subsection Complex Number Operations
@rnindex make-rectangular
@rnindex make-polar
@rnindex real-part
@rnindex imag-part
@rnindex magnitude
@rnindex angle
@deffn {Scheme Procedure} make-rectangular real imaginary
@deffnx {C Function} scm_make_rectangular (real, imaginary)
Return a complex number constructed of the given @var{real} and
@var{imaginary} parts.
@end deffn
@deffn {Scheme Procedure} make-polar x y
@deffnx {C Function} scm_make_polar (x, y)
Return the complex number @var{x} * e^(i * @var{y}).
@end deffn
@c begin (texi-doc-string "guile" "real-part")
@deffn {Scheme Procedure} real-part
Return the real part of the number @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "imag-part")
@deffn {Scheme Procedure} imag-part
Return the imaginary part of the number @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "magnitude")
@deffn {Scheme Procedure} magnitude
Return the magnitude of the number @var{z}. This is the same as
@code{abs} for real arguments, but also allows complex numbers.
@end deffn
@c begin (texi-doc-string "guile" "angle")
@deffn {Scheme Procedure} angle
Return the angle of the complex number @var{z}.
@end deffn
@node Arithmetic
@subsection Arithmetic Functions
@rnindex max
@rnindex min
@rnindex +
@rnindex *
@rnindex -
@rnindex /
@rnindex abs
@rnindex floor
@rnindex ceiling
@rnindex truncate
@rnindex round
@c begin (texi-doc-string "guile" "+")
@deffn {Scheme Procedure} + z1 @dots{}
Return the sum of all parameter values. Return 0 if called without any
parameters.
@end deffn
@c begin (texi-doc-string "guile" "-")
@deffn {Scheme Procedure} - z1 z2 @dots{}
If called with one argument @var{z1}, -@var{z1} is returned. Otherwise
the sum of all but the first argument are subtracted from the first
argument.
@end deffn
@c begin (texi-doc-string "guile" "*")
@deffn {Scheme Procedure} * z1 @dots{}
Return the product of all arguments. If called without arguments, 1 is
returned.
@end deffn
@c begin (texi-doc-string "guile" "/")
@deffn {Scheme Procedure} / z1 z2 @dots{}
Divide the first argument by the product of the remaining arguments. If
called with one argument @var{z1}, 1/@var{z1} is returned.
@end deffn
@c begin (texi-doc-string "guile" "abs")
@deffn {Scheme Procedure} abs x
Return the absolute value of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "max")
@deffn {Scheme Procedure} max x1 x2 @dots{}
Return the maximum of all parameter values.
@end deffn
@c begin (texi-doc-string "guile" "min")
@deffn {Scheme Procedure} min x1 x2 @dots{}
Return the minium of all parameter values.
@end deffn
@c begin (texi-doc-string "guile" "truncate")
@deffn {Scheme Procedure} truncate
Round the inexact number @var{x} towards zero.
@end deffn
@c begin (texi-doc-string "guile" "round")
@deffn {Scheme Procedure} round x
Round the inexact number @var{x} towards zero.
@end deffn
@c begin (texi-doc-string "guile" "floor")
@deffn {Scheme Procedure} floor x
Round the number @var{x} towards minus infinity.
@end deffn
@c begin (texi-doc-string "guile" "ceiling")
@deffn {Scheme Procedure} ceiling x
Round the number @var{x} towards infinity.
@end deffn
@node Scientific
@subsection Scientific Functions
The following procedures accept any kind of number as arguments,
including complex numbers.
@rnindex sqrt
@c begin (texi-doc-string "guile" "sqrt")
@deffn {Scheme Procedure} sqrt z
Return the square root of @var{z}.
@end deffn
@rnindex expt
@c begin (texi-doc-string "guile" "expt")
@deffn {Scheme Procedure} expt z1 z2
Return @var{z1} raised to the power of @var{z2}.
@end deffn
@rnindex sin
@c begin (texi-doc-string "guile" "sin")
@deffn {Scheme Procedure} sin z
Return the sine of @var{z}.
@end deffn
@rnindex cos
@c begin (texi-doc-string "guile" "cos")
@deffn {Scheme Procedure} cos z
Return the cosine of @var{z}.
@end deffn
@rnindex tan
@c begin (texi-doc-string "guile" "tan")
@deffn {Scheme Procedure} tan z
Return the tangent of @var{z}.
@end deffn
@rnindex asin
@c begin (texi-doc-string "guile" "asin")
@deffn {Scheme Procedure} asin z
Return the arcsine of @var{z}.
@end deffn
@rnindex acos
@c begin (texi-doc-string "guile" "acos")
@deffn {Scheme Procedure} acos z
Return the arccosine of @var{z}.
@end deffn
@rnindex atan
@c begin (texi-doc-string "guile" "atan")
@deffn {Scheme Procedure} atan z
Return the arctangent of @var{z}.
@end deffn
@rnindex exp
@c begin (texi-doc-string "guile" "exp")
@deffn {Scheme Procedure} exp z
Return e to the power of @var{z}, where e is the base of natural
logarithms (2.71828@dots{}).
@end deffn
@rnindex log
@c begin (texi-doc-string "guile" "log")
@deffn {Scheme Procedure} log z
Return the natural logarithm of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "log10")
@deffn {Scheme Procedure} log10 z
Return the base 10 logarithm of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "sinh")
@deffn {Scheme Procedure} sinh z
Return the hyperbolic sine of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "cosh")
@deffn {Scheme Procedure} cosh z
Return the hyperbolic cosine of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "tanh")
@deffn {Scheme Procedure} tanh z
Return the hyperbolic tangent of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "asinh")
@deffn {Scheme Procedure} asinh z
Return the hyperbolic arcsine of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "acosh")
@deffn {Scheme Procedure} acosh z
Return the hyperbolic arccosine of @var{z}.
@end deffn
@c begin (texi-doc-string "guile" "atanh")
@deffn {Scheme Procedure} atanh z
Return the hyperbolic arctangent of @var{z}.
@end deffn
@node Primitive Numerics
@subsection Primitive Numeric Functions
Many of Guile's numeric procedures which accept any kind of numbers as
arguments, including complex numbers, are implemented as Scheme
procedures that use the following real number-based primitives. These
primitives signal an error if they are called with complex arguments.
@c begin (texi-doc-string "guile" "$abs")
@deffn {Scheme Procedure} $abs x
Return the absolute value of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$sqrt")
@deffn {Scheme Procedure} $sqrt x
Return the square root of @var{x}.
@end deffn
@deffn {Scheme Procedure} $expt x y
@deffnx {C Function} scm_sys_expt (x, y)
Return @var{x} raised to the power of @var{y}. This
procedure does not accept complex arguments.
@end deffn
@c begin (texi-doc-string "guile" "$sin")
@deffn {Scheme Procedure} $sin x
Return the sine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$cos")
@deffn {Scheme Procedure} $cos x
Return the cosine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$tan")
@deffn {Scheme Procedure} $tan x
Return the tangent of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$asin")
@deffn {Scheme Procedure} $asin x
Return the arcsine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$acos")
@deffn {Scheme Procedure} $acos x
Return the arccosine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$atan")
@deffn {Scheme Procedure} $atan x
Return the arctangent of @var{x} in the range -PI/2 to PI/2.
@end deffn
@deffn {Scheme Procedure} $atan2 x y
@deffnx {C Function} scm_sys_atan2 (x, y)
Return the arc tangent of the two arguments @var{x} and
@var{y}. This is similar to calculating the arc tangent of
@var{x} / @var{y}, except that the signs of both arguments
are used to determine the quadrant of the result. This
procedure does not accept complex arguments.
@end deffn
@c begin (texi-doc-string "guile" "$exp")
@deffn {Scheme Procedure} $exp x
Return e to the power of @var{x}, where e is the base of natural
logarithms (2.71828@dots{}).
@end deffn
@c begin (texi-doc-string "guile" "$log")
@deffn {Scheme Procedure} $log x
Return the natural logarithm of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$sinh")
@deffn {Scheme Procedure} $sinh x
Return the hyperbolic sine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$cosh")
@deffn {Scheme Procedure} $cosh x
Return the hyperbolic cosine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$tanh")
@deffn {Scheme Procedure} $tanh x
Return the hyperbolic tangent of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$asinh")
@deffn {Scheme Procedure} $asinh x
Return the hyperbolic arcsine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$acosh")
@deffn {Scheme Procedure} $acosh x
Return the hyperbolic arccosine of @var{x}.
@end deffn
@c begin (texi-doc-string "guile" "$atanh")
@deffn {Scheme Procedure} $atanh x
Return the hyperbolic arctangent of @var{x}.
@end deffn
@node Bitwise Operations
@subsection Bitwise Operations
@deffn {Scheme Procedure} logand n1 n2
Return the bitwise AND of the integer arguments.
@lisp
(logand) @result{} -1
(logand 7) @result{} 7
(logand #b111 #b011 #b001) @result{} 1
@end lisp
@end deffn
@deffn {Scheme Procedure} logior n1 n2
Return the bitwise OR of the integer arguments.
@lisp
(logior) @result{} 0
(logior 7) @result{} 7
(logior #b000 #b001 #b011) @result{} 3
@end lisp
@end deffn
@deffn {Scheme Procedure} logxor n1 n2
Return the bitwise XOR of the integer arguments. A bit is
set in the result if it is set in an odd number of arguments.
@lisp
(logxor) @result{} 0
(logxor 7) @result{} 7
(logxor #b000 #b001 #b011) @result{} 2
(logxor #b000 #b001 #b011 #b011) @result{} 1
@end lisp
@end deffn
@deffn {Scheme Procedure} lognot n
@deffnx {C Function} scm_lognot (n)
Return the integer which is the 2s-complement of the integer
argument.
@lisp
(number->string (lognot #b10000000) 2)
@result{} "-10000001"
(number->string (lognot #b0) 2)
@result{} "-1"
@end lisp
@end deffn
@deffn {Scheme Procedure} logtest j k
@deffnx {C Function} scm_logtest (j, k)
@lisp
(logtest j k) @equiv{} (not (zero? (logand j k)))
(logtest #b0100 #b1011) @result{} #f
(logtest #b0100 #b0111) @result{} #t
@end lisp
@end deffn
@deffn {Scheme Procedure} logbit? index j
@deffnx {C Function} scm_logbit_p (index, j)
@lisp
(logbit? index j) @equiv{} (logtest (integer-expt 2 index) j)
(logbit? 0 #b1101) @result{} #t
(logbit? 1 #b1101) @result{} #f
(logbit? 2 #b1101) @result{} #t
(logbit? 3 #b1101) @result{} #t
(logbit? 4 #b1101) @result{} #f
@end lisp
@end deffn
@deffn {Scheme Procedure} ash n cnt
@deffnx {C Function} scm_ash (n, cnt)
The function ash performs an arithmetic shift left by @var{cnt}
bits (or shift right, if @var{cnt} is negative). 'Arithmetic'
means, that the function does not guarantee to keep the bit
structure of @var{n}, but rather guarantees that the result
will always be rounded towards minus infinity. Therefore, the
results of ash and a corresponding bitwise shift will differ if
@var{n} is negative.
Formally, the function returns an integer equivalent to
@code{(inexact->exact (floor (* @var{n} (expt 2 @var{cnt}))))}.
@lisp
(number->string (ash #b1 3) 2) @result{} "1000"
(number->string (ash #b1010 -1) 2) @result{} "101"
@end lisp
@end deffn
@deffn {Scheme Procedure} logcount n
@deffnx {C Function} scm_logcount (n)
Return the number of bits in integer @var{n}. If integer is
positive, the 1-bits in its binary representation are counted.
If negative, the 0-bits in its two's-complement binary
representation are counted. If 0, 0 is returned.
@lisp
(logcount #b10101010)
@result{} 4
(logcount 0)
@result{} 0
(logcount -2)
@result{} 1
@end lisp
@end deffn
@deffn {Scheme Procedure} integer-length n
@deffnx {C Function} scm_integer_length (n)
Return the number of bits neccessary to represent @var{n}.
@lisp
(integer-length #b10101010)
@result{} 8
(integer-length 0)
@result{} 0
(integer-length #b1111)
@result{} 4
@end lisp
@end deffn
@deffn {Scheme Procedure} integer-expt n k
@deffnx {C Function} scm_integer_expt (n, k)
Return @var{n} raised to the non-negative integer exponent
@var{k}.
@lisp
(integer-expt 2 5)
@result{} 32
(integer-expt -3 3)
@result{} -27
@end lisp
@end deffn
@deffn {Scheme Procedure} bit-extract n start end
@deffnx {C Function} scm_bit_extract (n, start, end)
Return the integer composed of the @var{start} (inclusive)
through @var{end} (exclusive) bits of @var{n}. The
@var{start}th bit becomes the 0-th bit in the result.
@lisp
(number->string (bit-extract #b1101101010 0 4) 2)
@result{} "1010"
(number->string (bit-extract #b1101101010 4 9) 2)
@result{} "10110"
@end lisp
@end deffn
@node Random
@subsection Random Number Generation
@deffn {Scheme Procedure} copy-random-state [state]
@deffnx {C Function} scm_copy_random_state (state)
Return a copy of the random state @var{state}.
@end deffn
@deffn {Scheme Procedure} random n [state]
@deffnx {C Function} scm_random (n, state)
Return a number in [0,N).
Accepts a positive integer or real n and returns a
number of the same type between zero (inclusive) and
N (exclusive). The values returned have a uniform
distribution.
The optional argument @var{state} must be of the type produced
by @code{seed->random-state}. It defaults to the value of the
variable @var{*random-state*}. This object is used to maintain
the state of the pseudo-random-number generator and is altered
as a side effect of the random operation.
@end deffn
@deffn {Scheme Procedure} random:exp [state]
@deffnx {C Function} scm_random_exp (state)
Return an inexact real in an exponential distribution with mean
1. For an exponential distribution with mean u use (* u
(random:exp)).
@end deffn
@deffn {Scheme Procedure} random:hollow-sphere! v [state]
@deffnx {C Function} scm_random_hollow_sphere_x (v, state)
Fills vect with inexact real random numbers
the sum of whose squares is equal to 1.0.
Thinking of vect as coordinates in space of
dimension n = (vector-length vect), the coordinates
are uniformly distributed over the surface of the
unit n-sphere.
@end deffn
@deffn {Scheme Procedure} random:normal [state]
@deffnx {C Function} scm_random_normal (state)
Return an inexact real in a normal distribution. The
distribution used has mean 0 and standard deviation 1. For a
normal distribution with mean m and standard deviation d use
@code{(+ m (* d (random:normal)))}.
@end deffn
@deffn {Scheme Procedure} random:normal-vector! v [state]
@deffnx {C Function} scm_random_normal_vector_x (v, state)
Fills vect with inexact real random numbers that are
independent and standard normally distributed
(i.e., with mean 0 and variance 1).
@end deffn
@deffn {Scheme Procedure} random:solid-sphere! v [state]
@deffnx {C Function} scm_random_solid_sphere_x (v, state)
Fills vect with inexact real random numbers
the sum of whose squares is less than 1.0.
Thinking of vect as coordinates in space of
dimension n = (vector-length vect), the coordinates
are uniformly distributed within the unit n-sphere.
The sum of the squares of the numbers is returned.
@end deffn
@deffn {Scheme Procedure} random:uniform [state]
@deffnx {C Function} scm_random_uniform (state)
Return a uniformly distributed inexact real random number in
[0,1).
@end deffn
@deffn {Scheme Procedure} seed->random-state seed
@deffnx {C Function} scm_seed_to_random_state (seed)
Return a new random state using @var{seed}.
@end deffn
@node Characters
@section Characters
@tpindex Characters
Most of the characters in the ASCII character set may be referred to by
name: for example, @code{#\tab}, @code{#\esc}, @code{#\stx}, and so on.
The following table describes the ASCII names for each character.
@multitable @columnfractions .25 .25 .25 .25
@item 0 = @code{#\nul}
@tab 1 = @code{#\soh}
@tab 2 = @code{#\stx}
@tab 3 = @code{#\etx}
@item 4 = @code{#\eot}
@tab 5 = @code{#\enq}
@tab 6 = @code{#\ack}
@tab 7 = @code{#\bel}
@item 8 = @code{#\bs}
@tab 9 = @code{#\ht}
@tab 10 = @code{#\nl}
@tab 11 = @code{#\vt}
@item 12 = @code{#\np}
@tab 13 = @code{#\cr}
@tab 14 = @code{#\so}
@tab 15 = @code{#\si}
@item 16 = @code{#\dle}
@tab 17 = @code{#\dc1}
@tab 18 = @code{#\dc2}
@tab 19 = @code{#\dc3}
@item 20 = @code{#\dc4}
@tab 21 = @code{#\nak}
@tab 22 = @code{#\syn}
@tab 23 = @code{#\etb}
@item 24 = @code{#\can}
@tab 25 = @code{#\em}
@tab 26 = @code{#\sub}
@tab 27 = @code{#\esc}
@item 28 = @code{#\fs}
@tab 29 = @code{#\gs}
@tab 30 = @code{#\rs}
@tab 31 = @code{#\us}
@item 32 = @code{#\sp}
@end multitable
The @code{delete} character (octal 177) may be referred to with the name
@code{#\del}.
Several characters have more than one name:
@itemize @bullet
@item
@code{#\space}, @code{#\sp}
@item
@code{#\newline}, @code{#\nl}
@item
@code{#\tab}, @code{#\ht}
@item
@code{#\backspace}, @code{#\bs}
@item
@code{#\return}, @code{#\cr}
@item
@code{#\page}, @code{#\np}
@item
@code{#\null}, @code{#\nul}
@end itemize
@rnindex char?
@deffn {Scheme Procedure} char? x
@deffnx {C Function} scm_char_p (x)
Return @code{#t} iff @var{x} is a character, else @code{#f}.
@end deffn
@rnindex char=?
@deffn {Scheme Procedure} char=? x y
Return @code{#t} iff @var{x} is the same character as @var{y}, else @code{#f}.
@end deffn
@rnindex char<?
@deffn {Scheme Procedure} char<? x y
Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence,
else @code{#f}.
@end deffn
@rnindex char<=?
@deffn {Scheme Procedure} char<=? x y
Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
ASCII sequence, else @code{#f}.
@end deffn
@rnindex char>?
@deffn {Scheme Procedure} char>? x y
Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
sequence, else @code{#f}.
@end deffn
@rnindex char>=?
@deffn {Scheme Procedure} char>=? x y
Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
ASCII sequence, else @code{#f}.
@end deffn
@rnindex char-ci=?
@deffn {Scheme Procedure} char-ci=? x y
Return @code{#t} iff @var{x} is the same character as @var{y} ignoring
case, else @code{#f}.
@end deffn
@rnindex char-ci<?
@deffn {Scheme Procedure} char-ci<? x y
Return @code{#t} iff @var{x} is less than @var{y} in the ASCII sequence
ignoring case, else @code{#f}.
@end deffn
@rnindex char-ci<=?
@deffn {Scheme Procedure} char-ci<=? x y
Return @code{#t} iff @var{x} is less than or equal to @var{y} in the
ASCII sequence ignoring case, else @code{#f}.
@end deffn
@rnindex char-ci>?
@deffn {Scheme Procedure} char-ci>? x y
Return @code{#t} iff @var{x} is greater than @var{y} in the ASCII
sequence ignoring case, else @code{#f}.
@end deffn
@rnindex char-ci>=?
@deffn {Scheme Procedure} char-ci>=? x y
Return @code{#t} iff @var{x} is greater than or equal to @var{y} in the
ASCII sequence ignoring case, else @code{#f}.
@end deffn
@rnindex char-alphabetic?
@deffn {Scheme Procedure} char-alphabetic? chr
@deffnx {C Function} scm_char_alphabetic_p (chr)
Return @code{#t} iff @var{chr} is alphabetic, else @code{#f}.
Alphabetic means the same thing as the isalpha C library function.
@end deffn
@rnindex char-numeric?
@deffn {Scheme Procedure} char-numeric? chr
@deffnx {C Function} scm_char_numeric_p (chr)
Return @code{#t} iff @var{chr} is numeric, else @code{#f}.
Numeric means the same thing as the isdigit C library function.
@end deffn
@rnindex char-whitespace?
@deffn {Scheme Procedure} char-whitespace? chr
@deffnx {C Function} scm_char_whitespace_p (chr)
Return @code{#t} iff @var{chr} is whitespace, else @code{#f}.
Whitespace means the same thing as the isspace C library function.
@end deffn
@rnindex char-upper-case?
@deffn {Scheme Procedure} char-upper-case? chr
@deffnx {C Function} scm_char_upper_case_p (chr)
Return @code{#t} iff @var{chr} is uppercase, else @code{#f}.
Uppercase means the same thing as the isupper C library function.
@end deffn
@rnindex char-lower-case?
@deffn {Scheme Procedure} char-lower-case? chr
@deffnx {C Function} scm_char_lower_case_p (chr)
Return @code{#t} iff @var{chr} is lowercase, else @code{#f}.
Lowercase means the same thing as the islower C library function.
@end deffn
@deffn {Scheme Procedure} char-is-both? chr
@deffnx {C Function} scm_char_is_both_p (chr)
Return @code{#t} iff @var{chr} is either uppercase or lowercase, else @code{#f}.
Uppercase and lowercase are as defined by the isupper and islower
C library functions.
@end deffn
@rnindex char->integer
@deffn {Scheme Procedure} char->integer chr
@deffnx {C Function} scm_char_to_integer (chr)
Return the number corresponding to ordinal position of @var{chr} in the
ASCII sequence.
@end deffn
@rnindex integer->char
@deffn {Scheme Procedure} integer->char n
@deffnx {C Function} scm_integer_to_char (n)
Return the character at position @var{n} in the ASCII sequence.
@end deffn
@rnindex char-upcase
@deffn {Scheme Procedure} char-upcase chr
@deffnx {C Function} scm_char_upcase (chr)
Return the uppercase character version of @var{chr}.
@end deffn
@rnindex char-downcase
@deffn {Scheme Procedure} char-downcase chr
@deffnx {C Function} scm_char_downcase (chr)
Return the lowercase character version of @var{chr}.
@end deffn
@node Strings
@section Strings
@tpindex Strings
Strings are fixed-length sequences of characters. They can be created
by calling constructor procedures, but they can also literally get
entered at the REPL or in Scheme source files.
Guile provides a rich set of string processing procedures, because text
handling is very important when Guile is used as a scripting language.
Strings always carry the information about how many characters they are
composed of with them, so there is no special end-of-string character,
like in C. That means that Scheme strings can contain any character,
even the NUL character @code{'\0'}. But note: Since most operating
system calls dealing with strings (such as for file operations) expect
strings to be zero-terminated, they might do unexpected things when
called with string containing unusal characters.
@menu
* String Syntax:: Read syntax for strings.
* String Predicates:: Testing strings for certain properties.
* String Constructors:: Creating new string objects.
* List/String Conversion:: Converting from/to lists of characters.
* String Selection:: Select portions from strings.
* String Modification:: Modify parts or whole strings.
* String Comparison:: Lexicographic ordering predicates.
* String Searching:: Searching in strings.
* Alphabetic Case Mapping:: Convert the alphabetic case of strings.
* Appending Strings:: Appending strings to form a new string.
@end menu
@node String Syntax
@subsection String Read Syntax
The read syntax for strings is an arbitrarily long sequence of
characters enclosed in double quotes (@code{"}). @footnote{Actually, the
current implementation restricts strings to a length of 2^24
characters.} If you want to insert a double quote character into a
string literal, it must be prefixed with a backslash @code{\} character
(called an @dfn{escape character}).
The following are examples of string literals:
@lisp
"foo"
"bar plonk"
"Hello World"
"\"Hi\", he said."
@end lisp
@c FIXME::martin: What about escape sequences like \r, \n etc.?
@node String Predicates
@subsection String Predicates
The following procedures can be used to check whether a given string
fulfills some specified property.
@rnindex string?
@deffn {Scheme Procedure} string? obj
@deffnx {C Function} scm_string_p (obj)
Return @code{#t} iff @var{obj} is a string, else @code{#f}.
@end deffn
@deffn {Scheme Procedure} string-null? str
@deffnx {C Function} scm_string_null_p (str)
Return @code{#t} if @var{str}'s length is zero, and
@code{#f} otherwise.
@lisp
(string-null? "") @result{} #t
y @result{} "foo"
(string-null? y) @result{} #f
@end lisp
@end deffn
@node String Constructors
@subsection String Constructors
The string constructor procedures create new string objects, possibly
initializing them with some specified character data.
@c FIXME::martin: list->string belongs into `List/String Conversion'
@rnindex string
@rnindex list->string
@deffn {Scheme Procedure} string . chrs
@deffnx {Scheme Procedure} list->string chrs
@deffnx {C Function} scm_string (chrs)
Return a newly allocated string composed of the arguments,
@var{chrs}.
@end deffn
@rnindex make-string
@deffn {Scheme Procedure} make-string k [chr]
@deffnx {C Function} scm_make_string (k, chr)
Return a newly allocated string of
length @var{k}. If @var{chr} is given, then all elements of
the string are initialized to @var{chr}, otherwise the contents
of the @var{string} are unspecified.
@end deffn
@node List/String Conversion
@subsection List/String conversion
When processing strings, it is often convenient to first convert them
into a list representation by using the procedure @code{string->list},
work with the resulting list, and then convert it back into a string.
These procedures are useful for similar tasks.
@rnindex string->list
@deffn {Scheme Procedure} string->list str
@deffnx {C Function} scm_string_to_list (str)
Return a newly allocated list of the characters that make up
the given string @var{str}. @code{string->list} and
@code{list->string} are inverses as far as @samp{equal?} is
concerned.
@end deffn
@deffn {Scheme Procedure} string-split str chr
@deffnx {C Function} scm_string_split (str, chr)
Split the string @var{str} into the a list of the substrings delimited
by appearances of the character @var{chr}. Note that an empty substring
between separator characters will result in an empty string in the
result list.
@lisp
(string-split "root:x:0:0:root:/root:/bin/bash" #\:)
@result{}
("root" "x" "0" "0" "root" "/root" "/bin/bash")
(string-split "::" #\:)
@result{}
("" "" "")
(string-split "" #\:)
@result{}
("")
@end lisp
@end deffn
@node String Selection
@subsection String Selection
Portions of strings can be extracted by these procedures.
@code{string-ref} delivers individual characters whereas
@code{substring} can be used to extract substrings from longer strings.
@rnindex string-length
@deffn {Scheme Procedure} string-length string
@deffnx {C Function} scm_string_length (string)
Return the number of characters in @var{string}.
@end deffn
@rnindex string-ref
@deffn {Scheme Procedure} string-ref str k
@deffnx {C Function} scm_string_ref (str, k)
Return character @var{k} of @var{str} using zero-origin
indexing. @var{k} must be a valid index of @var{str}.
@end deffn
@rnindex string-copy
@deffn {Scheme Procedure} string-copy str
@deffnx {C Function} scm_string_copy (str)
Return a newly allocated copy of the given @var{string}.
@end deffn
@rnindex substring
@deffn {Scheme Procedure} substring str start [end]
@deffnx {C Function} scm_substring (str, start, end)
Return a newly allocated string formed from the characters
of @var{str} beginning with index @var{start} (inclusive) and
ending with index @var{end} (exclusive).
@var{str} must be a string, @var{start} and @var{end} must be
exact integers satisfying:
0 <= @var{start} <= @var{end} <= (string-length @var{str}).
@end deffn
@node String Modification
@subsection String Modification
These procedures are for modifying strings in-place. This means that the
result of the operation is not a new string; instead, the original string's
memory representation is modified.
@rnindex string-set!
@deffn {Scheme Procedure} string-set! str k chr
@deffnx {C Function} scm_string_set_x (str, k, chr)
Store @var{chr} in element @var{k} of @var{str} and return
an unspecified value. @var{k} must be a valid index of
@var{str}.
@end deffn
@rnindex string-fill!
@deffn {Scheme Procedure} string-fill! str chr
@deffnx {C Function} scm_string_fill_x (str, chr)
Store @var{char} in every element of the given @var{string} and
return an unspecified value.
@end deffn
@deffn {Scheme Procedure} substring-fill! str start end fill
@deffnx {C Function} scm_substring_fill_x (str, start, end, fill)
Change every character in @var{str} between @var{start} and
@var{end} to @var{fill}.
@lisp
(define y "abcdefg")
(substring-fill! y 1 3 #\r)
y
@result{} "arrdefg"
@end lisp
@end deffn
@deffn {Scheme Procedure} substring-move! str1 start1 end1 str2 start2
@deffnx {C Function} scm_substring_move_x (str1, start1, end1, str2, start2)
Copy the substring of @var{str1} bounded by @var{start1} and @var{end1}
into @var{str2} beginning at position @var{start2}.
@var{str1} and @var{str2} can be the same string.
@end deffn
@node String Comparison
@subsection String Comparison
The procedures in this section are similar to the character ordering
predicates (@pxref{Characters}), but are defined on character sequences.
They all return @code{#t} on success and @code{#f} on failure. The
predicates ending in @code{-ci} ignore the character case when comparing
strings.
@rnindex string=?
@deffn {Scheme Procedure} string=? s1 s2
Lexicographic equality predicate; return @code{#t} if the two
strings are the same length and contain the same characters in
the same positions, otherwise return @code{#f}.
The procedure @code{string-ci=?} treats upper and lower case
letters as though they were the same character, but
@code{string=?} treats upper and lower case as distinct
characters.
@end deffn
@rnindex string<?
@deffn {Scheme Procedure} string<? s1 s2
Lexicographic ordering predicate; return @code{#t} if @var{s1}
is lexicographically less than @var{s2}.
@end deffn
@rnindex string<=?
@deffn {Scheme Procedure} string<=? s1 s2
Lexicographic ordering predicate; return @code{#t} if @var{s1}
is lexicographically less than or equal to @var{s2}.
@end deffn
@rnindex string>?
@deffn {Scheme Procedure} string>? s1 s2
Lexicographic ordering predicate; return @code{#t} if @var{s1}
is lexicographically greater than @var{s2}.
@end deffn
@rnindex string>=?
@deffn {Scheme Procedure} string>=? s1 s2
Lexicographic ordering predicate; return @code{#t} if @var{s1}
is lexicographically greater than or equal to @var{s2}.
@end deffn
@rnindex string-ci=?
@deffn {Scheme Procedure} string-ci=? s1 s2
Case-insensitive string equality predicate; return @code{#t} if
the two strings are the same length and their component
characters match (ignoring case) at each position; otherwise
return @code{#f}.
@end deffn
@rnindex string-ci<
@deffn {Scheme Procedure} string-ci<? s1 s2
Case insensitive lexicographic ordering predicate; return
@code{#t} if @var{s1} is lexicographically less than @var{s2}
regardless of case.
@end deffn
@rnindex string<=?
@deffn {Scheme Procedure} string-ci<=? s1 s2
Case insensitive lexicographic ordering predicate; return
@code{#t} if @var{s1} is lexicographically less than or equal
to @var{s2} regardless of case.
@end deffn
@rnindex string-ci>?
@deffn {Scheme Procedure} string-ci>? s1 s2
Case insensitive lexicographic ordering predicate; return
@code{#t} if @var{s1} is lexicographically greater than
@var{s2} regardless of case.
@end deffn
@rnindex string-ci>=?
@deffn {Scheme Procedure} string-ci>=? s1 s2
Case insensitive lexicographic ordering predicate; return
@code{#t} if @var{s1} is lexicographically greater than or
equal to @var{s2} regardless of case.
@end deffn
@node String Searching
@subsection String Searching
When searching for the index of a character in a string, these
procedures can be used.
@deffn {Scheme Procedure} string-index str chr [frm [to]]
@deffnx {C Function} scm_string_index (str, chr, frm, to)
Return the index of the first occurrence of @var{chr} in
@var{str}. The optional integer arguments @var{frm} and
@var{to} limit the search to a portion of the string. This
procedure essentially implements the @code{index} or
@code{strchr} functions from the C library.
@lisp
(string-index "weiner" #\e)
@result{} 1
(string-index "weiner" #\e 2)
@result{} 4
(string-index "weiner" #\e 2 4)
@result{} #f
@end lisp
@end deffn
@deffn {Scheme Procedure} string-rindex str chr [frm [to]]
@deffnx {C Function} scm_string_rindex (str, chr, frm, to)
Like @code{string-index}, but search from the right of the
string rather than from the left. This procedure essentially
implements the @code{rindex} or @code{strrchr} functions from
the C library.
@lisp
(string-rindex "weiner" #\e)
@result{} 4
(string-rindex "weiner" #\e 2 4)
@result{} #f
(string-rindex "weiner" #\e 2 5)
@result{} 4
@end lisp
@end deffn
@node Alphabetic Case Mapping
@subsection Alphabetic Case Mapping
These are procedures for mapping strings to their upper- or lower-case
equivalents, respectively, or for capitalizing strings.
@deffn {Scheme Procedure} string-upcase str
@deffnx {C Function} scm_string_upcase (str)
Return a freshly allocated string containing the characters of
@var{str} in upper case.
@end deffn
@deffn {Scheme Procedure} string-upcase! str
@deffnx {C Function} scm_string_upcase_x (str)
Destructively upcase every character in @var{str} and return
@var{str}.
@lisp
y @result{} "arrdefg"
(string-upcase! y) @result{} "ARRDEFG"
y @result{} "ARRDEFG"
@end lisp
@end deffn
@deffn {Scheme Procedure} string-downcase str
@deffnx {C Function} scm_string_downcase (str)
Return a freshly allocation string containing the characters in
@var{str} in lower case.
@end deffn
@deffn {Scheme Procedure} string-downcase! str
@deffnx {C Function} scm_string_downcase_x (str)
Destructively downcase every character in @var{str} and return
@var{str}.
@lisp
y @result{} "ARRDEFG"
(string-downcase! y) @result{} "arrdefg"
y @result{} "arrdefg"
@end lisp
@end deffn
@deffn {Scheme Procedure} string-capitalize str
@deffnx {C Function} scm_string_capitalize (str)
Return a freshly allocated string with the characters in
@var{str}, where the first character of every word is
capitalized.
@end deffn
@deffn {Scheme Procedure} string-capitalize! str
@deffnx {C Function} scm_string_capitalize_x (str)
Upcase the first character of every word in @var{str}
destructively and return @var{str}.
@lisp
y @result{} "hello world"
(string-capitalize! y) @result{} "Hello World"
y @result{} "Hello World"
@end lisp
@end deffn
@node Appending Strings
@subsection Appending Strings
The procedure @code{string-append} appends several strings together to
form a longer result string.
@rnindex string-append
@deffn {Scheme Procedure} string-append . args
@deffnx {C Function} scm_string_append (args)
Return a newly allocated string whose characters form the
concatenation of the given strings, @var{args}.
@end deffn
@node Regular Expressions
@section Regular Expressions
@tpindex Regular expressions
@cindex regular expressions
@cindex regex
@cindex emacs regexp
A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
describes a whole class of strings. A full description of regular
expressions and their syntax is beyond the scope of this manual;
an introduction can be found in the Emacs manual (@pxref{Regexps,
, Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
in many general Unix reference books.
If your system does not include a POSIX regular expression library, and
you have not linked Guile with a third-party regexp library such as Rx,
these functions will not be available. You can tell whether your Guile
installation includes regular expression support by checking whether the
@code{*features*} list includes the @code{regex} symbol.
@menu
* Regexp Functions:: Functions that create and match regexps.
* Match Structures:: Finding what was matched by a regexp.
* Backslash Escapes:: Removing the special meaning of regexp metacharacters.
@end menu
[FIXME: it may be useful to include an Examples section. Parts of this
interface are bewildering on first glance.]
@node Regexp Functions
@subsection Regexp Functions
By default, Guile supports POSIX extended regular expressions.
That means that the characters @samp{(}, @samp{)}, @samp{+} and
@samp{?} are special, and must be escaped if you wish to match the
literal characters.
This regular expression interface was modeled after that
implemented by SCSH, the Scheme Shell. It is intended to be
upwardly compatible with SCSH regular expressions.
@c begin (scm-doc-string "regex.scm" "string-match")
@deffn {Scheme Procedure} string-match pattern str [start]
Compile the string @var{pattern} into a regular expression and compare
it with @var{str}. The optional numeric argument @var{start} specifies
the position of @var{str} at which to begin matching.
@code{string-match} returns a @dfn{match structure} which
describes what, if anything, was matched by the regular
expression. @xref{Match Structures}. If @var{str} does not match
@var{pattern} at all, @code{string-match} returns @code{#f}.
@end deffn
Each time @code{string-match} is called, it must compile its
@var{pattern} argument into a regular expression structure. This
operation is expensive, which makes @code{string-match} inefficient if
the same regular expression is used several times (for example, in a
loop). For better performance, you can compile a regular expression in
advance and then match strings against the compiled regexp.
@deffn {Scheme Procedure} make-regexp pat . flags
@deffnx {C Function} scm_make_regexp (pat, flags)
Compile the regular expression described by @var{pat}, and
return the compiled regexp structure. If @var{pat} does not
describe a legal regular expression, @code{make-regexp} throws
a @code{regular-expression-syntax} error.
The @var{flags} arguments change the behavior of the compiled
regular expression. The following flags may be supplied:
@table @code
@item regexp/icase
Consider uppercase and lowercase letters to be the same when
matching.
@item regexp/newline
If a newline appears in the target string, then permit the
@samp{^} and @samp{$} operators to match immediately after or
immediately before the newline, respectively. Also, the
@samp{.} and @samp{[^...]} operators will never match a newline
character. The intent of this flag is to treat the target
string as a buffer containing many lines of text, and the
regular expression as a pattern that may match a single one of
those lines.
@item regexp/basic
Compile a basic (``obsolete'') regexp instead of the extended
(``modern'') regexps that are the default. Basic regexps do
not consider @samp{|}, @samp{+} or @samp{?} to be special
characters, and require the @samp{@{...@}} and @samp{(...)}
metacharacters to be backslash-escaped (@pxref{Backslash
Escapes}). There are several other differences between basic
and extended regular expressions, but these are the most
significant.
@item regexp/extended
Compile an extended regular expression rather than a basic
regexp. This is the default behavior; this flag will not
usually be needed. If a call to @code{make-regexp} includes
both @code{regexp/basic} and @code{regexp/extended} flags, the
one which comes last will override the earlier one.
@end table
@end deffn
@deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
@deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
Match the compiled regular expression @var{rx} against
@code{str}. If the optional integer @var{start} argument is
provided, begin matching from that position in the string.
Return a match structure describing the results of the match,
or @code{#f} if no match could be found.
The @var{flags} arguments change the matching behavior.
The following flags may be supplied:
@table @code
@item regexp/notbol
Operator @samp{^} always fails (unless @code{regexp/newline}
is used). Use this when the beginning of the string should
not be considered the beginning of a line.
@item regexp/noteol
Operator @samp{$} always fails (unless @code{regexp/newline}
is used). Use this when the end of the string should not be
considered the end of a line.
@end table
@end deffn
@deffn {Scheme Procedure} regexp? obj
@deffnx {C Function} scm_regexp_p (obj)
Return @code{#t} if @var{obj} is a compiled regular expression,
or @code{#f} otherwise.
@end deffn
Regular expressions are commonly used to find patterns in one string and
replace them with the contents of another string.
@c begin (scm-doc-string "regex.scm" "regexp-substitute")
@deffn {Scheme Procedure} regexp-substitute port match [item@dots{}]
Write to the output port @var{port} selected contents of the match
structure @var{match}. Each @var{item} specifies what should be
written, and may be one of the following arguments:
@itemize @bullet
@item
A string. String arguments are written out verbatim.
@item
An integer. The submatch with that number is written.
@item
The symbol @samp{pre}. The portion of the matched string preceding
the regexp match is written.
@item
The symbol @samp{post}. The portion of the matched string following
the regexp match is written.
@end itemize
@var{port} may be @code{#f}, in which case nothing is written; instead,
@code{regexp-substitute} constructs a string from the specified
@var{item}s and returns that.
@end deffn
@c begin (scm-doc-string "regex.scm" "regexp-substitute")
@deffn {Scheme Procedure} regexp-substitute/global port regexp target [item@dots{}]
Similar to @code{regexp-substitute}, but can be used to perform global
substitutions on @var{str}. Instead of taking a match structure as an
argument, @code{regexp-substitute/global} takes two string arguments: a
@var{regexp} string describing a regular expression, and a @var{target}
string which should be matched against this regular expression.
Each @var{item} behaves as in @var{regexp-substitute}, with the
following exceptions:
@itemize @bullet
@item
A function may be supplied. When this function is called, it will be
passed one argument: a match structure for a given regular expression
match. It should return a string to be written out to @var{port}.
@item
The @samp{post} symbol causes @code{regexp-substitute/global} to recurse
on the unmatched portion of @var{str}. This @emph{must} be supplied in
order to perform global search-and-replace on @var{str}; if it is not
present among the @var{item}s, then @code{regexp-substitute/global} will
return after processing a single match.
@end itemize
@end deffn
@node Match Structures
@subsection Match Structures
@cindex match structures
A @dfn{match structure} is the object returned by @code{string-match} and
@code{regexp-exec}. It describes which portion of a string, if any,
matched the given regular expression. Match structures include: a
reference to the string that was checked for matches; the starting and
ending positions of the regexp match; and, if the regexp included any
parenthesized subexpressions, the starting and ending positions of each
submatch.
In each of the regexp match functions described below, the @code{match}
argument must be a match structure returned by a previous call to
@code{string-match} or @code{regexp-exec}. Most of these functions
return some information about the original target string that was
matched against a regular expression; we will call that string
@var{target} for easy reference.
@c begin (scm-doc-string "regex.scm" "regexp-match?")
@deffn {Scheme Procedure} regexp-match? obj
Return @code{#t} if @var{obj} is a match structure returned by a
previous call to @code{regexp-exec}, or @code{#f} otherwise.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:substring")
@deffn {Scheme Procedure} match:substring match [n]
Return the portion of @var{target} matched by subexpression number
@var{n}. Submatch 0 (the default) represents the entire regexp match.
If the regular expression as a whole matched, but the subexpression
number @var{n} did not match, return @code{#f}.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:start")
@deffn {Scheme Procedure} match:start match [n]
Return the starting position of submatch number @var{n}.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:end")
@deffn {Scheme Procedure} match:end match [n]
Return the ending position of submatch number @var{n}.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:prefix")
@deffn {Scheme Procedure} match:prefix match
Return the unmatched portion of @var{target} preceding the regexp match.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:suffix")
@deffn {Scheme Procedure} match:suffix match
Return the unmatched portion of @var{target} following the regexp match.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:count")
@deffn {Scheme Procedure} match:count match
Return the number of parenthesized subexpressions from @var{match}.
Note that the entire regular expression match itself counts as a
subexpression, and failed submatches are included in the count.
@end deffn
@c begin (scm-doc-string "regex.scm" "match:string")
@deffn {Scheme Procedure} match:string match
Return the original @var{target} string.
@end deffn
@node Backslash Escapes
@subsection Backslash Escapes
Sometimes you will want a regexp to match characters like @samp{*} or
@samp{$} exactly. For example, to check whether a particular string
represents a menu entry from an Info node, it would be useful to match
it against a regexp like @samp{^* [^:]*::}. However, this won't work;
because the asterisk is a metacharacter, it won't match the @samp{*} at
the beginning of the string. In this case, we want to make the first
asterisk un-magic.
You can do this by preceding the metacharacter with a backslash
character @samp{\}. (This is also called @dfn{quoting} the
metacharacter, and is known as a @dfn{backslash escape}.) When Guile
sees a backslash in a regular expression, it considers the following
glyph to be an ordinary character, no matter what special meaning it
would ordinarily have. Therefore, we can make the above example work by
changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
the regular expression engine to match only a single asterisk in the
target string.
Since the backslash is itself a metacharacter, you may force a regexp to
match a backslash in the target string by preceding the backslash with
itself. For example, to find variable references in a @TeX{} program,
you might want to find occurrences of the string @samp{\let\} followed
by any number of alphabetic characters. The regular expression
@samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
regexp each match a single backslash in the target string.
@c begin (scm-doc-string "regex.scm" "regexp-quote")
@deffn {Scheme Procedure} regexp-quote str
Quote each special character found in @var{str} with a backslash, and
return the resulting string.
@end deffn
@strong{Very important:} Using backslash escapes in Guile source code
(as in Emacs Lisp or C) can be tricky, because the backslash character
has special meaning for the Guile reader. For example, if Guile
encounters the character sequence @samp{\n} in the middle of a string
while processing Scheme code, it replaces those characters with a
newline character. Similarly, the character sequence @samp{\t} is
replaced by a horizontal tab. Several of these @dfn{escape sequences}
are processed by the Guile reader before your code is executed.
Unrecognized escape sequences are ignored: if the characters @samp{\*}
appear in a string, they will be translated to the single character
@samp{*}.
This translation is obviously undesirable for regular expressions, since
we want to be able to include backslashes in a string in order to
escape regexp metacharacters. Therefore, to make sure that a backslash
is preserved in a string in your Guile program, you must use @emph{two}
consecutive backslashes:
@lisp
(define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
@end lisp
The string in this example is preprocessed by the Guile reader before
any code is executed. The resulting argument to @code{make-regexp} is
the string @samp{^\* [^:]*}, which is what we really want.
This also means that in order to write a regular expression that matches
a single backslash character, the regular expression string in the
source code must include @emph{four} backslashes. Each consecutive pair
of backslashes gets translated by the Guile reader to a single
backslash, and the resulting double-backslash is interpreted by the
regexp engine as matching a single backslash character. Hence:
@lisp
(define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
@end lisp
The reason for the unwieldiness of this syntax is historical. Both
regular expression pattern matchers and Unix string processing systems
have traditionally used backslashes with the special meanings
described above. The POSIX regular expression specification and ANSI C
standard both require these semantics. Attempting to abandon either
convention would cause other kinds of compatibility problems, possibly
more severe ones. Therefore, without extending the Scheme reader to
support strings with different quoting conventions (an ungainly and
confusing extension when implemented in other languages), we must adhere
to this cumbersome escape syntax.
@node Symbols
@section Symbols
@tpindex Symbols
Symbols have two main uses. Crucially, they are used for denoting
variables in a Scheme program. In addition, they are very useful for
describing discrete literal data.
A symbol is an object with a name that consists of a string of
characters. In the usual case (where the name doesn't include any
characters that could be confused with other elements of Scheme syntax)
a symbol can be written in a Scheme program by writing the sequence of
characters that make up the symbol's name. For example, the read syntax
for the symbol named "multiply-by-2" is simply
@lisp
multiply-by-2
@end lisp
Symbols, then, look rather like strings but without any quotation marks.
But there are several functional differences between them. The first
big functional difference between symbols and strings concerns
uniqueness. If the same-looking string is read twice from two different
places in a program, the result is two @emph{distinguishable} string
objects whose contents just happen to be the same. If, on the other
hand, the same-looking symbol is read twice from two different places in
a program, the result is the @emph{same} symbol object both times.
@lisp
(define str1 "hello")
(define str2 "hello")
(eq? str1 str2) @result{} #f
(define sym1 (quote hello))
(define sym2 (quote hello))
(eq? sym1 sym2) @result{} #t
@end lisp
The second important difference is that symbols, unlike strings, are not
self-evaluating. An unquoted symbol is interpreted as a variable
reference, and the result of evaluating that symbol is the corresponding
variable's value. (By the way, this is why we needed the @code{(quote
@dots{})}s in the example above: @code{(quote hello)} returns the symbol
object named "hello" itself, whereas an unquoted @code{hello} would try
to find and dereference a variable associated with that symbol.)
For example, when the expression @code{(string-length "abcd")} is read
and evaluated, the sequence of characters @code{string-length} is read
as the symbol whose name is "string-length". This symbol is associated
with a variable whose value is the procedure that implements string
length calculation. Therefore evaluation of the @code{string-length}
symbol results in that procedure.
Although the use of symbols for variable references is undoubtedly their
most important role in Scheme, it is not documented further here. See
instead @ref{Binding Constructs}, for how associations between symbols
and variables are created, and @ref{Modules}, for how those associations
are affected by Guile's module system. The rest of this section
explains how symbols can also be used to represent discrete values, and
documents the procedures available that relate to symbols as data
objects @i{per se}.
@menu
* Symbol Read Syntax:: Extended read syntax for symbols.
* Symbol Primitives:: Operations related to symbols.
* Symbol Discrete:: Using symbols as discrete values.
* Symbol Props:: Function slots and property lists.
@end menu
@node Symbol Read Syntax
@subsection Extended Read Syntax for Symbols
The read syntax for symbols is a sequence of letters, digits, and
@dfn{extended alphabetic characters}, beginning with a character that
cannot begin a number. In addition, the special cases of @code{+},
@code{-}, and @code{...} are read as symbols even though numbers can
begin with @code{+}, @code{-} or @code{.}.
Extended alphabetic characters may be used within identifiers as if
they were letters. The set of extended alphabetic characters is:
@example
! $ % & * + - . / : < = > ? @@ ^ _ ~
@end example
In addition to the standard read syntax defined above (which is taken
from R5RS (@pxref{Formal syntax,,,r5rs,The Revised^5 Report on
Scheme})), Guile provides an extended symbol read syntax that allows the
inclusion of unusual characters such as space characters, newlines and
parentheses. If (for whatever reason) you need to write a symbol
containing characters not mentioned above, you can do so as follows.
@itemize @bullet
@item
Begin the symbol with the characters @code{#@{},
@item
write the characters of the symbol and
@item
finish the symbol with the characters @code{@}#}.
@end itemize
Here are a few examples of this form of read syntax. The first symbol
needs to use extended syntax because it contains a space character, the
second because it contains a line break, and the last because it looks
like a number.
@lisp
#@{foo bar@}#
#@{what
ever@}#
#@{4242@}#
@end lisp
Although Guile provides this extended read syntax for symbols,
widespread usage of it is discouraged because it is not portable and not
very readable.
@node Symbol Primitives
@subsection Operations Related to Symbols
@rnindex symbol?
@deffn {Scheme Procedure} symbol? obj
@deffnx {C Function} scm_symbol_p (obj)
Return @code{#t} if @var{obj} is a symbol, otherwise return
@code{#f}.
@end deffn
@rnindex string->symbol
@deffn {Scheme Procedure} string->symbol string
@deffnx {C Function} scm_string_to_symbol (string)
Return the symbol whose name is @var{string}. This procedure
can create symbols with names containing special characters or
letters in the non-standard case, but it is usually a bad idea
to create such symbols because in some implementations of
Scheme they cannot be read as themselves. See
@code{symbol->string}.
The following examples assume that the implementation's
standard case is lower case:
@lisp
(eq? 'mISSISSIppi 'mississippi) @result{} #t
(string->symbol "mISSISSIppi") @result{} @r{the symbol with name "mISSISSIppi"}
(eq? 'bitBlt (string->symbol "bitBlt")) @result{} #f
(eq? 'JollyWog
(string->symbol (symbol->string 'JollyWog))) @result{} #t
(string=? "K. Harper, M.D."
(symbol->string
(string->symbol "K. Harper, M.D."))) @result{}#t
@end lisp
@end deffn
@deffn {Scheme Procedure} string-ci->symbol str
@deffnx {C Function} scm_string_ci_to_symbol (str)
Return the symbol whose name is @var{str}. @var{str} is
converted to lowercase before the conversion is done, if Guile
is currently reading symbols case-insensitively.
@end deffn
@rnindex symbol->string
@deffn {Scheme Procedure} symbol->string s
@deffnx {C Function} scm_symbol_to_string (s)
Return the name of @var{symbol} as a string. If the symbol was
part of an object returned as the value of a literal expression
(section @pxref{Literal expressions,,,r5rs, The Revised^5
Report on Scheme}) or by a call to the @code{read} procedure,
and its name contains alphabetic characters, then the string
returned will contain characters in the implementation's
preferred standard case---some implementations will prefer
upper case, others lower case. If the symbol was returned by
@code{string->symbol}, the case of characters in the string
returned will be the same as the case in the string that was
passed to @code{string->symbol}. It is an error to apply
mutation procedures like @code{string-set!} to strings returned
by this procedure.
The following examples assume that the implementation's
standard case is lower case:
@lisp
(symbol->string 'flying-fish) @result{} "flying-fish"
(symbol->string 'Martin) @result{} "martin"
(symbol->string
(string->symbol "Malvina")) @result{} "Malvina"
@end lisp
@end deffn
@deffn {Scheme Procedure} symbol-hash symbol
@deffnx {C Function} scm_symbol_hash (symbol)
Return a hash value for @var{symbol}.
@end deffn
@deffn {Scheme Procedure} gensym [prefix]
@deffnx {C Function} scm_gensym (prefix)
Create a new symbol with a name constructed from a prefix and
a counter value. The string @var{prefix} can be specified as
an optional argument. Default prefix is @code{g}. The counter
is increased by 1 at each call. There is no provision for
resetting the counter.
@end deffn
@node Symbol Discrete
@subsection Using Symbols as Discrete Values
Symbols are especially useful because two symbols which are spelled the
same way are equivalent in the sense of @code{eq?}. That means that
they are actually the same Scheme object. The advantage is that symbols
can be compared extremely efficiently, although they carry more
information for the human reader than, say, numbers.
It is very common in Scheme programs to use symbols as keys in
association lists (@pxref{Association Lists}) or hash tables
(@pxref{Hash Tables}), because this usage improves the readability a
lot, and does not cause any performance loss.
@node Symbol Props
@subsection Function Slots and Property Lists
@deffn {Scheme Procedure} symbol-fref symbol
@deffnx {C Function} scm_symbol_fref (symbol)
Return the contents of @var{symbol}'s @dfn{function slot}.
@end deffn
@deffn {Scheme Procedure} symbol-fset! symbol value
@deffnx {C Function} scm_symbol_fset_x (symbol, value)
Change the binding of @var{symbol}'s function slot.
@end deffn
@deffn {Scheme Procedure} symbol-pref symbol
@deffnx {C Function} scm_symbol_pref (symbol)
Return the @dfn{property list} currently associated with @var{symbol}.
@end deffn
@deffn {Scheme Procedure} symbol-pset! symbol value
@deffnx {C Function} scm_symbol_pset_x (symbol, value)
Change the binding of @var{symbol}'s property slot.
@end deffn
@node Keywords
@section Keywords
@tpindex Keywords
Keywords are self-evaluating objects with a convenient read syntax that
makes them easy to type.
Guile's keyword support conforms to R5RS, and adds a (switchable) read
syntax extension to permit keywords to begin with @code{:} as well as
@code{#:}.
@menu
* Why Use Keywords?:: Motivation for keyword usage.
* Coding With Keywords:: How to use keywords.
* Keyword Read Syntax:: Read syntax for keywords.
* Keyword Procedures:: Procedures for dealing with keywords.
* Keyword Primitives:: The underlying primitive procedures.
@end menu
@node Why Use Keywords?
@subsection Why Use Keywords?
Keywords are useful in contexts where a program or procedure wants to be
able to accept a large number of optional arguments without making its
interface unmanageable.
To illustrate this, consider a hypothetical @code{make-window}
procedure, which creates a new window on the screen for drawing into
using some graphical toolkit. There are many parameters that the caller
might like to specify, but which could also be sensibly defaulted, for
example:
@itemize @bullet
@item
colour depth -- Default: the colour depth for the screen
@item
background colour -- Default: white
@item
width -- Default: 600
@item
height -- Default: 400
@end itemize
If @code{make-window} did not use keywords, the caller would have to
pass in a value for each possible argument, remembering the correct
argument order and using a special value to indicate the default value
for that argument:
@lisp
(make-window 'default ;; Colour depth
'default ;; Background colour
800 ;; Width
100 ;; Height
@dots{}) ;; More make-window arguments
@end lisp
With keywords, on the other hand, defaulted arguments are omitted, and
non-default arguments are clearly tagged by the appropriate keyword. As
a result, the invocation becomes much clearer:
@lisp
(make-window #:width 800 #:height 100)
@end lisp
On the other hand, for a simpler procedure with few arguments, the use
of keywords would be a hindrance rather than a help. The primitive
procedure @code{cons}, for example, would not be improved if it had to
be invoked as
@lisp
(cons #:car x #:cdr y)
@end lisp
So the decision whether to use keywords or not is purely pragmatic: use
them if they will clarify the procedure invocation at point of call.
@node Coding With Keywords
@subsection Coding With Keywords
If a procedure wants to support keywords, it should take a rest argument
and then use whatever means is convenient to extract keywords and their
corresponding arguments from the contents of that rest argument.
The following example illustrates the principle: the code for
@code{make-window} uses a helper procedure called
@code{get-keyword-value} to extract individual keyword arguments from
the rest argument.
@lisp
(define (get-keyword-value args keyword default)
(let ((kv (memq keyword args)))
(if (and kv (>= (length kv) 2))
(cadr kv)
default)))
(define (make-window . args)
(let ((depth (get-keyword-value args #:depth screen-depth))
(bg (get-keyword-value args #:bg "white"))
(width (get-keyword-value args #:width 800))
(height (get-keyword-value args #:height 100))
@dots{})
@dots{}))
@end lisp
But you don't need to write @code{get-keyword-value}. The @code{(ice-9
optargs)} module provides a set of powerful macros that you can use to
implement keyword-supporting procedures like this:
@lisp
(use-modules (ice-9 optargs))
(define (make-window . args)
(let-keywords args #f ((depth screen-depth)
(bg "white")
(width 800)
(height 100))
...))
@end lisp
@noindent
Or, even more economically, like this:
@lisp
(use-modules (ice-9 optargs))
(define* (make-window #:key (depth screen-depth)
(bg "white")
(width 800)
(height 100))
...)
@end lisp
For further details on @code{let-keywords}, @code{define*} and other
facilities provided by the @code{(ice-9 optargs)} module, see
@ref{Optional Arguments}.
@node Keyword Read Syntax
@subsection Keyword Read Syntax
Guile, by default, only recognizes the keyword syntax specified by R5RS.
A token of the form @code{#:NAME}, where @code{NAME} has the same syntax
as a Scheme symbol (@pxref{Symbol Read Syntax}), is the external
representation of the keyword named @code{NAME}. Keyword objects print
using this syntax as well, so values containing keyword objects can be
read back into Guile. When used in an expression, keywords are
self-quoting objects.
If the @code{keyword} read option is set to @code{'prefix}, Guile also
recognizes the alternative read syntax @code{:NAME}. Otherwise, tokens
of the form @code{:NAME} are read as symbols, as required by R5RS.
To enable and disable the alternative non-R5RS keyword syntax, you use
the @code{read-options} procedure documented in @ref{General option
interface} and @ref{Reader options}.
@smalllisp
(read-set! keywords 'prefix)
#:type
@result{}
#:type
:type
@result{}
#:type
(read-set! keywords #f)
#:type
@result{}
#:type
:type
@print{}
ERROR: In expression :type:
ERROR: Unbound variable: :type
ABORT: (unbound-variable)
@end smalllisp
@node Keyword Procedures
@subsection Keyword Procedures
@c FIXME::martin: Review me!
The following procedures can be used for converting symbols to keywords
and back.
@deffn {Scheme Procedure} symbol->keyword sym
Return a keyword with the same characters as in @var{sym}.
@end deffn
@deffn {Scheme Procedure} keyword->symbol kw
Return a symbol with the same characters as in @var{kw}.
@end deffn
@node Keyword Primitives
@subsection Keyword Primitives
Internally, a keyword is implemented as something like a tagged symbol,
where the tag identifies the keyword as being self-evaluating, and the
symbol, known as the keyword's @dfn{dash symbol} has the same name as
the keyword name but prefixed by a single dash. For example, the
keyword @code{#:name} has the corresponding dash symbol @code{-name}.
Most keyword objects are constructed automatically by the reader when it
reads a token beginning with @code{#:}. However, if you need to
construct a keyword object programmatically, you can do so by calling
@code{make-keyword-from-dash-symbol} with the corresponding dash symbol
(as the reader does). The dash symbol for a keyword object can be
retrieved using the @code{keyword-dash-symbol} procedure.
@deffn {Scheme Procedure} make-keyword-from-dash-symbol symbol
@deffnx {C Function} scm_make_keyword_from_dash_symbol (symbol)
Make a keyword object from a @var{symbol} that starts with a dash.
@end deffn
@deffn {Scheme Procedure} keyword? obj
@deffnx {C Function} scm_keyword_p (obj)
Return @code{#t} if the argument @var{obj} is a keyword, else
@code{#f}.
@end deffn
@deffn {Scheme Procedure} keyword-dash-symbol keyword
@deffnx {C Function} scm_keyword_dash_symbol (keyword)
Return the dash symbol for @var{keyword}.
This is the inverse of @code{make-keyword-from-dash-symbol}.
@end deffn
@node Other Types
@section ``Functionality-Centric'' Data Types
Procedures and macros are documented in their own chapter: see
@ref{Procedures and Macros}.
Variable objects are documented as part of the description of Guile's
module system: see @ref{Variables}.
Asyncs, dynamic roots and fluids are described in the chapter on
scheduling: see @ref{Scheduling}.
Hooks are documented in the chapter on general utility functions: see
@ref{Hooks}.
Ports are described in the chapter on I/O: see @ref{Input and Output}.
@c Local Variables:
@c TeX-master: "guile.texi"
@c End: