This is guile.info, produced by makeinfo version 4.3 from guile.texi.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY

   Guile Reference Manual Copyright (C) 1996 Free Software Foundation
Copyright (C) 1997 Free Software Foundation
Copyright (C) 2000 Free Software Foundation
Copyright (C) 2001 Free Software Foundation
Copyright (C) 2002 Free Software Foundation

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.


File: guile.info,  Node: Primitive Numerics,  Next: Bitwise Operations,  Prev: Scientific,  Up: Numbers

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.

   For the hyperbolic arc-functions, the Guile library exports C
functions corresponding to these Scheme procedures, but taking and
returning arguments of type `double' rather than the usual `SCM'.

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

   For all the other Scheme procedures above, except `expt' and `atan2'
(whose entries specifically mention an equivalent C function), the
equivalent C functions are those provided by the standard mathematics
library.  The mapping is as follows.

     Scheme Procedure   C Function
     `$abs'             `fabs'
     `$sqrt'            `sqrt'
     `$sin'             `sin'
     `$cos'             `cos'
     `$tan'             `tan'
     `$asin'            `asin'
     `$acos'            `acos'
     `$atan'            `atan'
     `$exp'             `exp'
     `$log'             `log'
     `$sinh'            `sinh'
     `$cosh'            `cosh'
     `$tanh'            `tanh'

Naturally, these C functions expect and return `double' arguments.


File: guile.info,  Node: Bitwise Operations,  Next: Random,  Prev: Primitive Numerics,  Up: Numbers

Bitwise Operations
------------------

 - Scheme Procedure: 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
     Return the bitwise OR of the integer arguments.

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

 - Scheme Procedure: logxor n1 n2
     Return the bitwise XOR of the integer arguments.  A bit is set in
     the result if it is set in an odd number of arguments.
          (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 2s-complement of the integer
     argument.

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

 - Scheme Procedure: logtest j k
 - C Function: scm_logtest (j, k)
          (logtest j k) == (not (zero? (logand j k)))
          
          (logtest #b0100 #b1011) => #f
          (logtest #b0100 #b0111) => #t

 - Scheme Procedure: logbit? index j
 - C Function: scm_logbit_p (index, j)
          (logbit? index j) == (logtest (integer-expt 2 index) j)
          
          (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)
     The function ash performs an arithmetic shift left by CNT bits (or
     shift right, if CNT is negative).  'Arithmetic' means, that the
     function does not guarantee to keep the bit structure of N, but
     rather guarantees that the result will always be rounded towards
     minus infinity.  Therefore, the results of ash and a corresponding
     bitwise shift will differ if N is negative.

     Formally, the function returns an integer equivalent to
     `(inexact->exact (floor (* N (expt 2 CNT))))'.

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

 - Scheme Procedure: logcount n
 - C Function: scm_logcount (n)
     Return the number of bits in integer N.  If integer is positive,
     the 1-bits in its binary representation are counted.  If negative,
     the 0-bits in its two's-complement binary representation are
     counted.  If 0, 0 is returned.

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

          (integer-length #b10101010)
             => 8
          (integer-length 0)
             => 0
          (integer-length #b1111)
             => 4

 - Scheme Procedure: integer-expt n k
 - C Function: scm_integer_expt (n, k)
     Return N raised to the non-negative integer exponent K.

          (integer-expt 2 5)
             => 32
          (integer-expt -3 3)
             => -27

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


File: guile.info,  Node: Random,  Prev: Bitwise Operations,  Up: Numbers

Random Number Generation
------------------------

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

     The optional argument STATE must be of the type produced by
     `seed->random-state'. It defaults to the value of the variable
     *RANDOM-STATE*. This object is used to maintain the state of the
     pseudo-random-number generator and is altered as a side effect of
     the random operation.

 - 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! v [state]
 - C Function: scm_random_hollow_sphere_x (v, state)
     Fills vect with inexact real random numbers the sum of whose
     squares is equal to 1.0.  Thinking of vect as coordinates in space
     of dimension n = (vector-length vect), the coordinates are
     uniformly distributed over the surface of the unit n-sphere.

 - 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! v [state]
 - C Function: scm_random_normal_vector_x (v, state)
     Fills vect with inexact real random numbers that are independent
     and standard normally distributed (i.e., with mean 0 and variance
     1).

 - Scheme Procedure: random:solid-sphere! v [state]
 - C Function: scm_random_solid_sphere_x (v, state)
     Fills vect with inexact real random numbers the sum of whose
     squares is less than 1.0.  Thinking of vect as coordinates in
     space of dimension n = (vector-length vect), the coordinates are
     uniformly distributed within the unit n-sphere.  The sum of the
     squares of the numbers is returned.

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


File: guile.info,  Node: Characters,  Next: Strings,  Prev: Numbers,  Up: Simple Data Types

Characters
==========

   Most of the characters in the ASCII character set may be referred to
by name: 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:

   * `#\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'.  Alphabetic means
     the same thing as the isalpha C library function.

 - Scheme Procedure: char-numeric? chr
 - C Function: scm_char_numeric_p (chr)
     Return `#t' iff CHR is numeric, else `#f'.  Numeric means the same
     thing as the isdigit C library function.

 - Scheme Procedure: char-whitespace? chr
 - C Function: scm_char_whitespace_p (chr)
     Return `#t' iff CHR is whitespace, else `#f'.  Whitespace means
     the same thing as the isspace C library function.

 - Scheme Procedure: char-upper-case? chr
 - C Function: scm_char_upper_case_p (chr)
     Return `#t' iff CHR is uppercase, else `#f'.  Uppercase means the
     same thing as the isupper C library function.

 - Scheme Procedure: char-lower-case? chr
 - C Function: scm_char_lower_case_p (chr)
     Return `#t' iff CHR is lowercase, else `#f'.  Lowercase means the
     same thing as the islower C library function.

 - 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'.
     Uppercase and lowercase are as defined by the isupper and islower
     C library functions.

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


File: guile.info,  Node: Strings,  Next: Regular Expressions,  Prev: Characters,  Up: Simple Data Types

Strings
=======

   Strings are fixed-length sequences of characters.  They can be
created by calling constructor procedures, but they can also literally
get entered at the REPL or in Scheme source files.

   Guile provides a rich set of string processing procedures, because
text handling is very important when Guile is used as a scripting
language.

   Strings always carry the information about how many characters they
are composed of with them, so there is no special end-of-string
character, like in C.  That means that Scheme strings can contain any
character, even the NUL character `'\0''.  But note: Since most
operating system calls dealing with strings (such as for file
operations) expect strings to be zero-terminated, they might do
unexpected things when called with string containing unusual characters.

* Menu:

* String Syntax::               Read syntax for strings.
* String Predicates::           Testing strings for certain properties.
* String Constructors::         Creating new string objects.
* List/String Conversion::      Converting from/to lists of characters.
* String Selection::            Select portions from strings.
* String Modification::         Modify parts or whole strings.
* String Comparison::           Lexicographic ordering predicates.
* String Searching::            Searching in strings.
* Alphabetic Case Mapping::     Convert the alphabetic case of strings.
* Appending Strings::           Appending strings to form a new string.


File: guile.info,  Node: String Syntax,  Next: String Predicates,  Up: Strings

String Read Syntax
------------------

   The read syntax for strings is an arbitrarily long sequence of
characters enclosed in double quotes (`"'). (1)  If you want to insert
a double quote character into a string literal, it must be prefixed
with a backslash `\' character (called an "escape character").

   The following are examples of string literals:

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

   ---------- Footnotes ----------

   (1) Actually, the current implementation restricts strings to a
length of 2^24 characters.


File: guile.info,  Node: String Predicates,  Next: String Constructors,  Prev: String Syntax,  Up: Strings

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

 - 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


File: guile.info,  Node: String Constructors,  Next: List/String Conversion,  Prev: String Predicates,  Up: Strings

String Constructors
-------------------

   The string constructor procedures create new string objects, possibly
initializing them with some specified character data.

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


File: guile.info,  Node: List/String Conversion,  Next: String Selection,  Prev: String Constructors,  Up: Strings

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
 - C Function: scm_string_to_list (str)
     Return a newly allocated list of the characters that make up the
     given string STR. `string->list' and `list->string' are inverses
     as far as `equal?' is concerned.

 - 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 "" #\:)
          =>
          ("")


File: guile.info,  Node: String Selection,  Next: String Modification,  Prev: List/String Conversion,  Up: Strings

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.

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

 - Scheme Procedure: string-copy str
 - C Function: scm_string_copy (str)
     Return a newly allocated copy of the given STRING.

 - Scheme Procedure: substring str start [end]
 - C Function: scm_substring (str, start, end)
     Return a newly allocated 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).


File: guile.info,  Node: String Modification,  Next: String Comparison,  Prev: String Selection,  Up: Strings

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.

 - Scheme Procedure: string-fill! str chr
 - C Function: scm_string_fill_x (str, chr)
     Store CHAR in every element of the given STRING and return 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.


File: guile.info,  Node: String Comparison,  Next: String Searching,  Prev: String Modification,  Up: Strings

String Comparison
-----------------

   The procedures in this section are similar to the character ordering
predicates (*note Characters::), but are defined on character sequences.
They all return `#t' on success and `#f' on failure.  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.


File: guile.info,  Node: String Searching,  Next: Alphabetic Case Mapping,  Prev: String Comparison,  Up: Strings

String Searching
----------------

   When searching for the index of a character in a string, these
procedures can be used.

 - Scheme Procedure: string-index str chr [frm [to]]
 - C Function: scm_string_index (str, chr, frm, to)
     Return the index of the first occurrence of CHR in STR.  The
     optional integer arguments FRM and TO limit the search to a
     portion of the string.  This procedure essentially implements the
     `index' or `strchr' functions from the C library.

          (string-index "weiner" #\e)
          => 1
          
          (string-index "weiner" #\e 2)
          => 4
          
          (string-index "weiner" #\e 2 4)
          => #f

 - Scheme Procedure: string-rindex str chr [frm [to]]
 - C Function: scm_string_rindex (str, chr, frm, to)
     Like `string-index', but search from the right of the string
     rather than from the left.  This procedure essentially implements
     the `rindex' or `strrchr' functions from the C library.

          (string-rindex "weiner" #\e)
          => 4
          
          (string-rindex "weiner" #\e 2 4)
          => #f
          
          (string-rindex "weiner" #\e 2 5)
          => 4


File: guile.info,  Node: Alphabetic Case Mapping,  Next: Appending Strings,  Prev: String Searching,  Up: Strings

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
 - C Function: scm_string_upcase (str)
     Return a freshly allocated string containing the characters of STR
     in upper case.

 - Scheme Procedure: string-upcase! str
 - C Function: scm_string_upcase_x (str)
     Destructively upcase every character in STR and return STR.
          y                  => "arrdefg"
          (string-upcase! y) => "ARRDEFG"
          y                  => "ARRDEFG"

 - Scheme Procedure: string-downcase str
 - C Function: scm_string_downcase (str)
     Return a freshly allocation string containing the characters in
     STR in lower case.

 - Scheme Procedure: string-downcase! str
 - C Function: scm_string_downcase_x (str)
     Destructively downcase every character in STR and return 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"


File: guile.info,  Node: Appending Strings,  Prev: Alphabetic Case Mapping,  Up: Strings

Appending Strings
-----------------

   The procedure `string-append' appends several strings together to
form a longer result string.

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


File: guile.info,  Node: Regular Expressions,  Next: Symbols,  Prev: Strings,  Up: Simple Data Types

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 (*note Syntax of Regular Expressions:
(emacs)Regexps.), 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))'.

* Menu:

* Regexp Functions::            Functions that create and match regexps.
* Match Structures::            Finding what was matched by a regexp.
* Backslash Escapes::           Removing the special meaning of regexp
                                meta-characters.


File: guile.info,  Node: Regexp Functions,  Next: Match Structures,  Up: Regular Expressions

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.  *Note 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 . flags
 - C Function: scm_make_regexp (pat, flags)
     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 FLAGS arguments change the behavior of the compiled regular
     expression.  The following flags may be supplied:

    `regexp/icase'
          Consider uppercase and lowercase letters to be the same when
          matching.

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

    `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 (*note Backslash Escapes::).  There are
          several other differences between basic and extended regular
          expressions, but these are the most significant.

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

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

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

 - Scheme Procedure: regexp-substitute port match [item...]
     Write to the output port PORT selected contents of the match
     structure MATCH.  Each ITEM specifies what should be written, and
     may be one of the following arguments:

        * A string.  String arguments are written out verbatim.

        * An integer.  The submatch with that number is written.

        * The symbol `pre'.  The portion of the matched string preceding
          the regexp match is written.

        * The symbol `post'.  The portion of the matched string
          following the regexp match is written.

     The PORT argument may be `#f', in which case nothing is written;
     instead, `regexp-substitute' constructs a string from the
     specified ITEMs and returns that.

   The following example takes a regular expression that matches a
standard YYYYMMDD-format date such as `"20020828"'.  The
`regexp-substitute' call returns a string computed from the information
in the match structure, consisting of the fields and text from the
original string reordered and reformatted.

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

 - Scheme Procedure: regexp-substitute/global port regexp target
          [item...]
     Similar to `regexp-substitute', but can be used to perform global
     substitutions on STR.  Instead of taking a match structure as an
     argument, `regexp-substitute/global' takes two string arguments: a
     REGEXP string describing a regular expression, and a TARGET string
     which should be matched against this regular expression.

     Each ITEM behaves as in REGEXP-SUBSTITUTE, with the following
     exceptions:

        * A function may be supplied.  When this function is called, it
          will be passed one argument: a match structure for a given
          regular expression match.  It should return a string to be
          written out to PORT.

        * The `post' symbol causes `regexp-substitute/global' to recurse
          on the unmatched portion of STR.  This _must_ be supplied in
          order to perform global search-and-replace on STR; if it is
          not present among the ITEMs, then `regexp-substitute/global'
          will return after processing a single match.

   The example above for `regexp-substitute' could be rewritten as
follows to remove the `string-match' stage:

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


File: guile.info,  Node: Match Structures,  Next: Backslash Escapes,  Prev: Regexp Functions,  Up: Regular Expressions

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"


File: guile.info,  Node: Backslash Escapes,  Prev: Match Structures,  Up: Regular Expressions

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.


File: guile.info,  Node: Symbols,  Next: Keywords,  Prev: Regular Expressions,  Up: Simple Data Types

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 (*note Symbol Variables::).

* Menu:

* Symbol Data::                 Symbols as discrete data.
* Symbol Keys::                 Symbols as lookup keys.
* Symbol Variables::            Symbols as denoting variables.
* Symbol Primitives::           Operations related to symbols.
* Symbol Props::                Function slots and property lists.
* Symbol Read Syntax::          Extended read syntax for symbols.


File: guile.info,  Node: Symbol Data,  Next: Symbol Keys,  Up: Symbols

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.

