code:
@node Introduction
@chapter Introduction

Guile is an interpreter for Scheme, a clean, economical programming
language in the Lisp family.  You can invoke Guile from the shell to
evaluate Scheme expressions interactively, or use it as an interpreter
for script files.  However, Guile is also packaged as a library, to be
embedded as an extension language into other applications.  The
application can supplement the base language with special-purpose
functions and datatypes, allowing the user to customize and extend it by
writing Scheme code.

In its simplest form, Guile is an ordinary interpreter.  The
@code{guile} program can read and evaluate Scheme expressions entered
from the terminal.  Here is a sample interaction between Guile and a
user; the user's input appears after the @code{$} and @code{guile>}
prompts:

@example
$ guile
guile> (+ 1 2 3)                ; add some numbers
6
guile> (define (factorial n)    ; define a function
         (if (zero? n) 1 (* n (factorial (- n 1)))))
guile> (factorial 20)
2432902008176640000
guile> (getpwnam "jimb")        ; find my entry in /etc/passwd
#("jimb" ".0krIpK2VqNbU" 4008 10 "Jim Blandy" "/u/jimb"
  "/usr/local/bin/bash")
guile> @kbd{C-d}
$
@end example

Guile can also interpret script files.  For example, here is a Guile script
containing a script which displays the

application can
supplement the base language with its own functions, datatypes and
syntax, allowing the user to extend and

 Guile interpret

.  An
application the Guile interpreter to allow

, allowing
applications to incorporate the Scheme interpreter for customization

[[interactive]]
[[script interpreter]]
[[embedded]]

[[other languages]]
The concept of an extension language library does not originate with
Guile.  However, Guile is the first to offer users a choice of languages
to program in.

Guile currently supports Scheme and Ctax , and we expect to support Emacs Lisp in the near future.

Scheme is powerful enough that other languages can be
conveniently translated into it,

However, unlike other extension packages, Guile gives users a choice of
languages to program in.  Guile can

In this sense, Guile resembles the Tcl and Python packages, providing
both an ordinary interpreter and an extension language library.
However, unlike those packages, Guile supports more than one programming
language.

; users can
write Scheme code to control and customize applications which
incorporate Guile

, adding their own functions,
datatypes, and syntax, to allow the user to programm

link it into your own programs to make them

Guile is a library containing an interpreter for Scheme, a complete but
economical programming language, which the developer can customize to
suit the application at hand by adding new functions, data types, and
control structures.  These may be implemented in C, and then
``exported'' for use by the interpreted code.  Because Guile already
provides a full-featured interpreter, the developer need not neglect the
language's design in order to concentrate on code relevant to the task.
In this way, Guile provides a framework for the construction of
domain-specific languages.

Guile provides first-class functions, a rich set of data types,
exception handling, a module system, and a powerful macro facility.
Guile also supports dynamic linking and direct access to Unix system
calls.  Releases in the near future will support a source-level
debugger and bindings for the Tk user interface toolkit.

Guile is a framework for writing applications controlled by specialized
languages.  In its simplest form, Guile is an interpreter for Scheme, a
clean, economical programming language in the Lisp family.  However,
Guile is packaged as a library, allowing applications to link against it
and use Scheme as their extension language.  The application can add
primitive functions to the language, implement new data types, and even
adjust the language's syntax.

[the introduction is probably not what Jim has in mind; I just took the
one I had in earlier, since the file had the same name intro.texi]

Guile is an implementation of the Scheme programming language, but, like
other modern implementations of Scheme, it adds many features that the
community of Scheme programmers considers necessary for an ``industrial
strength'' language.

Examples of extensions to Scheme are the module system
(@pxref{Modules}), the Unix system programming tools (@pxref{POSIX
system calls and networking} and @pxref{The Scheme shell (scsh)}), an
interface to @emph{libtool} to make it easier to add C libraries as
primitives (@pxref{Linking Guile with your code}), and (FIXME add more).

On top of these extensions, which many other Scheme implementations
provide, Guile also offers the possibility of writing routines in other
languages and running them simultaneously with Scheme.  The desire to
implement other languages (in particular Emacs Lisp) on top of Scheme is
responsible for Guile's only deviation from the R4RS @footnote{R4RS is
the Revised^4 Report on the Algorithmic Language Scheme, the closest
thing to a standard Scheme specification today} Scheme standard
(@cite{r4rs}): Guile is case sensitive, whereas ``standard'' Scheme is
not.

But even more fundamentally, Guile is meant to be an @emph{embeddable}
Scheme interpreter.  This means that a lot of work has gone into
packaging the interpreter as a C library (@pxref{A Portable C to Scheme Interface} and @pxref{Scheme data representation}).

This reference manual is mainly driven by the need to document all the
features that go beyond standard Scheme.

@menu
* Getting started::
* Guile feature list::
* What you need to use Guile::
* Roadmap to the Manual::
* Motivation for Guile::
* History of Guile::
@end menu

@node Getting started
@section Getting started

We assume that you know how to program in Scheme, although we do not
assume advanced knowledge.  If you don't know Scheme, there are many
good books on Scheme at all levels, and the Guile Tutorial might give
you a good enough feel for the language.  We also assume that you know
how to program in C, since there will be many examples of how to program
in C using Guile as a library.

Many diverse topics from the world of Unix hacking will be covered here,
such as shared libraries, socket programming, garbage collection, and so
forth.  If at any time you feel you don't have enough background on a
given topic, just go up a level or two in the manual, and you will find
that the chapter begins with a few paragraphs that introduce the topic.
If you are still lost, read through the Guile tutorial and then come
back to this reference manual.

To run the core Guile interpreter and extension library you need no more
than a basically configured GNU/Unix system and the Guile sources.  You
should download and install the Guile sources (@pxref{Obtaining and
Installing Guile}).

@node Guile feature list
@section Guile feature list

In a reductionist view, Guile could be regarded as:
@itemize @bullet
@item
An R4RS-compliant Scheme interpreter.

@item
Some Scheme features that go beyond the R4RS standard, notably a module
system, exception handling primitives and an interface to Aubrey
Jaffer's SLIB.

@item
A symbolic debugger for Scheme, and gdb extensions to facilitate
debugging libguile programs.

@item
An embeddable version of the same interpreter, called @emph{libguile}.

@item
A portable high level API on top of libguile (the @code{gh_} interface).

@item
A collection of bundled C libraries with a Guile API.  As we write, this
list includes:

@table @strong
@item Rx
a regular expression library.

@item Unix
a low-level interface to the POSIX system calls, socket library
and other Unix system services.

@item Tk
an interface to John Ousterhout's Tk toolkit.

@end table

@item
A set of tools for implementing other languages @emph{on top of Scheme},
and an example implementation of a language called @emph{Ctax}.

@end itemize

@node What you need to use Guile
@section What you need to use Guile

@node Roadmap to the Manual
@section Roadmap to the Manual

@node Motivation for Guile
@section Motivation for Guile

@node History of Guile
@section History of Guile

@page
@node Using Guile
@chapter Using Guile

[I think that this might go in the appendix in Jim's view of the manual]

@page
@node Invoking Guile
@appendix Invoking Guile
        --- mentions read-eval-print loops
	--- both the SCSH and GAWK manuals relegate invocation details
            to an appendix.  We can give examples in the introduction.

@table @samp
@item -h
@itemx --help
Display a helpful message.
@item -v
@item --version
Display the current version.
@item --emacs
To be used for emacs editing support.
@item -s @var{file}
Process @var{file} as a script then quit.  This is a terminating option:
any further command line arguments can be accessed by the script using
the @code{(program-arguments)} procedure.

An executable script can start with the following:

@smallexample
#!/usr/bin/guile -s
!#
@end smallexample

Note the @code{!#} token on the second line.  It is very important
to include this token when writing Guile scripts.  Guile and SCSH,
the Scheme shell, share the convention that @code{#!}  and
@code{!#} may be used to mark block comments (@pxref{Block
comments and interpreter triggers}).  If the closing @code{!#}
token is not included, then Guile will consider the block comment
to be unclosed, and the script will probably not compile
correctly.

It is also important to include the @samp{-s} option at the
beginning of the Guile script, so that Guile knows not to behave
in an interactive fashion.

@end table


code:
@node Examples of adding libraries
@chapter Examples of adding libraries

Should contain examples of brute-force gh_, Guile magic snarfer,
libtool, SWIG on a dummy API, followed by some real examples of how
libraries are added.

license: unknown


code:
@node Guile Scheme concepts
@chapter Guile Scheme concepts

Most Scheme implementations go beyond what is specified in the R4RS
document @footnote{Remember?  R4RS is the Revised^4 report on the
Algorithmic Language Scheme}, mostly because R4RS does not give
specifications (or even recommendations) regarding some issues that are
quite important in practical programming.

Here is a list of how Guile implements some of these much-needed Scheme
extensions; other Scheme implementations do so quite similarly.

@menu
* Scheme slang::
* Read-eval-print loops::
* Extra data types::
* Miscellaneous features::
@end menu

@node Scheme slang
@section Scheme slang
@cindex slang

Even if you read some of the nice books on Scheme, or the R4RS report,
you might not find some of the terms frequently used by Scheme hackers,
both in the manual and in the @url{news:comp.lang.scheme} newsgroup.

Here is a glossary of some of the terms that make Scheme beginners and
intermediate users say ``huh?''

@table @strong
@item thunk
@cindex thunk
A Scheme procedure that takes no arguments.  In this example,
@code{thunk} and @code{another-thunk} are both thunks:
@lisp
(define (thunk)
  (display "Dude, I'm a thunk!")
  (newline))
(define another-thunk
  (lambda ()
    (display "Me too!\n")
    (newline)))
@end lisp

@item closure
@cindex closure
A closure is a procedure.  However, the term emphasizes the fact that a
Scheme procedure remembers (or @dfn{closes over}) the variables that
were visible when the @code{lambda} expression was
evaluated.

In the example below, we might refer to @code{q} as a closure, because
it has closed over the value of @code{x}:
@lisp
(define p
  (lambda (x)
    (lambda (y)
      (+ x y))))
(define q (p 5.7))

(q 10)
@result{} 15.7
@end lisp

However, strictly speaking, every Scheme procedure is really a closure,
since it closes over the top-level environment.

@item alist
@itemx association list

@item plist
@itemx property list

@end table

@node Read-eval-print loops
@section Read-eval-print loops
@cindex Read-eval-print loop
@cindex REPL

To explicitly mention the Scheme read-eval-print loop (REPL) seems weird
because we are all accustomed to firing up an interpreter and having it
read and execute commands.

But the REPL is not specified in R4RS; rather, it is proposed by the
Scheme Bible @cite{Structure and Interpretation of Computer Programs}
(also known as @emph{SICP}), and implemented in some form in all Scheme
interpreters.
@cindex Structure and Interpretation of Computer Programs
@cindex SICP

[FIXME: Someone needs to tell me what needs to be said about Guile's
REPL.]

@node Extra data types
@section Extra data types

The fundamental Scheme data types specified in R4RS are @emph{numbers}
(both exact and inexact), @emph{characters}, @emph{strings},
@emph{symbols}, @emph{vectors}, @emph{pairs} and @emph{lists} [FIXME: is
this complete?].

Many Scheme interpreters offer more types, and Guile is no exception.
Guile is based on Aubrey Jaffer's SCM interpreter, and thus inherits
@emph{uniform arrays}, [FIXME: any others?  How about records?].

On top of that, Guile allows you to add extra types, but that is covered
in @ref{Adding types to Guile}.  Here I will simply document all the
extra Scheme types shipped with Guile.

@menu
* Conventional arrays::
* Uniform arrays::
* Bit vectors::
* Complex numbers::
@end menu

@node Conventional arrays
@subsection Conventional arrays

@node Uniform arrays
@subsection Uniform arrays
@cindex arrays - uniform

The motivation for uniform arrays in Scheme is performance.  A vector
provides a performance increase over lists when you want a fixed-size
indexable list.  But the elements in a vector can be of different types,
and this makes for larger storage requirements and slightly lower
performance.

A uniform array is similar to a vector, but all elements have to be of
the same type.

arrays, uniform arrays, bit vectors:

@deffn procedure array-fill ra fill
@end deffn
@deffn procedure serial-array-copy! src dst
@end deffn
@deffn procedure serial-array-map ra0 proc [lra]
@end deffn
@deffn procedure array-map ra0 proc [lra]
@end deffn
@deffn procedure array-for-each proc ra0 [lra]
@end deffn
@deffn procedure array-index-map! ra proc
@end deffn
@deffn procedure array-copy! src dst
@end deffn
@deffn procedure array-copy! src dst
@end deffn
@deffn procedure array-copy! src dst
@end deffn
@deffn procedure array-copy! src dst
@end deffn
@deffn procedure array-copy! src dst
@end deffn
@deffn procedure array? ra [prot]
@end deffn
@deffn procedure array-rank ra
@end deffn
@deffn procedure array-dimensions ra
@end deffn
@deffn procedure dimensions->uniform-array dims prot fill ...
@end deffn
@deffn procedure make-shared-array ra mapfunc dims ...
@end deffn
@deffn procedure transpose-array arg ...
@end deffn
@deffn procedure enclose-array axes ...
@end deffn
@deffn procedure array-in-bounds? arg ...
@end deffn
@deffn procedure array-ref ra arg ..
@end deffn
@deffn procedure uniform-vector-ref vec pos
@end deffn
@deffn procedure array-set! ra obj arg ...
@end deffn
@deffn procedure uniform-array-set1! ua obj arg
@end deffn
@deffn procedure array-contents ra [strict]
@end deffn
@deffn procedure uniform-array-read! ra [port-or-fd] [start] [end]
@end deffn
@deffn procedure uniform-array-write! ra [port-or-fd] [start] [end]
@end deffn
@deffn procedure bit-count item seq
@end deffn
@deffn procedure bit-position item v k
@end deffn
@deffn procedure bit-set! v kv obj
@end deffn
@deffn procedure bit-count* v kv obj
@end deffn
@deffn procedure bit-invert v
@end deffn
@deffn procedure array->list ra
@end deffn
@deffn procedure list->uniform-array ndim prot list
@end deffn
@deffn procedure array-prototype ra
@end deffn

Unform arrays can be written and read, but @code{read} won't recognize
them unless the optional @code{read-sharp} parameter is supplied,
e.g,
@smalllisp
(read port #t read-sharp)
@end smalllisp

where @code{read-sharp} is the default procedure for parsing extended
sharp notations.

Reading an array is not very efficient at present, since it's implemented
by reading a list and converting the list to an array.

@c FIXME: must use @deftp, but its generation of TeX code is buggy.
@c Must fix it when TeXinfo gets fixed.
@deftp {Scheme type} {uniform array}

@end deftp

@node Bit vectors
@subsection Bit vectors

@node Complex numbers
@subsection Complex numbers

@c FIXME: must use @deftp, but its generation of TeX code is buggy.
@c Must fix it when TeXinfo gets fixed.
@deftp {Scheme type} complex
Standard complex numbers.
@end deftp

@node Miscellaneous features
@section Miscellaneous features

@defun defined? symbol
Returns @code{#t} if a symbol is bound to a value, @code{#f} otherwise.
This kind of procedure is not specified in R4RS because @c FIXME: finish
this thought
@end defun

@defun object-properties OBJ
and so forth
@end defun


code:
@node Libguile -- SCM interface
@chapter Libguile -- SCM interface


code:
@node Strings
@chapter Facilities for string manipulation

@deffn procedure string? string
@end deffn
@deffn procedure read-only-string? string
@end deffn
@deffn procedure list->string list
@end deffn
@deffn procedure make-string length [char]
@end deffn
@deffn procedure string-length string
@end deffn
@deffn procedure string-ref string [index]
@end deffn
@deffn procedure string-set! string index char
@end deffn
@deffn procedure substring string start [end]
@end deffn
@deffn procedure string-append arg ...
@end deffn
@deffn procedure make-shared-substring string [from] [to]
@end deffn
@deffn procedure string-set! string index char
@end deffn
@deffn procedure string-index string char [from] [to]
@end deffn
@deffn procedure string-rindex string char [from] [to]
@end deffn
@deffn procedure substring-move-left! string1 start1 [end1] [string2] [start2]
@end deffn
@deffn procedure substring-move-right! string1 start1 [end1] [string2] [start2]
@end deffn
@deffn procedure substring-fill! string start [end] [fill]
@end deffn
@deffn procedure string-null? string
@end deffn
@deffn procedure string->list string
@end deffn
@deffn procedure string-copy string
@end deffn
@deffn procedure string-upcase! string
@end deffn
@deffn procedure string-downcase! string
@end deffn


code:
@node Tk interface
@chapter Tk interface

For now Guile has no well-specified Tk interface.  It is an important part
of Guile, though, and will be documented here when it is written.


code:
@node Other Unix
@chapter Other Unix-specific facilities

@menu
* Expect::              Expect, for pattern matching from a port.
@end menu

@node Expect
@section Expect: Pattern Matching from a Port

@code{expect} is a macro for selecting actions based on the output from
a port.  The name comes from a tool of similar functionality by Don Libes.
Actions can be taken when a particular string is matched, when a timeout
occurs, or when end-of-file is seen on the port.  The @code{expect} macro
is described below; @code{expect-strings} is a front-end to @code{expect}
based on regexec @xref{Regular expressions}.

Using these macros requires for now:
@smalllisp
(load-from-path "ice-9/expect")
@end smalllisp

@defun expect-strings clause @dots{}
By default, @code{expect-strings} will read from the current input port.
The first term in each clause consists of an expression evaluating to
a string pattern (regular expression).  As characters
are read one-by-one from the port, they are accumulated in a buffer string
which is matched against each of the patterns.  When a
pattern matches, the remaining expression(s) in
the clause are evaluated and the value of the last is returned.  For example:

@smalllisp
(with-input-from-file "/etc/passwd"
  (lambda ()
    (expect-strings
      ("^nobody" (display "Got a nobody user.\n")
                 (display "That's no problem.\n"))
      ("^daemon" (display "Got a daemon user.\n")))))
@end smalllisp

The regular expression is compiled with the @code{REG_NEWLINE} flag, so
that the @code{^} and @code{$} anchors will match at any newline, not
just at the start
and end of the string.

There are two other ways to write a clause:

The expression(s) to evaluate on a match
can be omitted, in which case the result of the match
(converted to strings, as obtained from regexec with @var{match-pick}
set to @code{""}) will be returned if the pattern matches.

The symbol @code{=>} can be used to indicate that there is a single
expression to evaluate on a match, which must be a
procedure which will accept the result of a successful match (converted
to strings, as obtained from regexec with @var{match-pick} set to
@code{""}).  E.g.,

@smalllisp
("^daemon" => write)
("^d\\(aemon\\)" => (lambda args (map write args)))
("^da\\(em\\)on" => (lambda (all sub)
                         (write all)
                         (write sub)))
@end smalllisp

The order of the substrings corresponds to the order in which the
opening brackets occur in the regular expression.

A number of variables can be used to control the behaviour
of @code{expect} (and @code{expect-strings}).
By default they are all bound at the top level to
the value @code{#f}, which produces the default behaviour.
They can be redefined at the
top level or locally bound in a form enclosing the @code{expect} expression.

@table @code
@item expect-port
A port to read characters from, instead of the current input port.
@item expect-timeout
@code{expect} will terminate after this number of
seconds, returning @code{#f} or the value returned by
@code{expect-timeout-proc}.
@item expect-timeout-proc
A procedure called if timeout occurs.  The procedure takes a single argument:
the accumulated string.
@item expect-eof-proc
A procedure called if end-of-file is detected on the input port.  The
procedure takes a single argument: the accumulated string.
@item expect-char-proc
A procedure to be called every time a character is read from the
port.  The procedure takes a single argument: the character which was read.
@end table

Here's an example using all of the variables:

@smalllisp
(let ((expect-port (open-input-file "/etc/passwd"))
      (expect-timeout 1)
      (expect-timeout-proc
        (lambda (s) (display "Times up!\n")))
      (expect-eof-proc
        (lambda (s) (display "Reached the end of the file!\n")))
      (expect-char-proc display))
   (expect-strings
     ("^nobody"  (display "Got a nobody user\n"))))
@end smalllisp
@end defun

@defun expect clause @dots{}
@code{expect} is used in the same way as @code{expect-strings},
but tests are specified not as patterns, but as procedures.  The
procedures are called in turn after each character is read from the
port, with the value of the accumulated string as the argument.  The
test is successful if the procedure returns a non-false value.

If the @code{=>} syntax is used, then if the test succeeds it must return
a list containing the arguments to be provided to the corresponding
expression.

In the following example, a string will only be matched at the beginning
of the file:
@smalllisp
(let ((expect-port (open-input-file "/etc/passwd")))
  (expect
     ((lambda (s) (string=? s "fnord!"))
        (display "Got a nobody user!\n"))))
@end smalllisp

The control variables described for @code{expect-strings} can also
be used with @code{expect}.
@end defun


code:
@node Low level Unix
@chapter Low level Unix interfaces

The low level Unix interfaces are currently available by
default in the Guile top level.  However in the future they will probably
be placed in a module and @code{use-modules} or something similar will
be required to make them available.

@menu
* Unix conventions::            Conventions followed by the low level Unix
                                interfaces.
* Ports and descriptors::       Ports, file descriptors and how they
                                interact.
* Extended I/O::                Reading and writing to ports.
* File system::                 Working in a hierarchical filesystem.
* User database::               Information about users from system databases.
* Processes::                   Information and control of Unix processes.
* Terminals::                   Terminals and pseudo-terminals.
* Network databases::           Network address conversion and information
                                from system databases.
* Network sockets::             An interface to the BSD socket library.
* Miscellaneous Unix::          Miscellaneous Unix interfaces.
@end menu

@node Unix conventions
@section Low level Unix conventions

The low-level interfaces are designed to give Scheme programs
access to as much functionality as possible from the underlying
Unix system.  They can be used to implement higher level
intefaces such as the Scheme shell @ref{scsh}.

Generally there is a single procedure for each corresponding Unix
facility.  However some of the procedures are implemented for
speed and convenience in Scheme and have no Unix equivalent
(e.g., @code{read-delimited}, @code{copy-file}.)

This interface is intended as far as possible to be portable across
different versions of Unix, so that Scheme programmers don't need to be
concerned with implementation differences.  In some cases procedures
which can't be implemented (or reimplemented) on particular systems may
become no-ops, or perform limited actions.  In other cases they may
throw errors.  It should be possible to use the feature system to
determine what functionality is available.

General naming conventions are as follows:

@itemize @bullet
@item
The Scheme name is often identical to the name of the underlying Unix
facility.
@item
Underscores in Unix names are converted to hyphens.
@item
Procedures which destructively modify Scheme data gain postpended
exclaimation marks, e.g., @code{recv!}.
@item
Predicates are postpended with question marks, e.g., @code{access?}.
@item
Some names are changed to avoid conflict with dissimilar interfaces
defined by scsh.
@item
Unix preprocessor names such as @code{EPERM} or @code{R_OK} are converted
to Scheme variables of the same name (underscores are not replaced
with hyphens)
@end itemize

Most of the Unix interface procedures can be relied on to return a
well-specified value.  Unexpected conditions are handled by raising
exceptions.

There are a few procedures which return a special
value if they don't succeed, e.g., @code{getenv} returns @code{#f}
if it the requested string is not found in the environment.  These
cases will be noted in the documentation.

For ways to deal with exceptions, @ref{Exceptions}.

Errors which the C-library would report by returning a NULL
pointer or through some other means cause a @code{system-error} exception
to be raised.  The value of the Unix @code{errno} variable is available
in the data passed by the exception, so there is no need to access the
global errno value (doing so would be unreliable in the presence of
continuations or multiple threads).

@deffn procedure errno [n]
@end deffn
@deffn procedure perror string
@end deffn

@node Ports and descriptors
@section Ports and file descriptors

@deffn procedure move->fdes port fd
@end deffn
@deffn procedure release-port-handle port
@end deffn
@deffn procedure set-port-revealed! @var{port} count
@end deffn
@deffn procedure fdes->ports fdes
@end deffn
@deffn procedure fileno port
@end deffn
@deffn procedure fdopen fdes modes
@end deffn
@deffn procedure duplicate-port port modes
@end deffn
@deffn procedure redirect-port into-port from-port
@end deffn
@deffn procedure freopen filename modes port
@end deffn

@node Extended I/O
@section Extended I/O

Extended I/O procedures are available which read or write lines of text,
read text delimited by a specified set of characters, or report or
set the current position of a port.

@findex fwrite
@findex fread
Interfaces to @code{read}/@code{fread} and @code{write}/@code{fwrite} are
also available, as @code{uniform-array-read!} and @code{uniform-array-write!},
@ref{Uniform arrays}.

@deffn procedure read-line [port] [handle-delim]
Return a line of text from @var{port} if specified, otherwise from the
value returned by @code{(current-input-port)}.  Under Unix, a line of text
is terminated by the first end-of-line character or by end-of-file.

If @var{handle-delim} is specified, it should be one of the following
symbols:
@table @code
@item trim
Discard the terminating delimiter.  This is the default, but it will
be impossible to tell whether the read terminated with a delimiter or
end-of-file.
@item concat
Append the terminating delimiter (if any) to the returned string.
@item peek
Push the terminating delimiter (if any) back on to the port.
@item split
Return a pair containing the string read from the port and the
terminating delimiter or end-of-file object.

NOTE: if the scsh module is loaded then
multiple values are returned instead of a pair.
@end table
@end deffn
@deffn procedure read-line! buf [port]
Read a line of text into the supplied string @var{buf} and return the
number of characters added to @var{buf}.  If @var{buf} is filled, then
@code{#f} is returned.
Read from @var{port} if
specified, otherwise from the value returned by @code{(current-input-port)}.
@end deffn
@deffn procedure read-delimited delims [port] [handle-delim]
Read text until one of the characters in the string @var{delims} is found
or end-of-file is reached.  Read from @var{port} if supplied, otherwise
from the value returned by @code{(current-input-port)}.
@var{handle-delim} takes the same values as described for @code{read-line}.

NOTE: if the scsh module is loaded then @var{delims} must be an scsh
char-set, not a string.
@end deffn
@deffn procedure read-delimited! delims buf [port] [handle-delim] [start] [end]
Read text into the supplied string @var{buf} and return the number of
characters added to @var{buf} (subject to @var{handle-delim}, which takes
the same values specified for @code{read-line}.  If @var{buf} is filled,
@code{#f} is returned for both the number of characters read and the
delimiter.  Also terminates if one of the characters in the string
@var{delims} is found
or end-of-file is reached.  Read from @var{port} if supplied, otherwise
from the value returned by @code{(current-input-port)}.

NOTE: if the scsh module is loaded then @var{delims} must be an scsh
char-set, not a string.
@end deffn
@deffn procedure write-line obj [port]
Display @var{obj} and a new-line character to @var{port} if specified,
otherwise to the
value returned by @code{(current-output-port)}; equivalent to:

@smalllisp
(display obj [port])
(newline [port])
@end smalllisp
@end deffn
@deffn procedure ftell port
Returns an integer representing the current position of @var{port},
measured from the beginning.
@end deffn
@deffn procedure fseek port offset whence
Sets the current position of @var{port} to the integer @var{offset},
which is interpreted according to the value of @var{whence}.

One of the following variables should be supplied
for @var{whence}:
@defvar SEEK_SET
Seek from the beginning of the file.
@end defvar
@defvar SEEK_CUR
Seek from the current position.
@end defvar
@defvar SEEK_END
Seek from the end of the file.
@end defvar
@end deffn

@node File system
@section File system

These procedures query and set file system attributes (such as owner,
permissions, sizes and types of files); deleting, copying, renaming and
linking files; creating and removing directories and querying their
contents; and the @code{sync} interface.

@deffn procedure access? path how
Evaluates to @code{#t} if @var{path} corresponds to an existing
file and the current process
has the type of access specified by @var{how}, otherwise
@code{#f}.
@var{how} should be specified
using the values of the variables listed below.  Multiple values can
be combined using a bitwise or, in which case @code{#t} will only
be returned if all accesses are granted.

Permissions are checked using the real id of the current process,
not the effective id, although it's the effective id which determines
whether the access would actually be granted.

@defvar R_OK
test for read permission.
@end defvar
@defvar W_OK
test for write permission.
@end defvar
@defvar X_OK
test for execute permission.
@end defvar
@defvar F_OK
test for existence of the file.
@end defvar
@end deffn
@findex fstat
@deffn procedure stat obj
Evaluates to an object containing various information
about the file determined by @var{obj}.
@var{obj} can be a string containing a file name or a port or file
descriptor which is open on a file (in which case @code{fstat} is used
as the underlying system call).

The object returned by @code{stat} can be passed as a single parameter
to the following procedures, all of which return integers:

@table @r
@item stat:dev
The device containing the file.
@item stat:ino
The file serial number, which distinguishes this file from all other
files on the same device.
@item stat:mode
The mode of the file.  This includes file type information
and the file permission bits.  See @code{stat:type} and @code{stat:perms}
below.
@item stat:nlink
The number of hard links to the file.
@item stat:uid
The user ID of the file's owner.
@item stat:gid
The group ID of the file.
@item stat:rdev
Device ID; this entry is defined only for character or block
special files.
@item stat:size
The size of a regular file in bytes.
@item stat:atime
The last access time for the file.
@item stat:mtime
The last modification time for the file.
@item stat:ctime
The last modification time for the attributes of the file.
@item stat:blksize
The optimal block size for reading or writing the file, in bytes.
@item stat:blocks
The amount of disk space that the file occupies measured in units of
512 byte blocks.
@end table

In addition, the following procedures return the information
from stat:mode in a more convenient form:

@table @r
@item stat:type
A symbol representing the type of file.  Possible values are
currently: regular, directory, symlink, block-special, char-special,
fifo, socket, unknown
@item stat:perms
An integer representing the access permission bits.
@end table
@end deffn
@deffn procedure lstat path
Similar to @code{stat}, but does not follow symbolic links, i.e.,
it will return information about a symbolic link itself, not the
file it points to.  @var{path} must be a string.
@end deffn
@deffn procedure readlink path
@end deffn
@deffn procedure chown path owner group
@end deffn
@deffn procedure chmod port-or-path mode
@end deffn
@deffn procedure utime path [actime] [modtime]
@end deffn
@deffn procedure delete-file path
@end deffn
@deffn procedure copy-file path-from path-to
@end deffn
@deffn procedure rename-file path-from path-to
@end deffn
@deffn procedure link path-from path-to
@end deffn
@deffn procedure symlink path-from path-to
@end deffn
@deffn procedure mkdir path [mode]
@end deffn
@deffn procedure rmdir path
@end deffn
@deffn procedure opendir path
@end deffn
@deffn procedure readdir port
@end deffn
@deffn procedure rewinddir port
@end deffn
@deffn procedure closedir port
@end deffn
@deffn procedure sync
@end deffn

@node User database
@section User database

@deffn procedure getpwuid uid
@end deffn
@deffn procedure getpwnam name
@end deffn
@deffn procedure getpwent
@end deffn
@deffn procedure setpwent port
@end deffn
@deffn procedure endpwent
@end deffn
@deffn procedure getgrgid uid
@end deffn
@deffn procedure getgrnam name
@end deffn
@deffn procedure getgrent
@end deffn
@deffn procedure setgrent port
@end deffn
@deffn procedure endgrent
@end deffn

@node Processes
@section Processes

@deffn procedure chdir path
@end deffn
@deffn procedure getcwd
@end deffn
@deffn procedure umask [mode]
@end deffn
@deffn procedure getpid
@end deffn
@deffn procedure getgroups
@end deffn
@deffn procedure kill pid sig

@var{sig} should be specified using a variable corresponding to
the Unix symbolic name, e.g,
@defvar SIGHUP
Hang-up signal.
@end defvar
@defvar SIGINT
Interrupt signal.
@end defvar
@end deffn
@deffn procedure waitpid pid options
@defvar WAIT_ANY
@end defvar
@defvar WAIT_MYPGRP
@end defvar
@defvar WNOHANG
@end defvar
@defvar WUNTRACED
@end defvar
@end deffn
@deffn procedure getppid
@end deffn
@deffn procedure getuid
@end deffn
@deffn procedure getgid
@end deffn
@deffn procedure geteuid
@end deffn
@deffn procedure getegid
@end deffn
@deffn procedure setuid id
@end deffn
@deffn procedure setgid id
@end deffn
@deffn procedure seteuid id
@end deffn
@deffn procedure setegid id
@end deffn
@deffn procedure getpgrp
@end deffn
@deffn procedure setpgid pid pgid
@end deffn
@deffn procedure setsid
@end deffn
@deffn procedure execl arg ...
@end deffn
@deffn procedure execlp arg ...
@end deffn
@deffn procedure primitive-fork
@end deffn
@deffn procedure environ [env]
@end deffn
@deffn procedure putenv string
@end deffn
@deffn procedure nice incr
@end deffn

@node Terminals
@section Terminals and pseudo-terminals

@deffn procedure isatty? port
@end deffn
@deffn procedure ttyname port
@end deffn
@deffn procedure ctermid
@end deffn
@deffn procedure tcgetpgrp port
@end deffn
@deffn procedure tcsetpgrp port pgid
@end deffn

@node Network databases
@section Network address conversion and system databases

@deffn procedure inet-aton address
@end deffn
@deffn procedure inet-ntoa number
@end deffn
@deffn procedure inet-netof address
@end deffn
@deffn procedure inet-lnaof address
@end deffn
@deffn procedure inet-makeaddr net lna
@end deffn
@deffn procedure gethostbyname name
@end deffn
@deffn procedure gethostbyaddr address
@end deffn
@deffn procedure gethostent
@end deffn
@deffn procedure sethostent port
@end deffn
@deffn procedure endhostent
@end deffn
@deffn procedure getnetbyname name
@end deffn
@deffn procedure getnetbyaddr address
@end deffn
@deffn procedure getnetent
@end deffn
@deffn procedure setnetent port
@end deffn
@deffn procedure endnetent
@end deffn
@deffn procedure getprotobyname name
@end deffn
@deffn procedure getprotobynumber number
@end deffn
@deffn procedure getprotoent
@end deffn
@deffn procedure setprotoent port
@end deffn
@deffn procedure endprotoent
@end deffn
@deffn procedure getservbyname name protocol
@end deffn
@deffn procedure getservbyport port protocol
@end deffn
@deffn procedure getservent
@end deffn
@deffn procedure setservent port
@end deffn
@deffn procedure endservent
@end deffn

@node Network sockets
@section BSD socket library interface

@deffn procedure socket family style protocol
@end deffn
@deffn procedure socketpair family style protocol
@end deffn
@deffn procedure getsockopt socket level optname
@end deffn
@deffn procedure setsockopt socket level optname value
@end deffn
@deffn procedure shutdown socket how
@end deffn
@deffn procedure connect socket family address arg ...
@end deffn
@deffn procedure bind socket family address arg ...
@end deffn
@deffn procedure listen socket backlog
@end deffn
@deffn procedure accept socket
@end deffn
@deffn procedure getsockname socket
@end deffn
@deffn procedure getpeername socket
@end deffn
@deffn procedure recv! socket buf [flags]
@end deffn
@deffn procedure send socket message [flags]
@end deffn
@deffn procedure recvfrom! socket buf [flags] [start] [end]
@end deffn
@deffn procedure sendto socket message family address args ... [flags]
@end deffn

@node Miscellaneous Unix
@section Miscellaneous Unix interfaces

Things which haven't been classified elsewhere (yet?).

@deffn procedure open path flags [mode]
@defvar O_RDONLY
@end defvar
@defvar O_WRONLY
@end defvar
@defvar O_RDWR
@end defvar
@defvar O_CREAT
@end defvar
@defvar O_EXCL
@end defvar
@defvar O_NOCTTY
@end defvar
@defvar O_TRUNC
@end defvar
@defvar O_APPEND
@end defvar
@defvar O_NONBLOCK
@end defvar
@defvar O_NDELAY
@end defvar
@defvar O_SYNC
@end defvar
@end deffn
@deffn procedure select reads writes excepts secs msecs
@end deffn
@deffn procedure uname
@end deffn
@deffn procedure pipe
@end deffn
@deffn procedure open-pipe command modes
@end deffn
@deffn procedure open-input-pipe command
@end deffn
@deffn procedure open-output-pipe command
@end deffn
@deffn procedure setlocale category [locale]
@defvar LC_COLLATE
@end defvar
@defvar LC_CTYPE
@end defvar
@defvar LC_MONETARY
@end defvar
@defvar LC_NUMERIC
@end defvar
@defvar LC_TIME
@end defvar
@defvar LC_MESSAGES
@end defvar
@defvar LC_ALL
@end defvar
@end deffn
@deffn procedure strftime format stime
@end deffn
@deffn procedure strptime format string
@end deffn
@deffn procedure mknod
@end deffn

@node scsh
@chapter The Scheme shell (scsh)

Guile includes an incomplete port of the Scheme shell (scsh) 0.4.4.

For information about scsh on the Web see
@url{http://www-swiss.ai.mit.edu/scsh/scsh.html}.
The original scsh is available by ftp from
@url{ftp://swiss-ftp.ai.mit.edu:/pub/su}.

This port of scsh does not currently use the Guile module system, but
can be initialized using:
@smalllisp
(load-from-path "scsh/init")
@end smalllisp

Note that SLIB must be installed before scsh can be initialized, see
@ref{SLIB} for details.

@node Threads
@chapter Programming Threads.


code:
2004-07-29  Kevin Ryde  <user42@zip.com.au>

	* doc/tutorial/guile-tut.texi (What is libguile): Correction to
	reference manual "Data representation" cross reference.

2004-06-28  Marius Vollmer  <marius.vollmer@uni-dortmund.de>

	* Makefile.am: Removed home-grown code for HTML generation.
	Automake does it for us now.

	* guile-tut.texi (Top): Use @ifnottex instead of @ifinfo for the
	beneift of makeinfo --html.

2003-09-27  Neil Jerram  <neil@ossau.uklinux.net>

	* guile-tut.texi (Using Guile to program in Scheme): Fix result of
	`(reverse ls)', and change `squaring function' example to use `(*
	n n)' instead of `(expt n n)'.  Thanks to Jack Pavlovsky for
	pointing these out.

2003-05-27  Dirk Herrmann  <D.Herrmann@tu-bs.de>

	* guile-tut.texi: Fix example, where a vector constant is used
	without quoting.

2002-07-16  Neil Jerram  <neil@ossau.uklinux.net>

	* guile-tut.texi (Jump Start): Apply patch from M. Luedde on use
	of tail recursion to avoid stack overflow (with minor editing).

2001-11-18  Neil Jerram  <neil@ossau.uklinux.net>

	* guile-tut.texi (History of Guile and its motivations): Update
	Tcl war URLs.

2001-09-19  Thien-Thi Nguyen  <ttn@glug.org>

	* guile-tut.texi: Fix improper `@result' usage.
	Fix number typo in "Jump Start" section.

2001-08-27  Neil Jerram  <neil@ossau.uklinux.net>

	* Makefile.am (guile_tut_TEXINFOS): Removed.
	(TEXINFO_TEX): Added; avoids shipping multiple copies of
	texinfo.tex in a single distribution.

	* guile-tut.texi: Incorporate text previously in separate AUTHORS
	file.

2001-08-27  Neil Jerram  <neil@ossau.uklinux.net>

	The change log for files in this directory continues backwards
	from 2001-08-27 in ../ChangeLog, as all the Guile documentation
	prior to this date was contained in a single directory.


code:
2001-01-27  Neil Jerram  <neil@ossau.uklinux.net>

	* texinfo.tex: Replaced by latest version from ftp.gnu.org.

1999-12-06  Gary Houston  <ghouston@freewire.co.uk>

	* guile-tut.texi: tweaked the dircategory.

1998-01-28  Mark Galassi  <rosalia@nis.lanl.gov>

	* guile-tut.texi: set @dircategory to "Scheme Programming".

Mon Aug 18 16:11:43 1997  Jim Blandy  <jimb@totoro.red-bean.com>

	* texinfo.tex: Installed from texinfo release 3.11.


code:
## Process this file with Automake to create Makefile.in
##
##  	Copyright (C) 1998, 2006, 2008 Free Software Foundation, Inc.
##
##   This file is part of GUILE.
##
##   GUILE is free software; you can redistribute it and/or modify
##   it under the terms of the GNU General Public License as
##   published by the Free Software Foundation; either version 2, or
##   (at your option) any later version.
##
##   GUILE is distributed in the hope that it will be useful, but
##   WITHOUT ANY WARRANTY; without even the implied warranty of
##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##   GNU General Public License for more details.
##
##   You should have received a copy of the GNU General Public
##   License along with GUILE; see the file COPYING.  If not, write
##   to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
##   Floor, Boston, MA 02110-1301 USA

AUTOMAKE_OPTIONS = gnu

info_TEXINFOS = guile-tut.texi

EXTRA_DIST = ChangeLog-2008


code:
\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename guile-tut.info
@settitle Guile Tutorial
@set guile-tut

@include version.texi

@dircategory The Algorithmic Language Scheme
@direntry
* Guile Tutorial: (guile-tut).  The Guile tutorial.
@end direntry

@setchapternewpage off
@c Choices for setchapternewpage are {on,off,odd}.
@paragraphindent 2
@c %**end of header

@iftex
@finalout
@c DL: lose the egregious vertical whitespace, esp. around examples
@c but paras in @defun-like things don't have parindent
@parskip 4pt plus 1pt
@end iftex

@titlepage
@title Guile Tutorial
@subtitle For use with Guile @value{VERSION}
@subtitle Last updated @value{UPDATED}

@author Mark Galassi
@author Cygnus Solutions and Los Alamos National Laboratory
@author @email{rosalia@@nis.lanl.gov}

@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1997, 1998, 2004, 2006 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 author.
@end titlepage

@ifnottex
@node Top
@top Guile Tutorial
@end ifnottex

@ifinfo
This file gives a tutorial introduction to Guile.

Copyright (C) 1997, 2004, 2006 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.

@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).

@end ignore
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 author.
@end ifinfo

@menu
* Jump Start::
* Introduction::
* Using Guile to program in Scheme::
* Guile in a Library::
* Regular Expression Support::
* UNIX System Programming::
* Where to find more Guile/Scheme resources::
* Concept Index::
* Procedure and Macro Index::
* Variable Index::
* Type Index::
@end menu

@node Jump Start
@chapter Jump Start

@noindent
Before giving an overview of Guile, I present some simple commands and
programs that you can type to get going immediately.

Start by invoking the Guile interpreter.  Usually you do this by just
typing @code{guile}.  Then type (or paste) the following expressions at
the prompt; the interpreter's response is preceded (in this manual) by
@result{}.

@example
<shell-prompt> guile
@end example
@lisp
(+ 20 35)
@result{} 55
(define (recursive-factorial n)
  (if (zero? n)
      1
      (* n (recursive-factorial (- n 1)))))
(recursive-factorial 5)
@result{} 120
(quit)
@end lisp

In this example we did some simple arithmetic @code{(+ 20 35)} and got
the answer @code{55}.  Then we coded the classic (and rather wasteful)
factorial algorithm and computed the factorial of @code{55}.  Finally we
quit with @code{(quit)}.

@cindex bignumbers
We can find out about some of Scheme's nice features by asking for the
factorial of some big number, say @code{500}.  On some systems the
correct answer will be returned (I do not indicate calling and leaving
the guile session anymore).

@lisp
(recursive-factorial 500)
@result{} 1220136825991110068701238785423046926253574342803192842192413588
   3858453731538819976054964475022032818630136164771482035841633787
   2207817720048078520515932928547790757193933060377296085908627042
   9174547882424912726344305670173270769461062802310452644218878789
   4657547771498634943677810376442740338273653974713864778784954384
   8959553753799042324106127132698432774571554630997720278101456108
   1188373709531016356324432987029563896628911658974769572087926928
   8712817800702651745077684107196243903943225364226052349458501299
   1857150124870696156814162535905669342381300885624924689156412677
   5654481886506593847951775360894005745238940335798476363944905313
   0623237490664450488246650759467358620746379251842004593696929810
   2226397195259719094521782333175693458150855233282076282002340262
   6907898342451712006207714640979456116127629145951237229913340169
   5523638509428855920187274337951730145863575708283557801587354327
   6888868012039988238470215146760544540766353598417443048012893831
   3896881639487469658817504506926365338175055478128640000000000000
   0000000000000000000000000000000000000000000000000000000000000000
   00000000000000000000000000000000000000000000000
@end lisp

The result is an example of Scheme's @emph{bignumbers}.  However, there
are operating environments that provide (by default) too little stack
space.  They will instead produce an error message like this:

@lisp
(recursive-factorial 500)
@print{}
ERROR: Stack overflow
ABORT: (stack-overflow)
@end lisp

Rather than enlarging the system's stack, we can implement the algorithm
such that it does not consume increasing stack space.  This is called a
@emph{tail recursive} implementation.  The following definition is tail
recursive and so should work on all systems.

@lisp
(define (tail-recursive-factorial n)
  (define (loop k l)
    (if (zero? k) l
	(loop (- k 1) (* k l))))
  (loop n 1))

(tail-recursive-factorial 500)
@result{} 1220136825991110068701238785423046926253574342803192842192413588
        ;; ... skipped
@end lisp

This is the most basic use of Guile: a simple Scheme interpreter.  In
the rest of this tutorial I will show you how Guile has many facets: it
is also an @emph{extensible} interpreter (to which many features can be
easilly added) and an @emph{embeddable} interpreter (which can be
invoked from your C programs).

@node Introduction
@chapter Introduction

@noindent
@dfn{Guile} (which can stand for @emph{GNU Ubiquitous Intelligent
Language Extension}) is the GNU extension language.  It started out as
an embeddable Scheme interpreter, and has rapidly evolved into a
kitchen-sink package including a standalone Scheme interpreter, an
embeddable Scheme interpreter, several graphics options, other languages
that can be used along with Scheme (for now just @emph{ctax} and
@emph{Tcl}), and hooks for much more.

@menu
* What are scripting and extension languages::
* History of Guile and its motivations::
* How to characterize Guile::
@end menu

@node What are scripting and extension languages
@section What are scripting and extension languages
@cindex scripting languages
@cindex extension languages

A @dfn{scripting language} is a programming language which serves as
glue between other system programs.  In the UNIX world, the traditional
scripting language is the @emph{Bourne shell}, which allows many UNIX
commands to be executed in sequence, or in a pipeline.  Traditional UNIX
commands are cleverly written to work well when put together in a
script.

Other examples of UNIX scripting languages are AWK, Perl, Scsh (the
Scheme Shell: a Scheme interpreter enhanced to do good scripting),
Python, Tcl, Java @dots{}
@cindex scripting languages - examples

UNIX programmers noticed, more than 25 years ago, that scripting
languages can do serious work, so the Bourne shell was written to have
variables, operators and control structures, just like a full-featured
programming language.
@cindex Bourne shell

What scripting languages have, that traditional programming languages do
not, is the ability to easily run an external program (or a pipeline of
external programs) and use the returned values and output from that
program in useful ways.

An @dfn{extension language} is a programming language interpreter
offered by an application program, so that users can write macros or
even full-fledged programs to extend the original application.
Extension languages have a C interface (it is usually C, but it could be
any other compiled language), and can be given access to the C data
structures.  Likewise, there are C routines to access the extension
language data structures.

Extension languages abound in the software world, even though the name
@emph{extension language} is seldom used.  Examples are:
@cindex extension languages - examples

@itemize @bullet
@item
Emacs Lisp, the language used to program and customize GNU Emacs.
@cindex Emacs Lisp

@item
Tcl, John Ousterhout's general-purpose scripting and extension language.
@cindex Tcl

@item
The Lotus 1-2-3 macro language (any spreadsheet macro language,
really).  I mention this one first because it is a classic, even though
it is seldom used any more.
@cindex Lotus 1-2-3

@item
Other spreadsheet and database macro languages.

@item
The Dominion empire-style game's @emph{exec} files.
@cindex Dominion

@item
Any syntax for a ".*rc" file you might have used.  Almost all programs
end up parsing some kind of startup or configuration file.  The syntax
for those can get pretty involved, thus justifying calling them
"extension languages".  The @emph{fvwm} window manager, for example,
parses a rather elaborate @file{.fvwmrc} file.

@item
Brent Benson's libscheme.a, an embeddable Scheme interpreter.
@cindex Benson, Brent
@cindex libscheme

@item
Guile, the GNU extension language, which is the subject of this
tutorial.

@end itemize

One lesson we can learn from looking at classical large software
applications is that "writers of large programs" always end up throwing
in some kind of parser for configuration or scripting.

Of the examples listed above, Emacs Lisp, Tcl, Libscheme and Guile have
an important property: they are not added as an afterthought for a
specific application.  They are general-purpose languages which a user
can learn (even in college courses) and then use to customize the
application program.

This is a recent and (in my opinion) very exciting direction in
large-program software engineering: program designers can link in the
Guile or Tcl library from the very beginning, and tell their users "You
want to customize this program?  Just use Scheme (or Tcl, or whatever
language), which you already know!"
@cindex large programs

@node History of Guile and its motivations
@section History of Guile and its motivations

A few separate threads of events led to the development of Guile.

In the fall of 1994, Richard Stallman, director of the GNU project,
posted an article with the subject "Why you should not use Tcl", in
which he argued that Tcl is inadequate as an extension language.  This
generated a flurry of flames (available in the hypermail archive
(@url{http://www.vanderburg.org/Tcl/war/}) @strong{The Tcl War}).
@cindex Stallman, Richard
@cindex GNU project
@cindex Tcl

The result was that Stallman then proposed his design for the GNU
Extension Language, first called GEL and then renamed Guile.  The
discussion triggered by that article is also available in a hypermail
archive, @url{http://www.vanderburg.org/Tcl/war2/}.

One interesting feature of this GNU Extension Language plan was that
users should have a @emph{choice} of languages to use in extending their
program.  The basic language would be a slightly modified Scheme, and
translators would be written to convert other languages (like Tcl,
Python, Perl, C-like languages @dots{}) into Scheme.

Tom Lord started working on this project immediately, taking Aubrey
Jaffer's small and portable implementation of Scheme, SCM, and making it
into an embeddable interpreter: callable from C and allowing new Scheme
procedures to be written in C.
@cindex Lord, Tom
@cindex Jaffer, Aubrey

In the spring of 1995, the guile-ii snapshot was released.  This made it
possible to start writing code in C and Scheme using the guile
facilities.

The guile-iii snapshot was released the summer of 1995, and it had fixed
enough problems so that the access to Scheme data structures from C was
almost complete.

After this, Cygnus Support added many features to Guile and finished
implementing others, so that Guile acquired thread support, a regular
expression matcher, a Tk interface, an interface to the SGI OpenGL
graphics system, an @emph{applet} formalism, and some other packages.
This was all in the Cygnus Guile r0.3 and r0.4 releases.
@cindex Cygnus Support

Meanwhile, Tom Lord left the project after having produced a divergent
version of Guile: 1.0b2.  The Free Software Foundation hired Jim Blandy
to coordinate Guile development.  The FSF released its first version of
Guile in January 1997.  In the future, many of the Cygnus packages will
be re-integrated into Guile.
@cindex Blandy, Jim
@cindex Free Software Foundation

@node How to characterize Guile
@section How to characterize Guile

I have already mentioned that Guile has become a kitchen sink package;
here you can see how Guile freely takes new commands and constructs from
the portable Scheme library @emph{slib}, the @emph{Tk} widget set, a
posix library (useful for UNIX systems programming), the regular
expression library @emph{rx}, and many more @dots{}
@cindex slib
@cindex Tk
@cindex POSIX
@c @cindex OpenGL
@cindex rx

So Guile has many more primitive procedures available to it than those
specified in @ref{Standard Procedures, Revised(5) Report on the
Algorithmic Language Scheme, , r5rs, Revised(5) Report on the
Algorithmic Language Scheme}.  On top of that, Guile will interpret
almost all standard Scheme programs.  The only incompatible difference
between the basic Guile language and R5RS Scheme is that Guile is case
sensitive, whereas R5RS is case insensitive.  We hope that few people
have written Scheme programs that depend on case insensitivity.
@cindex case sensitivity
@cindex Revised(5) Report on the Algorithmic Language Scheme
@cindex report on Scheme
@cindex Scheme language - report
@cindex Scheme language - definition

Here is a possible view of the @emph{sum of the parts} in Guile:
@cindex extensions to standard Scheme
@cindex extensions to R5RS
@cindex Scheme extensions
@example
guile   =       standard Scheme (R5RS)
        PLUS    extensions to R5RS offered by SCM
        PLUS    some extra primitives offered by Guile (catch/throw)
        PLUS    portable Scheme library (SLIB)
        PLUS    embeddable Scheme interpreter library (libguile)
        PLUS    Tk toolkit
        PLUS    threads
        PLUS    Posix library
@c         PLUS    OpenGL library (mesa)
@c         PLUS    OpenGL toolkit (glut)
        PLUS    Regular expression library (rx)
@c         PLUS    Applet formalism
        PLUS    Tcl library
@end example

@node Using Guile to program in Scheme
@chapter Using Guile to program in Scheme
@cindex Scheme programming tutorial
@cindex tutorial on Scheme programming

In this section I give a tutorial introduction to programming in Scheme,
with a slant toward the interesting things that can be done in Guile.

@c Applets are so @emph{chic} that they get their own section, but this
This section will try to touch on many of the interesting and cool
aspects of Guile, showing you how new types of problems can be solved
with Guile.  Note that using Guile as a library with @code{libguile.a}
is described in its own chapter (@pxref{Guile in a Library}).  Also note
that some small examples are given in @ref{Jump Start}.

To get started you need to know how to program in @dfn{Scheme} (a
dialect of LISP).  Fortunately Scheme is a small, clean language and is
not hard to learn.  It is also used in many undergraduate courses to
introduce computer programming.
@cindex lisp dialects

I will not try to teach you Scheme here (although you might end up
learning by example), since there are many good books on the subject,
listed in @ref{Where to find more Guile/Scheme resources}. @footnote{To
get started, look at the books @cite{Simply Scheme} and @cite{The Little
Schemer} from that list.}

@subsection Hello World
@cindex hello world

Our first program is the typical Scheme "hello world" program.  Put the
following code in a file called @code{hello.scm} (this can be find in
@file{examples/scheme/hello.scm}).

@smalllisp
#!/usr/local/bin/guile -s
!#

(display "hello world")
(newline)
@end smalllisp

Then run guile on it.  One way to do so is to start up guile and load
this file:

@smallexample
<shell-prompt> @kbd{guile}
guile> @kbd{(load "hello")}
@end smallexample

Another way is to make the file executable and execute it directly.
Notice how Guile recognizes a @code{-s} option which tells it to run a
script and then exit.  Guile also has a new type of block comment
enclosed by @code{#!} and @code{!#}, so that you can make executable
Scheme scripts with the standard UNIX @code{#!} mechanism.

In the given example, the first line is used to invoke the Guile
interpreter (make sure you correct the path if you installed Guile in
something other than /usr/local/bin).  Once Guile is invoked on this
file, it will understand that the first line is a comment.  The comment
is then terminated with @code{!#} on the second line so as to not
interfere with the execution mechanism.

@subsection A bunch of operations in Scheme

Here is some code you can type at the @code{guile>} prompt to see some
of the Scheme data types at work (mostly lists and vectors).  I have
inserted brief comments @emph{before} each line of code explaining what
happens.

@smalllisp
;; @r{make a list and bind it to the symbol @code{ls}}
guile> @kbd{(define ls (list 1 2 3 4 5 6 7))}
       @result{}
;; @r{display the list}
guile> @kbd{ls}
       @result{} (1 2 3 4 5 6 7)
;; @r{ask if @code{ls} is a vector; @code{#f} means it is not}
guile> @kbd{(vector? ls)}
       @result{} #f
;; @r{ask if @code{ls} is a list; @code{#t} means it is}
guile> @kbd{(list? ls)}
       @result{} #t
;; @r{ask for the length of @code{ls}}
guile> @kbd{(length ls)}
       @result{} 7
;; @r{pick out the first element of the list}
guile> @kbd{(car ls)}
       @result{} 1
;; @r{pick the rest of the list without the first element}
guile> @kbd{(cdr ls)}
       @result{} (2 3 4 5 6 7)
;; @r{this should pick out the 3rd element of the list}
guile> @kbd{(car (cdr (cdr ls)))}
       @result{} 3
;; @r{a shorthand for doing the same thing}
guile> @kbd{(caddr ls)}
       @result{} 3
;; @r{append the given list onto @code{ls}, print the result}
;; @r{@strong{NOTE:} the original list @code{ls} is @emph{not} modified}
guile> @kbd{(append ls (list 8 9 10))}
       @result{} (1 2 3 4 5 6 7 8 9 10)
guile> @kbd{(reverse ls)}
       @result{} (7 6 5 4 3 2 1)
;; @r{ask if 12 is in the list --- it obviously is not}
guile> @kbd{(memq 12 ls)}
       @result{} #f
;; @r{ask if 4 is in the list --- returns the list from 4 on.}
;; @r{Notice that the result will behave as true in conditionals}
guile> @kbd{(memq 4 ls)}
       @result{} (4 5 6 7)
;; @r{an @code{if} statement using the aforementioned result}
guile> @kbd{(if (memq 4 ls)
           (display "hey, it's true!\n")
           (display "dude, it's false\n"))}
       @print{hey, it's true!}
       @result{}
guile> @kbd{(if (memq 12 ls)
           (display "hey, it's true!\n")
           (display "dude, it's false\n"))}
       @print{dude, it's false}
       @result{}
guile> @kbd{(memq 4 (reverse ls))}
       @result{} (4 3 2 1)
;; @r{make a smaller list @code{ls2} to work with}
guile> @kbd{(define ls2 (list 2 3 4))}
;; @r{make a list in which the function @code{sin} has been}
;; @r{applied to all elements of @code{ls2}}
guile> @kbd{(map sin ls2)}
       @result{} (0.909297426825682 0.141120008059867 -0.756802495307928)
;; @r{make a list in which the squaring function has been}
;; @r{applied to all elements of @code{ls}}
guile> @kbd{(map (lambda (n) (* n n)) ls)}
       @result{} (1 4 9 16 25 36 49)
@end smalllisp

@smalllisp
;; @r{make a vector and bind it to the symbol @code{v}}
guile> @kbd{(define v '#(1 2 3 4 5 6 7))}
guile> @kbd{v}
       @result{} #(1 2 3 4 5 6 7)
guile> @kbd{(vector? v)}
       @result{} #t
guile> @kbd{(list? v)}
       @result{} #f
guile> @kbd{(vector-length v)}
       @result{} 7
;; @r{vector-ref allows you to pick out elements by index}
guile> @kbd{(vector-ref v 2)}
       @result{} 3
;; @r{play around with the vector: make it into a list, reverse}
;; @r{the list, go back to a vector and take the second element}
guile> @kbd{(vector-ref (list->vector (reverse (vector->list v))) 2)}
       @result{} 5
;; @r{this demonstrates that the entries in a vector do not have}
;; @r{to be of uniform type}
guile> @kbd{(vector-set! v 4 "hi there")}
       @result{} "hi there"
guile> @kbd{v}
       @result{} #(1 2 3 4 "hi there" 6 7)
@end smalllisp

@subsection Using recursion to process lists
@cindex recursion
@cindex list processing

Here are some typical examples of using recursion to process a list.

@smalllisp
;; @r{this is a rather trivial way of reversing a list}
(define (my-reverse l)
  (if (null? l)
      l
      (append (my-reverse (cdr l)) (list (car l)))))
(my-reverse '(27 32 33 40))
@result{} (40 33 32 27)
@end smalllisp

@subsection Processing matrices

Suppose you have a matrix represented as a list of lists:

@smalllisp
(define m
  (list
   (list 7 2 1 3 2 8 5 3 6)
   (list 4 1 1 1 3 8 9 8 1)
   (list 5 5 4 8 1 8 2 2 4)))
@end smalllisp

Then you could apply a certain function to each element of the matrix in
the following manner:
@smalllisp
;; @r{apply the function func to the matrix m element-by-element;}
;; @r{return a matrix with the result.}
(define (process-matrix m func)
  (map (lambda (l)
         (map func l))
       m))
@end smalllisp
Notice that I have used the Scheme @code{map} procedure because I am
interested in the matrix that results from the application of
@code{func}, rather than in the side effects associated with applying
@code{func}.

This could be invoked with @code{(process-matrix m sin)} or
@code{(process-matrix m (lambda (x) (* x x)))}; for example:

@smalllisp
(process-matrix m (lambda (x) (* x x)))
@result{} ((49 4 1 9 4 64 25 9 36) (16 1 1 1 9 64 81 64 1) (25 25 16 64 1 64 4 4 16))
@end smalllisp

To print a representation of the matrix, we could define a generalized
routine:
@smalllisp
;; @r{proc is a procedure to represent the single element,}
;; @r{row-proc is a procedure that is invoked after each row.}
;; @r{Example: proc could be (lambda (x) (begin (display x) (display " ")))}
;; @r{and row-proc could be (lambda (l) (display "\n"))}
(define (represent-matrix m proc row-proc)
  (for-each (lambda (l)
              (begin
                (for-each proc l)
                (row-proc l)))
            m))
@end smalllisp
@findex represent-matrix

And then invoke it with
@smalllisp
(represent-matrix m
                  (lambda (x) (begin (display x) (display " ")))
                  (lambda (l) (begin (display "\n"))))
@print{7 2 1 3 2 8 5 3 6}
@print{4 1 1 1 3 8 9 8 1}
@print{5 5 4 8 1 8 2 2 4}
@end smalllisp

@cindex objects

Now we write a helper routine that uses Scheme @dfn{closures} to make
objects with state that then receive messages to draw little squares.
@cindex closures
@cindex syntactic closures

But let us take it one step at a time.  I will start by showing you a
simple example of object in Scheme.  The object I make here represents a
cell, which could be a cell in a matrix.  The cell responds to commands
to draw itself, to return the next cell, and so forth.  @emph{Guile does
not currently have a Tk interface, so I will leave the hooks for
graphical rendering.  In a future release of Guile I will add graphical
rendering messages to the cell object.}

@smallexample
;; @r{cell-object.scm: routines for creating and manipulating cell objects}

;; @r{(the-x, the-y) is the initial position of the cell.}
;; @r{the-color is a string representing a color; must be something Tk can grok.}
;; @r{square-size is the size of the square that gets drawn.}
;; @r{(sizex, sizey) is the size of the matrix.}
(define (MAKE-CELL the-x the-y the-color square-size sizex sizey)
  (define (get-x) the-x)
  (define (get-y) the-y)

  (define (set-x! new-x)
    (set! the-x new-x)
    the-x)
  (define (set-y! new-y)
    (set! the-y new-y)
    the-y)
  (define (get-color) the-color)
  (define (set-color! new-color)
    (set! the-color new-color)
    the-color)
  (define (next!)
    (set! the-x (+ the-x 1))
    (if (>= the-x sizex)
	(begin
	  (set! the-x 0)
	  (set! the-y (+ the-y 1))))
	(if (>= the-y sizey)
	    (begin
	      (display "CELL next!: value of y is too big; not changing it\n")
	      (set! the-y (- the-y 1))))
	(cons the-x the-y))
  (define (draw)
    (let* ((x0 (* the-x square-size))
	   (y0 (* the-y square-size))
	   (x1 (+ x0 square-size))
	   (y1 (+ y0 square-size)))
      (display "I should draw a ")
      (display the-color)
      (display " rectangle with corners at ")
      (display x0) (display y0) (display x1) (display y1)
      ))

  ;; self is the dispatch procedure
  (define (self message)
    (case message
      ((x)            get-x)
      ((y)            get-y)
      ((set-x!)       set-x!)
      ((set-y!)       set-y!)
      ((color)        get-color)
      ((set-color!)   set-color!)
      ((next!)        next!)
      ((draw)         draw)
      (else (error "CELL: Unknown message -> " message))))
  ;; and now return the dispatch procedure
  self
  )
@end smallexample
@cindex cell-object
@findex MAKE-CELL

What does this procedure do?  It returns another procedure
(@code{self}) which receives a message (x, y, set-x!, set-y!, @dots{})
and takes an action to return or modify its state.  The state consists
of the values of variables @code{the-x}, @code{the-y}, @code{the-color}
and so forth.

Here are some examples of how to use MAKE-CELL and the cell object it
creates:
@smallexample
(define c (MAKE-CELL 0 0 "red" 10 7 9))

;; @r{retrieve the x and y coordinates}
((c 'x))
@result{} 0
((c 'y))
@result{} 0
;; @r{change the x coordinate}
((c 'set-x!) 5)
@result{} 5
((c 'x))
@result{} 5
;; @r{change the color}
((c 'color))
@result{} "red"
((c 'set-color!) "green")
@result{} "green"
((c 'color))
@result{} "green"
;; @r{now use the next! message to move to the next cell}
((c 'next!))
@result{} (6 . 0)
((c 'x))
@result{} 6
((c 'y))
@result{} 0
;; @r{now make things wrap around}
((c 'next!))
@result{} (0 . 1)
((c 'next!))
@result{} (1 . 1)
((c 'next!))
@result{} (2 . 1)
((c 'x))
@result{} 2
((c 'y))
@result{} 1
@end smallexample

You will notice that expressions like @code{(c 'next)} return procedures
that do the job, so we have to use extra parentheses to make the job
happen.  This syntax is rather awkward; one way around it is to define a
@code{send} procedure:

@smallexample
;; @r{send makes object syntax a bit easier; instead of saying}
;; @r{    ((my-cell 'set-x!) 4)}
;; @r{you can say}
;; @r{    (send my-cell 'set-x! 4)}
(define (send obj . args)
  (let ((first-eval (apply obj (list (car args)))))
    (if (null? (cdr args))
	(first-eval)
	(apply first-eval (cdr args)))))
@end smallexample
@findex send

You can see that @code{send} passes the message to the object, making
sure that things are evaluated the proper number of times.  You can now
type:

@smallexample
(define c2 (MAKE-CELL 0 0 "red" 10 7 9))
(send c2 'x)
@result{} 0
(send c2 'set-x! 5)
@result{} 5
(send c2 'color)
@result{} "red"
(send c2 'set-color! "green")
@result{} "green"
(send c2 'next!)
@result{} (1 . 0)
(send c2 'x)
@result{} 1
(send c2 'y)
@result{} 0
@end smallexample

@cindex object-based programming
@cindex object-oriented programming

This is the simplest way of implementing objects in Scheme, but it does
not really allow for full @emph{object-oriented programming} (for
example, there is no inheritance).  But it is useful for
@emph{object-based programming}.

Guile comes with a couple more complete object-oriented extensions to
Scheme: these are part of slib (@pxref{Object, , , slib, SLIB: the
portable Scheme library} and @pxref{Yasos, , , slib, SLIB: the portable
Scheme library}).

@node Guile in a Library
@chapter Guile in a Library

@iftex
@nobreak
@end iftex
In the previous chapters Guile was used to write programs entirely in
Scheme, and no C code was seen; but I have been claiming @emph{ad
nauseam} that Guile is an @emph{extension} language.  Here we see how
that is done, and how that can be useful.
@cindex libguile
@cindex extending C programs

@menu
* Two world views::
* What is libguile::
* How to get started with libguile::
* More interesting programming with libguile::
* Further examples::
@end menu

@node Two world views
@section Two world views
@cindex master world

In this manual, I usually jump into examples and explain them as you
type in the code; here I will digress and ramble for a few paragraphs to
set some concepts straight, and then let you type (or paste) in fun
examples.

In 1995, I implemented a large program, @dfn{Gnudl}, using Guile quite
extensively.  In the design phase of Gnudl, I found I had to make a
choice: should the fundamental data structures be C or Scheme data
structures?
@cindex gnudl
@cindex GNU Data Language
@cindex Galassi, Mark

Guile allows C to see its data structures (scalar types, lists, vectors,
strings @dots{}).  C also allows Guile to see its data structures.  As a
large program designer, you have to decide which of those capabilities
to use.  You have two main choices:

@enumerate 1
@item
You can write your software mostly in Scheme.  In this case, your C
software will mostly parse the Scheme code with Guile calls, and provide
some new primitive procedures to be used by Scheme.  This is what Gnudl
does.

@item
You can write your software mostly in C, occasionally allowing Scheme
code to be parsed by Guile, either to allow the user to modify data
structures, or to parse a configuration file, @dots{}
@end enumerate

Mixing the two approaches seems unwise: the overall layout would be
confusing.  But who knows?  There might be problems that are best solved
by a hybrid approach.  Please let me know if you think of such a
problem.

If you use the former approach, we will say that the @dfn{master world}
is Scheme, and the C routines serve Scheme and access Scheme data
structures.  In the latter case, the master world is C, and Scheme
routines serve the C code and access C data structures.

In both approaches the @code{libguile.a} library is the same, but a
predominantly different set of routines will be used.  When we go
through examples of libguile use, we will point out which is the master
world in order to clarify these two approaches.

@node What is libguile
@section What is libguile
@cindex libguile
@cindex gh interface
@cindex scm interface

@dfn{Libguile} is the library which allows C programs to start a Scheme
interpreter and execute Scheme code.  There are also facilities in
libguile to make C data structures available to Scheme, and vice versa.

The interface provided by the libguile C library is somewhat specific to
the implementation of the Scheme interpreter.  This low-level libguile
interface is usually referred to as the @code{scm_} interface, since its
public calls (API) all have the @code{scm_} prefix.

There is also a higher-level libguile interface, which is usually
referred to as the @code{gh_} interface (libGuile High).  Its public
calls all have the @code{gh_} prefix.  The @code{gh_} library interface
is designed to hide the implementation details, thus making it easier to
assimilate and portable to other underlying Scheme implementations.

People extending Guile by adding bindings to C libraries (like OpenGL or
Rx) are encouraged to use the @code{gh_} interface, so their work will
be portable to other Scheme systems.  The @code{gh_} interface should be
more stable, because it is simpler.

The @code{scm_} interface is necessary if you want to poke into the
innards of Scheme data structures, or do anything else that is not
offered by the @code{gh_} interface.  It is not covered in this
tutorial, but is covered extensively in @ref{Data representation,, Data
Representation in Guile, guile, Guile Reference Manual}.

This chapter gives a gentle introduction to the @code{gh_} interface,
presenting some @emph{hello world}-style programs which I wrote while
teaching myself to use libguile.
@cindex hello world

The @cite{Guile Programmer's Manual} gives more examples of programs
written using libguile, illustrating diverse applications.  You can also
consult my @emph{Gnudl} documentation at
@url{http://nis-www.lanl.gov/~rosalia/mydocs/} to see a large scale
project that uses C and Scheme code together.

@node How to get started with libguile
@section How to get started with libguile
@cindex learn0

Here is an elementary first program, @code{learn0}, to get going with
libguile.  The program (which uses Scheme as a master world) is in a
single source file, @code{learn0.c}:

@smallexample
/* @r{test the new libgh.a (Guile High-level library) with a trivial
   program} */

#include <stdio.h>

#include <guile/gh.h>

void main_prog(int argc, char *argv[]);

main(int argc, char *argv[])
@{
  gh_enter(argc, argv, main_prog);
@}

void main_prog(int argc, char *argv[])
@{
  int done;
  char input_str[200];

  gh_eval_str("(display \"hello Guile\")");
  gh_eval_str("(newline)");

  /* @r{for fun, evaluate some simple Scheme expressions here} */
  gh_eval_str("(define (square x) (* x x))");
  gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
  gh_eval_str("(square 9)");

  /* @r{now sit in a Scheme eval loop: I input the expressions, have
     Guile evaluate them, and then get another expression.} */
  done = 0;
  fputs("learn0> ", stdout);
  while (fgets(input_str, 199, stdin) != NULL) @{
    gh_eval_str(input_str);
    fputs("\nlearn0> ", stdout);
  @}

  exit(0);
@}
@end smallexample

If you name this program @code{learn0.c}, it can now be compiled with:
@smallexample
gcc -g -c learn0.c -o learn0.o
gcc -o learn0 learn0.o -lguile -lm
@end smallexample

@c @emph{NOTE: If you are in the Guile development tree, you can simply do
@c ``cd doc/examples/c; make; ./learn0''.}

The program is simple: it creates a Scheme interpreter, passes a couple
of strings to it that define new Scheme functions @code{square} and
@code{factorial}, and then a couple of strings that invoke those
functions.

It then goes into a read-eval-print-loop (REPL), so you could type
one-line Scheme expressions to it and have them evaluated.  For example:
@smallexample
<shell-prompt> ./learn0
hello Guile
learn0> (display (sin 1.3))
963.558185417193e-3
learn0> (display (fact 10))
3628800
learn0> (quit)
<shell-prompt>
@end smallexample

You should notice the key steps involved in this @code{learn0} program:

@cartouche
@enumerate
@item
@code{#include <guile/gh.h>}
@item
You need to invoke the initialization routine @code{gh_enter()}.  This
starts up a Scheme interpreter, handling many implementation-specific
details.
@item
Your main() function should be almost empty: the real main program goes
in a separate function main_prog() which is passed to gh_enter().  This
rather arcane convention is due to the way Guile's garbage collector
works: the whole program has to run in the dynamic context of
@code{gh_enter()}.
@item
You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
routine.
@item
You link your program with @code{-lguile}.
@end enumerate
@end cartouche

@node More interesting programming with libguile
@section More interesting programming with libguile
@cindex learn1
@cindex callback
@cindex builtin functions

The @code{learn0} program shows how you can invoke Scheme commands from
a C program.  This is not such a great achievement: the same could have
been done by opening a pipe to SCM or any other Scheme interpreter.

A true extension language must allow @dfn{callbacks}.  Callbacks allow
you to write C routines that can be invoked as Scheme procedures, thus
adding new primitive procedures to Scheme.  This also means that a
Scheme procedure can modify a C data structure.

Guile allows you to define new Scheme procedures in C, and provides a
mechanism to go back and forth between C and Scheme data types.

Here is a second program, @code{learn1}, which demonstrates these
features.  It is split into three source files: @code{learn1.c},
@code{c_builtins.h} and @code{c_builtins.c}.  I am including the code
here.
@c , but you might just want to look at the online source code and the
@c Makefile.am that come with Guile in the
@c @file{doc/examples/c} directory.

Notice that @code{learn1} uses a Scheme master world, and the C routines
in @code{c_builtins.c} are simply adding new primitives to Scheme.

@menu
* learn1.c::
* c_builtins.h::
* c_builtins.c::
* What learn1 is doing::
* Compiling and running learn1::
@end menu

@node learn1.c
@subsection learn1.c

Here is @file{learn1.c}:
@smallexample
#include <stdio.h>

#include <guile/gh.h>

#include "c_builtins.h"

void main_prog(int argc, char *argv[]);

main(int argc, char *argv[])
@{
  gh_enter(argc, argv, main_prog);
@}

void main_prog(int argc, char *argv[])
@{
  char input_str[200];		/* @r{ugly hack: assume strlen(line) < 200} */
  int done;

  /* @r{for fun, evaluate some simple Scheme expressions here} */
  gh_eval_str("(define (square x) (* x x))");
  gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
  gh_eval_str("(square 9)");
  gh_eval_str("(fact 100)");

  /* @r{now try to define some new builtins, coded in C, so that they are
     available in Scheme.} */
  gh_new_procedure1_0("c-factorial", c_factorial);
  gh_new_procedure1_0("c-sin", c_sin);
  gh_new_procedure1_0("v-t", vector_test);

  /* @r{now sit in a Scheme eval loop: I input the expressions, have
     Guile evaluate them, and then get another expression.}  */
  done = 0;
  fputs("learn1> ", stdout);
  while (!done) @{
    if (gets(input_str) == NULL) @{
      done = 1;
    @} else @{
      gh_eval_str(input_str);
      fputs("learn1> ", stdout);
    @}
  @}

  exit(0);
@}
@end smallexample

@node c_builtins.h
@subsection c_builtins.h

Here is @file{c_builtins.h}:
@smallexample
/* @r{builtin function prototypes} */

#include <guile/gh.h>

SCM c_factorial(SCM n);
SCM c_sin(SCM n);
SCM vector_test(SCM s_length);
@end smallexample

@node c_builtins.c
@subsection c_builtins.c

Here is @file{c_builtins.c}:
@smallexample
#include <stdio.h>
#include <math.h>

#include <guile/gh.h>

#include "c_builtins.h"

/* @r{this is a factorial routine in C, made to be callable by Scheme} */
SCM c_factorial(SCM s_n)
@{
  int i;
  unsigned long result = 1, n;

  n = gh_scm2ulong(s_n);

  gh_defer_ints();
  for (i = 1; i <= n; ++i) @{
    result = result*i;
  @}
  gh_allow_ints();
  return gh_ulong2scm(result);
@}

/* @r{a sin routine in C, callable from Scheme.  it is named c_sin() to
   distinguish it from the default Scheme sin function} */
SCM c_sin(SCM s_x)
@{
  double x = gh_scm2double(s_x);

  return gh_double2scm(sin(x));
@}

/* @r{play around with vectors in Guile: this routine creates a vector of
   the given length, initializes it all to zero except element 2 which
   is set to 1.9.}  */
SCM vector_test(SCM s_length)
@{
  SCM xvec;

  c_length = gh_scm2ulong(s_length);
  printf("requested length for vector: %ld\n", gh_scm2ulong(s_length));

  /* create a vector */
  xvec = gh_make_vector(s_length, gh_double2scm(0.0));
  /* set the second element in it */
  gh_vector_set_x(xvec, gh_int2scm(2), gh_double2scm(1.9));

  return xvec;
@}
@end smallexample

@node What learn1 is doing
@subsection What learn1 is doing
@cindex registering callbacks
@cindex registering C functions
@cindex primitive procedures

If you compare learn1 to learn0, you will find that learn1 uses a new
Guile construct: the function @code{gh_new_procedure()}, and its
siblings:

@smallexample
  /* @r{now try to define some new builtins, coded in C, so that they are
     available in Scheme.} */
  gh_new_procedure1_0("c-factorial", c_factorial);
  gh_new_procedure1_0("c-sin", c_sin);
  gh_new_procedure1_0("v-t", vector_test);
@end smallexample

It is clear that @code{gh_new_procedure()} adds a new builtin
routine written in C which can be invoked from Scheme.  We can now
revise our checklist for programming with libguile, so it includes
adding callbacks.
@cindex libguile - step by step

@cartouche
@enumerate
@item
@code{#include <guile/gh.h>}
@item
You need to invoke the initialization routine @code{gh_enter()}.  This
starts up a Scheme interpreter, handling many details.
@item
Your main() function should be almost empty: the real main program goes
in a separate function main_prog() which is passed to gh_enter().  This
rather arcane convention is due to the way Guile's garbage collector
works: the whole program has to run in the dynamic context of
@code{gh_enter()}.
@item
You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
routine.
@item
@strong{[new]} You can now define new builtin Scheme functions;
i.e. define new builtin Scheme functions, with the
@code{gh_new_procedure()} routine.
@item
You pass strings to the Scheme interpreter with the
@code{gh_eval_str()} routine.
@item
You link your program with @code{-lguile}.
@end enumerate
@end cartouche

I breezed by the issue of how to write your C routines that are
registered to be called from Scheme.  This is non-trivial, and is
discussed at length in the @cite{Guile Programmer's Manual}.

@node Compiling and running learn1
@subsection Compiling and running learn1

@smallexample
gcc -g -c learn1.c -o learn1.o
gcc -g -c c_builtins.c -o c_builtins.o
gcc -o learn1 learn1.o c_builtins.o -lguile -lm
@end smallexample

If you run @code{learn1}, it will prompt you for a one-line Scheme
expression, just as @code{learn0} did.  The difference is that you can
use the new C builtin procedures (@code{c-factorial}, @code{c-sin},
@code{v-t}).

@smallexample
<shell-prompt> ./learn1
welcome to Guile
hello Guile
learn1> (display (c-factorial 6))
720
learn1> (display (c-factorial 20))
2192834560
learn1> (display (c-factorial 100))
0
learn1> (display (c-sin 1.5))
0.997494986604054
learn1> (display (v-t 10))
requested length for vector: 10
#(0.0 0.0 1.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0)
learn1> (display (v-t 15))
requested length for vector: 15
#(0.0 0.0 1.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0)
learn1> (quit)
<shell-prompt>
@end smallexample

As you see, taking @code{(c-factorial 100)} does not use bignumbers and
returns a bogus answer.

@node Further examples
@section Further examples

Further ``idealized'' examples are included in the @code{doc/examples/c}
distribution.  They include programs to:

@c [FIXME: still have to write some of these; then I will revise the list.]

@itemize @bullet
@item
Parse a startup file (C is the master world).
@item
Set up initial conditions for an n-body simulation (C is the master
world).
@item
Implement a Scheme interpreter with all of Guile's goodies, @emph{plus}
the readline library @emph{and} a fast Fourier transform routine
provided in C (Scheme is the master world).
@end itemize

@node Regular Expression Support
@chapter Regular Expression Support

@node UNIX System Programming
@chapter UNIX System Programming

@node Where to find more Guile/Scheme resources
@chapter Where to find more Guile/Scheme resources

@node Concept Index
@unnumbered Concept Index

@printindex cp

@node Procedure and Macro Index
@unnumbered Procedure and Macro Index

This is an alphabetical list of all the procedures and macros in Dominion.

@printindex fn

@node Variable Index
@unnumbered Variable Index

This is an alphabetical list of the major global variables in Dominion.

@printindex vr

@node Type Index
@unnumbered Type Index

This is an alphabetical list of the major data structures in Dominion.

@printindex tp

@contents

@bye


code:
2008-07-17  Neil Jerram  <neil@ossau.uklinux.net>

	* gds-scheme.el (gds-eval-region, gds-eval-expression)
	(gds-eval-defun, gds-eval-last-sexp): Support `C-u' prefix,
	meaning that user wants to single step through the code.

2008-03-12  Neil Jerram  <neil@ossau.uklinux.net>

	* Makefile.am, gds-scheme.el, gds-server.el, gds.el: New (merged
	with modifications from CVS HEAD).

2005-07-09  Neil Jerram  <neil@ossau.uklinux.net>

	* Makefile.am, REAME.GDS, gds-client.scm, gds-problems.txt,
	gds-server.scm, gds-tutorial.txt, gds.el, gds.texi: Removed.

2004-03-10  Neil Jerram  <neil@ossau.uklinux.net>

	* guileint: Subdirectory (with contents) removed.  This was a dead
	end of development that only I was working on, and which is now
	superseded by the GDS work in this directory.

2004-02-25  Neil Jerram  <neil@ossau.uklinux.net>

	* gds-client.scm (handle-instruction-1): In `eval' protocol, catch
	and report read errors nicely.

	* gds.el (gds-display-buffers): Don't select the GDS window.

2004-02-22  Neil Jerram  <neil@ossau.uklinux.net>

	* Makefile.am (EXTRA_DIST): Distribute new files.

	* gds-tutorial.txt, gds-problems.txt: New files.

2004-02-21  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el: Add requirements: cl, comint, info.
	(gds-guile-program): New.
	(gds-start): When starting or restarting, kill captive if it
	exists.  Use gds-guile-program instead of just "guile".
	(gds-mode): Use widget minor mode.
	(gds-client-ref): New optional client arg.
	(gds-update-buffers): Don't call widget-setup.
	(gds-heading-face): New.
	(gds-insert-interaction): Various prettifications.
	(gds-heading-insert): New.
	(gds-choose-client): Check that numbers in client and gds-client
	are still valid.
	(gds-eval-expression, gds-apropos): Remove text properties from
	expression to evaluate.
	(gds-mode-map): Don't set widget-mode-map as parent.
	(gds-start-captive): Use gds-guile-program instead of just
	"guile".

	* gds-client.scm (install-breakpoints): Bugfix: avoid null lists
	in traversal.
	(eval-thread, gds-eval): Where expression has multiple parts,
	modify output to say which part is being evaluated.

2004-02-08  Mikael Djurfeldt  <djurfeldt@nada.kth.se>

	* Makefile.am (TAGS_FILES): Use this variable instead of
	ETAGS_ARGS so that TAGS can be built using separate build
	directory.

2004-01-28  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el (gds-handle-client-input): Handle new `thread-status'
	protocol.
	(gds-display-slow-eval): New.
	(gds-client-ref): Bugfix: buf -> (cdr buf).
	(gds-display-buffers): Bugfix: minimum overlay end value is 1, not
	0.
	(gds-evals-in-progress): New.
	(gds-results): New.
	(gds-insert-interaction): Show evaluations in progress (with
	button to interrupt them) and results of last help or evaluation.
	(gds-interrupt-eval): New.
	(gds-debug-trap-hooks, gds-up, gds-down): New.
	(gds-eval-region, gds-eval-expression): Include abbreviated code
	in eval correlator.
	(gds-abbreviated-length, gds-abbreviated): New.
	(gds-mode-map): New keys for gds-debug-trap-hooks, gds-up,
	gds-down.
	(gds-debug-menu): New menu entries for gds-up, gds-down.

	* gds-client.scm (gds-connect): Enable trapping for gds-eval
	stacks.
	(ui-read-thread-proc): Write 'running status earlier.
	(stack->emacs-readable): Limit stack length to 'depth debug
	option.
	(handle-instruction): Update format of eval correlator.
	(handle-instruction-1): Resolve module names from root module
	instead of from current module.
	(resolve-module-from-root): New.
	(handle-instruction-1): New protocol `interrupt-eval'.
	(eval-thread-table): New.
	(eval-thread): Add thread to eval-thread-table; write new protocol
	to frontend to communicate eval thread status; update for new
	correlator format; bind correlator local before entering loop2.
	(gds-eval): Use start-stack 'gds-eval-stack to rebase stack.

	* gds.el (gds-start, gds-start-captive): Do
	`process-kill-without-query' as soon as processes started, ...
	(gds-shutdown, gds-kill-captive): ... instead of here.
	(gds-display-results): More clearly show unspecified results; show
	results in interaction view instead of in separate window.
	(gds-send): Add sent protocol to transcript.

2004-01-26  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el (gds-request-focus, gds-quit): Simplify.  Old algorithm
	left in as a big comment.
	(gds-focus-in-function, gds-focus-in, gds-focus-out-function,
	gds-focus-out): New.

	* gds-client.scm (ui-read-thread-proc): Fix `with-mutex' syntax
	error.

2004-01-25  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el (gds-handle-client-input, gds-async-break,
	gds-select-stack-frame, gds-query-modules, gds-go, gds-next,
	gds-evaluate, gds-step-in, gds-step-out, gds-trace-finish,
	gds-frame-info, gds-frame-args, gds-set-module-breakpoint,
	gds-read-client, gds-choose-client): Change gds-focus-client to
	gds-client.
	(gds-choose-client): Set local value of gds-client to determined
	client.
	(gds-menu): Use gds-client rather than gds-focus-client.
	(gds-client-ref): New.
	(gds-client-blocked): Rewrite using gds-client-ref.
	(gds-display-buffers): Take `client' arg instead of global
	`gds-focus-client'.
	(gds-request-focus): Call gds-display-buffers with explicit arg.

2004-01-20  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el: Changes throughout because of (i) change of gds-send
	args, (ii) introduction of evaluation correlator.

	* gds-client.scm: Extensive changes to implement eval threads, and
	to tidy up and organize the rest of the code.

2003-12-06  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.texi: New.

	* Makefile.am (info_TEXINFOS): Added.

2003-11-27  Neil Jerram  <neil@ossau.uklinux.net>

	Initial support for setting source breakpoints...

	* gds.el (gds-handle-client-input): Handle new `breakpoint-set'
	protocol.
	(gds-breakpoint-face): New.
	(gds-new-breakpoint-before-string): New.
	(gds-new-breakpoint-after-string): New.
	(gds-active-breakpoint-before-string): New.
	(gds-active-breakpoint-after-string): New.
	(gds-source-breakpoint-pos): New.
	(gds-source-breakpoint-overlay-at): New.
	(gds-set-source-breakpoint): New.
	(gds-delete-source-breakpoint): New.
	(gds-region-breakpoint-info): New.
	(gds-eval-region): Include bpinfo in `eval' protocol.
	(scheme-mode-map): New keys for setting and deleting breakpoints.
	(gds-breakpoint-menu): New.
	(gds-menu): Include `gds-breakpoint-menu'.

	* gds-client.scm (handle-instruction-1): Handle bpinfo protocol
	field and pass to `gds-eval'.
	(install-breakpoints): New.
	(gds-eval): Call `install-breakpoints'.

2003-11-19  Neil Jerram  <neil@ossau.uklinux.net>

	* gds-client.scm (start-async-gds-thread): Changes to fix
	interaction between async and debugger threads.
	(gds-connect): Don't send module list immediately after initial
	connection.

	* gds.el (gds-immediate-display): Removed.

2003-11-19  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el (gds-update-buffers): Rewrite to only show one view at a
	time.
	(gds-display-buffers): Remove separate stack buffer display code.
	(gds-switch-to-view), gds-view-interaction, gds-view-stack,
	gds-view-breakpoints, gds-view-browser, gds-view-messages,
	gds-view-menu): New.
	(gds-maybe-skip-region): Removed.
	(gds-maybe-delete-region): Removed.
	(gds-display-types): Removed.
	(gds-display-type-regexp): Removed.
	(gds-displayed-modules): Removed.

2003-11-19  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el (gds-views, gds-promote-view, gds-add-view,
	gds-delete-view, gds-switch-to-view): New.
	(gds-handle-client-input): Use gds-promote-view.
	(gds-update-buffers): Remove unnecessary client arg.
	(gds-module-notify, gds-handle-client-input): Update callers
	accordingly.
	(gds-insert-messages): New.
	(gds-insert-interaction): New (using code from
	gds-update-buffers).
	(gds-update-buffers): Use gds-insert-interaction.

2003-11-17  Rob Browning  <rlb@defaultvalue.org>

	* .cvsignore: new file.

2003-11-11  Neil Jerram  <neil@ossau.uklinux.net>

	* gds.el: New.  (Or rather, first mention in this ChangeLog.)

	* Makefile.am, README.GDS: New.

	* gds-client.scm, gds-server.scm: New (moved here from
	ice-9/debugger/ui-{client,server}.scm).

2003-08-20  Neil Jerram  <neil@ossau.uklinux.net>

	* guileint: New subdirectory.

	* README: Mention it.

2001-11-19  Thien-Thi Nguyen  <ttn@giblet.glug.org>

	* README: Use less forking for indexing command.
	Update index.

	* gud-guile.el: New file.

	* update-changelog.el:
	When run as a batch program, invoke `(ucl-update "ChangeLog")'
	instead of `(ucl-update-all)'.

	(ucl-outdir): Delete this var.
	(ucl-update): Arg now specifies change log file
	instead of cvs module directory.
	Make interactive.
	(ucl-update-all): Delete this func.

	* update-changelog.el: New file.

	* patch.el (patch-send):
	Renamed from `patch-submit'.
	Gadzooks what kind of world is this?

2001-10-25  Thien-Thi Nguyen  <ttn@giblet.glug.org>

	* README, patch.el:
	New file.

2001-10-25  Thien-Thi Nguyen  <ttn@glug.org>

	* patch.el, README: New files.

2001-06-21  Neil Jerram  <neil@ossau.uklinux.net>

	* guile.el (guile-channel-file): Signal an error if unable to find
	channel.scm.
	Change "gulie" typos to "guile".

2001-05-06  Keisuke Nishida  <kxn30@po.cwru.edu>

	* guile.el (guile:eval): Propagate user interrupt.
	(keywordp): Define it if not defined yet.
	(guile-use-module): New macro.
	(guile-process-import-module): Renamed from guile-process-use-module.

	* guile-emacs.scm (guile-emacs-apropos, guile-emacs-describe):
	New procedures.

	* guile-scheme.el (guile-scheme-mode-map): Use
	`shared-lisp-mode-map' as the parent keymap if
	`lisp-mode-shared-map' is not defined.
	(guile-scheme-module): New variable.
	(guile-scheme-set-module): Set module only when necessary.
	(guile-scheme-eval-print-last-sexp): Insert newline after eval.
	(guile-scheme-complete-table): New variable.
	(guile-scheme-input-symbol): New function.
	(guile-scheme-apropos, guile-scheme-describe,
	guile-scheme-kill-process): New commands.

2001-04-25  Keisuke Nishida  <kxn30@po.cwru.edu>

	* guile.el, guile-scheme.el, guile-emacs.scm: New files.

2001-03-13  Martin Grabmueller  <mgrabmue@cs.tu-berlin.de>

	* guile-c.el (guile-c-edit-docstring): Set fill-column to 63, so
	that fill-paragraph'ed docstrings fit nicely when indented.

2001-03-13  Keisuke Nishida  <kxn30@po.cwru.edu>

	* guile-c.el (guile-c-window-configuration): New variable.
	(guile-c-edit-docstring, guile-c-edit-finish):
	Save/restore window-configuration.

2001-03-12  Keisuke Nishida  <kxn30@po.cwru.edu>

	* guile-c.el (guile-c-deprecate-region): New command.

2001-03-11  Keisuke Nishida  <kxn30@po.cwru.edu>

	* guile-c.el: New file.

2000-05-28  Mikael Djurfeldt  <mdj@thalamus.nada.kth.se>

	* ppexpand.el: New file.

2000-01-18  Mikael Djurfeldt  <mdj@mdj.nada.kth.se>

	* multistring.el: New file.