1 \input texinfo @c -*-texinfo-*-
3 @setfilename guile-tut.info
4 @settitle Guile Tutorial
7 @include version-tutorial.texi
9 @dircategory The Algorithmic Language Scheme
11 * Guile Tutorial: (guile-tut). The Guile tutorial.
14 @setchapternewpage off
15 @c Choices for setchapternewpage are {on,off,odd}.
21 @c DL: lose the egregious vertical whitespace, esp. around examples
22 @c but paras in @defun-like things don't have parindent
28 @subtitle For use with Guile @value{VERSION}
29 @subtitle Last updated @value{UPDATED}
33 @vskip 0pt plus 1filll
34 Copyright @copyright{} 1997, 1998 Free Software Foundation
36 Permission is granted to make and distribute verbatim copies of
37 this manual provided the copyright notice and this permission notice
38 are preserved on all copies.
40 Permission is granted to copy and distribute modified versions of this
41 manual under the conditions for verbatim copying, provided that the entire
42 resulting derived work is distributed under the terms of a permission
43 notice identical to this one.
45 Permission is granted to copy and distribute translations of this manual
46 into another language, under the above conditions for modified versions,
47 except that this permission notice may be stated in a translation approved
58 This file gives a tutorial introductionto Guile.
60 Copyright (C) 1997 Free Software Foundation
62 Permission is granted to make and distribute verbatim copies of
63 this manual provided the copyright notice and this permission notice
64 are preserved on all copies.
67 Permission is granted to process this file through TeX and print the
68 results, provided the printed document carries copying permission
69 notice identical to this one except for the removal of this paragraph
70 (this paragraph not being relevant to the printed manual).
73 Permission is granted to copy and distribute modified versions of this
74 manual under the conditions for verbatim copying, provided that the entire
75 resulting derived work is distributed under the terms of a permission
76 notice identical to this one.
78 Permission is granted to copy and distribute translations of this manual
79 into another language, under the above conditions for modified versions,
80 except that this permission notice may be stated in a translation approved
88 * Using Guile to program in Scheme::
89 * Guile in a Library::
90 * Regular Expression Support::
91 * UNIX System Programming::
92 * Where to find more Guile/Scheme resources::
94 * Procedure and Macro Index::
103 Before giving an overview of Guile, I present some simple commands and
104 programs that you can type to get going immediately.
106 Start by invoking the Guile interpreter (usually you do this by just
107 typing @code{guile}). Then type (or paste) the following expressions at
108 the prompt; the interpreter's response is preceded (in this manual) by
117 (define (recursive-factorial n)
120 (* n (recursive-factorial (- n 1)))))
121 (recursive-factorial 5)
123 (recursive-factorial 500)
124 @result{} 1220136825991110068701238785423046926253574342803192842192413588
125 3858453731538819976054964475022032818630136164771482035841633787
126 2207817720048078520515932928547790757193933060377296085908627042
127 9174547882424912726344305670173270769461062802310452644218878789
128 4657547771498634943677810376442740338273653974713864778784954384
129 8959553753799042324106127132698432774571554630997720278101456108
130 1188373709531016356324432987029563896628911658974769572087926928
131 8712817800702651745077684107196243903943225364226052349458501299
132 1857150124870696156814162535905669342381300885624924689156412677
133 5654481886506593847951775360894005745238940335798476363944905313
134 0623237490664450488246650759467358620746379251842004593696929810
135 2226397195259719094521782333175693458150855233282076282002340262
136 6907898342451712006207714640979456116127629145951237229913340169
137 5523638509428855920187274337951730145863575708283557801587354327
138 6888868012039988238470215146760544540766353598417443048012893831
139 3896881639487469658817504506926365338175055478128640000000000000
140 0000000000000000000000000000000000000000000000000000000000000000
141 00000000000000000000000000000000000000000000000
145 In this example we did some simple arithmetic @code{(+ 20 35)} and got
146 the answer @code{55}. Then we coded the classic (and rather wasteful)
147 factorial algorithm, and got a glimpse of Scheme's nice
148 @emph{bignumbers} by asking for the factorial of 1000. Then we quit
152 This is the most basic use of Guile: a simple Scheme interpreter. In
153 the rest of this tutorial I will show you how Guile has many facets: it
154 is also an @emph{extensible} interpreter (to which many features can be
155 easilly added) and an @emph{embeddable} interpreter (which can be
156 invoked from your C programs).
160 @chapter Introduction
163 @dfn{Guile} (which can stand for @emph{GNU Ubiquitous Intelligent
164 Language Extension}) is the GNU extension language. It started out as
165 an embeddable Scheme interpreter, and has rapidly evolved into a
166 kitchen-sink package including a standalone Scheme interpreter, an
167 embeddable Scheme interpreter, several graphics options, other languages
168 that can be used along with Scheme (for now just @emph{ctax} and
169 @emph{Tcl}), and hooks for much more.
173 * What are scripting and extension languages::
174 * History of Guile and its motivations::
175 * How to characterize Guile::
178 @node What are scripting and extension languages
179 @section What are scripting and extension languages
180 @cindex scripting languages
181 @cindex extension languages
183 A @dfn{scripting language} is a programming language which serves as
184 glue between other system programs. In the UNIX world, the traditional
185 scripting language is the @emph{Bourne shell}, which allows many UNIX
186 commands to be executed in sequence, or in a pipeline. Traditional UNIX
187 commands are cleverly written to work well when put together in a
190 Other examples of UNIX scripting languages are AWK, Perl, Scsh (the
191 Scheme Shell: a Scheme interpreter enhanced to do good scripting),
192 Python, Tcl, Java @dots{}
193 @cindex scripting languages - examples
195 UNIX programmers noticed, more than 25 years ago, that scripting
196 languages can do serious work, so the Bourne shell was written to have
197 variables, operators and control structures, just like a full-featured
198 programming language.
201 What scripting languages have, that traditional programming languages do
202 not, is the ability to easily run an external program (or a pipeline of
203 external programs) and use the returned values and output from that
204 program in useful ways.
206 An @dfn{extension language} is a programming language interpreter
207 offered by an application program, so that users can write macros or
208 even full-fledged programs to extend the original application.
209 Extension languages have a C interface (it is usually C, but it could be
210 any other compiled language), and can be given access to the C data
211 structures. Likewise, there are C routines to access the extension
212 language data structures.
214 Extension languages abound in the software world, even though the name
215 @emph{extension language} is seldom used. Examples are:
216 @cindex extension languages - examples
220 Emacs Lisp, the language used to program and customize GNU Emacs.
224 Tcl, John Ousterhout's general-purpose scripting and extension language.
228 The Lotus 1-2-3 macro language (any spreadsheet macro language,
229 really). I mention this one first because it is a classic, even though
230 it is seldom used any more.
234 Other spreadsheet and database macro languages.
237 The Dominion empire-style game's @emph{exec} files.
241 Any syntax for a ".*rc" file you might have used. Almost all programs
242 end up parsing some kind of startup or configuration file. The syntax
243 for those can get pretty involved, thus justifying calling them
244 "extension languages". The @emph{fvwm} window manager, for example,
245 parses a rather elaborate @file{.fvwmrc} file.
248 Brent Benson's libscheme.a, an embeddable Scheme interpreter.
249 @cindex Benson, Brent
253 Guile, the GNU extension language, which is the subject of this
258 One lesson we can learn from looking at classical large software
259 applications is that "writers of large programs" always end up throwing
260 in some kind of parser for configuration or scripting.
262 Of the examples listed above, Emacs Lisp, Tcl, Libscheme and Guile have
263 an important property: they are not added as an afterthought for a
264 specific application. They are general-purpose languages which a user
265 can learn (even in college courses) and then use to customize the
268 This is a recent and (in my opinion) very exciting direction in
269 large-program software engineering: program designers can link in the
270 Guile or Tcl library from the very beginning, and tell their users "You
271 want to customize this program? Just use Scheme (or Tcl, or whatever
272 language), which you already know!"
273 @cindex large programs
276 @node History of Guile and its motivations
277 @section History of Guile and its motivations
279 A few separate threads of events led to the development of Guile.
281 In the fall of 1994, Richard Stallman, director of the GNU project,
282 posted an article with the subject "Why you should not use Tcl", in
283 which he argued that Tcl is inadequate as an extension language. This
284 generated a flurry of flames (available in the hypermail archive
285 (@url{http://www.utdallas.edu/acc/glv/Tcl/war/}) @strong{The Tcl War}).
286 @cindex Stallman, Richard
290 The result was that Stallman then proposed his design for the GNU
291 Extension Language, first called GEL and then renamed Guile. The
292 discussion triggered by that article is also available in a hypermail
293 archive, @url{http://www.utdallas.edu/acc/glv/Tcl/war2/}.
295 One interesting feature of this GNU Extension Language plan was that
296 users should have a @emph{choice} of languages to use in extending their
297 program. The basic language would be a slightly modified Scheme, and
298 translators would be written to convert other languages (like Tcl,
299 Python, Perl, C-like languages @dots{}) into Scheme.
301 Tom Lord started working on this project immediately, taking Aubrey
302 Jaffer's small and portable implementation of Scheme, SCM, and making it
303 into an embeddable interpreter: callable from C and allowing new Scheme
304 procedures to be written in C.
306 @cindex Jaffer, Aubrey
308 In the spring of 1995, the guile-ii snapshot was released. This made it
309 possible to start writing code in C and Scheme using the guile
312 The guile-iii snapshot was released the summer of 1995, and it had fixed
313 enough problems so that the access to Scheme data structures from C was
316 After this, Cygnus Support added many features to Guile and finished
317 implementing others, so that Guile acquired thread support, a regular
318 expression matcher, a Tk interface, an interface to the SGI OpenGL
319 graphics system, an @emph{applet} formalism, and some other packages.
320 This was all in the Cygnus Guile r0.3 and r0.4 releases.
321 @cindex Cygnus Support
323 Meanwhile, Tom Lord left the project after having produced a divergent
324 version of Guile: 1.0b2. The Free Software Foundation hired Jim Blandy
325 to coordinate Guile development. The FSF released its first version of
326 Guile in January 1997. In the future, many of the Cygnus packages will
327 be re-integrated into Guile.
329 @cindex Free Software Foundation
333 @node How to characterize Guile
334 @section How to characterize Guile
336 I have already mentioned that Guile has become a kitchen sink package;
337 here you can see how Guile freely takes new commands and constructs from
338 the portable Scheme library @emph{slib}, the @emph{Tk} widget set, a
339 posix library (useful for UNIX systems programming), the regular
340 expression library @emph{rx}, and many more @dots{}
347 So Guile has many more primitive procedures available to it than those
348 specified in @ref{Standard Procedures, Revised(5) Report on the
349 Algorithmic Language Scheme, , r5rs, Revised(5) Report on the
350 Algorithmic Language Scheme}. On top of that, Guile will interpret
351 almost all standard Scheme programs. The only incompatible difference
352 between the basic Guile language and R5RS Scheme is that Guile is case
353 sensitive, whereas R5RS is case insensitive. We hope that few people
354 have written Scheme programs that depend on case insensitivity.
355 @cindex case sensitivity
356 @cindex Revised(5) Report on the Algorithmic Language Scheme
357 @cindex report on Scheme
358 @cindex Scheme language - report
359 @cindex Scheme language - definition
361 Here is a possible view of the @emph{sum of the parts} in Guile:
362 @cindex extensions to standard Scheme
363 @cindex extensions to R5RS
364 @cindex Scheme extensions
366 guile = standard Scheme (R5RS)
367 PLUS extensions to R5RS offered by SCM
368 PLUS some extra primitives offered by Guile (catch/throw)
369 PLUS portable Scheme library (SLIB)
370 PLUS embeddable Scheme interpreter library (libguile)
374 @c PLUS OpenGL library (mesa)
375 @c PLUS OpenGL toolkit (glut)
376 PLUS Regular expression library (rx)
377 @c PLUS Applet formalism
382 @node Using Guile to program in Scheme
383 @chapter Using Guile to program in Scheme
384 @cindex Scheme programming tutorial
385 @cindex tutorial on Scheme programming
387 In this section I give a tutorial introduction to programming in Scheme,
388 with a slant toward the interesting things that can be done in Guile.
390 @c Applets are so @emph{chic} that they get their own section, but this
391 This section will try to touch on many of the interesting and cool
392 aspects of Guile, showing you how new types of problems can be solved
393 with Guile. Note that using Guile as a library with @code{libguile.a}
394 is described in its own chapter (@pxref{Guile in a Library}). Also note
395 that some small examples are given in @ref{Jump Start}.
397 To get started you need to know how to program in @dfn{Scheme} (a
398 dialect of LISP). Fortunately Scheme is a small, clean language and is
399 not hard to learn. It is also used in many undergraduate courses to
400 introduce computer programming.
401 @cindex lisp dialects
403 I will not try to teach you Scheme here (although you might end up
404 learning by example), since there are many good books on the subject,
405 listed in @ref{Where to find more Guile/Scheme resources}. @footnote{To
406 get started, look at the books @cite{Simply Scheme} and @cite{The Little
407 Schemer} from that list.}
410 @subsection Hello World
413 Our first program is the typical Scheme "hello world" program. Put the
414 following code in a file called @code{hello.scm} (this can be find in
415 @file{examples/scheme/hello.scm}).
418 #!/usr/local/bin/guile -s
421 (display "hello world")
425 Then run guile on it. One way to do so is to start up guile and load
429 <shell-prompt> @kbd{guile}
430 guile> @kbd{(load "hello")}
433 Another way is to make the file executable and execute it directly.
434 Notice how Guile recognizes a @code{-s} option which tells it to run a
435 script and then exit. Guile also has a new type of block comment
436 enclosed by @code{#!} and @code{!#}, so that you can make executable
437 Scheme scripts with the standard UNIX @code{#!} mechanism.
439 In the given example, the first line is used to invoke the Guile
440 interpreter (make sure you correct the path if you installed Guile in
441 something other than /usr/local/bin). Once Guile is invoked on this
442 file, it will understand that the first line is a comment. The comment
443 is then terminated with @code{!#} on the second line so as to not
444 interfere with the execution mechanism.
447 @subsection A bunch of operations in Scheme
449 Here is some code you can type at the @code{guile>} prompt to see some
450 of the Scheme data types at work (mostly lists and vectors). I have
451 inserted brief comments @emph{before} each line of code explaining what
455 ;; @r{make a list and bind it to the symbol @code{ls}}
456 guile> @kbd{(define ls (list 1 2 3 4 5 6 7))}
458 ;; @r{display the list}
460 @result{(1 2 3 4 5 6 7)}
461 ;; @r{ask if @code{ls} is a vector; @code{#f} means it is not}
462 guile> @kbd{(vector? ls)}
464 ;; @r{ask if @code{ls} is a list; @code{#t} means it is}
465 guile> @kbd{(list? ls)}
467 ;; @r{ask for the length of @code{ls}}
468 guile> @kbd{(length ls)}
470 ;; @r{pick out the first element of the list}
471 guile> @kbd{(car ls)}
473 ;; @r{pick the rest of the list without the first element}
474 guile> @kbd{(cdr ls)}
475 @result{(2 3 4 5 6 7}
476 ;; @r{this should pick out the 3rd element of the list}
477 guile> @kbd{(car (cdr (cdr ls)))}
479 ;; @r{a shorthand for doing the same thing}
480 guile> @kbd{(caddr ls)}
482 ;; @r{append the given list onto @code{ls}, print the result}
483 ;; @r{@strong{NOTE:} the original list @code{ls} is @emph{not} modified}
484 guile> @kbd{(append ls (list 8 9 10))}
485 @result{(1 2 3 4 5 6 7 8 9 10)}
486 guile> @kbd{(reverse ls)}
487 @result{(10 9 8 7 6 5 4 3 2 1)}
488 ;; @r{ask if 12 is in the list --- it obviously is not}
489 guile> @kbd{(memq 12 ls)}
491 ;; @r{ask if 4 is in the list --- returns the list from 4 on.}
492 ;; @r{Notice that the result will behave as true in conditionals}
493 guile> @kbd{(memq 4 ls)}
495 ;; @r{an @code{if} statement using the aforementioned result}
496 guile> @kbd{(if (memq 4 ls)
497 (display "hey, it's true!\n")
498 (display "dude, it's false\n"))}
499 @print{hey, it's true!}
501 guile> @kbd{(if (memq 12 ls)
502 (display "hey, it's true!\n")
503 (display "dude, it's false\n"))}
504 @print{dude, it's false}
506 guile> @kbd{(memq 4 (reverse ls))}
508 ;; @r{make a smaller list @code{ls2} to work with}
509 guile> @kbd{(define ls2 (list 2 3 4))}
510 ;; @r{make a list in which the function @code{sin} has been}
511 ;; @r{applied to all elements of @code{ls2}}
512 guile> @kbd{(map sin ls2)}
513 @result{(0.909297426825682 0.141120008059867 -0.756802495307928)}
514 ;; @r{make a list in which the squaring function has been}
515 ;; @r{applied to all elements of @code{ls}}
516 guile> @kbd{(map (lambda (n) (expt n n)) ls)}
517 @result{(1 4 27 256 3125 46656 823543)}
521 ;; @r{make a vector and bind it to the symbol @code{v}}
522 guile> @kbd{(define v #(1 2 3 4 5 6 7))}
524 @result{#(1 2 3 4 5 6 7)}
525 guile> @kbd{(vector? v)}
527 guile> @kbd{(list? v)}
529 guile> @kbd{(vector-length v)}
531 ;; @r{vector-ref allows you to pick out elements by index}
532 guile> @kbd{(vector-ref v 2)}
534 ;; @r{play around with the vector: make it into a list, reverse}
535 ;; @r{the list, go back to a vector and take the second element}
536 guile> @kbd{(vector-ref (list->vector (reverse (vector->list v))) 2)}
538 ;; @r{this demonstrates that the entries in a vector do not have}
539 ;; @r{to be of uniform type}
540 guile> @kbd{(vector-set! v 4 "hi there")}
543 @result{#(1 2 3 4 "hi there" 6 7)}
547 @subsection Using recursion to process lists
549 @cindex list processing
551 Here are some typical examples of using recursion to process a list.
554 ;; @r{this is a rather trivial way of reversing a list}
555 (define (my-reverse l)
558 (append (my-reverse (cdr l)) (list (car l)))))
559 (my-reverse '(27 32 33 40))
560 @result{(40 33 32 27)}
564 @subsection Processing matrices
566 Suppose you have a matrix represented as a list of lists:
571 (list 7 2 1 3 2 8 5 3 6)
572 (list 4 1 1 1 3 8 9 8 1)
573 (list 5 5 4 8 1 8 2 2 4)))
576 Then you could apply a certain function to each element of the matrix in
577 the following manner:
579 ;; @r{apply the function func to the matrix m element-by-element;}
580 ;; @r{return a matrix with the result.}
581 (define (process-matrix m func)
586 Notice that I have used the Scheme @code{map} procedure because I am
587 interested in the matrix that results from the application of
588 @code{func}, rather than in the side effects associated with applying
591 This could be invoked with @code{(process-matrix m sin)} or
592 @code{(process-matrix m (lambda (x) (* x x)))}; for example:
595 (process-matrix m (lambda (x) (* x x)))
596 @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))}
599 To print a representation of the matrix, we could define a generalized
602 ;; @r{proc is a procedure to represent the single element,}
603 ;; @r{row-proc is a procedure that is invoked after each row.}
604 ;; @r{Example: proc could be (lambda (x) (begin (display x) (display " ")))}
605 ;; @r{and row-proc could be (lambda (l) (display "\n"))}
606 (define (represent-matrix m proc row-proc)
607 (for-each (lambda (l)
613 @findex represent-matrix
615 And then invoke it with
618 (lambda (x) (begin (display x) (display " ")))
619 (lambda (l) (begin (display "\n"))))
620 @print{7 2 1 3 2 8 5 3 6}
621 @print{4 1 1 1 3 8 9 8 1}
622 @print{5 5 4 8 1 8 2 2 4}
627 Now we write a helper routine that uses Scheme @dfn{closures} to make
628 objects with state that then receive messages to draw little squares.
630 @cindex syntactic closures
632 But let us take it one step at a time. I will start by showing you a
633 simple example of object in Scheme. The object I make here represents a
634 cell, which could be a cell in a matrix. The cell responds to commands
635 to draw itself, to return the next cell, and so forth. @emph{Guile does
636 not currently have a Tk interface, so I will leave the hooks for
637 graphical rendering. In a future release of Guile I will add graphical
638 rendering messages to the cell object.}
641 ;; @r{cell-object.scm: routines for creating and manipulating cell objects}
643 ;; @r{(the-x, the-y) is the initial position of the cell.}
644 ;; @r{the-color is a string representing a color; must be something Tk can grok.}
645 ;; @r{square-size is the size of the square that gets drawn.}
646 ;; @r{(sizex, sizey) is the size of the matrix.}
647 (define (MAKE-CELL the-x the-y the-color square-size sizex sizey)
648 (define (get-x) the-x)
649 (define (get-y) the-y)
651 (define (set-x! new-x)
654 (define (set-y! new-y)
657 (define (get-color) the-color)
658 (define (set-color! new-color)
659 (set! the-color new-color)
662 (set! the-x (+ the-x 1))
666 (set! the-y (+ the-y 1))))
669 (display "CELL next!: value of y is too big; not changing it\n")
670 (set! the-y (- the-y 1))))
673 (let* ((x0 (* the-x square-size))
674 (y0 (* the-y square-size))
675 (x1 (+ x0 square-size))
676 (y1 (+ y0 square-size)))
677 (display "I should draw a ")
679 (display " rectangle with corners at ")
680 (display x0) (display y0) (display x1) (display y1)
683 ;; self is the dispatch procedure
684 (define (self message)
691 ((set-color!) set-color!)
694 (else (error "CELL: Unknown message -> " message))))
695 ;; and now return the dispatch procedure
702 What does this procedure do? It returns another procedure
703 (@code{self}) which receives a message (x, y, set-x!, set-y!, @dots{})
704 and takes an action to return or modify its state. The state consists
705 of the values of variables @code{the-x}, @code{the-y}, @code{the-color}
708 Here are some examples of how to use MAKE-CELL and the cell object it
711 (define c (MAKE-CELL 0 0 "red" 10 7 9))
713 ;; @r{retrieve the x and y coordinates}
718 ;; @r{change the x coordinate}
723 ;; @r{change the color}
726 ((c 'set-color!) "green")
730 ;; @r{now use the next! message to move to the next cell}
737 ;; @r{now make things wrap around}
750 You will notice that expressions like @code{(c 'next)} return procedures
751 that do the job, so we have to use extra parentheses to make the job
752 happen. This syntax is rather awkward; one way around it is to define a
753 @code{send} procedure:
756 ;; @r{send makes object syntax a bit easier; instead of saying}
757 ;; @r{ ((my-cell 'set-x!) 4)}
759 ;; @r{ (send my-cell 'set-x! 4)}
760 (define (send obj . args)
761 (let ((first-eval (apply obj (list (car args)))))
762 (if (null? (cdr args))
764 (apply first-eval (cdr args)))))
768 You can see that @code{send} passes the message to the object, making
769 sure that things are evaluated the proper number of times. You can now
773 (define c2 (MAKE-CELL 0 0 "red" 10 7 9))
780 (send c2 'set-color! "green")
790 @cindex object-based programming
791 @cindex object-oriented programming
793 This is the simplest way of implementing objects in Scheme, but it does
794 not really allow for full @emph{object-oriented programming} (for
795 example, there is no inheritance). But it is useful for
796 @emph{object-based programming}.
798 Guile comes with a couple more complete object-oriented extensions to
799 Scheme: these are part of slib (@pxref{Object, , , slib, SLIB: the
800 portable Scheme library} and @pxref{Yasos, , , slib, SLIB: the portable
803 @node Guile in a Library
804 @chapter Guile in a Library
809 In the previous chapters Guile was used to write programs entirely in
810 Scheme, and no C code was seen; but I have been claiming @emph{ad
811 nauseam} that Guile is an @emph{extension} language. Here we see how
812 that is done, and how that can be useful.
814 @cindex extending C programs
820 * How to get started with libguile::
821 * More interesting programming with libguile::
825 @node Two world views
826 @section Two world views
829 In this manual, I usually jump into examples and explain them as you
830 type in the code; here I will digress and ramble for a few paragraphs to
831 set some concepts straight, and then let you type (or paste) in fun
834 In 1995, I implemented a large program, @dfn{Gnudl}, using Guile quite
835 extensively. In the design phase of Gnudl, I found I had to make a
836 choice: should the fundamental data structures be C or Scheme data
839 @cindex GNU Data Language
840 @cindex Galassi, Mark
842 Guile allows C to see its data structures (scalar types, lists, vectors,
843 strings @dots{}). C also allows Guile to see its data structures. As a
844 large program designer, you have to decide which of those capabilities
845 to use. You have two main choices:
849 You can write your software mostly in Scheme. In this case, your C
850 software will mostly parse the Scheme code with Guile calls, and provide
851 some new primitive procedures to be used by Scheme. This is what Gnudl
855 You can write your software mostly in C, occasionally allowing Scheme
856 code to be parsed by Guile, either to allow the user to modify data
857 structures, or to parse a configuration file, @dots{}
860 Mixing the two approaches seems unwise: the overall layout would be
861 confusing. But who knows? There might be problems that are best solved
862 by a hybrid approach. Please let me know if you think of such a
865 If you use the former approach, we will say that the @dfn{master world}
866 is Scheme, and the C routines serve Scheme and access Scheme data
867 structures. In the latter case, the master world is C, and Scheme
868 routines serve the C code and access C data structures.
870 In both approaches the @code{libguile.a} library is the same, but a
871 predominantly different set of routines will be used. When we go
872 through examples of libguile use, we will point out which is the master
873 world in order to clarify these two approaches.
876 @node What is libguile
877 @section What is libguile
880 @cindex scm interface
882 @dfn{Libguile} is the library which allows C programs to start a Scheme
883 interpreter and execute Scheme code. There are also facilities in
884 libguile to make C data structures available to Scheme, and vice versa.
886 The interface provided by the libguile C library is somewhat specific to
887 the implementation of the Scheme interpreter. This low-level libguile
888 interface is usually referred to as the @code{scm_} interface, since its
889 public calls (API) all have the @code{scm_} prefix.
891 There is also a higher-level libguile interface, which is usually
892 referred to as the @code{gh_} interface (libGuile High). Its public
893 calls all have the @code{gh_} prefix. The @code{gh_} library interface
894 is designed to hide the implementation details, thus making it easier to
895 assimilate and portable to other underlying Scheme implementations.
897 People extending Guile by adding bindings to C libraries (like OpenGL or
898 Rx) are encouraged to use the @code{gh_} interface, so their work will
899 be portable to other Scheme systems. The @code{gh_} interface should be
900 more stable, because it is simpler.
902 The @code{scm_} interface is necessary if you want to poke into the
903 innards of Scheme data structures, or do anything else that is not
904 offered by the @code{gh_} interface. It is not covered in this
905 tutorial, but is covered extensively in @ref{Scheme data representation,
906 Guile Reference Manual, guile-ref, Guile Reference Manual}.
908 This chapter gives a gentle introduction to the @code{gh_} interface,
909 presenting some @emph{hello world}-style programs which I wrote while
910 teaching myself to use libguile.
913 The @cite{Guile Programmer's Manual} gives more examples of programs
914 written using libguile, illustrating diverse applications. You can also
915 consult my @emph{Gnudl} documentation at
916 @url{http://nis-www.lanl.gov/~rosalia/mydocs/} to see a large scale
917 project that uses C and Scheme code together.
920 @node How to get started with libguile
921 @section How to get started with libguile
924 Here is an elementary first program, @code{learn0}, to get going with
925 libguile. The program (which uses Scheme as a master world) is in a
926 single source file, @code{learn0.c}:
929 /* @r{test the new libgh.a (Guile High-level library) with a trivial
934 #include <guile/gh.h>
936 void main_prog(int argc, char *argv[]);
938 main(int argc, char *argv[])
940 gh_enter(argc, argv, main_prog);
943 void main_prog(int argc, char *argv[])
948 gh_eval_str("(display \"hello Guile\")");
949 gh_eval_str("(newline)");
951 /* @r{for fun, evaluate some simple Scheme expressions here} */
952 gh_eval_str("(define (square x) (* x x))");
953 gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
954 gh_eval_str("(square 9)");
956 /* @r{now sit in a Scheme eval loop: I input the expressions, have
957 Guile evaluate them, and then get another expression.} */
959 fputs("learn0> ", stdout);
960 while (fgets(input_str, 199, stdin) != NULL) @{
961 gh_eval_str(input_str);
962 fputs("\nlearn0> ", stdout);
969 If you name this program @code{learn0.c}, it can now be compiled with:
971 gcc -g -c learn0.c -o learn0.o
972 gcc -o learn0 learn0.o -lguile -lm
975 @c @emph{NOTE: If you are in the Guile development tree, you can simply do
976 @c ``cd doc/examples/c; make; ./learn0''.}
978 The program is simple: it creates a Scheme interpreter, passes a couple
979 of strings to it that define new Scheme functions @code{square} and
980 @code{factorial}, and then a couple of strings that invoke those
983 It then goes into a read-eval-print-loop (REPL), so you could type
984 one-line Scheme expressions to it and have them evaluated. For example:
986 <shell-prompt> ./learn0
988 learn0> (display (sin 1.3))
990 learn0> (display (fact 10))
996 You should notice the key steps involved in this @code{learn0} program:
1001 @code{#include <guile/gh.h>}
1003 You need to invoke the initialization routine @code{gh_enter()}. This
1004 starts up a Scheme interpreter, handling many implementation-specific
1007 Your main() function should be almost empty: the real main program goes
1008 in a separate function main_prog() which is passed to gh_enter(). This
1009 rather arcane convention is due to the way Guile's garbage collector
1010 works: the whole program has to run in the dynamic context of
1013 You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
1016 You link your program with @code{-lguile}.
1021 @node More interesting programming with libguile
1022 @section More interesting programming with libguile
1025 @cindex builtin functions
1027 The @code{learn0} program shows how you can invoke Scheme commands from
1028 a C program. This is not such a great achievement: the same could have
1029 been done by opening a pipe to SCM or any other Scheme interpreter.
1031 A true extension language must allow @dfn{callbacks}. Callbacks allow
1032 you to write C routines that can be invoked as Scheme procedures, thus
1033 adding new primitive procedures to Scheme. This also means that a
1034 Scheme procedure can modify a C data structure.
1036 Guile allows you to define new Scheme procedures in C, and provides a
1037 mechanism to go back and forth between C and Scheme data types.
1039 Here is a second program, @code{learn1}, which demonstrates these
1040 features. It is split into three source files: @code{learn1.c},
1041 @code{c_builtins.h} and @code{c_builtins.c}. I am including the code
1043 @c , but you might just want to look at the online source code and the
1044 @c Makefile.am that come with Guile in the
1045 @c @file{doc/examples/c} directory.
1047 Notice that @code{learn1} uses a Scheme master world, and the C routines
1048 in @code{c_builtins.c} are simply adding new primitives to Scheme.
1054 * What learn1 is doing::
1055 * Compiling and running learn1::
1059 @subsection learn1.c
1061 Here is @file{learn1.c}:
1065 #include <guile/gh.h>
1067 #include "c_builtins.h"
1069 void main_prog(int argc, char *argv[]);
1071 main(int argc, char *argv[])
1073 gh_enter(argc, argv, main_prog);
1076 void main_prog(int argc, char *argv[])
1078 char input_str[200]; /* @r{ugly hack: assume strlen(line) < 200} */
1081 /* @r{for fun, evaluate some simple Scheme expressions here} */
1082 gh_eval_str("(define (square x) (* x x))");
1083 gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
1084 gh_eval_str("(square 9)");
1085 gh_eval_str("(fact 100)");
1087 /* @r{now try to define some new builtins, coded in C, so that they are
1088 available in Scheme.} */
1089 gh_new_procedure1_0("c-factorial", c_factorial);
1090 gh_new_procedure1_0("c-sin", c_sin);
1091 gh_new_procedure1_0("v-t", vector_test);
1093 /* @r{now sit in a Scheme eval loop: I input the expressions, have
1094 Guile evaluate them, and then get another expression.} */
1096 fputs("learn1> ", stdout);
1098 if (gets(input_str) == NULL) @{
1101 gh_eval_str(input_str);
1102 fputs("learn1> ", stdout);
1111 @subsection c_builtins.h
1113 Here is @file{c_builtins.h}:
1115 /* @r{builtin function prototypes} */
1117 #include <guile/gh.h>
1119 SCM c_factorial(SCM n);
1121 SCM vector_test(SCM s_length);
1125 @subsection c_builtins.c
1127 Here is @file{c_builtins.c}:
1132 #include <guile/gh.h>
1134 #include "c_builtins.h"
1136 /* @r{this is a factorial routine in C, made to be callable by Scheme} */
1137 SCM c_factorial(SCM s_n)
1140 unsigned long result = 1, n;
1142 n = gh_scm2ulong(s_n);
1145 for (i = 1; i <= n; ++i) @{
1149 return gh_ulong2scm(result);
1152 /* @r{a sin routine in C, callable from Scheme. it is named c_sin() to
1153 distinguish it from the default Scheme sin function} */
1156 double x = gh_scm2double(s_x);
1158 return gh_double2scm(sin(x));
1161 /* @r{play around with vectors in Guile: this routine creates a vector of
1162 the given length, initializes it all to zero except element 2 which
1164 SCM vector_test(SCM s_length)
1168 c_length = gh_scm2ulong(s_length);
1169 printf("requested length for vector: %ld\n", gh_scm2ulong(s_length));
1171 /* create a vector */
1172 xvec = gh_make_vector(s_length, gh_double2scm(0.0));
1173 /* set the second element in it */
1174 gh_vector_set_x(xvec, gh_int2scm(2), gh_double2scm(1.9));
1180 @node What learn1 is doing
1181 @subsection What learn1 is doing
1182 @cindex registering callbacks
1183 @cindex registering C functions
1184 @cindex primitive procedures
1186 If you compare learn1 to learn0, you will find that learn1 uses a new
1187 Guile construct: the function @code{gh_new_procedure()}, and its
1191 /* @r{now try to define some new builtins, coded in C, so that they are
1192 available in Scheme.} */
1193 gh_new_procedure1_0("c-factorial", c_factorial);
1194 gh_new_procedure1_0("c-sin", c_sin);
1195 gh_new_procedure1_0("v-t", vector_test);
1198 It is clear that @code{gh_new_procedure()} adds a new builtin
1199 routine written in C which can be invoked from Scheme. We can now
1200 revise our checklist for programming with libguile, so it includes
1202 @cindex libguile - step by step
1207 @code{#include <guile/gh.h>}
1209 You need to invoke the initialization routine @code{gh_enter()}. This
1210 starts up a Scheme interpreter, handling many details.
1212 Your main() function should be almost empty: the real main program goes
1213 in a separate function main_prog() which is passed to gh_enter(). This
1214 rather arcane convention is due to the way Guile's garbage collector
1215 works: the whole program has to run in the dynamic context of
1218 You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
1221 @strong{[new]} You can now define new builtin Scheme functions;
1222 i.e. define new builtin Scheme functions, with the
1223 @code{gh_new_procedure()} routine.
1225 You pass strings to the Scheme interpreter with the
1226 @code{gh_eval_str()} routine.
1228 You link your program with @code{-lguile}.
1232 I breezed by the issue of how to write your C routines that are
1233 registered to be called from Scheme. This is non-trivial, and is
1234 discussed at length in the @cite{Guile Programmer's Manual}.
1237 @node Compiling and running learn1
1238 @subsection Compiling and running learn1
1241 gcc -g -c learn1.c -o learn1.o
1242 gcc -g -c c_builtins.c -o c_builtins.o
1243 gcc -o learn1 learn1.o c_builtins.o -lguile -lm
1246 If you run @code{learn1}, it will prompt you for a one-line Scheme
1247 expression, just as @code{learn0} did. The difference is that you can
1248 use the new C builtin procedures (@code{c-factorial}, @code{c-sin},
1252 <shell-prompt> ./learn1
1255 learn1> (display (c-factorial 6))
1257 learn1> (display (c-factorial 20))
1259 learn1> (display (c-factorial 100))
1261 learn1> (display (c-sin 1.5))
1263 learn1> (display (v-t 10))
1264 requested length for vector: 10
1265 #(0.0 0.0 1.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0)
1266 learn1> (display (v-t 15))
1267 requested length for vector: 15
1268 #(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)
1273 As you see, taking @code{(c-factorial 100)} does not use bignumbers and
1274 returns a bogus answer.
1276 @node Further examples
1277 @section Further examples
1279 Further ``idealized'' examples are included in the @code{doc/examples/c}
1280 distribution. They include programs to:
1282 @c [FIXME: still have to write some of these; then I will revise the list.]
1286 Parse a startup file (C is the master world).
1288 Set up initial conditions for an n-body simulation (C is the master
1291 Implement a Scheme interpreter with all of Guile's goodies, @emph{plus}
1292 the readline library @emph{and} a fast Fourier transform routine
1293 provided in C (Scheme is the master world).
1296 @node Regular Expression Support
1297 @chapter Regular Expression Support
1299 @node UNIX System Programming
1300 @chapter UNIX System Programming
1302 @node Where to find more Guile/Scheme resources
1303 @chapter Where to find more Guile/Scheme resources
1307 @unnumbered Concept Index
1311 @node Procedure and Macro Index
1312 @unnumbered Procedure and Macro Index
1314 This is an alphabetical list of all the procedures and macros in Dominion.
1318 @node Variable Index
1319 @unnumbered Variable Index
1321 This is an alphabetical list of the major global variables in Dominion.
1326 @unnumbered Type Index
1328 This is an alphabetical list of the major data structures in Dominion.