Simple Generic Data Types
=========================

This chapter describes those of Guile's simple data types which are primarily used for their role as items of generic data.  By 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 compound data types, see Compound Data Types.

Booleans
--------

The two boolean values are #t for true and #f for false.

Boolean values are returned by predicate procedures, such as the general equality predicates eq?, eqv? and equal? (see Equality) and numerical and string comparison operators like string=? (see String Comparison) and <= (see Comparison).

     (<= 3 8)
     => #t

     (<= 3 -3)
     => #f

     (equal? "house" "houses")
     => #f

     (eq? #f #f)
     =>
     #t

In test condition contexts like if and cond (see if cond case), where a group of subexpressions will be evaluated only if a CONDITION expression evaluates to ``true'', ``true'' means any value at all except #f.

     (if #t "yes" "no")
     => "yes"

     (if 0 "yes" "no")
     => "yes"

     (if #f "yes" "no")
     => "no"

A result of this asymmetry is that typical Scheme source code more often uses #f explicitly than #t: #f is necessary to represent an if or cond false value, whereas #t is not necessary to represent an if or cond true value.

It is important to note that #f is not equivalent to any other Scheme value.  In particular, #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).

In C, the two Scheme boolean values are available as the two constants SCM_BOOL_T for #t and SCM_BOOL_F for #f. Care must be taken with the false value SCM_BOOL_F: it is not false when used in C conditionals.  In order to test for it, use scm_is_false or scm_is_true.

 -- Scheme Procedure: not x
 -- C Function: scm_not (x)
     Return #t if X is #f, else return #f.

 -- Scheme Procedure: boolean? obj
 -- C Function: scm_boolean_p (obj)
     Return #t if OBJ is either #t or #f, else return #f.

 -- C Macro: SCM SCM_BOOL_T
     The SCM representation of the Scheme object #t.

 -- C Macro: SCM SCM_BOOL_F
     The SCM representation of the Scheme object #f.

 -- C Function: int scm_is_true (SCM obj)
     Return 0 if OBJ is #f, else return 1.

 -- C Function: int scm_is_false (SCM obj)
     Return 1 if OBJ is #f, else return 0.

 -- C Function: int scm_is_bool (SCM obj)
     Return 1 if OBJ is either #t or #f, else return 0.

 -- C Function: SCM scm_from_bool (int val)
     Return #f if VAL is 0, else return #t.

 -- C Function: int scm_to_bool (SCM val)
     Return 1 if VAL is SCM_BOOL_T, return 0 when VAL is SCM_BOOL_F, else signal a `wrong type' error.

     You should probably use scm_is_true instead of this function when you just want to test a SCM value for trueness.

Numerical data types
--------------------

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 Numbers (R5RS).

Scheme's Numerical ``Tower''
............................

Scheme's numerical ``tower'' consists of the following categories of numbers:

integers
     Whole numbers, positive or negative; e.g. --5, 0, 18.

rationals
     The set of numbers that can be expressed as P/Q where P and Q are integers; e.g. 9/16 works, but pi (an irrational number) doesn't. These include integers (N/1).

real numbers
     The set of numbers that describes all possible positions along a one-dimensional line. This includes rationals as well as irrational numbers.

complex numbers
     The set of numbers that describes all possible positions in a two dimensional space. This includes real as well as imaginary numbers (A+Bi, where A is the real part, B is the imaginary part, and i is the square root of -1.)

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).

In addition to the classification into integers, rationals, reals and complex numbers, Scheme also distinguishes between whether a number is represented exactly or not.  For example, the result of 2\sin(\pi/4),sin(pi/4) is exactly \sqrt2,2^(1/2) but Guile can neither represent \pi/4,pi/4 nor \sqrt2,2^(1/2) exactly. Instead, it stores an inexact approximation, using the C type double.

Guile can represent exact rationals of any magnitude, inexact rationals that fit into a C double, and inexact complex numbers with double real and imaginary parts.

The number? predicate may be applied to any Scheme value to discover whether the value is any of the supported numerical types.

 -- Scheme Procedure: number? obj
 -- C Function: scm_number_p (obj)
     Return #t if OBJ is any kind of number, else #f.

For example:

     (number? 3)
     => #t

     (number? "hello there!")
     => #f

     (define pi 3.141592654)
     (number? pi)
     => #t

 -- C Function: int scm_is_number (SCM obj)
     This is equivalent to scm_is_true (scm_number_p (obj)).

The next few subsections document each of Guile's numerical data types in detail.

Integers
........

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.

     (define (factorial n)
       (let loop ((n n) (product 1))
         (if (= n 0)
             product
             (loop (- n 1) (* product n)))))

     (factorial 3)
     => 6

     (factorial 20)
     => 2432902008176640000

     (- (factorial 45))
     => -119622220865480194561963161495657715064383733760000000000

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.

The infinities +inf.0 and -inf.0 are considered to be inexact integers.  They are explained in detail in the next section, together with reals and rationals.

C has a host of different integer types, and Guile offers a host of functions to convert between them and the SCM representation. For example, a C int can be handled with scm_to_int and scm_from_int.  Guile also defines a few C integer types of its own, to help with differences between systems.

C integer types that are not covered can be handled with the generic scm_to_signed_integer and scm_from_signed_integer for signed types, or with scm_to_unsigned_integer and scm_from_unsigned_integer for unsigned types.

Scheme integers can be exact and inexact.  For example, a number written as 3.0 with an explicit decimal-point is inexact, but it is also an integer.  The functions integer? and scm_is_integer report true for such a number, but the functions scm_is_signed_integer and scm_is_unsigned_integer only allow exact integers and thus report false.  Likewise, the conversion functions like scm_to_signed_integer only accept exact integers.

The motivation for this behavior is that the inexactness of a number should not be lost silently.  If you want to allow inexact integers, you can explicitely insert a call to inexact->exact or to its C equivalent scm_inexact_to_exact.  (Only inexact integers will be converted by this call into exact integers; inexact non-integers will become exact fractions.)

 -- Scheme Procedure: integer? x
 -- C Function: scm_integer_p (x)
     Return #t if X is an exact or inexact integer number, else #f.

          (integer? 487)
          => #t

          (integer? 3.0)
          => #t

          (integer? -3.4)
          => #f

          (integer? +inf.0)
          => #t

 -- C Function: int scm_is_integer (SCM x)
     This is equivalent to scm_is_true (scm_integer_p (x)).

 -- C Type: scm_t_int8
 -- C Type: scm_t_uint8
 -- C Type: scm_t_int16
 -- C Type: scm_t_uint16
 -- C Type: scm_t_int32
 -- C Type: scm_t_uint32
 -- C Type: scm_t_int64
 -- C Type: scm_t_uint64
 -- C Type: scm_t_intmax
 -- C Type: scm_t_uintmax
     The C types are equivalent to the corresponding ISO C types but are defined on all platforms, with the exception of scm_t_int64 and scm_t_uint64, which are only defined when a 64-bit type is available.  For example, scm_t_int8 is equivalent to int8_t.

     You can regard these definitions as a stop-gap measure until all platforms provide these types.  If you know that all the platforms that you are interested in already provide these types, it is better to use them directly instead of the types provided by Guile.

 -- C Function: int scm_is_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
 -- C Function: int scm_is_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
     Return 1 when X represents an exact integer that is between MIN and MAX, inclusive.

     These functions can be used to check whether a SCM value will fit into a given range, such as the range of a given C integer type. If you just want to convert a SCM value to a given C integer type, use one of the conversion functions directly.

 -- C Function: scm_t_intmax scm_to_signed_integer (SCM x, scm_t_intmax min, scm_t_intmax max)
 -- C Function: scm_t_uintmax scm_to_unsigned_integer (SCM x, scm_t_uintmax min, scm_t_uintmax max)
     When X represents an exact integer that is between MIN and MAX inclusive, return that integer.  Else signal an error, either a `wrong-type' error when X is not an exact integer, or an `out-of-range' error when it doesn't fit the given range.

 -- C Function: SCM scm_from_signed_integer (scm_t_intmax x)
 -- C Function: SCM scm_from_unsigned_integer (scm_t_uintmax x)
     Return the SCM value that represents the integer X.  This function will always succeed and will always return an exact number.

 -- C Function: char scm_to_char (SCM x)
 -- C Function: signed char scm_to_schar (SCM x)
 -- C Function: unsigned char scm_to_uchar (SCM x)
 -- C Function: short scm_to_short (SCM x)
 -- C Function: unsigned short scm_to_ushort (SCM x)
 -- C Function: int scm_to_int (SCM x)
 -- C Function: unsigned int scm_to_uint (SCM x)
 -- C Function: long scm_to_long (SCM x)
 -- C Function: unsigned long scm_to_ulong (SCM x)
 -- C Function: long long scm_to_long_long (SCM x)
 -- C Function: unsigned long long scm_to_ulong_long (SCM x)
 -- C Function: size_t scm_to_size_t (SCM x)
 -- C Function: ssize_t scm_to_ssize_t (SCM x)
 -- C Function: scm_t_int8 scm_to_int8 (SCM x)
 -- C Function: scm_t_uint8 scm_to_uint8 (SCM x)
 -- C Function: scm_t_int16 scm_to_int16 (SCM x)
 -- C Function: scm_t_uint16 scm_to_uint16 (SCM x)
 -- C Function: scm_t_int32 scm_to_int32 (SCM x)
 -- C Function: scm_t_uint32 scm_to_uint32 (SCM x)
 -- C Function: scm_t_int64 scm_to_int64 (SCM x)
 -- C Function: scm_t_uint64 scm_to_uint64 (SCM x)
 -- C Function: scm_t_intmax scm_to_intmax (SCM x)
 -- C Function: scm_t_uintmax scm_to_uintmax (SCM x)
     When X represents an exact integer that fits into the indicated C type, return that integer.  Else signal an error, either a `wrong-type' error when X is not an exact integer, or an `out-of-range' error when it doesn't fit the given range.

     The functions scm_to_long_long, scm_to_ulong_long, scm_to_int64, and scm_to_uint64 are only available when the corresponding types are.

 -- C Function: SCM scm_from_char (char x)
 -- C Function: SCM scm_from_schar (signed char x)
 -- C Function: SCM scm_from_uchar (unsigned char x)
 -- C Function: SCM scm_from_short (short x)
 -- C Function: SCM scm_from_ushort (unsigned short x)
 -- C Function: SCM scm_from_int (int x)
 -- C Function: SCM scm_from_uint (unsigned int x)
 -- C Function: SCM scm_from_long (long x)
 -- C Function: SCM scm_from_ulong (unsigned long x)
 -- C Function: SCM scm_from_long_long (long long x)
 -- C Function: SCM scm_from_ulong_long (unsigned long long x)
 -- C Function: SCM scm_from_size_t (size_t x)
 -- C Function: SCM scm_from_ssize_t (ssize_t x)
 -- C Function: SCM scm_from_int8 (scm_t_int8 x)
 -- C Function: SCM scm_from_uint8 (scm_t_uint8 x)
 -- C Function: SCM scm_from_int16 (scm_t_int16 x)
 -- C Function: SCM scm_from_uint16 (scm_t_uint16 x)
 -- C Function: SCM scm_from_int32 (scm_t_int32 x)
 -- C Function: SCM scm_from_uint32 (scm_t_uint32 x)
 -- C Function: SCM scm_from_int64 (scm_t_int64 x)
 -- C Function: SCM scm_from_uint64 (scm_t_uint64 x)
 -- C Function: SCM scm_from_intmax (scm_t_intmax x)
 -- C Function: SCM scm_from_uintmax (scm_t_uintmax x)
     Return the SCM value that represents the integer X. These functions will always succeed and will always return an exact number.

 -- C Function: void scm_to_mpz (SCM val, mpz_t rop)
     Assign VAL to the multiple precision integer ROP. VAL must be an exact integer, otherwise an error will be signalled.  ROP must have been initialized with mpz_init before this function is called.  When ROP is no longer needed the occupied space must be freed with mpz_clear. See Initializing Integers (GNU MP Manual), for details.

 -- C Function: SCM scm_from_mpz_t (mpz_t val)
     Return the SCM value that represents VAL.

Real and Rational Numbers
.........................

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 can represent both exact and inexact rational numbers, but it can not represent irrational numbers.  Exact rationals are represented by storing the numerator and denominator as two exact integers. Inexact rationals are stored as floating point numbers using the C type double.

Exact rationals are written as a fraction of integers.  There must be no whitespace around the slash:

     1/2
     -22/7

Even though the actual encoding of inexact rationals 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:

     0.34
     -0.00000142857931198
     -5648394822220000000000.0
     4.0

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, -0.00000142857931198 is the same as -142857931198 divided by 100000000000000000.  In Guile's current incarnation, therefore, the rational? and real? predicates are equivalent.

Dividing by an exact zero leads to a error message, as one might expect.  However, dividing by an inexact zero does not produce an error.  Instead, the result of the division is either plus or minus infinity, depending on the sign of the divided number.

The infinities are written +inf.0 and -inf.0, respectivly.  This syntax is also recognized by read as an extension to the usual Scheme syntax.

Dividing zero by zero yields something that is not a number at all: +nan.0.  This is the special `not a number' value.

On platforms that follow IEEE 754 for their floating point arithmetic, the +inf.0, -inf.0, and +nan.0 values are implemented using the corresponding IEEE 754 values. They behave in arithmetic operations like IEEE 754 describes it, i.e., (= +nan.0 +nan.0) => #f.

The infinities are inexact integers and are considered to be both even and odd.  While +nan.0 is not = to itself, it is eqv? to itself.

To test for the special values, use the functions inf? and nan?.

 -- Scheme Procedure: real? obj
 -- C Function: scm_real_p (obj)
     Return #t if OBJ is a real number, else #f.  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 OBJ is an integer number or a rational number.

 -- Scheme Procedure: rational? x
 -- C Function: scm_rational_p (x)
     Return #t if X is a rational number, #f otherwise. 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 X is an integer number.

     Since Guile can not represent irrational numbers, every number satisfying real? also satisfies rational? in Guile.

 -- Scheme Procedure: rationalize x eps
 -- C Function: scm_rationalize (x, eps)
     Returns the simplest rational number differing from X by no more than EPS.

     As required by R5RS, rationalize only returns an exact result when both its arguments are exact.  Thus, you might need to use inexact->exact on the arguments.

          (rationalize (inexact->exact 1.2) 1/100)
          => 6/5

 -- Scheme Procedure: inf? x
 -- C Function: scm_inf_p (x)
     Return #t if X is either +inf.0 or -inf.0, #f otherwise.

 -- Scheme Procedure: nan? x
 -- C Function: scm_nan_p (x)
     Return #t if X is +nan.0, #f otherwise.

 -- Scheme Procedure: nan
 -- C Function: scm_nan ()
     Return NaN.

 -- Scheme Procedure: inf
 -- C Function: scm_inf ()
     Return Inf.

 -- Scheme Procedure: numerator x
 -- C Function: scm_numerator (x)
     Return the numerator of the rational number X.

 -- Scheme Procedure: denominator x
 -- C Function: scm_denominator (x)
     Return the denominator of the rational number X.

 -- C Function: int scm_is_real (SCM val)
 -- C Function: int scm_is_rational (SCM val)
     Equivalent to scm_is_true (scm_real_p (val)) and scm_is_true (scm_rational_p (val)), respectively.

 -- C Function: double scm_to_double (SCM val)
     Returns the number closest to VAL that is representable as a double.  Returns infinity for a VAL that is too large in magnitude.  The argument VAL must be a real number.

 -- C Function: SCM scm_from_double (double val)
     Return the SCM value that representats VAL.  The returned value is inexact according to the predicate inexact?, but it will be exactly equal to VAL.

Complex Numbers
...............

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 real and 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 i to indicate the imaginary part.

     3+4i
     =>
     3.0+4.0i

     (* 3-8i 2.3+0.3i)
     =>
     9.3-17.5i

Guile represents a complex number with a non-zero imaginary part as a pair of inexact rationals, so the real and imaginary parts of a complex number have the same properties of inexactness and limited precision as single inexact rational numbers.  Guile can not represent exact complex numbers with non-zero imaginary parts.

 -- Scheme Procedure: complex? z
 -- C Function: scm_complex_p (z)
     Return #t if X is a complex number, #f otherwise.  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 X is a real, rational or integer number.

 -- C Function: int scm_is_complex (SCM val)
     Equivalent to scm_is_true (scm_complex_p (val)).

Exact and Inexact Numbers
.........................

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 5 and the corresponding inexact real value which, to the limited precision available, has no fractional part, and is printed as 5.0.  Guile will only convert the latter value to the former when forced to do so by an invocation of the inexact->exact procedure.

 -- Scheme Procedure: exact? z
 -- C Function: scm_exact_p (z)
     Return #t if the number Z is exact, #f otherwise.

          (exact? 2)
          => #t

          (exact? 0.5)
          => #f

          (exact? (/ 2))
          => #t

 -- Scheme Procedure: inexact? z
 -- C Function: scm_inexact_p (z)
     Return #t if the number Z is inexact, #f else.

 -- Scheme Procedure: inexact->exact z
 -- C Function: scm_inexact_to_exact (z)
     Return an exact number that is numerically closest to Z, when there is one.  For inexact rationals, Guile returns the exact rational that is numerically equal to the inexact rational.  Inexact complex numbers with a non-zero imaginary part can not be made exact.

          (inexact->exact 0.5)
          => 1/2

     The following happens because 12/10 is not exactly representable as a double (on most platforms).  However, when reading a decimal number that has been marked exact with the ``#e'' prefix, Guile is able to represent it correctly.

          (inexact->exact 1.2)
          => 5404319552844595/4503599627370496

          #e1.2
          => 6/5

 -- Scheme Procedure: exact->inexact z
 -- C Function: scm_exact_to_inexact (z)
     Convert the number Z to its inexact representation.

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:

#b
#B
     the integer is written in binary (base 2)

#o
#O
     the integer is written in octal (base 8)

#d
#D
     the integer is written in decimal (base 10)

#x
#X
     the integer is written in hexadecimal (base 16)

If the base code is omitted, the integer is assumed to be decimal.  The following examples show how these base codes are used.

     -13
     => -13

     #d-13
     => -13

     #x-13
     => -19

     #b+1101
     => 13

     #o377
     => 255

The codes for indicating exactness (which can, incidentally, be applied to all numerical values) are:

#e
#E
     the number is exact

#i
#I
     the number is inexact.

If the exactness indicator is omitted, the number is exact unless it contains a radix point.  Since Guile can not represent exact complex numbers, an error is signalled when asking for them.

     (exact? 1.2)
     => #f

     (exact? #e1.2)
     => #t

     (exact? #e+1i)
     ERROR: Wrong type argument

Guile also understands the syntax +inf.0 and -inf.0 for plus and minus infinity, respectively.  The value must be written exactly as shown, that is, they always must have a sign and exactly one zero digit after the decimal point.  It also understands +nan.0 and -nan.0 for the special `not-a-number' value. The sign is ignored for `not-a-number' and the value is always printed as +nan.0.

Operations on Integer Values
............................

 -- Scheme Procedure: odd? n
 -- C Function: scm_odd_p (n)
     Return #t if N is an odd number, #f otherwise.

 -- Scheme Procedure: even? n
 -- C Function: scm_even_p (n)
     Return #t if N is an even number, #f otherwise.

 -- Scheme Procedure: quotient n d
 -- Scheme Procedure: remainder n d
 -- C Function: scm_quotient (n, d)
 -- C Function: scm_remainder (n, d)
     Return the quotient or remainder from N divided by D.  The quotient is rounded towards zero, and the remainder will have the same sign as N.  In all cases quotient and remainder satisfy N = Q*D + R.

          (remainder 13 4) => 1
          (remainder -13 4) => -1

 -- Scheme Procedure: modulo n d
 -- C Function: scm_modulo (n, d)
     Return the remainder from N divided by D, with the same sign as D.

          (modulo 13 4) => 1
          (modulo -13 4) => 3
          (modulo 13 -4) => -3
          (modulo -13 -4) => -1

 -- Scheme Procedure: gcd
 -- C Function: scm_gcd (x, y)
     Return the greatest common divisor of all arguments. If called without arguments, 0 is returned.

     The C function scm_gcd always takes two arguments, while the Scheme function can take an arbitrary number.

 -- Scheme Procedure: lcm
 -- C Function: scm_lcm (x, y)
     Return the least common multiple of the arguments. If called without arguments, 1 is returned.

     The C function scm_lcm always takes two arguments, while the Scheme function can take an arbitrary number.

 -- Scheme Procedure: modulo-expt n k m
 -- C Function: scm_modulo_expt (n, k, m)
     Return N raised to the integer exponent K, modulo M.

          (modulo-expt 2 3 5)
             => 3

Comparison Predicates
.....................

The C comparison functions below always takes two arguments, while the Scheme functions can take an arbitrary number.  Also keep in mind that the C functions return one of the Scheme boolean values SCM_BOOL_T or SCM_BOOL_F which are both true as far as C is concerned.  Thus, always write scm_is_true (scm_num_eq_p (x, y)) when testing the two Scheme numbers x and y for equality, for example.

 -- Scheme Procedure: =
 -- C Function: scm_num_eq_p (x, y)
     Return #t if all parameters are numerically equal.

 -- Scheme Procedure: <
 -- C Function: scm_less_p (x, y)
     Return #t if the list of parameters is monotonically increasing.

 -- Scheme Procedure: >
 -- C Function: scm_gr_p (x, y)
     Return #t if the list of parameters is monotonically decreasing.

 -- Scheme Procedure: <=
 -- C Function: scm_leq_p (x, y)
     Return #t if the list of parameters is monotonically non-decreasing.

 -- Scheme Procedure: >=
 -- C Function: scm_geq_p (x, y)
     Return #t if the list of parameters is monotonically non-increasing.

 -- Scheme Procedure: zero? z
 -- C Function: scm_zero_p (z)
     Return #t if Z is an exact or inexact number equal to zero.

 -- Scheme Procedure: positive? x
 -- C Function: scm_positive_p (x)
     Return #t if X is an exact or inexact number greater than zero.

 -- Scheme Procedure: negative? x
 -- C Function: scm_negative_p (x)
     Return #t if X is an exact or inexact number less than zero.

Converting Numbers To and From Strings
......................................

 -- Scheme Procedure: number->string n [radix]
 -- C Function: scm_number_to_string (n, radix)
     Return a string holding the external representation of the number N in the given RADIX.  If N is inexact, a radix of 10 will be used.

 -- Scheme Procedure: string->number string [radix]
 -- C Function: scm_string_to_number (string, radix)
     Return a number of the maximally precise representation expressed by the given STRING. RADIX must be an exact integer, either 2, 8, 10, or 16. If supplied, RADIX is a default radix that may be overridden by an explicit radix prefix in STRING (e.g. "#o177"). If RADIX is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number, then string->number returns #f.

Complex Number Operations
.........................

 -- Scheme Procedure: make-rectangular real imaginary
 -- C Function: scm_make_rectangular (real, imaginary)
     Return a complex number constructed of the given REAL and IMAGINARY parts.

 -- Scheme Procedure: make-polar x y
 -- C Function: scm_make_polar (x, y)
     Return the complex number X * e^(i * Y).

 -- Scheme Procedure: real-part z
 -- C Function: scm_real_part (z)
     Return the real part of the number Z.

 -- Scheme Procedure: imag-part z
 -- C Function: scm_imag_part (z)
     Return the imaginary part of the number Z.

 -- Scheme Procedure: magnitude z
 -- C Function: scm_magnitude (z)
     Return the magnitude of the number Z. This is the same as abs for real arguments, but also allows complex numbers.

 -- Scheme Procedure: angle z
 -- C Function: scm_angle (z)
     Return the angle of the complex number Z.

 -- C Function: SCM scm_c_make_rectangular (double re, double im)
 -- C Function: SCM scm_c_make_polar (double x, double y)
     Like scm_make_rectangular or scm_make_polar, respectively, but these functions take doubles as their arguments.

 -- C Function: double scm_c_real_part (z)
 -- C Function: double scm_c_imag_part (z)
     Returns the real or imaginary part of Z as a double.

 -- C Function: double scm_c_magnitude (z)
 -- C Function: double scm_c_angle (z)
     Returns the magnitude or angle of Z as a double.

Arithmetic Functions
....................

The C arithmetic functions below always takes two arguments, while the Scheme functions can take an arbitrary number.  When you need to invoke them with just one argument, for example to compute the equivalent od (- x), pass SCM_UNDEFINED as the second one: scm_difference (x, SCM_UNDEFINED).

 -- Scheme Procedure: + z1 ...
 -- C Function: scm_sum (z1, z2)
     Return the sum of all parameter values.  Return 0 if called without any parameters.

 -- Scheme Procedure: - z1 z2 ...
 -- C Function: scm_difference (z1, z2)
     If called with one argument Z1, -Z1 is returned. Otherwise the sum of all but the first argument are subtracted from the first argument.

 -- Scheme Procedure: * z1 ...
 -- C Function: scm_product (z1, z2)
     Return the product of all arguments.  If called without arguments, 1 is returned.

 -- Scheme Procedure: / z1 z2 ...
 -- C Function: scm_divide (z1, z2)
     Divide the first argument by the product of the remaining arguments.  If called with one argument Z1, 1/Z1 is returned.

 -- Scheme Procedure: abs x
 -- C Function: scm_abs (x)
     Return the absolute value of X.

     X must be a number with zero imaginary part.  To calculate the magnitude of a complex number, use magnitude instead.

 -- Scheme Procedure: max x1 x2 ...
 -- C Function: scm_max (x1, x2)
     Return the maximum of all parameter values.

 -- Scheme Procedure: min x1 x2 ...
 -- C Function: scm_min (x1, x2)
     Return the minimum of all parameter values.

 -- Scheme Procedure: truncate
 -- C Function: scm_truncate_number (x)
     Round the inexact number X towards zero.

 -- Scheme Procedure: round x
 -- C Function: scm_round_number (x)
     Round the inexact number X to the nearest integer.  When exactly halfway between two integers, round to the even one.

 -- Scheme Procedure: floor x
 -- C Function: scm_floor (x)
     Round the number X towards minus infinity.

 -- Scheme Procedure: ceiling x
 -- C Function: scm_ceiling (x)
     Round the number X towards infinity.

 -- C Function: double scm_c_truncate (double x)
 -- C Function: double scm_c_round (double x)
     Like scm_truncate_number or scm_round_number, respectively, but these functions take and return double values.

Scientific Functions
....................

The following procedures accept any kind of number as arguments, including complex numbers.

 -- Scheme Procedure: sqrt z
     Return the square root of Z.

 -- Scheme Procedure: expt z1 z2
     Return Z1 raised to the power of Z2.

 -- Scheme Procedure: sin z
     Return the sine of Z.

 -- Scheme Procedure: cos z
     Return the cosine of Z.

 -- Scheme Procedure: tan z
     Return the tangent of Z.

 -- Scheme Procedure: asin z
     Return the arcsine of Z.

 -- Scheme Procedure: acos z
     Return the arccosine of Z.

 -- Scheme Procedure: atan z
 -- Scheme Procedure: atan y x
     Return the arctangent of Z, or of Y/X.

 -- Scheme Procedure: exp z
     Return e to the power of Z, where e is the base of natural logarithms (2.71828...).

 -- Scheme Procedure: log z
     Return the natural logarithm of Z.

 -- Scheme Procedure: log10 z
     Return the base 10 logarithm of Z.

 -- Scheme Procedure: sinh z
     Return the hyperbolic sine of Z.

 -- Scheme Procedure: cosh z
     Return the hyperbolic cosine of Z.

 -- Scheme Procedure: tanh z
     Return the hyperbolic tangent of Z.

 -- Scheme Procedure: asinh z
     Return the hyperbolic arcsine of Z.

 -- Scheme Procedure: acosh z
     Return the hyperbolic arccosine of Z.

 -- Scheme Procedure: atanh z
     Return the hyperbolic arctangent of Z.

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.

 -- Scheme Procedure: $abs x
     Return the absolute value of X.

 -- Scheme Procedure: $sqrt x
     Return the square root of X.

 -- Scheme Procedure: $expt x y
 -- C Function: scm_sys_expt (x, y)
     Return X raised to the power of Y. This procedure does not accept complex arguments.

 -- Scheme Procedure: $sin x
     Return the sine of X.

 -- Scheme Procedure: $cos x
     Return the cosine of X.

 -- Scheme Procedure: $tan x
     Return the tangent of X.

 -- Scheme Procedure: $asin x
     Return the arcsine of X.

 -- Scheme Procedure: $acos x
     Return the arccosine of X.

 -- Scheme Procedure: $atan x
     Return the arctangent of X in the range -PI/2 to PI/2.

 -- Scheme Procedure: $atan2 x y
 -- C Function: scm_sys_atan2 (x, y)
     Return the arc tangent of the two arguments X and Y. This is similar to calculating the arc tangent of X / Y, except that the signs of both arguments are used to determine the quadrant of the result. This procedure does not accept complex arguments.

 -- Scheme Procedure: $exp x
     Return e to the power of X, where e is the base of natural logarithms (2.71828...).

 -- Scheme Procedure: $log x
     Return the natural logarithm of X.

 -- Scheme Procedure: $sinh x
     Return the hyperbolic sine of X.

 -- Scheme Procedure: $cosh x
     Return the hyperbolic cosine of X.

 -- Scheme Procedure: $tanh x
     Return the hyperbolic tangent of X.

 -- Scheme Procedure: $asinh x
     Return the hyperbolic arcsine of X.

 -- Scheme Procedure: $acosh x
     Return the hyperbolic arccosine of X.

 -- Scheme Procedure: $atanh x
     Return the hyperbolic arctangent of X.

C functions for the above are provided by the standard mathematics library.  Naturally these expect and return double arguments (see Mathematics (GNU C Library Reference Manual)).

  Scheme Procedure   C Function

  $abs        fabs
  $sqrt       sqrt
  $sin        sin
  $cos        cos
  $tan        tan
  $asin       asin
  $acos       acos
  $atan       atan
  $atan2      atan2
  $exp        exp
  $expt       pow
  $log        log
  $sinh       sinh
  $cosh       cosh
  $tanh       tanh
  $asinh      asinh
  $acosh      acosh
  $atanh      atanh

asinh, acosh and atanh are C99 standard but might not be available on older systems.  Guile provides the following equivalents (on all systems).

 -- C Function: double scm_asinh (double x)
 -- C Function: double scm_acosh (double x)
 -- C Function: double scm_atanh (double x)
     Return the hyperbolic arcsine, arccosine or arctangent of X respectively.

Bitwise Operations
..................

For the following bitwise functions, negative numbers are treated as infinite precision twos-complements.  For instance -6 is bits ...111010, with infinitely many ones on the left.  It can be seen that adding 6 (binary 110) to such a bit pattern gives all zeros.

 -- Scheme Procedure: logand n1 n2 ...
 -- C Function: scm_logand (n1, n2)
     Return the bitwise AND of the integer arguments.

          (logand) => -1
          (logand 7) => 7
          (logand #b111 #b011 #b001) => 1

 -- Scheme Procedure: logior n1 n2 ...
 -- C Function: scm_logior (n1, n2)
     Return the bitwise OR of the integer arguments.

          (logior) => 0
          (logior 7) => 7
          (logior #b000 #b001 #b011) => 3

 -- Scheme Procedure: logxor n1 n2 ...
 -- C Function: scm_loxor (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.

          (logxor) => 0
          (logxor 7) => 7
          (logxor #b000 #b001 #b011) => 2
          (logxor #b000 #b001 #b011 #b011) => 1

 -- Scheme Procedure: lognot n
 -- C Function: scm_lognot (n)
     Return the integer which is the ones-complement of the integer argument, ie. each 0 bit is changed to 1 and each 1 bit to 0.

          (number->string (lognot #b10000000) 2)
             => "-10000001"
          (number->string (lognot #b0) 2)
             => "-1"

 -- Scheme Procedure: logtest j k
 -- C Function: scm_logtest (j, k)
     Test whether J and K have any 1 bits in common.  This is equivalent to (not (zero? (logand j k))), but without actually calculating the logand, just testing for non-zero.

          (logtest #b0100 #b1011) => #f
          (logtest #b0100 #b0111) => #t

 -- Scheme Procedure: logbit? index j
 -- C Function: scm_logbit_p (index, j)
     Test whether bit number INDEX in J is set.  INDEX starts from 0 for the least significant bit.

          (logbit? 0 #b1101) => #t
          (logbit? 1 #b1101) => #f
          (logbit? 2 #b1101) => #t
          (logbit? 3 #b1101) => #t
          (logbit? 4 #b1101) => #f

 -- Scheme Procedure: ash n cnt
 -- C Function: scm_ash (n, cnt)
     Return N shifted left by CNT bits, or shifted right if CNT is negative.  This is an ``arithmetic'' shift.

     This is effectively a multiplication by 2^cnt, 2^CNT, and when CNT is negative it's a division, rounded towards negative infinity.  (Note that this is not the same rounding as quotient does.)

     With N viewed as an infinite precision twos complement, ash means a left shift introducing zero bits, or a right shift dropping bits.

          (number->string (ash #b1 3) 2)     => "1000"
          (number->string (ash #b1010 -1) 2) => "101"

          ;; -23 is bits ...11101001, -6 is bits ...111010
          (ash -23 -2) => -6

 -- Scheme Procedure: logcount n
 -- C Function: scm_logcount (n)
     Return the number of bits in integer N.  If N 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 zero, 0 is returned.

          (logcount #b10101010)
             => 4
          (logcount 0)
             => 0
          (logcount -2)
             => 1

 -- Scheme Procedure: integer-length n
 -- C Function: scm_integer_length (n)
     Return the number of bits necessary to represent N.

     For positive N this is how many bits to the most significant one bit.  For negative N it's how many bits to the most significant zero bit in twos complement form.

          (integer-length #b10101010) => 8
          (integer-length #b1111)     => 4
          (integer-length 0)          => 0
          (integer-length -1)         => 0
          (integer-length -256)       => 8
          (integer-length -257)       => 9

 -- Scheme Procedure: integer-expt n k
 -- C Function: scm_integer_expt (n, k)
     Return N raised to the power K.  K must be an exact integer, N can be any number.

     Negative K is supported, and results in 1/n^|k|, 1/n^abs(k) in the usual way.  N^0 is 1, as usual, and that includes 0^0 is 1.

          (integer-expt 2 5)   => 32
          (integer-expt -3 3)  => -27
          (integer-expt 5 -3)  => 1/125
          (integer-expt 0 0)   => 1

 -- Scheme Procedure: bit-extract n start end
 -- C Function: scm_bit_extract (n, start, end)
     Return the integer composed of the START (inclusive) through END (exclusive) bits of N.  The STARTth bit becomes the 0-th bit in the result.

          (number->string (bit-extract #b1101101010 0 4) 2)
             => "1010"
          (number->string (bit-extract #b1101101010 4 9) 2)
             => "10110"

Random Number Generation
........................

Pseudo-random numbers are generated from a random state object, which can be created with seed->random-state.  The STATE parameter to the various functions below is optional, it defaults to the state object in the *random-state* variable.

 -- Scheme Procedure: copy-random-state [state]
 -- C Function: scm_copy_random_state (state)
     Return a copy of the random state STATE.

 -- Scheme Procedure: random n [state]
 -- 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.

 -- Scheme Procedure: random:exp [state]
 -- 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)).

 -- Scheme Procedure: random:hollow-sphere! vect [state]
 -- C Function: scm_random_hollow_sphere_x (vect, 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.

 -- Scheme Procedure: random:normal [state]
 -- 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 (+ M (* D (random:normal))).

 -- Scheme Procedure: random:normal-vector! vect [state]
 -- C Function: scm_random_normal_vector_x (vect, state)
     Fills VECT with inexact real random numbers that are independent and standard normally distributed (i.e., with mean 0 and variance 1).

 -- Scheme Procedure: random:solid-sphere! vect [state]
 -- C Function: scm_random_solid_sphere_x (vect, 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.

 -- Scheme Procedure: random:uniform [state]
 -- C Function: scm_random_uniform (state)
     Return a uniformly distributed inexact real random number in [0,1).

 -- Scheme Procedure: seed->random-state seed
 -- C Function: scm_seed_to_random_state (seed)
     Return a new random state using SEED.

 -- Variable: *random-state*
     The global random state used by the above functions when the STATE parameter is not given.

Characters
----------

In Scheme, a character literal is written as #\NAME where NAME is the name of the character that you want.  Printable characters have their usual single character name; for example, #\a is a lower case a.

Most of the ``control characters'' (those below codepoint 32) in the ASCII character set, as well as the space, may be referred to by longer names: for example, #\tab, #\esc, #\stx, and so on.  The following table describes the ASCII names for each character.

0 = #\nul
1 = #\soh
2 = #\stx
3 = #\etx
4 = #\eot
5 = #\enq
6 = #\ack
7 = #\bel
8 = #\bs
9 = #\ht
10 = #\nl
11 = #\vt
12 = #\np
13 = #\cr
14 = #\so
15 = #\si
16 = #\dle
17 = #\dc1
18 = #\dc2
19 = #\dc3
20 = #\dc4
21 = #\nak
22 = #\syn
23 = #\etb
24 = #\can
25 = #\em
26 = #\sub
27 = #\esc
28 = #\fs
29 = #\gs
30 = #\rs
31 = #\us
32 = #\sp

The ``delete'' character (octal 177) may be referred to with the name #\del.

Several characters have more than one name:

Alias   Original
#\space   #\sp
#\newline   #\nl
#\tab   #\ht
#\backspace   #\bs
#\return   #\cr
#\page   #\np
#\null   #\nul

 -- Scheme Procedure: char? x
 -- C Function: scm_char_p (x)
     Return #t iff X is a character, else #f.

 -- Scheme Procedure: char=? x y
     Return #t iff X is the same character as Y, else #f.

 -- Scheme Procedure: char<? x y
     Return #t iff X is less than Y in the ASCII sequence, else #f.

 -- Scheme Procedure: char<=? x y
     Return #t iff X is less than or equal to Y in the ASCII sequence, else #f.

 -- Scheme Procedure: char>? x y
     Return #t iff X is greater than Y in the ASCII sequence, else #f.

 -- Scheme Procedure: char>=? x y
     Return #t iff X is greater than or equal to Y in the ASCII sequence, else #f.

 -- Scheme Procedure: char-ci=? x y
     Return #t iff X is the same character as Y ignoring case, else #f.

 -- Scheme Procedure: char-ci<? x y
     Return #t iff X is less than Y in the ASCII sequence ignoring case, else #f.

 -- Scheme Procedure: char-ci<=? x y
     Return #t iff X is less than or equal to Y in the ASCII sequence ignoring case, else #f.

 -- Scheme Procedure: char-ci>? x y
     Return #t iff X is greater than Y in the ASCII sequence ignoring case, else #f.

 -- Scheme Procedure: char-ci>=? x y
     Return #t iff X is greater than or equal to Y in the ASCII sequence ignoring case, else #f.

 -- Scheme Procedure: char-alphabetic? chr
 -- C Function: scm_char_alphabetic_p (chr)
     Return #t iff CHR is alphabetic, else #f.

 -- Scheme Procedure: char-numeric? chr
 -- C Function: scm_char_numeric_p (chr)
     Return #t iff CHR is numeric, else #f.

 -- Scheme Procedure: char-whitespace? chr
 -- C Function: scm_char_whitespace_p (chr)
     Return #t iff CHR is whitespace, else #f.

 -- Scheme Procedure: char-upper-case? chr
 -- C Function: scm_char_upper_case_p (chr)
     Return #t iff CHR is uppercase, else #f.

 -- Scheme Procedure: char-lower-case? chr
 -- C Function: scm_char_lower_case_p (chr)
     Return #t iff CHR is lowercase, else #f.

 -- Scheme Procedure: char-is-both? chr
 -- C Function: scm_char_is_both_p (chr)
     Return #t iff CHR is either uppercase or lowercase, else #f.

 -- Scheme Procedure: char->integer chr
 -- C Function: scm_char_to_integer (chr)
     Return the number corresponding to ordinal position of CHR in the ASCII sequence.

 -- Scheme Procedure: integer->char n
 -- C Function: scm_integer_to_char (n)
     Return the character at position N in the ASCII sequence.

 -- Scheme Procedure: char-upcase chr
 -- C Function: scm_char_upcase (chr)
     Return the uppercase character version of CHR.

 -- Scheme Procedure: char-downcase chr
 -- C Function: scm_char_downcase (chr)
     Return the lowercase character version of CHR.

Character Sets
--------------

The features described in this section correspond directly to SRFI-14.

The data type charset implements sets of characters (see Characters).  Because the internal representation of character sets is not visible to the user, a lot of procedures for handling them are provided.

Character sets can be created, extended, tested for the membership of a characters and be compared to other character sets.

The Guile implementation of character sets currently deals only with 8-bit characters.  In the future, when Guile gets support for international character sets, this will change, but the functions provided here will always then be able to efficiently cope with very large character sets.

Character Set Predicates/Comparison
...................................

Use these procedures for testing whether an object is a character set, or whether several character sets are equal or subsets of each other. char-set-hash can be used for calculating a hash value, maybe for usage in fast lookup procedures.

 -- Scheme Procedure: char-set? obj
 -- C Function: scm_char_set_p (obj)
     Return #t if OBJ is a character set, #f otherwise.

 -- Scheme Procedure: char-set= . char_sets
 -- C Function: scm_char_set_eq (char_sets)
     Return #t if all given character sets are equal.

 -- Scheme Procedure: char-set<= . char_sets
 -- C Function: scm_char_set_leq (char_sets)
     Return #t if every character set CSi is a subset of character set CSi+1.

 -- Scheme Procedure: char-set-hash cs [bound]
 -- C Function: scm_char_set_hash (cs, bound)
     Compute a hash value for the character set CS.  If BOUND is given and non-zero, it restricts the returned value to the range 0 ... BOUND - 1.

Iterating Over Character Sets
.............................

Character set cursors are a means for iterating over the members of a character sets.  After creating a character set cursor with char-set-cursor, a cursor can be dereferenced with char-set-ref, advanced to the next member with char-set-cursor-next.  Whether a cursor has passed past the last element of the set can be checked with end-of-char-set?.

Additionally, mapping and (un-)folding procedures for character sets are provided.

 -- Scheme Procedure: char-set-cursor cs
 -- C Function: scm_char_set_cursor (cs)
     Return a cursor into the character set CS.

 -- Scheme Procedure: char-set-ref cs cursor
 -- C Function: scm_char_set_ref (cs, cursor)
     Return the character at the current cursor position CURSOR in the character set CS.  It is an error to pass a cursor for which end-of-char-set? returns true.

 -- Scheme Procedure: char-set-cursor-next cs cursor
 -- C Function: scm_char_set_cursor_next (cs, cursor)
     Advance the character set cursor CURSOR to the next character in the character set CS.  It is an error if the cursor given satisfies end-of-char-set?.

 -- Scheme Procedure: end-of-char-set? cursor
 -- C Function: scm_end_of_char_set_p (cursor)
     Return #t if CURSOR has reached the end of a character set, #f otherwise.

 -- Scheme Procedure: char-set-fold kons knil cs
 -- C Function: scm_char_set_fold (kons, knil, cs)
     Fold the procedure KONS over the character set CS, initializing it with KNIL.

 -- Scheme Procedure: char-set-unfold p f g seed [base_cs]
 -- C Function: scm_char_set_unfold (p, f, g, seed, base_cs)
     This is a fundamental constructor for character sets.

       * G is used to generate a series of ``seed'' values from the initial seed: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

       * P tells us when to stop -- when it returns true when applied to one of the seed values.

       * F maps each seed value to a character. These characters are added to the base character set BASE_CS to form the result; BASE_CS defaults to the empty set.

 -- Scheme Procedure: char-set-unfold! p f g seed base_cs
 -- C Function: scm_char_set_unfold_x (p, f, g, seed, base_cs)
     This is a fundamental constructor for character sets.

       * G is used to generate a series of ``seed'' values from the initial seed: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

       * P tells us when to stop -- when it returns true when applied to one of the seed values.

       * F maps each seed value to a character. These characters are added to the base character set BASE_CS to form the result; BASE_CS defaults to the empty set.

 -- Scheme Procedure: char-set-for-each proc cs
 -- C Function: scm_char_set_for_each (proc, cs)
     Apply PROC to every character in the character set CS.  The return value is not specified.

 -- Scheme Procedure: char-set-map proc cs
 -- C Function: scm_char_set_map (proc, cs)
     Map the procedure PROC over every character in CS. PROC must be a character -> character procedure.

Creating Character Sets
.......................

New character sets are produced with these procedures.

 -- Scheme Procedure: char-set-copy cs
 -- C Function: scm_char_set_copy (cs)
     Return a newly allocated character set containing all characters in CS.

 -- Scheme Procedure: char-set . rest
 -- C Function: scm_char_set (rest)
     Return a character set containing all given characters.

 -- Scheme Procedure: list->char-set list [base_cs]
 -- C Function: scm_list_to_char_set (list, base_cs)
     Convert the character list LIST to a character set.  If the character set BASE_CS is given, the character in this set are also included in the result.

 -- Scheme Procedure: list->char-set! list base_cs
 -- C Function: scm_list_to_char_set_x (list, base_cs)
     Convert the character list LIST to a character set.  The characters are added to BASE_CS and BASE_CS is returned.

 -- Scheme Procedure: string->char-set str [base_cs]
 -- C Function: scm_string_to_char_set (str, base_cs)
     Convert the string STR to a character set.  If the character set BASE_CS is given, the characters in this set are also included in the result.

 -- Scheme Procedure: string->char-set! str base_cs
 -- C Function: scm_string_to_char_set_x (str, base_cs)
     Convert the string STR to a character set.  The characters from the string are added to BASE_CS, and BASE_CS is returned.

 -- Scheme Procedure: char-set-filter pred cs [base_cs]
 -- C Function: scm_char_set_filter (pred, cs, base_cs)
     Return a character set containing every character from CS so that it satisfies PRED.  If provided, the characters from BASE_CS are added to the result.

 -- Scheme Procedure: char-set-filter! pred cs base_cs
 -- C Function: scm_char_set_filter_x (pred, cs, base_cs)
     Return a character set containing every character from CS so that it satisfies PRED.  The characters are added to BASE_CS and BASE_CS is returned.

 -- Scheme Procedure: ucs-range->char-set lower upper [error [base_cs]]
 -- C Function: scm_ucs_range_to_char_set (lower, upper, error, base_cs)
     Return a character set containing all characters whose character codes lie in the half-open range [LOWER,UPPER).

     If ERROR is a true value, an error is signalled if the specified range contains characters which are not contained in the implemented character range.  If ERROR is #f, these characters are silently left out of the resultung character set.

     The characters in BASE_CS are added to the result, if given.

 -- Scheme Procedure: ucs-range->char-set! lower upper error base_cs
 -- C Function: scm_ucs_range_to_char_set_x (lower, upper, error, base_cs)
     Return a character set containing all characters whose character codes lie in the half-open range [LOWER,UPPER).

     If ERROR is a true value, an error is signalled if the specified range contains characters which are not contained in the implemented character range.  If ERROR is #f, these characters are silently left out of the resultung character set.

     The characters are added to BASE_CS and BASE_CS is returned.

 -- Scheme Procedure: ->char-set x
 -- C Function: scm_to_char_set (x)
     Coerces x into a char-set. X may be a string, character or char-set. A string is converted to the set of its constituent characters; a character is converted to a singleton set; a char-set is returned as-is.

Querying Character Sets
.......................

Access the elements and other information of a character set with these procedures.

 -- Scheme Procedure: char-set-size cs
 -- C Function: scm_char_set_size (cs)
     Return the number of elements in character set CS.

 -- Scheme Procedure: char-set-count pred cs
 -- C Function: scm_char_set_count (pred, cs)
     Return the number of the elements int the character set CS which satisfy the predicate PRED.

 -- Scheme Procedure: char-set->list cs
 -- C Function: scm_char_set_to_list (cs)
     Return a list containing the elements of the character set CS.

 -- Scheme Procedure: char-set->string cs
 -- C Function: scm_char_set_to_string (cs)
     Return a string containing the elements of the character set CS.  The order in which the characters are placed in the string is not defined.

 -- Scheme Procedure: char-set-contains? cs ch
 -- C Function: scm_char_set_contains_p (cs, ch)
     Return #t iff the character CH is contained in the character set CS.

 -- Scheme Procedure: char-set-every pred cs
 -- C Function: scm_char_set_every (pred, cs)
     Return a true value if every character in the character set CS satisfies the predicate PRED.

 -- Scheme Procedure: char-set-any pred cs
 -- C Function: scm_char_set_any (pred, cs)
     Return a true value if any character in the character set CS satisfies the predicate PRED.

Character-Set Algebra
.....................

Character sets can be manipulated with the common set algebra operation, such as union, complement, intersection etc.  All of these procedures provide side-effecting variants, which modify their character set argument(s).

 -- Scheme Procedure: char-set-adjoin cs . rest
 -- C Function: scm_char_set_adjoin (cs, rest)
     Add all character arguments to the first argument, which must be a character set.

 -- Scheme Procedure: char-set-delete cs . rest
 -- C Function: scm_char_set_delete (cs, rest)
     Delete all character arguments from the first argument, which must be a character set.

 -- Scheme Procedure: char-set-adjoin! cs . rest
 -- C Function: scm_char_set_adjoin_x (cs, rest)
     Add all character arguments to the first argument, which must be a character set.

 -- Scheme Procedure: char-set-delete! cs . rest
 -- C Function: scm_char_set_delete_x (cs, rest)
     Delete all character arguments from the first argument, which must be a character set.

 -- Scheme Procedure: char-set-complement cs
 -- C Function: scm_char_set_complement (cs)
     Return the complement of the character set CS.

 -- Scheme Procedure: char-set-union . rest
 -- C Function: scm_char_set_union (rest)
     Return the union of all argument character sets.

 -- Scheme Procedure: char-set-intersection . rest
 -- C Function: scm_char_set_intersection (rest)
     Return the intersection of all argument character sets.

 -- Scheme Procedure: char-set-difference cs1 . rest
 -- C Function: scm_char_set_difference (cs1, rest)
     Return the difference of all argument character sets.

 -- Scheme Procedure: char-set-xor . rest
 -- C Function: scm_char_set_xor (rest)
     Return the exclusive-or of all argument character sets.

 -- Scheme Procedure: char-set-diff+intersection cs1 . rest
 -- C Function: scm_char_set_diff_plus_intersection (cs1, rest)
     Return the difference and the intersection of all argument character sets.

 -- Scheme Procedure: char-set-complement! cs
 -- C Function: scm_char_set_complement_x (cs)
     Return the complement of the character set CS.

 -- Scheme Procedure: char-set-union! cs1 . rest
 -- C Function: scm_char_set_union_x (cs1, rest)
     Return the union of all argument character sets.

 -- Scheme Procedure: char-set-intersection! cs1 . rest
 -- C Function: scm_char_set_intersection_x (cs1, rest)
     Return the intersection of all argument character sets.

 -- Scheme Procedure: char-set-difference! cs1 . rest
 -- C Function: scm_char_set_difference_x (cs1, rest)
     Return the difference of all argument character sets.

 -- Scheme Procedure: char-set-xor! cs1 . rest
 -- C Function: scm_char_set_xor_x (cs1, rest)
     Return the exclusive-or of all argument character sets.

 -- Scheme Procedure: char-set-diff+intersection! cs1 cs2 . rest
 -- C Function: scm_char_set_diff_plus_intersection_x (cs1, cs2, rest)
     Return the difference and the intersection of all argument character sets.

Standard Character Sets
.......................

In order to make the use of the character set data type and procedures useful, several predefined character set variables exist.

 -- Scheme Variable: char-set:lower-case
 -- C Variable: scm_char_set_lower_case
     All lower-case characters.

 -- Scheme Variable: char-set:upper-case
 -- C Variable: scm_char_set_upper_case
     All upper-case characters.

 -- Scheme Variable: char-set:title-case
 -- C Variable: scm_char_set_title_case
     This is empty, because ASCII has no titlecase characters.

 -- Scheme Variable: char-set:letter
 -- C Variable: scm_char_set_letter
     All letters, e.g. the union of char-set:lower-case and char-set:upper-case.

 -- Scheme Variable: char-set:digit
 -- C Variable: scm_char_set_digit
     All digits.

 -- Scheme Variable: char-set:letter+digit
 -- C Variable: scm_char_set_letter_and_digit
     The union of char-set:letter and char-set:digit.

 -- Scheme Variable: char-set:graphic
 -- C Variable: scm_char_set_graphic
     All characters which would put ink on the paper.

 -- Scheme Variable: char-set:printing
 -- C Variable: scm_char_set_printing
     The union of char-set:graphic and char-set:whitespace.

 -- Scheme Variable: char-set:whitespace
 -- C Variable: scm_char_set_whitespace
     All whitespace characters.

 -- Scheme Variable: char-set:blank
 -- C Variable: scm_char_set_blank
     All horizontal whitespace characters, that is #\space and #\tab.

 -- Scheme Variable: char-set:iso-control
 -- C Variable: scm_char_set_iso_control
     The ISO control characters with the codes 0--31 and 127.

 -- Scheme Variable: char-set:punctuation
 -- C Variable: scm_char_set_punctuation
     The characters !"#%&'()*,-./:;?@[\\]_{}

 -- Scheme Variable: char-set:symbol
 -- C Variable: scm_char_set_symbol
     The characters $+<=>^`|~.

 -- Scheme Variable: char-set:hex-digit
 -- C Variable: scm_char_set_hex_digit
     The hexadecimal digits 0123456789abcdefABCDEF.

 -- Scheme Variable: char-set:ascii
 -- C Variable: scm_char_set_ascii
     All ASCII characters.

 -- Scheme Variable: char-set:empty
 -- C Variable: scm_char_set_empty
     The empty character set.

 -- Scheme Variable: char-set:full
 -- C Variable: scm_char_set_full
     This character set contains all possible characters.

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.

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 \0.

To use strings efficiently, you need to know a bit about how Guile implements them.  In Guile, a string consists of two parts, a head and the actual memory where the characters are stored.  When a string (or a substring of it) is copied, only a new head gets created, the memory is usually not copied.  The two heads start out pointing to the same memory.

When one of these two strings is modified, as with string-set!, their common memory does get copied so that each string has its own memory and modifying one does not accidently modify the other as well. Thus, Guile's strings are `copy on write'; the actual copying of their memory is delayed until one string is written to.

This implementation makes functions like substring very efficient in the common case that no modifications are done to the involved strings.

If you do know that your strings are getting modified right away, you can use substring/copy instead of substring.  This function performs the copy immediately at the time of creation.  This is more efficient, especially in a multi-threaded program.  Also, substring/copy can avoid the problem that a short substring holds on to the memory of a very large original string that could otherwise be recycled.

If you want to avoid the copy altogether, so that modifications of one string show up in the other, you can use substring/shared.  The strings created by this procedure are called mutation sharing substrings since the substring and the original string share modifications to each other.

If you want to prevent modifications, use substring/read-only.

Guile provides all procedures of SRFI-13 and a few more.

String Read Syntax
..................

The read syntax for strings is an arbitrarily long sequence of characters enclosed in double quotes (").

Backslash is an escape character and can be used to insert the following special characters.  \" and \\ are R5RS standard, the rest are Guile extensions, notice they follow C string syntax.

\\
     Backslash character.

\"
     Double quote character (an unescaped " is otherwise the end of the string).

\0
     NUL character (ASCII 0).

\a
     Bell character (ASCII 7).

\f
     Formfeed character (ASCII 12).

\n
     Newline character (ASCII 10).

\r
     Carriage return character (ASCII 13).

\t
     Tab character (ASCII 9).

\v
     Vertical tab character (ASCII 11).

\xHH
     Character code given by two hexadecimal digits.  For example \x7f for an ASCII DEL (127).

The following are examples of string literals:

     "foo"
     "bar plonk"
     "Hello World"
     "\"Hi\", he said."

String Predicates
.................

The following procedures can be used to check whether a given string fulfills some specified property.

 -- Scheme Procedure: string? obj
 -- C Function: scm_string_p (obj)
     Return #t if OBJ is a string, else #f.

 -- C Function: int scm_is_string (SCM obj)
     Returns 1 if OBJ is a string, 0 otherwise.

 -- Scheme Procedure: string-null? str
 -- C Function: scm_string_null_p (str)
     Return #t if STR's length is zero, and #f otherwise.

          (string-null? "")  => #t
          y                    => "foo"
          (string-null? y)     => #f

 -- Scheme Procedure: string-any char_pred s [start [end]]
 -- C Function: scm_string_any (char_pred, s, start, end)
     Check if CHAR_PRED is true for any character in string S.

     CHAR_PRED can be a character to check for any equal to that, or a character set (see Character Sets) to check for any in that set, or a predicate procedure to call.

     For a procedure, calls (CHAR_PRED c) are made successively on the characters from START to END.  If CHAR_PRED returns true (ie. non-#f), string-any stops and that return value is the return from string-any.  The call on the last character (ie. at END-1), if that point is reached, is a tail call.

     If there are no characters in S (ie. START equals END) then the return is #f.

 -- Scheme Procedure: string-every char_pred s [start [end]]
 -- C Function: scm_string_every (char_pred, s, start, end)
     Check if CHAR_PRED is true for every character in string S.

     CHAR_PRED can be a character to check for every character equal to that, or a character set (see Character Sets) to check for every character being in that set, or a predicate procedure to call.

     For a procedure, calls (CHAR_PRED c) are made successively on the characters from START to END.  If CHAR_PRED returns #f, string-every stops and returns #f.  The call on the last character (ie. at END-1), if that point is reached, is a tail call and the return from that call is the return from string-every.

     If there are no characters in S (ie. START equals END) then the return is #t.

String Constructors
...................

The string constructor procedures create new string objects, possibly initializing them with some specified character data.  See also String Selection, for ways to create strings from existing strings.

 -- Scheme Procedure: string . chrs
 -- Scheme Procedure: list->string chrs
 -- C Function: scm_string (chrs)
     Return a newly allocated string composed of the arguments, CHRS.

 -- Scheme Procedure: make-string k [chr]
 -- C Function: scm_make_string (k, chr)
     Return a newly allocated string of length K.  If CHR is given, then all elements of the string are initialized to CHR, otherwise the contents of the STRING are unspecified.

 -- C Function: SCM scm_c_make_string (size_t len, SCM chr)
     Like scm_make_string, but expects the length as a size_t.

 -- Scheme Procedure: string-tabulate proc len
 -- C Function: scm_string_tabulate (proc, len)
     PROC is an integer->char procedure.  Construct a string of size LEN by applying PROC to each index to produce the corresponding string element.  The order in which PROC is applied to the indices is not specified.

 -- Scheme Procedure: reverse-list->string chrs
 -- C Function: scm_reverse_list_to_string (chrs)
     An efficient implementation of (compose string->list reverse):

          (reverse-list->string '(#\a #\B #\c)) => "cBa"

 -- Scheme Procedure: string-join ls [delimiter [grammar]]
 -- C Function: scm_string_join (ls, delimiter, grammar)
     Append the string in the string list LS, using the string DELIM as a delimiter between the elements of LS. GRAMMAR is a symbol which specifies how the delimiter is placed between the strings, and defaults to the symbol infix.

     infix
          Insert the separator between list elements.  An empty string will produce an empty list.

     string-infix
          Like infix, but will raise an error if given the empty list.

     suffix
          Insert the separator after every list element.

     prefix
          Insert the separator before each list element.

List/String conversion
......................

When processing strings, it is often convenient to first convert them into a list representation by using the procedure string->list, work with the resulting list, and then convert it back into a string. These procedures are useful for similar tasks.

 -- Scheme Procedure: string->list str [start [end]]
 -- C Function: scm_substring_to_list (str, start, end)
 -- C Function: scm_string_to_list (str)
     Convert the string STR into a list of characters.

 -- Scheme Procedure: string-split str chr
 -- C Function: scm_string_split (str, chr)
     Split the string STR into the a list of the substrings delimited by appearances of the character CHR.  Note that an empty substring between separator characters will result in an empty string in the result list.

          (string-split "root:x:0:0:root:/root:/bin/bash" #\:)
          =>
          ("root" "x" "0" "0" "root" "/root" "/bin/bash")

          (string-split "::" #\:)
          =>
          ("" "" "")

          (string-split "" #\:)
          =>
          ("")

String Selection
................

Portions of strings can be extracted by these procedures. string-ref delivers individual characters whereas substring can be used to extract substrings from longer strings.

 -- Scheme Procedure: string-length string
 -- C Function: scm_string_length (string)
     Return the number of characters in STRING.

 -- C Function: size_t scm_c_string_length (SCM str)
     Return the number of characters in STR as a size_t.

 -- Scheme Procedure: string-ref str k
 -- C Function: scm_string_ref (str, k)
     Return character K of STR using zero-origin indexing. K must be a valid index of STR.

 -- C Function: SCM scm_c_string_ref (SCM str, size_t k)
     Return character K of STR using zero-origin indexing. K must be a valid index of STR.

 -- Scheme Procedure: string-copy str [start [end]]
 -- C Function: scm_substring_copy (str, start, end)
 -- C Function: scm_string_copy (str)
     Return a copy of the given string STR.

     The returned string shares storage with STR initially, but it is copied as soon as one of the two strings is modified.

 -- Scheme Procedure: substring str start [end]
 -- C Function: scm_substring (str, start, end)
     Return a new string formed from the characters of STR beginning with index START (inclusive) and ending with index END (exclusive). STR must be a string, START and END must be exact integers satisfying:

     0 <= START <= END <= (string-length STR).

     The returned string shares storage with STR initially, but it is copied as soon as one of the two strings is modified.

 -- Scheme Procedure: substring/shared str start [end]
 -- C Function: scm_substring_shared (str, start, end)
     Like substring, but the strings continue to share their storage even if they are modified.  Thus, modifications to STR show up in the new string, and vice versa.

 -- Scheme Procedure: substring/copy str start [end]
 -- C Function: scm_substring_copy (str, start, end)
     Like substring, but the storage for the new string is copied immediately.

 -- Scheme Procedure: substring/read-only str start [end]
 -- C Function: scm_substring_read_only (str, start, end)
     Like substring, but the resulting string can not be modified.

 -- C Function: SCM scm_c_substring (SCM str, size_t start, size_t end)
 -- C Function: SCM scm_c_substring_shared (SCM str, size_t start, size_t end)
 -- C Function: SCM scm_c_substring_copy (SCM str, size_t start, size_t end)
 -- C Function: SCM scm_c_substring_read_only (SCM str, size_t start, size_t end)
     Like scm_substring, etc. but the bounds are given as a size_t.

 -- Scheme Procedure: string-take s n
 -- C Function: scm_string_take (s, n)
     Return the N first characters of S.

 -- Scheme Procedure: string-drop s n
 -- C Function: scm_string_drop (s, n)
     Return all but the first N characters of S.

 -- Scheme Procedure: string-take-right s n
 -- C Function: scm_string_take_right (s, n)
     Return the N last characters of S.

 -- Scheme Procedure: string-drop-right s n
 -- C Function: scm_string_drop_right (s, n)
     Return all but the last N characters of S.

 -- Scheme Procedure: string-pad s len [chr [start [end]]]
 -- Scheme Procedure: string-pad-right s len [chr [start [end]]]
 -- C Function: scm_string_pad (s, len, chr, start, end)
 -- C Function: scm_string_pad_right (s, len, chr, start, end)
     Take characters START to END from the string S and either pad with CHAR or truncate them to give LEN characters.

     string-pad pads or truncates on the left, so for example

          (string-pad "x" 3)     => "  x"
          (string-pad "abcde" 3) => "cde"

     string-pad-right pads or truncates on the right, so for example

          (string-pad-right "x" 3)     => "x  "
          (string-pad-right "abcde" 3) => "abc"

     The return string may share storage with S, or it can be S itself (if START to END is the whole string and it's already LEN characters).

 -- Scheme Procedure: string-trim s [char_pred [start [end]]]
 -- C Function: scm_string_trim (s, char_pred, start, end)
     Trim S by skipping over all characters on the left that satisfy the parameter CHAR_PRED:

       * if it is the character CH, characters equal to CH are trimmed,

       * if it is a procedure PRED characters that satisfy PRED are trimmed,

       * if it is a character set, characters in that set are trimmed.

     If called without a CHAR_PRED argument, all whitespace is trimmed.

 -- Scheme Procedure: string-trim-right s [char_pred [start [end]]]
 -- C Function: scm_string_trim_right (s, char_pred, start, end)
     Trim S by skipping over all characters on the rightt that satisfy the parameter CHAR_PRED:

       * if it is the character CH, characters equal to CH are trimmed,

       * if it is a procedure PRED characters that satisfy PRED are trimmed,

       * if it is a character sets, all characters in that set are trimmed.

     If called without a CHAR_PRED argument, all whitespace is trimmed.

 -- Scheme Procedure: string-trim-both s [char_pred [start [end]]]
 -- C Function: scm_string_trim_both (s, char_pred, start, end)
     Trim S by skipping over all characters on both sides of the string that satisfy the parameter CHAR_PRED:

       * if it is the character CH, characters equal to CH are trimmed,

       * if it is a procedure PRED characters that satisfy PRED are trimmed,

       * if it is a character set, the characters in the set are trimmed.

     If called without a CHAR_PRED argument, all whitespace is trimmed.

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.

 -- Scheme Procedure: string-set! str k chr
 -- C Function: scm_string_set_x (str, k, chr)
     Store CHR in element K of STR and return an unspecified value. K must be a valid index of STR.

 -- C Function: void scm_c_string_set_x (SCM str, size_t k, SCM chr)
     Like scm_string_set_x, but the index is given as a size_t.

 -- Scheme Procedure: string-fill! str chr [start [end]]
 -- C Function: scm_substring_fill_x (str, chr, start, end)
 -- C Function: scm_string_fill_x (str, chr)
     Stores CHR in every element of the given STR and returns an unspecified value.

 -- Scheme Procedure: substring-fill! str start end fill
 -- C Function: scm_substring_fill_x (str, start, end, fill)
     Change every character in STR between START and END to FILL.

          (define y "abcdefg")
          (substring-fill! y 1 3 #\r)
          y
          => "arrdefg"

 -- Scheme Procedure: substring-move! str1 start1 end1 str2 start2
 -- C Function: scm_substring_move_x (str1, start1, end1, str2, start2)
     Copy the substring of STR1 bounded by START1 and END1 into STR2 beginning at position START2. STR1 and STR2 can be the same string.

 -- Scheme Procedure: string-copy! target tstart s [start [end]]
 -- C Function: scm_string_copy_x (target, tstart, s, start, end)
     Copy the sequence of characters from index range [START, END) in string S to string TARGET, beginning at index TSTART.  The characters are copied left-to-right or right-to-left as needed -- the copy is guaranteed to work, even if TARGET and S are the same string.  It is an error if the copy operation runs off the end of the target string.

String Comparison
.................

The procedures in this section are similar to the character ordering predicates (see Characters), but are defined on character sequences.

The first set is specified in R5RS and has names that end in ?. The second set is specified in SRFI-13 and the names have no ending ?.  The predicates ending in -ci ignore the character case when comparing strings.

 -- Scheme Procedure: string=? s1 s2
     Lexicographic equality predicate; return #t if the two strings are the same length and contain the same characters in the same positions, otherwise return #f.

     The procedure string-ci=? treats upper and lower case letters as though they were the same character, but string=? treats upper and lower case as distinct characters.

 -- Scheme Procedure: string<? s1 s2
     Lexicographic ordering predicate; return #t if S1 is lexicographically less than S2.

 -- Scheme Procedure: string<=? s1 s2
     Lexicographic ordering predicate; return #t if S1 is lexicographically less than or equal to S2.

 -- Scheme Procedure: string>? s1 s2
     Lexicographic ordering predicate; return #t if S1 is lexicographically greater than S2.

 -- Scheme Procedure: string>=? s1 s2
     Lexicographic ordering predicate; return #t if S1 is lexicographically greater than or equal to S2.

 -- Scheme Procedure: string-ci=? s1 s2
     Case-insensitive string equality predicate; return #t if the two strings are the same length and their component characters match (ignoring case) at each position; otherwise return #f.

 -- Scheme Procedure: string-ci<? s1 s2
     Case insensitive lexicographic ordering predicate; return #t if S1 is lexicographically less than S2 regardless of case.

 -- Scheme Procedure: string-ci<=? s1 s2
     Case insensitive lexicographic ordering predicate; return #t if S1 is lexicographically less than or equal to S2 regardless of case.

 -- Scheme Procedure: string-ci>? s1 s2
     Case insensitive lexicographic ordering predicate; return #t if S1 is lexicographically greater than S2 regardless of case.

 -- Scheme Procedure: string-ci>=? s1 s2
     Case insensitive lexicographic ordering predicate; return #t if S1 is lexicographically greater than or equal to S2 regardless of case.

 -- Scheme Procedure: string-compare s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_compare (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
     Apply PROC_LT, PROC_EQ, PROC_GT to the mismatch index, depending upon whether S1 is less than, equal to, or greater than S2.  The mismatch index is the largest index I such that for every 0 <= J < I, S1[J] = S2[J] -- that is, I is the first position that does not match.

 -- Scheme Procedure: string-compare-ci s1 s2 proc_lt proc_eq proc_gt [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_compare_ci (s1, s2, proc_lt, proc_eq, proc_gt, start1, end1, start2, end2)
     Apply PROC_LT, PROC_EQ, PROC_GT to the mismatch index, depending upon whether S1 is less than, equal to, or greater than S2.  The mismatch index is the largest index I such that for every 0 <= J < I, S1[J] = S2[J] -- that is, I is the first position that does not match.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_eq (s1, s2, start1, end1, start2, end2)
     Return #f if S1 and S2 are not equal, a true value otherwise.

 -- Scheme Procedure: string<> s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_neq (s1, s2, start1, end1, start2, end2)
     Return #f if S1 and S2 are equal, a true value otherwise.

 -- Scheme Procedure: string< s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_lt (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is greater or equal to S2, a true value otherwise.

 -- Scheme Procedure: string> s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_gt (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is less or equal to S2, a true value otherwise.

 -- Scheme Procedure: string<= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_le (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is greater to S2, a true value otherwise.

 -- Scheme Procedure: string>= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ge (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is less to S2, a true value otherwise.

 -- Scheme Procedure: string-ci= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_eq (s1, s2, start1, end1, start2, end2)
     Return #f if S1 and S2 are not equal, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-ci<> s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_neq (s1, s2, start1, end1, start2, end2)
     Return #f if S1 and S2 are equal, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-ci< s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_lt (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is greater or equal to S2, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-ci> s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_gt (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is less or equal to S2, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-ci<= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_le (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is greater to S2, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-ci>= s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_ci_ge (s1, s2, start1, end1, start2, end2)
     Return #f if S1 is less to S2, a true value otherwise.  The character comparison is done case-insensitively.

 -- Scheme Procedure: string-hash s [bound [start [end]]]
 -- C Function: scm_substring_hash (s, bound, start, end)
     Compute a hash value for S.  the optional argument BOUND is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).

 -- Scheme Procedure: string-hash-ci s [bound [start [end]]]
 -- C Function: scm_substring_hash_ci (s, bound, start, end)
     Compute a hash value for S.  the optional argument BOUND is a non-negative exact integer specifying the range of the hash function. A positive value restricts the return value to the range [0,bound).

String Searching
................

 -- Scheme Procedure: string-index s char_pred [start [end]]
 -- C Function: scm_string_index (s, char_pred, start, end)
     Search through the string S from left to right, returning the index of the first occurence of a character which

       * equals CHAR_PRED, if it is character,

       * satisifies the predicate CHAR_PRED, if it is a procedure,

       * is in the set CHAR_PRED, if it is a character set.

 -- Scheme Procedure: string-rindex s char_pred [start [end]]
 -- C Function: scm_string_rindex (s, char_pred, start, end)
     Search through the string S from right to left, returning the index of the last occurence of a character which

       * equals CHAR_PRED, if it is character,

       * satisifies the predicate CHAR_PRED, if it is a procedure,

       * is in the set if CHAR_PRED is a character set.

 -- Scheme Procedure: string-prefix-length s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_prefix_length (s1, s2, start1, end1, start2, end2)
     Return the length of the longest common prefix of the two strings.

 -- Scheme Procedure: string-prefix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_prefix_length_ci (s1, s2, start1, end1, start2, end2)
     Return the length of the longest common prefix of the two strings, ignoring character case.

 -- Scheme Procedure: string-suffix-length s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_suffix_length (s1, s2, start1, end1, start2, end2)
     Return the length of the longest common suffix of the two strings.

 -- Scheme Procedure: string-suffix-length-ci s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_suffix_length_ci (s1, s2, start1, end1, start2, end2)
     Return the length of the longest common suffix of the two strings, ignoring character case.

 -- Scheme Procedure: string-prefix? s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_prefix_p (s1, s2, start1, end1, start2, end2)
     Is S1 a prefix of S2?

 -- Scheme Procedure: string-prefix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_prefix_ci_p (s1, s2, start1, end1, start2, end2)
     Is S1 a prefix of S2, ignoring character case?

 -- Scheme Procedure: string-suffix? s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_suffix_p (s1, s2, start1, end1, start2, end2)
     Is S1 a suffix of S2?

 -- Scheme Procedure: string-suffix-ci? s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_suffix_ci_p (s1, s2, start1, end1, start2, end2)
     Is S1 a suffix of S2, ignoring character case?

 -- Scheme Procedure: string-index-right s char_pred [start [end]]
 -- C Function: scm_string_index_right (s, char_pred, start, end)
     Search through the string S from right to left, returning the index of the last occurence of a character which

       * equals CHAR_PRED, if it is character,

       * satisifies the predicate CHAR_PRED, if it is a procedure,

       * is in the set if CHAR_PRED is a character set.

 -- Scheme Procedure: string-skip s char_pred [start [end]]
 -- C Function: scm_string_skip (s, char_pred, start, end)
     Search through the string S from left to right, returning the index of the first occurence of a character which

       * does not equal CHAR_PRED, if it is character,

       * does not satisify the predicate CHAR_PRED, if it is a procedure,

       * is not in the set if CHAR_PRED is a character set.

 -- Scheme Procedure: string-skip-right s char_pred [start [end]]
 -- C Function: scm_string_skip_right (s, char_pred, start, end)
     Search through the string S from right to left, returning the index of the last occurence of a character which

       * does not equal CHAR_PRED, if it is character,

       * does not satisfy the predicate CHAR_PRED, if it is a procedure,

       * is not in the set if CHAR_PRED is a character set.

 -- Scheme Procedure: string-count s char_pred [start [end]]
 -- C Function: scm_string_count (s, char_pred, start, end)
     Return the count of the number of characters in the string S which

       * equals CHAR_PRED, if it is character,

       * satisifies the predicate CHAR_PRED, if it is a procedure.

       * is in the set CHAR_PRED, if it is a character set.

 -- Scheme Procedure: string-contains s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_contains (s1, s2, start1, end1, start2, end2)
     Does string S1 contain string S2?  Return the index in S1 where S2 occurs as a substring, or false. The optional start/end indices restrict the operation to the indicated substrings.

 -- Scheme Procedure: string-contains-ci s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_contains_ci (s1, s2, start1, end1, start2, end2)
     Does string S1 contain string S2?  Return the index in S1 where S2 occurs as a substring, or false. The optional start/end indices restrict the operation to the indicated substrings.  Character comparison is done case-insensitively.

Alphabetic Case Mapping
.......................

These are procedures for mapping strings to their upper- or lower-case equivalents, respectively, or for capitalizing strings.

 -- Scheme Procedure: string-upcase str [start [end]]
 -- C Function: scm_substring_upcase (str, start, end)
 -- C Function: scm_string_upcase (str)
     Upcase every character in str.

 -- Scheme Procedure: string-upcase! str [start [end]]
 -- C Function: scm_substring_upcase_x (str, start, end)
 -- C Function: scm_string_upcase_x (str)
     Destructively upcase every character in str.

          (string-upcase! y)
          => "ARRDEFG"
          y
          => "ARRDEFG"

 -- Scheme Procedure: string-downcase str [start [end]]
 -- C Function: scm_substring_downcase (str, start, end)
 -- C Function: scm_string_downcase (str)
     Downcase every character in STR.

 -- Scheme Procedure: string-downcase! str [start [end]]
 -- C Function: scm_substring_downcase_x (str, start, end)
 -- C Function: scm_string_downcase_x (str)
     Destructively downcase every character in STR.

          y
          => "ARRDEFG"
          (string-downcase! y)
          => "arrdefg"
          y
          => "arrdefg"

 -- Scheme Procedure: string-capitalize str
 -- C Function: scm_string_capitalize (str)
     Return a freshly allocated string with the characters in STR, where the first character of every word is capitalized.

 -- Scheme Procedure: string-capitalize! str
 -- C Function: scm_string_capitalize_x (str)
     Upcase the first character of every word in STR destructively and return STR.

          y                      => "hello world"
          (string-capitalize! y) => "Hello World"
          y                      => "Hello World"

 -- Scheme Procedure: string-titlecase str [start [end]]
 -- C Function: scm_string_titlecase (str, start, end)
     Titlecase every first character in a word in STR.

 -- Scheme Procedure: string-titlecase! str [start [end]]
 -- C Function: scm_string_titlecase_x (str, start, end)
     Destructively titlecase every first character in a word in STR.

Reversing and Appending Strings
...............................

 -- Scheme Procedure: string-reverse str [start [end]]
 -- C Function: scm_string_reverse (str, start, end)
     Reverse the string STR.  The optional arguments START and END delimit the region of STR to operate on.

 -- Scheme Procedure: string-reverse! str [start [end]]
 -- C Function: scm_string_reverse_x (str, start, end)
     Reverse the string STR in-place.  The optional arguments START and END delimit the region of STR to operate on.  The return value is unspecified.

 -- Scheme Procedure: string-append . args
 -- C Function: scm_string_append (args)
     Return a newly allocated string whose characters form the concatenation of the given strings, ARGS.

          (let ((h "hello "))
            (string-append h "world"))
          => "hello world"

 -- Scheme Procedure: string-append/shared . ls
 -- C Function: scm_string_append_shared (ls)
     Like string-append, but the result may share memory with the argument strings.

 -- Scheme Procedure: string-concatenate ls
 -- C Function: scm_string_concatenate (ls)
     Append the elements of LS (which must be strings) together into a single string.  Guaranteed to return a freshly allocated string.

 -- Scheme Procedure: string-concatenate-reverse ls [final_string [end]]
 -- C Function: scm_string_concatenate_reverse (ls, final_string, end)
     Without optional arguments, this procedure is equivalent to

          (string-concatenate (reverse ls))

     If the optional argument FINAL_STRING is specified, it is consed onto the beginning to LS before performing the list-reverse and string-concatenate operations.  If END is given, only the characters of FINAL_STRING up to index END are used.

     Guaranteed to return a freshly allocated string.

 -- Scheme Procedure: string-concatenate/shared ls
 -- C Function: scm_string_concatenate_shared (ls)
     Like string-concatenate, but the result may share memory with the strings in the list LS.

 -- Scheme Procedure: string-concatenate-reverse/shared ls [final_string [end]]
 -- C Function: scm_string_concatenate_reverse_shared (ls, final_string, end)
     Like string-concatenate-reverse, but the result may share memory with the the strings in the LS arguments.

Mapping, Folding, and Unfolding
...............................

 -- Scheme Procedure: string-map proc s [start [end]]
 -- C Function: scm_string_map (proc, s, start, end)
     PROC is a char->char procedure, it is mapped over S.  The order in which the procedure is applied to the string elements is not specified.

 -- Scheme Procedure: string-map! proc s [start [end]]
 -- C Function: scm_string_map_x (proc, s, start, end)
     PROC is a char->char procedure, it is mapped over S.  The order in which the procedure is applied to the string elements is not specified.  The string S is modified in-place, the return value is not specified.

 -- Scheme Procedure: string-for-each proc s [start [end]]
 -- C Function: scm_string_for_each (proc, s, start, end)
     PROC is mapped over S in left-to-right order.  The return value is not specified.

 -- Scheme Procedure: string-for-each-index proc s [start [end]]
 -- C Function: scm_string_for_each_index (proc, s, start, end)
     Call (PROC i) for each index i in S, from left to right.

     For example, to change characters to alternately upper and lower case,

          (define str (string-copy "studly"))
          (string-for-each-index (lambda (i)
                                   (string-set! str i
                                     ((if (even? i) char-upcase char-downcase)
                                      (string-ref str i))))
                                 str)
          str => "StUdLy"

 -- Scheme Procedure: string-fold kons knil s [start [end]]
 -- C Function: scm_string_fold (kons, knil, s, start, end)
     Fold KONS over the characters of S, with KNIL as the terminating element, from left to right.  KONS must expect two arguments: The actual character and the last result of KONS' application.

 -- Scheme Procedure: string-fold-right kons knil s [start [end]]
 -- C Function: scm_string_fold_right (kons, knil, s, start, end)
     Fold KONS over the characters of S, with KNIL as the terminating element, from right to left.  KONS must expect two arguments: The actual character and the last result of KONS' application.

 -- Scheme Procedure: string-unfold p f g seed [base [make_final]]
 -- C Function: scm_string_unfold (p, f, g, seed, base, make_final)

       * G is used to generate a series of seed values from the initial SEED: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

       * P tells us when to stop -- when it returns true when applied to one of these seed values.

       * F maps each seed value to the corresponding character in the result string.  These chars are assembled into the string in a left-to-right order.

       * BASE is the optional initial/leftmost portion of the constructed string; it default to the empty string.

       * MAKE_FINAL is applied to the terminal seed value (on which P returns true) to produce the final/rightmost portion of the constructed string. It defaults to (lambda (x) ).

 -- Scheme Procedure: string-unfold-right p f g seed [base [make_final]]
 -- C Function: scm_string_unfold_right (p, f, g, seed, base, make_final)

       * G is used to generate a series of seed values from the initial SEED: SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...

       * P tells us when to stop -- when it returns true when applied to one of these seed values.

       * F maps each seed value to the corresponding character in the result string.  These chars are assembled into the string in a right-to-left order.

       * BASE is the optional initial/rightmost portion of the constructed string; it default to the empty string.

       * MAKE_FINAL is applied to the terminal seed value (on which P returns true) to produce the final/leftmost portion of the constructed string. It defaults to (lambda (x) ).

Miscellaneous String Operations
...............................

 -- Scheme Procedure: xsubstring s from [to [start [end]]]
 -- C Function: scm_xsubstring (s, from, to, start, end)
     This is the extended substring procedure that implements replicated copying of a substring of some string.

     S is a string, START and END are optional arguments that demarcate a substring of S, defaulting to 0 and the length of S.  Replicate this substring up and down index space, in both the positive and negative directions. xsubstring returns the substring of this string beginning at index FROM, and ending at TO, which defaults to FROM + (END - START).

 -- Scheme Procedure: string-xcopy! target tstart s sfrom [sto [start [end]]]
 -- C Function: scm_string_xcopy_x (target, tstart, s, sfrom, sto, start, end)
     Exactly the same as xsubstring, but the extracted text is written into the string TARGET starting at index TSTART.  The operation is not defined if (eq? TARGET S) or these arguments share storage -- you cannot copy a string on top of itself.

 -- Scheme Procedure: string-replace s1 s2 [start1 [end1 [start2 [end2]]]]
 -- C Function: scm_string_replace (s1, s2, start1, end1, start2, end2)
     Return the string S1, but with the characters START1 ... END1 replaced by the characters START2 ... END2 from S2.

 -- Scheme Procedure: string-tokenize s [token_set [start [end]]]
 -- C Function: scm_string_tokenize (s, token_set, start, end)
     Split the string S into a list of substrings, where each substring is a maximal non-empty contiguous sequence of characters from the character set TOKEN_SET, which defaults to char-set:graphic. If START or END indices are provided, they restrict string-tokenize to operating on the indicated substring of S.

 -- Scheme Procedure: string-filter s char_pred [start [end]]
 -- C Function: scm_string_filter (s, char_pred, start, end)
     Filter the string S, retaining only those characters that satisfy the CHAR_PRED argument.  If the argument is a procedure, it is applied to each character as a predicate, if it is a character, it is tested for equality and if it is a character set, it is tested for membership.

 -- Scheme Procedure: string-delete s char_pred [start [end]]
 -- C Function: scm_string_delete (s, char_pred, start, end)
     Filter the string S, retaining only those characters that do not satisfy the CHAR_PRED argument.  If the argument is a procedure, it is applied to each character as a predicate, if it is a character, it is tested for equality and if it is a character set, it is tested for membership.

Conversion to/from C
....................

When creating a Scheme string from a C string or when converting a Scheme string to a C string, the concept of character encoding becomes important.

In C, a string is just a sequence of bytes, and the character encoding describes the relation between these bytes and the actual characters that make up the string.  For Scheme strings, character encoding is not an issue (most of the time), since in Scheme you never get to see the bytes, only the characters.

Well, ideally, anyway.  Right now, Guile simply equates Scheme characters and bytes, ignoring the possibility of multi-byte encodings completely.  This will change in the future, where Guile will use Unicode codepoints as its characters and UTF-8 or some other encoding as its internal encoding.  When you exclusively use the functions listed in this section, you are `future-proof'.

Converting a Scheme string to a C string will often allocate fresh memory to hold the result.  You must take care that this memory is properly freed eventually.  In many cases, this can be achieved by using scm_frame_free inside an appropriate frame, see Frames.

 -- C Function: SCM scm_from_locale_string (const char *str)
 -- C Function: SCM scm_from_locale_stringn (const char *str, size_t len)
     Creates a new Scheme string that has the same contents as STR when interpreted in the current locale character encoding.

     For scm_from_locale_string, STR must be null-terminated.

     For scm_from_locale_stringn, LEN specifies the length of STR in bytes, and STR does not need to be null-terminated. If LEN is (size_t)-1, then STR does need to be null-terminated and the real length will be found with strlen.

 -- C Function: SCM scm_take_locale_string (char *str)
 -- C Function: SCM scm_take_locale_stringn (char *str, size_t len)
     Like scm_from_locale_string and scm_from_locale_stringn, respectively, but also frees STR with free eventually. Thus, you can use this function when you would free STR anyway immediately after creating the Scheme string.  In certain cases, Guile can then use STR directly as its internal representation.

 -- C Function: char * scm_to_locale_string (SCM str)
 -- C Function: char * scm_to_locale_stringn (SCM str, size_t *lenp)
     Returns a C string in the current locale encoding with the same contents as STR.  The C string must be freed with free eventually, maybe by using scm_frame_free, see Frames.

     For scm_to_locale_string, the returned string is null-terminated and an error is signalled when STR contains #\nul characters.

     For scm_to_locale_stringn and LENP not NULL, STR might contain #\nul characters and the length of the returned string in bytes is stored in *LENP.  The returned string will not be null-terminated in this case.  If LENP is NULL, scm_to_locale_stringn behaves like scm_to_locale_string.

 -- C Function: size_t scm_to_locale_stringbuf (SCM str, char *buf, size_t max_len)
     Puts STR as a C string in the current locale encoding into the memory pointed to by BUF.  The buffer at BUF has room for MAX_LEN bytes and scm_to_local_stringbuf will never store more than that.  No terminating '\0' will be stored.

     The return value of scm_to_locale_stringbuf is the number of bytes that are needed for all of STR, regardless of whether BUF was large enough to hold them.  Thus, when the return value is larger than MAX_LEN, only MAX_LEN bytes have been stored and you probably need to try again with a larger buffer.

Regular Expressions
-------------------

A regular expression (or 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 (see Syntax of Regular Expressions (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 (provided? 'regex) returns true.

The following regexp and string matching features are provided by the (ice-9 regex) module.  Before using the described functions, you should load this module by executing (use-modules (ice-9 regex)).

Regexp Functions
................

By default, Guile supports POSIX extended regular expressions. That means that the characters (, ), + and ? 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.

 -- Scheme Procedure: string-match pattern str [start]
     Compile the string PATTERN into a regular expression and compare it with STR.  The optional numeric argument START specifies the position of STR at which to begin matching.

     string-match returns a match structure which describes what, if anything, was matched by the regular expression.  See Match Structures.  If STR does not match PATTERN at all, string-match returns #f.

Two examples of a match follow.  In the first example, the pattern matches the four digits in the match string.  In the second, the pattern matches nothing.

     (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
     => #("blah2002" (4 . 8))

     (string-match "[A-Za-z]" "123456")
     => #f

Each time string-match is called, it must compile its PATTERN argument into a regular expression structure.  This operation is expensive, which makes 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.

 -- Scheme Procedure: make-regexp pat flag...
 -- C Function: scm_make_regexp (pat, flaglst)
     Compile the regular expression described by PAT, and return the compiled regexp structure.  If PAT does not describe a legal regular expression, make-regexp throws a regular-expression-syntax error.

     The FLAG arguments change the behavior of the compiled regular expression.  The following values may be supplied:

      -- Variable: regexp/icase
          Consider uppercase and lowercase letters to be the same when matching.

      -- Variable: regexp/newline
          If a newline appears in the target string, then permit the ^ and $ operators to match immediately after or immediately before the newline, respectively.  Also, the . and [^...] 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.

      -- Variable: regexp/basic
          Compile a basic (``obsolete'') regexp instead of the extended (``modern'') regexps that are the default.  Basic regexps do not consider |, + or ? to be special characters, and require the {...} and (...) metacharacters to be backslash-escaped (see Backslash Escapes).  There are several other differences between basic and extended regular expressions, but these are the most significant.

      -- Variable: 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 make-regexp includes both regexp/basic and regexp/extended flags, the one which comes last will override the earlier one.

 -- Scheme Procedure: regexp-exec rx str [start [flags]]
 -- C Function: scm_regexp_exec (rx, str, start, flags)
     Match the compiled regular expression RX against str.  If the optional integer START argument is provided, begin matching from that position in the string. Return a match structure describing the results of the match, or #f if no match could be found.

     The FLAGS arguments change the matching behavior. The following flags may be supplied:

      -- Variable: regexp/notbol
          Operator ^ always fails (unless regexp/newline is used).  Use this when the beginning of the string should not be considered the beginning of a line.

      -- Variable: regexp/noteol
          Operator $ always fails (unless regexp/newline is used).  Use this when the end of the string should not be considered the end of a line.

     ;; Regexp to match uppercase letters
     (define r (make-regexp "[A-Z]*"))

     ;; Regexp to match letters, ignoring case
     (define ri (make-regexp "[A-Z]*" regexp/icase))

     ;; Search for bob using regexp r
     (match:substring (regexp-exec r "bob"))
     => ""                  ; no match

     ;; Search for bob using regexp ri
     (match:substring (regexp-exec ri "Bob"))
     => "Bob"               ; matched case insensitive

 -- Scheme Procedure: regexp? obj
 -- C Function: scm_regexp_p (obj)
     Return #t if OBJ is a compiled regular expression, or #f otherwise.

Regular expressions are commonly used to find patterns in one string and replace them with the contents of another string.  The following functions are convenient ways to do this.

 -- Scheme Procedure: regexp-substitute port match [item...]
     Write to PORT selected parts of the match structure MATCH. Or if PORT is #f then form a string from those parts and return that.

     Each ITEM specifies a part to be written, and may be one of the following,

       * A string.  String arguments are written out verbatim.

       * An integer.  The submatch with that number is written (match:substring).  Zero is the entire match.

       * The symbol pre.  The portion of the matched string preceding the regexp match is written (match:prefix).

       * The symbol post.  The portion of the matched string following the regexp match is written (match:suffix).

     For example, changing a match and retaining the text before and after,

          (regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
                             'pre "37" 'post)
          => "number 37 is good"

     Or matching a YYYYMMDD format date such as 20020828 and re-ordering and hyphenating the fields.

          (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
          (define s "Date 20020429 12am.")
          (regexp-substitute #f (string-match date-regex s)
                             'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
          => "Date 04-29-2002 12am. (20020429)"

 -- Scheme Procedure: regexp-substitute/global port regexp target [item...]
     Write to PORT selected parts of matches of REGEXP in TARGET.  If PORT is #f then form a string from those parts and return that.  REGEXP can be a string or a compiled regex.

     This is similar to regexp-substitute, but allows global substitutions on TARGET.  Each ITEM behaves as per regexp-substitute, with the following differences,

       * A function.  Called as (ITEM match) with the match structure for the REGEXP match, it should return a string to be written to PORT.

       * The symbol post.  This doesn't output anything, but instead causes regexp-substitute/global to recurse on the unmatched portion of TARGET.

          This must be supplied to perform a global search and replace on TARGET; without it regexp-substitute/global returns after a single match and output.

     For example, to collapse runs of tabs and spaces to a single hyphen each,

          (regexp-substitute/global #f "[ \t]+"  "this   is   the text"
                                    'pre "-" 'post)
          => "this-is-the-text"

     Or using a function to reverse the letters in each word,

          (regexp-substitute/global #f "[a-z]+"  "to do and not-do"
            'pre (lambda (m) (string-reverse (match:substring m))) 'post)
          => "ot od dna ton-od"

     Without the post symbol, just one regexp match is made.  For example the following is the date example from regexp-substitute above, without the need for the separate string-match call.

          (define date-regex "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
          (define s "Date 20020429 12am.")
          (regexp-substitute/global #f date-regex s
                                    'pre 2 "-" 3 "-" 1 'post " (" 0 ")")

          => "Date 04-29-2002 12am. (20020429)"

Match Structures
................

A match structure is the object returned by string-match and 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 match argument must be a match structure returned by a previous call to string-match or 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 TARGET for easy reference.

 -- Scheme Procedure: regexp-match? obj
     Return #t if OBJ is a match structure returned by a previous call to regexp-exec, or #f otherwise.

 -- Scheme Procedure: match:substring match [n]
     Return the portion of TARGET matched by subexpression number N.  Submatch 0 (the default) represents the entire regexp match. If the regular expression as a whole matched, but the subexpression number N did not match, return #f.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:substring s)
     => "2002"

     ;; match starting at offset 6 in the string
     (match:substring
       (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
     => "7654"

 -- Scheme Procedure: match:start match [n]
     Return the starting position of submatch number N.

In the following example, the result is 4, since the match starts at character index 4:

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:start s)
     => 4

 -- Scheme Procedure: match:end match [n]
     Return the ending position of submatch number N.

In the following example, the result is 8, since the match runs between characters 4 and 8 (i.e. the ``2002'').

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:end s)
     => 8

 -- Scheme Procedure: match:prefix match
     Return the unmatched portion of TARGET preceding the regexp match.

          (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
          (match:prefix s)
          => "blah"

 -- Scheme Procedure: match:suffix match
     Return the unmatched portion of TARGET following the regexp match.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:suffix s)
     => "foo"

 -- Scheme Procedure: match:count match
     Return the number of parenthesized subexpressions from MATCH. Note that the entire regular expression match itself counts as a subexpression, and failed submatches are included in the count.

 -- Scheme Procedure: match:string match
     Return the original TARGET string.

     (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
     (match:string s)
     => "blah2002foo"

Backslash Escapes
.................

Sometimes you will want a regexp to match characters like * or $ 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 ^* [^:]*::.  However, this won't work; because the asterisk is a metacharacter, it won't match the * 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 \.  (This is also called quoting the metacharacter, and is known as a 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 ^\* [^:]*::.  The \* 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 \let\ followed by any number of alphabetic characters.  The regular expression \\let\\[A-Za-z]* would do this: the double backslashes in the regexp each match a single backslash in the target string.

 -- Scheme Procedure: regexp-quote str
     Quote each special character found in STR with a backslash, and return the resulting string.

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 \n in the middle of a string while processing Scheme code, it replaces those characters with a newline character.  Similarly, the character sequence \t is replaced by a horizontal tab.  Several of these escape sequences are processed by the Guile reader before your code is executed. Unrecognized escape sequences are ignored: if the characters \* appear in a string, they will be translated to the single character *.

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 two consecutive backslashes:

     (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))

The string in this example is preprocessed by the Guile reader before any code is executed.  The resulting argument to make-regexp is the string ^\* [^:]*, 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 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:

     (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))

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.

Symbols
-------

Symbols in Scheme are widely used in three ways: as items of discrete data, as lookup keys for alists and hash tables, and to denote variable references.

A symbol is similar to a string in that it is defined by a sequence of characters.  The sequence of characters is known as the symbol's name.  In the usual case --- that is, where the symbol's name doesn't include any characters that could be confused with other elements of Scheme syntax --- a symbol is written in a Scheme program by writing the sequence of characters that make up the name, without any quotation marks or other special syntax.  For example, the symbol whose name is ``multiply-by-2'' is written, simply:

     multiply-by-2

Notice how this differs from a string with contents ``multiply-by-2'', which is written with double quotation marks, like this:

     "multiply-by-2"

Looking beyond how they are written, symbols are different from strings in two important respects.

The first important difference is uniqueness.  If the same-looking string is read twice from two different places in a program, the result is two different 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 same symbol object both times.

Given two read symbols, you can use eq? to test whether they are the same (that is, have the same name).  eq? is the most efficient comparison operator in Scheme, and comparing two symbols like this is as fast as comparing, for example, two numbers.  Given two strings, on the other hand, you must use equal? or string=?, which are much slower comparison operators, to determine whether the strings have the same contents.

     (define sym1 (quote hello))
     (define sym2 (quote hello))
     (eq? sym1 sym2) => #t

     (define str1 "hello")
     (define str2 "hello")
     (eq? str1 str2) => #f
     (equal? str1 str2) => #t

The second important difference is that symbols, unlike strings, are not self-evaluating.  This is why we need the (quote ...)s in the example above: (quote hello) evaluates to the symbol named "hello" itself, whereas an unquoted hello is read as the symbol named "hello" and evaluated as a variable reference ... about which more below (see Symbol Variables).

Symbols as Discrete Data
........................

Numbers and symbols are similar to the extent that they both lend themselves to eq? comparison.  But symbols are more descriptive than numbers, because a symbol's name can be used directly to describe the concept for which that symbol stands.

For example, imagine that you need to represent some colours in a computer program.  Using numbers, you would have to choose arbitrarily some mapping between numbers and colours, and then take care to use that mapping consistently:

     ;; 1=red, 2=green, 3=purple

     (if (eq? (colour-of car) 1)
         ...)

You can make the mapping more explicit and the code more readable by defining constants:

     (define red 1)
     (define green 2)
     (define purple 3)

     (if (eq? (colour-of car) red)
         ...)

But the simplest and clearest approach is not to use numbers at all, but symbols whose names specify the colours that they refer to:

     (if (eq? (colour-of car) 'red)
         ...)

The descriptive advantages of symbols over numbers increase as the set of concepts that you want to describe grows.  Suppose that a car object can have other properties as well, such as whether it has or uses:

  * automatic or manual transmission

  * leaded or unleaded fuel

  * power steering (or not).

Then a car's combined property set could be naturally represented and manipulated as a list of symbols:

     (properties-of car1)
     =>
     (red manual unleaded power-steering)

     (if (memq 'power-steering (properties-of car1))
         (display "Unfit people can drive this car.\n")
         (display "You'll need strong arms to drive this car!\n"))
     -|
     Unfit people can drive this car.

Remember, the fundamental property of symbols that we are relying on here is that an occurrence of 'red in one part of a program is an indistinguishable symbol from an occurrence of 'red in another part of a program; this means that symbols can usefully be compared using eq?.  At the same time, symbols have naturally descriptive names.  This combination of efficiency and descriptive power makes them ideal for use as discrete data.

Symbols as Lookup Keys
......................

Given their efficiency and descriptive power, it is natural to use symbols as the keys in an association list or hash table.

To illustrate this, consider a more structured representation of the car properties example from the preceding subsection.  Rather than mixing all the properties up together in a flat list, we could use an association list like this:

     (define car1-properties '((colour . red)
                               (transmission . manual)
                               (fuel . unleaded)
                               (steering . power-assisted)))

Notice how this structure is more explicit and extensible than the flat list.  For example it makes clear that manual refers to the transmission rather than, say, the windows or the locking of the car. It also allows further properties to use the same symbols among their possible values without becoming ambiguous:

     (define car1-properties '((colour . red)
                               (transmission . manual)
                               (fuel . unleaded)
                               (steering . power-assisted)
                               (seat-colour . red)
                               (locking . manual)))

With a representation like this, it is easy to use the efficient assq-XXX family of procedures (see Association Lists) to extract or change individual pieces of information:

     (assq-ref car1-properties 'fuel) => unleaded
     (assq-ref car1-properties 'transmission) => manual

     (assq-set! car1-properties 'seat-colour 'black)
     =>
     ((colour . red)
      (transmission . manual)
      (fuel . unleaded)
      (steering . power-assisted)
      (seat-colour . black)
      (locking . manual)))

Hash tables also have keys, and exactly the same arguments apply to the use of symbols in hash tables as in association lists.  The hash value that Guile uses to decide where to add a symbol-keyed entry to a hash table can be obtained by calling the symbol-hash procedure:

 -- Scheme Procedure: symbol-hash symbol
 -- C Function: scm_symbol_hash (symbol)
     Return a hash value for SYMBOL.

See Hash Tables for information about hash tables in general, and for why you might choose to use a hash table rather than an association list.

Symbols as Denoting Variables
.............................

When an unquoted symbol in a Scheme program is evaluated, it is interpreted as a variable reference, and the result of the evaluation is the appropriate variable's value.

For example, when the expression (string-length "abcd") is read and evaluated, the sequence of characters 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 string-length symbol results in that procedure.

The details of the connection between an unquoted symbol and the variable to which it refers are explained elsewhere.  See Binding Constructs, for how associations between symbols and variables are created, and Modules, for how those associations are affected by Guile's module system.

Operations Related to Symbols
.............................

Given any Scheme value, you can determine whether it is a symbol using the symbol? primitive:

 -- Scheme Procedure: symbol? obj
 -- C Function: scm_symbol_p (obj)
     Return #t if OBJ is a symbol, otherwise return #f.

 -- C Function: int scm_is_symbol (SCM val)
     Equivalent to scm_is_true (scm_symbol_p (val)).

Once you know that you have a symbol, you can obtain its name as a string by calling symbol->string.  Note that Guile differs by default from R5RS on the details of symbol->string as regards case-sensitivity:

 -- Scheme Procedure: symbol->string s
 -- C Function: scm_symbol_to_string (s)
     Return the name of symbol S as a string.  By default, Guile reads symbols case-sensitively, so the string returned will have the same case variation as the sequence of characters that caused S to be created.

     If Guile is set to read symbols case-insensitively (as specified by R5RS), and S comes into being as part of a literal expression (see Literal expressions (The Revised^5 Report on Scheme)) or by a call to the read or string-ci->symbol procedures, Guile converts any alphabetic characters in the symbol's name to lower case before creating the symbol object, so the string returned here will be in lower case.

     If S was created by string->symbol, the case of characters in the string returned will be the same as that in the string that was passed to string->symbol, regardless of Guile's case-sensitivity setting at the time S was created.

     It is an error to apply mutation procedures like string-set! to strings returned by this procedure.

Most symbols are created by writing them literally in code.  However it is also possible to create symbols programmatically using the following string->symbol and string-ci->symbol procedures:

 -- Scheme Procedure: string->symbol string
 -- C Function: scm_string_to_symbol (string)
     Return the symbol whose name is 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.

 -- Scheme Procedure: string-ci->symbol str
 -- C Function: scm_string_ci_to_symbol (str)
     Return the symbol whose name is STR.  If Guile is currently reading symbols case-insensitively, STR is converted to lowercase before the returned symbol is looked up or created.

The following examples illustrate Guile's detailed behaviour as regards the case-sensitivity of symbols:

     (read-enable 'case-insensitive)   ; R5RS compliant behaviour

     (symbol->string 'flying-fish)    => "flying-fish"
     (symbol->string 'Martin)         => "martin"
     (symbol->string
        (string->symbol "Malvina"))   => "Malvina"

     (eq? 'mISSISSIppi 'mississippi)  => #t
     (string->symbol "mISSISSIppi")   => mISSISSIppi
     (eq? 'bitBlt (string->symbol "bitBlt")) => #f
     (eq? 'LolliPop
       (string->symbol (symbol->string 'LolliPop))) => #t
     (string=? "K. Harper, M.D."
       (symbol->string
         (string->symbol "K. Harper, M.D."))) => #t

     (read-disable 'case-insensitive)   ; Guile default behaviour

     (symbol->string 'flying-fish)    => "flying-fish"
     (symbol->string 'Martin)         => "Martin"
     (symbol->string
        (string->symbol "Malvina"))   => "Malvina"

     (eq? 'mISSISSIppi 'mississippi)  => #f
     (string->symbol "mISSISSIppi")   => mISSISSIppi
     (eq? 'bitBlt (string->symbol "bitBlt")) => #t
     (eq? 'LolliPop
       (string->symbol (symbol->string 'LolliPop))) => #t
     (string=? "K. Harper, M.D."
       (symbol->string
         (string->symbol "K. Harper, M.D."))) => #t

From C, there are lower level functions that construct a Scheme symbol from a C string in the current locale encoding.

When you want to do more from C, you should convert between symbols and strings using scm_symbol_to_string and scm_string_to_symbol and work with the strings.

 -- C Function: scm_from_locale_symbol (const char *name)
 -- C Function: scm_from_locale_symboln (const char *name, size_t len)
     Construct and return a Scheme symbol whose name is specified by NAME.  For scm_from_locale_symbol, NAME must be null terminated; for scm_from_locale_symboln the length of NAME is specified explicitly by LEN.

Finally, some applications, especially those that generate new Scheme code dynamically, need to generate symbols for use in the generated code.  The gensym primitive meets this need:

 -- Scheme Procedure: gensym [prefix]
 -- C Function: scm_gensym (prefix)
     Create a new symbol with a name constructed from a prefix and a counter value.  The string PREFIX can be specified as an optional argument.  Default prefix is  g.  The counter is increased by 1 at each call.  There is no provision for resetting the counter.

The symbols generated by gensym are likely to be unique, since their names begin with a space and it is only otherwise possible to generate such symbols if a programmer goes out of their way to do so.  Uniqueness can be guaranteed by instead using uninterned symbols (see Symbol Uninterned), though they can't be usefully written out and read back in.

Function Slots and Property Lists
.................................

In traditional Lisp dialects, symbols are often understood as having three kinds of value at once:

  * a variable value, which is used when the symbol appears in code in a variable reference context

  * a function value, which is used when the symbol appears in code in a function name position (i.e. as the first element in an unquoted list)

  * a property list value, which is used when the symbol is given as the first argument to Lisp's put or get functions.

Although Scheme (as one of its simplifications with respect to Lisp) does away with the distinction between variable and function namespaces, Guile currently retains some elements of the traditional structure in case they turn out to be useful when implementing translators for other languages, in particular Emacs Lisp.

Specifically, Guile symbols have two extra slots. for a symbol's property list, and for its ``function value.''  The following procedures are provided to access these slots.

 -- Scheme Procedure: symbol-fref symbol
 -- C Function: scm_symbol_fref (symbol)
     Return the contents of SYMBOL's function slot.

 -- Scheme Procedure: symbol-fset! symbol value
 -- C Function: scm_symbol_fset_x (symbol, value)
     Set the contents of SYMBOL's function slot to VALUE.

 -- Scheme Procedure: symbol-pref symbol
 -- C Function: scm_symbol_pref (symbol)
     Return the property list currently associated with SYMBOL.

 -- Scheme Procedure: symbol-pset! symbol value
 -- C Function: scm_symbol_pset_x (symbol, value)
     Set SYMBOL's property list to VALUE.

 -- Scheme Procedure: symbol-property sym prop
     From SYM's property list, return the value for property PROP.  The assumption is that SYM's property list is an association list whose keys are distinguished from each other using equal?; PROP should be one of the keys in that list.  If the property list has no entry for PROP, symbol-property returns #f.

 -- Scheme Procedure: set-symbol-property! sym prop val
     In SYM's property list, set the value for property PROP to VAL, or add a new entry for PROP, with value VAL, if none already exists.  For the structure of the property list, see symbol-property.

 -- Scheme Procedure: symbol-property-remove! sym prop
     From SYM's property list, remove the entry for property PROP, if there is one.  For the structure of the property list, see symbol-property.

Support for these extra slots may be removed in a future release, and it is probably better to avoid using them.  (In release 1.6, Guile itself uses the property list slot sparingly, and the function slot not at all.)  For a more modern and Schemely approach to properties, see Object Properties.

Extended Read Syntax for Symbols
................................

The read syntax for a symbol is a sequence of letters, digits, and extended alphabetic characters, beginning with a character that cannot begin a number.  In addition, the special cases of +, -, and ... are read as symbols even though numbers can begin with +, - or ..

Extended alphabetic characters may be used within identifiers as if they were letters.  The set of extended alphabetic characters is:

     ! $ % & * + - . / : < = > ? @ ^ _ ~

In addition to the standard read syntax defined above (which is taken from R5RS (see Formal syntax (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.

  * Begin the symbol with the characters #{,

  * write the characters of the symbol and

  * finish the symbol with the characters }#.

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.

     #{foo bar}#

     #{what
     ever}#

     #{4242}#

Although Guile provides this extended read syntax for symbols, widespread usage of it is discouraged because it is not portable and not very readable.

Uninterned Symbols
..................

What makes symbols useful is that they are automatically kept unique. There are no two symbols that are distinct objects but have the same name.  But of course, there is no rule without exception.  In addition to the normal symbols that have been discussed up to now, you can also create special uninterned symbols that behave slightly differently.

To understand what is different about them and why they might be useful, we look at how normal symbols are actually kept unique.

Whenever Guile wants to find the symbol with a specific name, for example during read or when executing string->symbol, it first looks into a table of all existing symbols to find out whether a symbol with the given name already exists.  When this is the case, Guile just returns that symbol.  When not, a new symbol with the name is created and entered into the table so that it can be found later.

Sometimes you might want to create a symbol that is guaranteed `fresh', i.e. a symbol that did not exist previously.  You might also want to somehow guarantee that no one else will ever unintentionally stumble across your symbol in the future.  These properties of a symbol are often needed when generating code during macro expansion.  When introducing new temporary variables, you want to guarantee that they don't conflict with variables in other people's code.

The simplest way to arrange for this is to create a new symbol but not enter it into the global table of all symbols.  That way, no one will ever get access to your symbol by chance.  Symbols that are not in the table are called uninterned.  Of course, symbols that are in the table are called interned.

You create new uninterned symbols with the function make-symbol. You can test whether a symbol is interned or not with symbol-interned?.

Uninterned symbols break the rule that the name of a symbol uniquely identifies the symbol object.  Because of this, they can not be written out and read back in like interned symbols.  Currently, Guile has no support for reading uninterned symbols.  Note that the function gensym does not return uninterned symbols for this reason.

 -- Scheme Procedure: make-symbol name
 -- C Function: scm_make_symbol (name)
     Return a new uninterned symbol with the name NAME.  The returned symbol is guaranteed to be unique and future calls to string->symbol will not return it.

 -- Scheme Procedure: symbol-interned? symbol
 -- C Function: scm_symbol_interned_p (symbol)
     Return #t if SYMBOL is interned, otherwise return #f.

For example:

     (define foo-1 (string->symbol "foo"))
     (define foo-2 (string->symbol "foo"))
     (define foo-3 (make-symbol "foo"))
     (define foo-4 (make-symbol "foo"))

     (eq? foo-1 foo-2)
     => #t
     ; Two interned symbols with the same name are the same object,

     (eq? foo-1 foo-3)
     => #f
     ; but a call to make-symbol with the same name returns a
     ; distinct object.

     (eq? foo-3 foo-4)
     => #f
     ; A call to make-symbol always returns a new object, even for
     ; the same name.

     foo-3
     => #<uninterned-symbol foo 8085290>
     ; Uninterned symbols print differently from interned symbols,

     (symbol? foo-3)
     => #t
     ; but they are still symbols,

     (symbol-interned? foo-3)
     => #f
     ; just not interned.

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 : as well as #:.

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 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:

  * color depth -- Default: the color depth for the screen

  * background color -- Default: white

  * width -- Default: 600

  * height -- Default: 400

If 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:

     (make-window 'default              ;; Color depth
                  'default              ;; Background color
                  800                   ;; Width
                  100                   ;; Height
                  ...)                  ;; More make-window arguments

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:

     (make-window #:width 800 #:height 100)

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 cons, for example, would not be improved if it had to be invoked as

     (cons #:car x #:cdr y)

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.

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 make-window uses a helper procedure called get-keyword-value to extract individual keyword arguments from the rest argument.

     (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))
             ...)
         ...))

But you don't need to write get-keyword-value.  The (ice-9 optargs) module provides a set of powerful macros that you can use to implement keyword-supporting procedures like this:

     (use-modules (ice-9 optargs))

     (define (make-window . args)
       (let-keywords args #f ((depth  screen-depth)
                              (bg     "white")
                              (width  800)
                              (height 100))
         ...))

Or, even more economically, like this:

     (use-modules (ice-9 optargs))

     (define* (make-window #:key (depth  screen-depth)
                                 (bg     "white")
                                 (width  800)
                                 (height 100))
       ...)

For further details on let-keywords, define* and other facilities provided by the (ice-9 optargs) module, see Optional Arguments.

Keyword Read Syntax
...................

Guile, by default, only recognizes a keyword syntax that is compatible with R5RS.  A token of the form #:NAME, where NAME has the same syntax as a Scheme symbol (see Symbol Read Syntax), is the external representation of the keyword named 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 keyword read option is set to 'prefix, Guile also recognizes the alternative read syntax :NAME.  Otherwise, tokens of the form :NAME are read as symbols, as required by R5RS.

To enable and disable the alternative non-R5RS keyword syntax, you use the read-set! procedure documented in User level options interfaces and Reader options.

     (read-set! keywords 'prefix)

     #:type
     =>
     #:type

     :type
     =>
     #:type

     (read-set! keywords #f)

     #:type
     =>
     #:type

     :type
     -|
     ERROR: In expression :type:
     ERROR: Unbound variable: :type
     ABORT: (unbound-variable)

Keyword Procedures
..................

 -- Scheme Procedure: keyword? obj
 -- C Function: scm_keyword_p (obj)
     Return #t if the argument OBJ is a keyword, else #f.

 -- Scheme Procedure: keyword->symbol keyword
 -- C Function: scm_keyword_to_symbol (keyword)
     Return the symbol with the same name as KEYWORD.

 -- Scheme Procedure: symbol->keyword symbol
 -- C Function: scm_symbol_to_keyword (symbol)
     Return the keyword with the same name as SYMBOL.

 -- C Function: int scm_is_keyword (SCM obj)
     Equivalent to scm_is_true (scm_keyword_p (OBJ)).

 -- C Function: SCM scm_from_locale_keyword (const char *str)
 -- C Function: SCM scm_from_locale_keywordn (const char *str, size_t len)
     Equivalent to scm_symbol_to_keyword (scm_from_locale_symbol (STR)) and scm_symbol_to_keyword (scm_from_locale_symboln (STR, LEN)), respectively.

``Functionality-Centric'' Data Types
------------------------------------

Procedures and macros are documented in their own chapter: see Procedures and Macros.

Variable objects are documented as part of the description of Guile's module system: see Variables.

Asyncs, dynamic roots and fluids are described in the chapter on scheduling: see Scheduling.

Hooks are documented in the chapter on general utility functions: see Hooks.

Ports are described in the chapter on I/O: see Input and Output.