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: Alist Example,  Prev: Sloppy Alist Functions,  Up: Association Lists

Alist Example
.............

   Here is a longer example of how alists may be used in practice.

     (define capitals '(("New York" . "Albany")
                        ("Oregon"   . "Salem")
                        ("Florida"  . "Miami")))
     
     ;; What's the capital of Oregon?
     (assoc "Oregon" capitals)       => ("Oregon" . "Salem")
     (assoc-ref capitals "Oregon")   => "Salem"
     
     ;; We left out South Dakota.
     (set! capitals
           (assoc-set! capitals "South Dakota" "Pierre"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Oregon" . "Salem")
         ("Florida" . "Miami"))
     
     ;; And we got Florida wrong.
     (set! capitals
           (assoc-set! capitals "Florida" "Tallahassee"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Oregon" . "Salem")
         ("Florida" . "Tallahassee"))
     
     ;; After Oregon secedes, we can remove it.
     (set! capitals
           (assoc-remove! capitals "Oregon"))
     capitals
     => (("South Dakota" . "Pierre")
         ("New York" . "Albany")
         ("Florida" . "Tallahassee"))


File: guile.info,  Node: Hash Tables,  Prev: Association Lists,  Up: Association Lists and Hash Tables

Hash Tables
-----------

   Hash tables are dictionaries which offer similar functionality as
association lists: They provide a mapping from keys to values.  The
difference is that association lists need time linear in the size of
elements when searching for entries, whereas hash tables can normally
search in constant time.  The drawback is that hash tables require a
little bit more memory, and that you can not use the normal list
procedures (*note Lists::) for working with them.

* Menu:

* Hash Table Examples::         Demonstration of hash table usage.
* Hash Table Reference::        Hash table procedure descriptions.


File: guile.info,  Node: Hash Table Examples,  Next: Hash Table Reference,  Up: Hash Tables

Hash Table Examples
...................

   For demonstration purposes, this section gives a few usage examples
of some hash table procedures, together with some explanation what they
do.

   First we start by creating a new hash table with 31 slots, and
populate it with two key/value pairs.

     (define h (make-hash-table 31))
     
     (hashq-create-handle! h 'foo "bar")
     =>
     (foo . "bar")
     
     (hashq-create-handle! h 'braz "zonk")
     =>
     (braz . "zonk")
     
     (hashq-create-handle! h 'frob #f)
     =>
     (frob . #f)

   You can get the value for a given key with the procedure
`hashq-ref', but the problem with this procedure is that you cannot
reliably determine whether a key does exists in the table.  The reason
is that the procedure returns `#f' if the key is not in the table, but
it will return the same value if the key is in the table and just
happens to have the value `#f', as you can see in the following
examples.

     (hashq-ref h 'foo)
     =>
     "bar"
     
     (hashq-ref h 'frob)
     =>
     #f
     
     (hashq-ref h 'not-there)
     =>
     #f

   Better is to use the procedure `hashq-get-handle', which makes a
distinction between the two cases.  Just like `assq', this procedure
returns a key/value-pair on success, and `#f' if the key is not found.

     (hashq-get-handle h 'foo)
     =>
     (foo . "bar")
     
     (hashq-get-handle h 'not-there)
     =>
     #f

   There is no procedure for calculating the number of key/value-pairs
in a hash table, but `hash-fold' can be used for doing exactly that.

     (hash-fold (lambda (key value seed) (+ 1 seed)) 0 h)
     =>
     3


File: guile.info,  Node: Hash Table Reference,  Prev: Hash Table Examples,  Up: Hash Tables

Hash Table Reference
....................

   Like the association list functions, the hash table functions come
in several varieties: `hashq', `hashv', and `hash'.  The `hashq'
functions use `eq?' to determine whether two keys match.  The `hashv'
functions use `eqv?', and the `hash' functions use `equal?'.

   In each of the functions that follow, the TABLE argument must be a
vector.  The KEY and VALUE arguments may be any Scheme object.

 - Scheme Procedure: make-hash-table size
     Create a new hash table of SIZE slots.  Note that the number of
     slots does not limit the size of the table, it just tells how large
     the underlying vector will be.  The SIZE should be similar to the
     expected number of elements which will be added to the table, but
     they need not match.  For good performance, it might be a good
     idea to use a prime number as the SIZE.

 - Scheme Procedure: hashq-ref table key [dflt]
 - C Function: scm_hashq_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `eq?' for equality
     testing.

 - Scheme Procedure: hashv-ref table key [dflt]
 - C Function: scm_hashv_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `eqv?' for equality
     testing.

 - Scheme Procedure: hash-ref table key [dflt]
 - C Function: scm_hash_ref (table, key, dflt)
     Look up KEY in the hash table TABLE, and return the value (if any)
     associated with it.  If KEY is not found, return DEFAULT (or `#f'
     if no DEFAULT argument is supplied).  Uses `equal?' for equality
     testing.

 - Scheme Procedure: hashq-set! table key val
 - C Function: scm_hashq_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `eq?' for equality testing.

 - Scheme Procedure: hashv-set! table key val
 - C Function: scm_hashv_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `eqv?' for equality testing.

 - Scheme Procedure: hash-set! table key val
 - C Function: scm_hash_set_x (table, key, val)
     Find the entry in TABLE associated with KEY, and store VALUE
     there. Uses `equal?' for equality testing.

 - Scheme Procedure: hashq-remove! table key
 - C Function: scm_hashq_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `eq?' for equality tests.

 - Scheme Procedure: hashv-remove! table key
 - C Function: scm_hashv_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `eqv?' for equality tests.

 - Scheme Procedure: hash-remove! table key
 - C Function: scm_hash_remove_x (table, key)
     Remove KEY (and any value associated with it) from TABLE.  Uses
     `equal?' for equality tests.

   The standard hash table functions may be too limited for some
applications.  For example, you may want a hash table to store strings
in a case-insensitive manner, so that references to keys named
"foobar", "FOOBAR" and "FooBaR" will all yield the same item.  Guile
provides you with "extended" hash tables that permit you to specify a
hash function and associator function of your choosing.  The functions
described in the rest of this section can be used to implement such
custom hash table structures.

   If you are unfamiliar with the inner workings of hash tables, then
this facility will probably be a little too abstract for you to use
comfortably.  If you are interested in learning more, see an
introductory textbook on data structures or algorithms for an
explanation of how hash tables are implemented.

 - Scheme Procedure: hashq key size
 - C Function: scm_hashq (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `eq?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.  Note that `hashq' may use internal addresses.  Thus two
     calls to hashq where the keys are `eq?' are not guaranteed to
     deliver the same value if the key object gets garbage collected in
     between.  This can happen, for example with symbols: `(hashq 'foo
     n) (gc) (hashq 'foo n)' may produce two different values, since
     `foo' will be garbage collected.

 - Scheme Procedure: hashv key size
 - C Function: scm_hashv (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `eqv?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.  Note that `(hashv key)' may use internal addresses.  Thus
     two calls to hashv where the keys are `eqv?' are not guaranteed to
     deliver the same value if the key object gets garbage collected in
     between.  This can happen, for example with symbols: `(hashv 'foo
     n) (gc) (hashv 'foo n)' may produce two different values, since
     `foo' will be garbage collected.

 - Scheme Procedure: hash key size
 - C Function: scm_hash (key, size)
     Determine a hash value for KEY that is suitable for lookups in a
     hash table of size SIZE, where `equal?' is used as the equality
     predicate.  The function returns an integer in the range 0 to SIZE
     - 1.

 - Scheme Procedure: hashx-ref hash assoc table key [dflt]
 - C Function: scm_hashx_ref (hash, assoc, table, key, dflt)
     This behaves the same way as the corresponding `ref' function, but
     uses HASH as a hash function and ASSOC to compare keys.  `hash'
     must be a function that takes two arguments, a key to be hashed
     and a table size.  `assoc' must be an associator function, like
     `assoc', `assq' or `assv'.

     By way of illustration, `hashq-ref table key' is equivalent to
     `hashx-ref hashq assq table key'.

 - Scheme Procedure: hashx-set! hash assoc table key val
 - C Function: scm_hashx_set_x (hash, assoc, table, key, val)
     This behaves the same way as the corresponding `set!' function,
     but uses HASH as a hash function and ASSOC to compare keys.
     `hash' must be a function that takes two arguments, a key to be
     hashed and a table size.  `assoc' must be an associator function,
     like `assoc', `assq' or `assv'.

     By way of illustration, `hashq-set! table key' is equivalent to
     `hashx-set!  hashq assq table key'.

 - Scheme Procedure: hashq-get-handle table key
 - C Function: scm_hashq_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `eq?' for equality testing.

 - Scheme Procedure: hashv-get-handle table key
 - C Function: scm_hashv_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `eqv?' for equality testing.

 - Scheme Procedure: hash-get-handle table key
 - C Function: scm_hash_get_handle (table, key)
     This procedure returns the `(key . value)' pair from the hash
     table TABLE.  If TABLE does not hold an associated value for KEY,
     `#f' is returned.  Uses `equal?' for equality testing.

 - Scheme Procedure: hashx-get-handle hash assoc table key
 - C Function: scm_hashx_get_handle (hash, assoc, table, key)
     This behaves the same way as the corresponding `-get-handle'
     function, but uses HASH as a hash function and ASSOC to compare
     keys.  `hash' must be a function that takes two arguments, a key
     to be hashed and a table size.  `assoc' must be an associator
     function, like `assoc', `assq' or `assv'.

 - Scheme Procedure: hashq-create-handle! table key init
 - C Function: scm_hashq_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hashv-create-handle! table key init
 - C Function: scm_hashv_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hash-create-handle! table key init
 - C Function: scm_hash_create_handle_x (table, key, init)
     This function looks up KEY in TABLE and returns its handle.  If
     KEY is not already present, a new handle is created which
     associates KEY with INIT.

 - Scheme Procedure: hashx-create-handle! hash assoc table key init
 - C Function: scm_hashx_create_handle_x (hash, assoc, table, key, init)
     This behaves the same way as the corresponding `-create-handle'
     function, but uses HASH as a hash function and ASSOC to compare
     keys.  `hash' must be a function that takes two arguments, a key
     to be hashed and a table size.  `assoc' must be an associator
     function, like `assoc', `assq' or `assv'.

 - Scheme Procedure: hash-fold proc init table
 - C Function: scm_hash_fold (proc, init, table)
     An iterator over hash-table elements.  Accumulates and returns a
     result by applying PROC successively.  The arguments to PROC are
     "(key value prior-result)" where key and value are successive
     pairs from the hash table TABLE, and prior-result is either INIT
     (for the first application of PROC) or the return value of the
     previous application of PROC.  For example, `(hash-fold acons '()
     tab)' will convert a hash table into an a-list of key-value pairs.


File: guile.info,  Node: Procedures and Macros,  Next: Utility Functions,  Prev: Compound Data Types,  Up: Top

Procedures and Macros
*********************

* Menu:

* Lambda::                      Basic procedure creation using lambda.
* Optional Arguments::          Handling keyword, optional and rest arguments.
* Procedure Properties::        Procedure properties and meta-information.
* Procedures with Setters::     Procedures with setters.
* Macros::                      Lisp style macro definitions.
* Syntax Rules::                Support for R5RS `syntax-rules'.
* Syntax Case::                 Support for the `syntax-case' system.
* Internal Macros::             Guile's internal representation.


File: guile.info,  Node: Lambda,  Next: Optional Arguments,  Up: Procedures and Macros

Lambda: Basic Procedure Creation
================================

   A `lambda' expression evaluates to a procedure.  The environment
which is in effect when a `lambda' expression is evaluated is enclosed
in the newly created procedure, this is referred to as a "closure"
(*note About Closure::).

   When a procedure created by `lambda' is called with some actual
arguments, the environment enclosed in the procedure is extended by
binding the variables named in the formal argument list to new locations
and storing the actual arguments into these locations.  Then the body of
the `lambda' expression is evaluation sequentially.  The result of the
last expression in the procedure body is then the result of the
procedure invocation.

   The following examples will show how procedures can be created using
`lambda', and what you can do with these procedures.

     (lambda (x) (+ x x))       => a procedure
     ((lambda (x) (+ x x)) 4)   => 8

   The fact that the environment in effect when creating a procedure is
enclosed in the procedure is shown with this example:

     (define add4
       (let ((x 4))
         (lambda (y) (+ x y))))
     (add4 6)                   => 10

 - syntax: lambda formals body
     FORMALS should be a formal argument list as described in the
     following table.

    `(VARIABLE1 ...)'
          The procedure takes a fixed number of arguments; when the
          procedure is called, the arguments will be stored into the
          newly created location for the formal variables.

    `VARIABLE'
          The procedure takes any number of arguments; when the
          procedure is called, the sequence of actual arguments will
          converted into a list and stored into the newly created
          location for the formal variable.

    `(VARIABLE1 ... VARIABLEN . VARIABLEN+1)'
          If a space-delimited period precedes the last variable, then
          the procedure takes N or more variables where N is the number
          of formal arguments before the period.  There must be at
          least one argument before the period.  The first N actual
          arguments will be stored into the newly allocated locations
          for the first N formal arguments and the sequence of the
          remaining actual arguments is converted into a list and the
          stored into the location for the last formal argument.  If
          there are exactly N actual arguments, the empty list is
          stored into the location of the last formal argument.

     BODY is a sequence of Scheme expressions which are evaluated in
     order when the procedure is invoked.


File: guile.info,  Node: Optional Arguments,  Next: Procedure Properties,  Prev: Lambda,  Up: Procedures and Macros

Optional Arguments
==================

   Scheme procedures, as defined in R5RS, can either handle a fixed
number of actual arguments, or a fixed number of actual arguments
followed by arbitrarily many additional arguments.  Writing procedures
of variable arity can be useful, but unfortunately, the syntactic means
for handling argument lists of varying length is a bit inconvenient.
It is possible to give names to the fixed number of argument, but the
remaining (optional) arguments can be only referenced as a list of
values (*note Lambda::).

   Guile comes with the module `(ice-9 optargs)', which makes using
optional arguments much more convenient.  In addition, this module
provides syntax for handling keywords in argument lists (*note
Keywords::).

   Before using any of the procedures or macros defined in this section,
you have to load the module `(ice-9 optargs)' with the statement:

     (use-modules (ice-9 optargs))

* Menu:

* let-optional Reference::      Locally binding optional arguments.
* let-keywords Reference::      Locally binding keywords arguments.
* lambda* Reference::           Creating advanced argument handling procedures.
* define* Reference::           Defining procedures and macros.


File: guile.info,  Node: let-optional Reference,  Next: let-keywords Reference,  Up: Optional Arguments

let-optional Reference
----------------------

   The syntax `let-optional' and `let-optional*' are for destructuring
rest argument lists and giving names to the various list elements.
`let-optional' binds all variables simultaneously, while
`let-optional*' binds them sequentially, consistent with `let' and
`let*' (*note Local Bindings::).

 - library syntax: let-optional rest-arg (binding ...) expr ...
 - library syntax: let-optional* rest-arg (binding ...) expr ...
     These two macros give you an optional argument interface that is
     very "Schemey" and introduces no fancy syntax. They are compatible
     with the scsh macros of the same name, but are slightly extended.
     Each of BINDING may be of one of the forms VAR or `(VAR
     DEFAULT-VALUE)'. REST-ARG should be the rest-argument of the
     procedures these are used from.  The items in REST-ARG are
     sequentially bound to the variable names are given. When REST-ARG
     runs out, the remaining vars are bound either to the default
     values or `#f' if no default value was specified. REST-ARG remains
     bound to whatever may have been left of REST-ARG.

     After binding the variables, the expressions EXPR ... are
     evaluated in order.


File: guile.info,  Node: let-keywords Reference,  Next: lambda* Reference,  Prev: let-optional Reference,  Up: Optional Arguments

let-keywords Reference
----------------------

   `let-keywords' and `let-keywords*' are used for extracting values
from argument lists which use keywords instead of argument position for
binding local variables to argument values.

   `let-keywords' binds all variables simultaneously, while
`let-keywords*' binds them sequentially, consistent with `let' and
`let*' (*note Local Bindings::).

 - library syntax: let-keywords rest-arg allow-other-keys? (binding
          ...) expr ...
 - library syntax: let-keywords rest-arg allow-other-keys? (binding
          ...) expr ...
     These macros pick out keyword arguments from REST-ARG, but do not
     modify it.  This is consistent at least with Common Lisp, which
     duplicates keyword arguments in the rest argument. More
     explanation of what keyword arguments in a lambda list look like
     can be found below in the documentation for `lambda*'  (*note
     lambda* Reference::).  BINDINGs can have the same form as for
     `let-optional'. If ALLOW-OTHER-KEYS? is false, an error will be
     thrown if anything that looks like a keyword argument but does not
     match a known keyword parameter will result in an error.

     After binding the variables, the expressions EXPR ... are
     evaluated in order.


File: guile.info,  Node: lambda* Reference,  Next: define* Reference,  Prev: let-keywords Reference,  Up: Optional Arguments

lambda* Reference
-----------------

   When using optional and keyword argument lists, using `lambda' for
creating procedures and using `let-optional' or `let-keywords' is a bit
lengthy.  Therefore, `lambda*' is provided, which combines the features
of those macros into a single convenient syntax.

   For quick reference, here is the syntax of the formal argument list
for `lambda*' (brackets are used to indicate grouping only):

     ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
       [#:key [ext-var-decl]+ [#:allow-other-keys]?]?
       [[#:rest identifier]|[. identifier]]?
     
     ext-var-decl ::= identifier | ( identifier expression )

   The characters `*', `+' and `?' are not to be taken literally; they
mean respectively, zero or more occurrences, one or more occurrences,
and one or zero occurrences.

 - library syntax: lambda* formals body
     `lambda*' creates a procedure that takes optional arguments. These
     are specified by putting them inside brackets at the end of the
     parameter list, but before any dotted rest argument. For example,

          (lambda* (a b #:optional c d . e) '())

     creates a procedure with fixed arguments A and B, optional
     arguments C and D, and rest argument E. If the optional arguments
     are omitted in a call, the variables for them are bound to `#f'.

     `lambda*' can also take keyword arguments. For example, a procedure
     defined like this:

          (lambda* (#:key xyzzy larch) '())

     can be called with any of the argument lists `(#:xyzzy 11)'
     `(#:larch 13)' `(#:larch 42 #:xyzzy 19)' `()'. Whichever arguments
     are given as keywords are bound to values.

     Optional and keyword arguments can also be given default values
     which they take on when they are not present in a call, by giving a
     two-item list in place of an optional argument, for example in:

          (lambda* (foo #:optional (bar 42) #:key (baz 73))
               (list foo bar baz))

     FOO is a fixed argument, BAR is an optional argument with default
     value 42, and baz is a keyword argument with default value 73.
     Default value expressions are not evaluated unless they are needed
     and until the procedure is called.

     `lambda*' also supports two more special parameter list keywords.

     `lambda*'-defined procedures now throw an error by default if a
     keyword other than one of those specified is found in the actual
     passed arguments. However, specifying `#:allow-other-keys'
     immediately after the keyword argument declarations restores the
     previous behavior of ignoring unknown keywords.  `lambda*' also now
     guarantees that if the same keyword is passed more than once, the
     last one passed is the one that takes effect. For example,

          ((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
              #:heads 37 #:tails 42 #:heads 99)

     would result in (99 47) being displayed.

     `#:rest' is also now provided as a synonym for the dotted syntax
     rest argument. The argument lists `(a . b)' and `(a #:rest b)' are
     equivalent in all respects to `lambda*'. This is provided for more
     similarity to DSSSL, MIT-Scheme and Kawa among others, as well as
     for refugees from other Lisp dialects.


File: guile.info,  Node: define* Reference,  Prev: lambda* Reference,  Up: Optional Arguments

define* Reference
-----------------

   Just like `define' has a shorthand notation for defining procedures
(*note Lambda Alternatives::), `define*' is provided as an abbreviation
of the combination of `define' and `lambda*'.

   `define*-public' is the `lambda*' version of `define-public';
`defmacro*' and `defmacro*-public' exist for defining macros with the
improved argument list handling possibilities.  The `-public' versions
not only define the procedures/macros, but also export them from the
current module.

 - library syntax: define* formals body
 - library syntax: define*-public formals body
     `define*' and `define*-public' support optional arguments with a
     similar syntax to `lambda*'. They also support arbitrary-depth
     currying, just like Guile's define. Some examples:

          (define* (x y #:optional a (z 3) #:key w . u)
             (display (list y z u)))
     defines a procedure `x' with a fixed argument Y, an optional
     argument A, another optional argument Z with default value 3, a
     keyword argument W, and a rest argument U.

          (define-public* ((foo #:optional bar) #:optional baz) '())

     This illustrates currying. A procedure `foo' is defined, which,
     when called with an optional argument BAR, returns a procedure
     that takes an optional argument BAZ.

     Of course, `define*[-public]' also supports `#:rest' and
     `#:allow-other-keys' in the same way as `lambda*'.

 - library syntax: defmacro* name formals body
 - library syntax: defmacro*-public name formals body
     These are just like `defmacro' and `defmacro-public' except that
     they take `lambda*'-style extended parameter lists, where
     `#:optional', `#:key', `#:allow-other-keys' and `#:rest' are
     allowed with the usual semantics. Here is an example of a macro
     with an optional argument:

          (defmacro* transmorgify (a #:optional b)
              (a 1))


File: guile.info,  Node: Procedure Properties,  Next: Procedures with Setters,  Prev: Optional Arguments,  Up: Procedures and Macros

Procedure Properties and Meta-information
=========================================

   Procedures always have attached the environment in which they were
created and information about how to apply them to actual arguments.  In
addition to that, properties and meta-information can be stored with
procedures.  The procedures in this section can be used to test whether
a given procedure satisfies a condition; and to access and set a
procedure's property.

   The first group of procedures are predicates to test whether a Scheme
object is a procedure, or a special procedure, respectively.
`procedure?' is the most general predicates, it returns `#t' for any
kind of procedure.  `closure?' does not return `#t' for primitive
procedures, and `thunk?' only returns `#t' for procedures which do not
accept any arguments.

 - Scheme Procedure: procedure? obj
 - C Function: scm_procedure_p (obj)
     Return `#t' if OBJ is a procedure.

 - Scheme Procedure: closure? obj
 - C Function: scm_closure_p (obj)
     Return `#t' if OBJ is a closure.

 - Scheme Procedure: thunk? obj
 - C Function: scm_thunk_p (obj)
     Return `#t' if OBJ is a thunk.

   Procedure properties are general properties to be attached to
procedures.  These can be the name of a procedure or other relevant
information, such as debug hints.

 - Scheme Procedure: procedure-name proc
 - C Function: scm_procedure_name (proc)
     Return the name of the procedure PROC

 - Scheme Procedure: procedure-source proc
 - C Function: scm_procedure_source (proc)
     Return the source of the procedure PROC.

 - Scheme Procedure: procedure-environment proc
 - C Function: scm_procedure_environment (proc)
     Return the environment of the procedure PROC.

 - Scheme Procedure: procedure-properties proc
 - C Function: scm_procedure_properties (proc)
     Return OBJ's property list.

 - Scheme Procedure: procedure-property obj key
 - C Function: scm_procedure_property (obj, key)
     Return the property of OBJ with name KEY.

 - Scheme Procedure: set-procedure-properties! proc alist
 - C Function: scm_set_procedure_properties_x (proc, alist)
     Set OBJ's property list to ALIST.

 - Scheme Procedure: set-procedure-property! obj key value
 - C Function: scm_set_procedure_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.

   Documentation for a procedure can be accessed with the procedure
`procedure-documentation'.

 - Scheme Procedure: procedure-documentation proc
 - C Function: scm_procedure_documentation (proc)
     Return the documentation string associated with `proc'.  By
     convention, if a procedure contains more than one expression and
     the first expression is a string constant, that string is assumed
     to contain documentation for that procedure.

   Source properties are properties which are related to the source
code of a procedure, such as the line and column numbers, the file name
etc.

 - Scheme Procedure: set-source-properties! obj plist
 - C Function: scm_set_source_properties_x (obj, plist)
     Install the association list PLIST as the source property list for
     OBJ.

 - Scheme Procedure: set-source-property! obj key datum
 - C Function: scm_set_source_property_x (obj, key, datum)
     Set the source property of object OBJ, which is specified by KEY
     to DATUM.  Normally, the key will be a symbol.

 - Scheme Procedure: source-properties obj
 - C Function: scm_source_properties (obj)
     Return the source property association list of OBJ.

 - Scheme Procedure: source-property obj key
 - C Function: scm_source_property (obj, key)
     Return the source property specified by KEY from OBJ's source
     property list.


File: guile.info,  Node: Procedures with Setters,  Next: Macros,  Prev: Procedure Properties,  Up: Procedures and Macros

Procedures with Setters
=======================

   A "procedure with setter" is a special kind of procedure which
normally behaves like any accessor procedure, that is a procedure which
accesses a data structure.  The difference is that this kind of
procedure has a so-called "setter" attached, which is a procedure for
storing something into a data structure.

   Procedures with setters are treated specially when the procedure
appears in the special form `set!' (REFFIXME).  How it works is best
shown by example.

   Suppose we have a procedure called `foo-ref', which accepts two
arguments, a value of type `foo' and an integer.  The procedure returns
the value stored at the given index in the `foo' object.  Let `f' be a
variable containing such a `foo' data structure.(1)

     (foo-ref f 0)       => bar
     (foo-ref f 1)       => braz

   Also suppose that a corresponding setter procedure called `foo-set!'
does exist.

     (foo-set! f 0 'bla)
     (foo-ref f 0)       => bla

   Now we could create a new procedure called `foo', which is a
procedure with setter, by calling `make-procedure-with-setter' with the
accessor and setter procedures `foo-ref' and `foo-set!'.  Let us call
this new procedure `foo'.

     (define foo (make-procedure-with-setter foo-ref foo-set!))

   `foo' can from now an be used to either read from the data structure
stored in `f', or to write into the structure.

     (set! (foo f 0) 'dum)
     (foo f 0)          => dum

 - Scheme Procedure: make-procedure-with-setter procedure setter
 - C Function: scm_make_procedure_with_setter (procedure, setter)
     Create a new procedure which behaves like PROCEDURE, but with the
     associated setter SETTER.

 - Scheme Procedure: procedure-with-setter? obj
 - C Function: scm_procedure_with_setter_p (obj)
     Return `#t' if OBJ is a procedure with an associated setter
     procedure.

 - Scheme Procedure: procedure proc
 - C Function: scm_procedure (proc)
     Return the procedure of PROC, which must be either a procedure
     with setter, or an operator struct.

 - Scheme Procedure: setter proc
     Return the setter of PROC, which must be either a procedure with
     setter or an operator struct.

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

   (1) Working definitions would be:
     (define foo-ref vector-ref)
     (define foo-set! vector-set!)
     (define f (make-vector 2 #f))


File: guile.info,  Node: Macros,  Next: Syntax Rules,  Prev: Procedures with Setters,  Up: Procedures and Macros

Lisp Style Macro Definitions
============================

   Macros are objects which cause the expression that they appear in to
be transformed in some way _before_ being evaluated.  In expressions
that are intended for macro transformation, the identifier that names
the relevant macro must appear as the first element, like this:

     (MACRO-NAME MACRO-ARGS ...)

   In Lisp-like languages, the traditional way to define macros is very
similar to procedure definitions.  The key differences are that the
macro definition body should return a list that describes the
transformed expression, and that the definition is marked as a macro
definition (rather than a procedure definition) by the use of a
different definition keyword: in Lisp, `defmacro' rather than `defun',
and in Scheme, `define-macro' rather than `define'.

   Guile supports this style of macro definition using both `defmacro'
and `define-macro'.  The only difference between them is how the macro
name and arguments are grouped together in the definition:

     (defmacro NAME (ARGS ...) BODY ...)

is the same as

     (define-macro (NAME ARGS ...) BODY ...)

The difference is analogous to the corresponding difference between
Lisp's `defun' and Scheme's `define'.

   `false-if-exception', from the `boot-9.scm' file in the Guile
distribution, is a good example of macro definition using `defmacro':

     (defmacro false-if-exception (expr)
       `(catch #t
               (lambda () ,expr)
               (lambda args #f)))

The effect of this definition is that expressions beginning with the
identifier `false-if-exception' are automatically transformed into a
`catch' expression following the macro definition specification.  For
example:

     (false-if-exception (open-input-file "may-not-exist"))
     ==
     (catch #t
            (lambda () (open-input-file "may-not-exist"))
            (lambda args #f))


File: guile.info,  Node: Syntax Rules,  Next: Syntax Case,  Prev: Macros,  Up: Procedures and Macros

The R5RS `syntax-rules' System
==============================

   R5RS defines an alternative system for macro and syntax
transformations using the keywords `define-syntax', `let-syntax',
`letrec-syntax' and `syntax-rules'.

   The main difference between the R5RS system and the traditional
macros of the previous section is how the transformation is specified.
In R5RS, rather than permitting a macro definition to return an
arbitrary expression, the transformation is specified in a pattern
language that

   * does not require complicated quoting and extraction of components
     of the source expression using `caddr' etc.

   * is designed such that the bindings associated with identifiers in
     the transformed expression are well defined, and such that it is
     impossible for the transformed expression to construct new
     identifiers.

The last point is commonly referred to as being "hygienic": the R5RS
`syntax-case' system provides "hygienic macros".

   For example, the R5RS pattern language for the `false-if-exception'
example of the previous section looks like this:

     (syntax-rules ()
       ((_ expr)
        (catch #t
               (lambda () expr)
               (lambda args #f))))

   In Guile, the `syntax-rules' system is provided by the `(ice-9
syncase)' module.  To make these facilities available in your code,
include the expression `(use-syntax (ice-9 syncase))' (*note Using
Guile Modules::) before the first usage of `define-syntax' etc.  If you
are writing a Scheme module, you can alternatively include the form
`#:use-syntax (ice-9 syncase)' in your `define-module' declaration
(*note Creating Guile Modules::).

* Menu:

* Pattern Language::            The `syntax-rules' pattern language.
* Define-Syntax::               Top level syntax definitions.
* Let-Syntax::                  Local syntax definitions.


File: guile.info,  Node: Pattern Language,  Next: Define-Syntax,  Up: Syntax Rules

The `syntax-rules' Pattern Language
-----------------------------------


File: guile.info,  Node: Define-Syntax,  Next: Let-Syntax,  Prev: Pattern Language,  Up: Syntax Rules

Top Level Syntax Definitions
----------------------------

   define-syntax:  The gist is

   (define-syntax <keyword> <transformer-spec>)

   makes the <keyword> into a macro so that

   (<keyword> ...)

   expands at _compile_ or _read_ time (i.e. before any evaluation
begins) into some expression that is given by the <transformer-spec>.


File: guile.info,  Node: Let-Syntax,  Prev: Define-Syntax,  Up: Syntax Rules

Local Syntax Definitions
------------------------


File: guile.info,  Node: Syntax Case,  Next: Internal Macros,  Prev: Syntax Rules,  Up: Procedures and Macros

Support for the `syntax-case' System
====================================


File: guile.info,  Node: Internal Macros,  Prev: Syntax Case,  Up: Procedures and Macros

Internal Representation of Macros and Syntax
============================================

   Internally, Guile uses three different flavors of macros.  The three
flavors are called "acro" (or "syntax"), "macro" and "mmacro".

   Given the expression

     (foo ...)

with `foo' being some flavor of macro, one of the following things will
happen when the expression is evaluated.

   * When `foo' has been defined to be an "acro", the procedure used in
     the acro definition of `foo' is passed the whole expression and
     the current lexical environment, and whatever that procedure
     returns is the value of evaluating the expression.  You can think
     of this a procedure that receives its argument as an unevaluated
     expression.

   * When `foo' has been defined to be a "macro", the procedure used in
     the macro definition of `foo' is passed the whole expression and
     the current lexical environment, and whatever that procedure
     returns is evaluated again.  That is, the procedure should return
     a valid Scheme expression.

   * When `foo' has been defined to be a "mmacro", the procedure used
     in the mmacro definition of `foo' is passed the whole expression
     and the current lexical environment, and whatever that procedure
     returns replaces the original expression.  Evaluation then starts
     over from the new expression that has just been returned.

   The key difference between a "macro" and a "mmacro" is that the
expression returned by a "mmacro" procedure is remembered (or
"memoized") so that the expansion does not need to be done again next
time the containing code is evaluated.

   The primitives `procedure->syntax', `procedure->macro' and
`procedure->memoizing-macro' are used to construct acros, macros and
mmacros respectively.  However, if you do not have a very special
reason to use one of these primitives, you should avoid them: they are
very specific to Guile's current implementation and therefore likely to
change.  Use `defmacro', `define-macro' (*note Macros::) or
`define-syntax' (*note Syntax Rules::) instead.  (In low level terms,
`defmacro', `define-macro' and `define-syntax' are all implemented as
mmacros.)

 - Scheme Procedure: procedure->syntax code
 - C Function: scm_makacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, returns the result of
     applying CODE to the expression and the environment.

 - Scheme Procedure: procedure->macro code
 - C Function: scm_makmacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, evaluates the result of
     applying CODE to the expression and the environment.  For example:

          (define trace
            (procedure->macro
              (lambda (x env)
                `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
          
          (trace foo)
          ==
          (set! foo (tracef foo 'foo)).

 - Scheme Procedure: procedure->memoizing-macro code
 - C Function: scm_makmmacro (code)
     Return a macro which, when a symbol defined to this value appears
     as the first symbol in an expression, evaluates the result of
     applying CODE to the expression and the environment.
     `procedure->memoizing-macro' is the same as `procedure->macro',
     except that the expression returned by CODE replaces the original
     macro expression in the memoized form of the containing code.

   In the following primitives, "acro" flavor macros are referred to as
"syntax transformers".

 - Scheme Procedure: macro? obj
 - C Function: scm_macro_p (obj)
     Return `#t' if OBJ is a regular macro, a memoizing macro or a
     syntax transformer.

 - Scheme Procedure: macro-type m
 - C Function: scm_macro_type (m)
     Return one of the symbols `syntax', `macro' or `macro!', depending
     on whether M is a syntax transformer, a regular macro, or a
     memoizing macro, respectively.  If M is not a macro, `#f' is
     returned.

 - Scheme Procedure: macro-name m
 - C Function: scm_macro_name (m)
     Return the name of the macro M.

 - Scheme Procedure: macro-transformer m
 - C Function: scm_macro_transformer (m)
     Return the transformer of the macro M.

 - Scheme Procedure: cons-source xorig x y
 - C Function: scm_cons_source (xorig, x, y)
     Create and return a new pair whose car and cdr are X and Y.  Any
     source properties associated with XORIG are also associated with
     the new pair.


File: guile.info,  Node: Utility Functions,  Next: Binding Constructs,  Prev: Procedures and Macros,  Up: Top

General Utility Functions
*************************

   This chapter contains information about procedures which are not
cleanly tied to a specific data type.  Because of their wide range of
applications, they are collected in a "utility" chapter.

* Menu:

* Equality::                    When are two values `the same'?
* Object Properties::           A modern interface to object properties.
* Sorting::                     Sort utility procedures.
* Copying::                     Copying deep structures.
* General Conversion::          Converting objects to strings.
* Hooks::                       User-customizable event lists.


File: guile.info,  Node: Equality,  Next: Object Properties,  Up: Utility Functions

Equality
========

   Three different kinds of "sameness" are defined in Scheme.

   * Two values can refer to exactly the same object.

   * Two objects can have the same "value".

   * Two objects can be structurally equivalent.

   The differentiation between these three kinds is important, because
determining whether two values are the same objects is very efficient,
while determining structural equivalence can be quite expensive
(consider comparing two very long lists).  Therefore, three different
procedures for testing for equality are provided, which correspond to
the three kinds of "sameness" defined above.

 - Scheme Procedure: eq? x y
     Return `#t' iff X references the same object as Y.  `eq?' is
     similar to `eqv?' except that in some cases it is capable of
     discerning distinctions finer than those detectable by `eqv?'.

 - Scheme Procedure: eqv? x y
     The `eqv?' procedure defines a useful equivalence relation on
     objects.  Briefly, it returns `#t' if X and Y should normally be
     regarded as the same object.  This relation is left slightly open
     to interpretation, but works for comparing immediate integers,
     characters, and inexact numbers.

 - Scheme Procedure: equal? x y
     Return `#t' iff X and Y are recursively `eqv?' equivalent.
     `equal?' recursively compares the contents of pairs, vectors, and
     strings, applying `eqv?' on other objects such as numbers and
     symbols.  A rule of thumb is that objects are generally `equal?'
     if they print the same.  `equal?' may fail to terminate if its
     arguments are circular data structures.


File: guile.info,  Node: Object Properties,  Next: Sorting,  Prev: Equality,  Up: Utility Functions

Object Properties
=================

   It's often useful to associate a piece of additional information
with a Scheme object even though that object does not have a dedicated
slot available in which the additional information could be stored.
Object properties allow you to do just that.

   An object property is most commonly used to associate one kind of
additional information with each instance of a class of similar Scheme
objects.  For example, all procedures have a `name' property, which
stores the name of the variable in which the procedure was stored by a
`define' expression, or `#f' if the procedure wasn't created by that
kind of expression.

   Guile's representation of an object property is a
procedure-with-setter (*note Procedures with Setters::) that can be
used with the generalized form of `set!' (REFFIXME) to set and retrieve
that property for any Scheme object.  So, setting a property looks like
this:

     (set! (my-property obj1) value-for-obj1)
     (set! (my-property obj2) value-for-obj2)

And retrieving values of the same property looks like this:

     (my-property obj1)
     =>
     value-for-obj1
     
     (my-property obj2)
     =>
     value-for-obj2

   To create an object property in the first place, use the
`make-object-property' procedure:

     (define my-property (make-object-property))

 - Scheme Procedure: make-object-property
     Create and return an object property.  An object property is a
     procedure-with-setter that can be called in two ways.  `(set!
     (PROPERTY OBJ) VAL)' sets OBJ's PROPERTY to VAL.  `(PROPERTY OBJ)'
     returns the current setting of OBJ's PROPERTY.

   A single object property created by `make-object-property' can
associate distinct property values with all Scheme values that are
distinguishable by `eq?' (including, for example, integers).

   Internally, object properties are implemented using a weak key hash
table.  This means that, as long as a Scheme value with property values
is protected from garbage collection, its property values are also
protected.  When the Scheme value is collected, its entry in the
property table is removed and so the (ex-) property values are no longer
protected by the table.

* Menu:

* Property Primitives::         Low level property implementation.
* Old-fashioned Properties::    An older approach to properties.


File: guile.info,  Node: Property Primitives,  Next: Old-fashioned Properties,  Up: Object Properties

Low Level Property Implementation.
----------------------------------

 - Scheme Procedure: primitive-make-property not_found_proc
 - C Function: scm_primitive_make_property (not_found_proc)
     Create a "property token" that can be used with
     `primitive-property-ref' and `primitive-property-set!'.  See
     `primitive-property-ref' for the significance of NOT_FOUND_PROC.

 - Scheme Procedure: primitive-property-ref prop obj
 - C Function: scm_primitive_property_ref (prop, obj)
     Return the property PROP of OBJ.  When no value has yet been
     associated with PROP and OBJ, call NOT-FOUND-PROC instead (see
     `primitive-make-property') and use its return value.  That value
     is also associated with OBJ via `primitive-property-set!'.  When
     NOT-FOUND-PROC is `#f', use `#f' as the default value of PROP.

 - Scheme Procedure: primitive-property-set! prop obj val
 - C Function: scm_primitive_property_set_x (prop, obj, val)
     Associate CODE with PROP and OBJ.

 - Scheme Procedure: primitive-property-del! prop obj
 - C Function: scm_primitive_property_del_x (prop, obj)
     Remove any value associated with PROP and OBJ.


File: guile.info,  Node: Old-fashioned Properties,  Prev: Property Primitives,  Up: Object Properties

An Older Approach to Properties
-------------------------------

   Traditionally, Lisp systems provide a different object property
interface to that provided by `make-object-property', in which the
object property that is being set or retrieved is indicated by a symbol.

   Guile includes this older kind of interface as well, but it may well
be removed in a future release, as it is less powerful than
`make-object-property' and so increases the size of the Guile library
for no benefit.  (And it is trivial to write a compatibility layer in
Scheme.)

 - Scheme Procedure: object-properties obj
 - C Function: scm_object_properties (obj)
     Return OBJ's property list.

 - Scheme Procedure: set-object-properties! obj alist
 - C Function: scm_set_object_properties_x (obj, alist)
     Set OBJ's property list to ALIST.

 - Scheme Procedure: object-property obj key
 - C Function: scm_object_property (obj, key)
     Return the property of OBJ with name KEY.

 - Scheme Procedure: set-object-property! obj key value
 - C Function: scm_set_object_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.

