64a4ce782d7c369fbf8b1a04aff8962fb1fed92a
[bpt/guile.git] / doc / tutorial / guile-tut.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename guile-tut.info
4 @settitle Guile Tutorial
5 @set guile-tut
6
7 @include version-tutorial.texi
8
9 @dircategory The Algorithmic Language Scheme
10 @direntry
11 * Guile Tutorial: (guile-tut). The Guile tutorial.
12 @end direntry
13
14 @setchapternewpage off
15 @c Choices for setchapternewpage are {on,off,odd}.
16 @paragraphindent 2
17 @c %**end of header
18
19 @iftex
20 @finalout
21 @c DL: lose the egregious vertical whitespace, esp. around examples
22 @c but paras in @defun-like things don't have parindent
23 @parskip 4pt plus 1pt
24 @end iftex
25
26 @titlepage
27 @title Guile Tutorial
28 @subtitle For use with Guile @value{VERSION}
29 @subtitle Last updated @value{UPDATED}
30 @include ../AUTHORS
31
32 @page
33 @vskip 0pt plus 1filll
34 Copyright @copyright{} 1997, 1998 Free Software Foundation
35
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.
39
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.
44
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
48 by the author.
49 @end titlepage
50
51
52 @ifinfo
53 @node Top
54 @top Guile Tutorial
55 @end ifinfo
56
57 @ifinfo
58 This file gives a tutorial introductionto Guile.
59
60 Copyright (C) 1997 Free Software Foundation
61
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.
65
66 @ignore
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).
71
72 @end ignore
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.
77
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
81 by the author.
82 @end ifinfo
83
84
85 @menu
86 * Jump Start::
87 * Introduction::
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::
93 * Concept Index::
94 * Procedure and Macro Index::
95 * Variable Index::
96 * Type Index::
97 @end menu
98
99 @node Jump Start
100 @chapter Jump Start
101
102 @noindent
103 Before giving an overview of Guile, I present some simple commands and
104 programs that you can type to get going immediately.
105
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
109 @result{}.
110
111 @example
112 <shell-prompt> guile
113 @end example
114 @lisp
115 (+ 20 35)
116 @result{} 55
117 (define (recursive-factorial n)
118 (if (= n 0)
119 1
120 (* n (recursive-factorial (- n 1)))))
121 (recursive-factorial 5)
122 @result{} 120
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
142 <control-D>
143 @end lisp
144
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
149 with @code{(quit)}.
150 @cindex bignumbers
151
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).
157
158
159 @node Introduction
160 @chapter Introduction
161
162 @noindent
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.
170
171
172 @menu
173 * What are scripting and extension languages::
174 * History of Guile and its motivations::
175 * How to characterize Guile::
176 @end menu
177
178 @node What are scripting and extension languages
179 @section What are scripting and extension languages
180 @cindex scripting languages
181 @cindex extension languages
182
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
188 script.
189
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
194
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.
199 @cindex Bourne shell
200
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.
205
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.
213
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
217
218 @itemize @bullet
219 @item
220 Emacs Lisp, the language used to program and customize GNU Emacs.
221 @cindex Emacs Lisp
222
223 @item
224 Tcl, John Ousterhout's general-purpose scripting and extension language.
225 @cindex Tcl
226
227 @item
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.
231 @cindex Lotus 1-2-3
232
233 @item
234 Other spreadsheet and database macro languages.
235
236 @item
237 The Dominion empire-style game's @emph{exec} files.
238 @cindex Dominion
239
240 @item
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.
246
247 @item
248 Brent Benson's libscheme.a, an embeddable Scheme interpreter.
249 @cindex Benson, Brent
250 @cindex libscheme
251
252 @item
253 Guile, the GNU extension language, which is the subject of this
254 tutorial.
255
256 @end itemize
257
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.
261
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
266 application program.
267
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
274
275
276 @node History of Guile and its motivations
277 @section History of Guile and its motivations
278
279 A few separate threads of events led to the development of Guile.
280
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
287 @cindex GNU project
288 @cindex Tcl
289
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/}.
294
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.
300
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.
305 @cindex Lord, Tom
306 @cindex Jaffer, Aubrey
307
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
310 facilities.
311
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
314 almost complete.
315
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
322
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.
328 @cindex Blandy, Jim
329 @cindex Free Software Foundation
330
331
332
333 @node How to characterize Guile
334 @section How to characterize Guile
335
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{}
341 @cindex slib
342 @cindex Tk
343 @cindex POSIX
344 @c @cindex OpenGL
345 @cindex rx
346
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
360
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
365 @example
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)
371 PLUS Tk toolkit
372 PLUS threads
373 PLUS Posix library
374 @c PLUS OpenGL library (mesa)
375 @c PLUS OpenGL toolkit (glut)
376 PLUS Regular expression library (rx)
377 @c PLUS Applet formalism
378 PLUS Tcl library
379 @end example
380
381
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
386
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.
389
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}.
396
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
402
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.}
408
409
410 @subsection Hello World
411 @cindex hello world
412
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}).
416
417 @smalllisp
418 #!/usr/local/bin/guile -s
419 !#
420
421 (display "hello world")
422 (newline)
423 @end smalllisp
424
425 Then run guile on it. One way to do so is to start up guile and load
426 this file:
427
428 @smallexample
429 <shell-prompt> @kbd{guile}
430 guile> @kbd{(load "hello")}
431 @end smallexample
432
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.
438
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.
445
446
447 @subsection A bunch of operations in Scheme
448
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
452 happens.
453
454 @smalllisp
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))}
457 @result{}
458 ;; @r{display the list}
459 guile> @kbd{ls}
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)}
463 @result{#f}
464 ;; @r{ask if @code{ls} is a list; @code{#t} means it is}
465 guile> @kbd{(list? ls)}
466 @result{#t}
467 ;; @r{ask for the length of @code{ls}}
468 guile> @kbd{(length ls)}
469 @result{7}
470 ;; @r{pick out the first element of the list}
471 guile> @kbd{(car ls)}
472 @result{1}
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)))}
478 @result{3}
479 ;; @r{a shorthand for doing the same thing}
480 guile> @kbd{(caddr ls)}
481 @result{3}
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)}
490 @result{#f}
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)}
494 @result{(4 5 6 7)}
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!}
500 @result{}
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}
505 @result{}
506 guile> @kbd{(memq 4 (reverse ls))}
507 @result{(4 3 2 1)}
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)}
518 @end smalllisp
519
520 @smalllisp
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))}
523 guile> @kbd{v}
524 @result{#(1 2 3 4 5 6 7)}
525 guile> @kbd{(vector? v)}
526 @result{#t}
527 guile> @kbd{(list? v)}
528 @result{#f}
529 guile> @kbd{(vector-length v)}
530 @result{7}
531 ;; @r{vector-ref allows you to pick out elements by index}
532 guile> @kbd{(vector-ref v 2)}
533 @result{3}
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)}
537 @result{5}
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")}
541 @result{"hi there"}
542 guile> @kbd{v}
543 @result{#(1 2 3 4 "hi there" 6 7)}
544 @end smalllisp
545
546
547 @subsection Using recursion to process lists
548 @cindex recursion
549 @cindex list processing
550
551 Here are some typical examples of using recursion to process a list.
552
553 @smalllisp
554 ;; @r{this is a rather trivial way of reversing a list}
555 (define (my-reverse l)
556 (if (null? l)
557 l
558 (append (my-reverse (cdr l)) (list (car l)))))
559 (my-reverse '(27 32 33 40))
560 @result{(40 33 32 27)}
561 @end smalllisp
562
563
564 @subsection Processing matrices
565
566 Suppose you have a matrix represented as a list of lists:
567
568 @smalllisp
569 (define m
570 (list
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)))
574 @end smalllisp
575
576 Then you could apply a certain function to each element of the matrix in
577 the following manner:
578 @smalllisp
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)
582 (map (lambda (l)
583 (map func l))
584 m))
585 @end smalllisp
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
589 @code{func}.
590
591 This could be invoked with @code{(process-matrix m sin)} or
592 @code{(process-matrix m (lambda (x) (* x x)))}; for example:
593
594 @smalllisp
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))}
597 @end smalllisp
598
599 To print a representation of the matrix, we could define a generalized
600 routine:
601 @smalllisp
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)
608 (begin
609 (for-each proc l)
610 (row-proc l)))
611 m))
612 @end smalllisp
613 @findex represent-matrix
614
615 And then invoke it with
616 @smalllisp
617 (represent-matrix m
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}
623 @end smalllisp
624
625 @cindex objects
626
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.
629 @cindex closures
630 @cindex syntactic closures
631
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.}
639
640 @smallexample
641 ;; @r{cell-object.scm: routines for creating and manipulating cell objects}
642
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)
650
651 (define (set-x! new-x)
652 (set! the-x new-x)
653 the-x)
654 (define (set-y! new-y)
655 (set! the-y new-y)
656 the-y)
657 (define (get-color) the-color)
658 (define (set-color! new-color)
659 (set! the-color new-color)
660 the-color)
661 (define (next!)
662 (set! the-x (+ the-x 1))
663 (if (>= the-x sizex)
664 (begin
665 (set! the-x 0)
666 (set! the-y (+ the-y 1))))
667 (if (>= the-y sizey)
668 (begin
669 (display "CELL next!: value of y is too big; not changing it\n")
670 (set! the-y (- the-y 1))))
671 (cons the-x the-y))
672 (define (draw)
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 ")
678 (display the-color)
679 (display " rectangle with corners at ")
680 (display x0) (display y0) (display x1) (display y1)
681 ))
682
683 ;; self is the dispatch procedure
684 (define (self message)
685 (case message
686 ((x) get-x)
687 ((y) get-y)
688 ((set-x!) set-x!)
689 ((set-y!) set-y!)
690 ((color) get-color)
691 ((set-color!) set-color!)
692 ((next!) next!)
693 ((draw) draw)
694 (else (error "CELL: Unknown message -> " message))))
695 ;; and now return the dispatch procedure
696 self
697 )
698 @end smallexample
699 @cindex cell-object
700 @findex MAKE-CELL
701
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}
706 and so forth.
707
708 Here are some examples of how to use MAKE-CELL and the cell object it
709 creates:
710 @smallexample
711 (define c (MAKE-CELL 0 0 "red" 10 7 9))
712
713 ;; @r{retrieve the x and y coordinates}
714 ((c 'x))
715 @result{0}
716 ((c 'y))
717 @result{0}
718 ;; @r{change the x coordinate}
719 ((c 'set-x!) 5)
720 @result{5}
721 ((c 'x))
722 @result{5}
723 ;; @r{change the color}
724 ((c 'color))
725 @result{"red"}
726 ((c 'set-color!) "green")
727 @result{"green"}
728 ((c 'color))
729 @result{"green"}
730 ;; @r{now use the next! message to move to the next cell}
731 ((c 'next!))
732 @result{(6 . 0)}
733 ((c 'x))
734 @result{6}
735 ((c 'y))
736 @result{0}
737 ;; @r{now make things wrap around}
738 ((c 'next!))
739 @result{(0 . 1)}
740 ((c 'next!))
741 @result{(1 . 1)}
742 ((c 'next!))
743 @result{(2 . 1)}
744 ((c 'x))
745 @result{2}
746 ((c 'y))
747 @result{1}
748 @end smallexample
749
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:
754
755 @smallexample
756 ;; @r{send makes object syntax a bit easier; instead of saying}
757 ;; @r{ ((my-cell 'set-x!) 4)}
758 ;; @r{you can say}
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))
763 (first-eval)
764 (apply first-eval (cdr args)))))
765 @end smallexample
766 @findex send
767
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
770 type:
771
772 @smallexample
773 (define c2 (MAKE-CELL 0 0 "red" 10 7 9))
774 (send c2 'x)
775 @result{0}
776 (send c2 'set-x! 5)
777 @result{5}
778 (send c2 'color)
779 @result{"red"}
780 (send c2 'set-color! "green")
781 @result{"green"}
782 (send c2 'next!)
783 @result{(1 . 0)}
784 (send c2 'x)
785 @result{1}
786 (send c2 'y)
787 @result{0}
788 @end smallexample
789
790 @cindex object-based programming
791 @cindex object-oriented programming
792
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}.
797
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
801 Scheme library}).
802
803 @node Guile in a Library
804 @chapter Guile in a Library
805
806 @iftex
807 @nobreak
808 @end iftex
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.
813 @cindex libguile
814 @cindex extending C programs
815
816
817 @menu
818 * Two world views::
819 * What is libguile::
820 * How to get started with libguile::
821 * More interesting programming with libguile::
822 * Further examples::
823 @end menu
824
825 @node Two world views
826 @section Two world views
827 @cindex master world
828
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
832 examples.
833
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
837 structures?
838 @cindex gnudl
839 @cindex GNU Data Language
840 @cindex Galassi, Mark
841
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:
846
847 @enumerate 1
848 @item
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
852 does.
853
854 @item
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{}
858 @end enumerate
859
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
863 problem.
864
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.
869
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.
874
875
876 @node What is libguile
877 @section What is libguile
878 @cindex libguile
879 @cindex gh interface
880 @cindex scm interface
881
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.
885
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.
890
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.
896
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.
901
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}.
907
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.
911 @cindex hello world
912
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.
918
919
920 @node How to get started with libguile
921 @section How to get started with libguile
922 @cindex learn0
923
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}:
927
928 @smallexample
929 /* @r{test the new libgh.a (Guile High-level library) with a trivial
930 program} */
931
932 #include <stdio.h>
933
934 #include <guile/gh.h>
935
936 void main_prog(int argc, char *argv[]);
937
938 main(int argc, char *argv[])
939 @{
940 gh_enter(argc, argv, main_prog);
941 @}
942
943 void main_prog(int argc, char *argv[])
944 @{
945 int done;
946 char input_str[200];
947
948 gh_eval_str("(display \"hello Guile\")");
949 gh_eval_str("(newline)");
950
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)");
955
956 /* @r{now sit in a Scheme eval loop: I input the expressions, have
957 Guile evaluate them, and then get another expression.} */
958 done = 0;
959 fputs("learn0> ", stdout);
960 while (fgets(input_str, 199, stdin) != NULL) @{
961 gh_eval_str(input_str);
962 fputs("\nlearn0> ", stdout);
963 @}
964
965 exit(0);
966 @}
967 @end smallexample
968
969 If you name this program @code{learn0.c}, it can now be compiled with:
970 @smallexample
971 gcc -g -c learn0.c -o learn0.o
972 gcc -o learn0 learn0.o -lguile -lm
973 @end smallexample
974
975 @c @emph{NOTE: If you are in the Guile development tree, you can simply do
976 @c ``cd doc/examples/c; make; ./learn0''.}
977
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
981 functions.
982
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:
985 @smallexample
986 <shell-prompt> ./learn0
987 hello Guile
988 learn0> (display (sin 1.3))
989 963.558185417193e-3
990 learn0> (display (fact 10))
991 3628800
992 learn0> (quit)
993 <shell-prompt>
994 @end smallexample
995
996 You should notice the key steps involved in this @code{learn0} program:
997
998 @cartouche
999 @enumerate
1000 @item
1001 @code{#include <guile/gh.h>}
1002 @item
1003 You need to invoke the initialization routine @code{gh_enter()}. This
1004 starts up a Scheme interpreter, handling many implementation-specific
1005 details.
1006 @item
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
1011 @code{gh_enter()}.
1012 @item
1013 You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
1014 routine.
1015 @item
1016 You link your program with @code{-lguile}.
1017 @end enumerate
1018 @end cartouche
1019
1020
1021 @node More interesting programming with libguile
1022 @section More interesting programming with libguile
1023 @cindex learn1
1024 @cindex callback
1025 @cindex builtin functions
1026
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.
1030
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.
1035
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.
1038
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
1042 here.
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.
1046
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.
1049
1050 @menu
1051 * learn1.c::
1052 * c_builtins.h::
1053 * c_builtins.c::
1054 * What learn1 is doing::
1055 * Compiling and running learn1::
1056 @end menu
1057
1058 @node learn1.c
1059 @subsection learn1.c
1060
1061 Here is @file{learn1.c}:
1062 @smallexample
1063 #include <stdio.h>
1064
1065 #include <guile/gh.h>
1066
1067 #include "c_builtins.h"
1068
1069 void main_prog(int argc, char *argv[]);
1070
1071 main(int argc, char *argv[])
1072 @{
1073 gh_enter(argc, argv, main_prog);
1074 @}
1075
1076 void main_prog(int argc, char *argv[])
1077 @{
1078 char input_str[200]; /* @r{ugly hack: assume strlen(line) < 200} */
1079 int done;
1080
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)");
1086
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);
1092
1093 /* @r{now sit in a Scheme eval loop: I input the expressions, have
1094 Guile evaluate them, and then get another expression.} */
1095 done = 0;
1096 fputs("learn1> ", stdout);
1097 while (!done) @{
1098 if (gets(input_str) == NULL) @{
1099 done = 1;
1100 @} else @{
1101 gh_eval_str(input_str);
1102 fputs("learn1> ", stdout);
1103 @}
1104 @}
1105
1106 exit(0);
1107 @}
1108 @end smallexample
1109
1110 @node c_builtins.h
1111 @subsection c_builtins.h
1112
1113 Here is @file{c_builtins.h}:
1114 @smallexample
1115 /* @r{builtin function prototypes} */
1116
1117 #include <guile/gh.h>
1118
1119 SCM c_factorial(SCM n);
1120 SCM c_sin(SCM n);
1121 SCM vector_test(SCM s_length);
1122 @end smallexample
1123
1124 @node c_builtins.c
1125 @subsection c_builtins.c
1126
1127 Here is @file{c_builtins.c}:
1128 @smallexample
1129 #include <stdio.h>
1130 #include <math.h>
1131
1132 #include <guile/gh.h>
1133
1134 #include "c_builtins.h"
1135
1136 /* @r{this is a factorial routine in C, made to be callable by Scheme} */
1137 SCM c_factorial(SCM s_n)
1138 @{
1139 int i;
1140 unsigned long result = 1, n;
1141
1142 n = gh_scm2ulong(s_n);
1143
1144 gh_defer_ints();
1145 for (i = 1; i <= n; ++i) @{
1146 result = result*i;
1147 @}
1148 gh_allow_ints();
1149 return gh_ulong2scm(result);
1150 @}
1151
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} */
1154 SCM c_sin(SCM s_x)
1155 @{
1156 double x = gh_scm2double(s_x);
1157
1158 return gh_double2scm(sin(x));
1159 @}
1160
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
1163 is set to 1.9.} */
1164 SCM vector_test(SCM s_length)
1165 @{
1166 SCM xvec;
1167
1168 c_length = gh_scm2ulong(s_length);
1169 printf("requested length for vector: %ld\n", gh_scm2ulong(s_length));
1170
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));
1175
1176 return xvec;
1177 @}
1178 @end smallexample
1179
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
1185
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
1188 siblings:
1189
1190 @smallexample
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);
1196 @end smallexample
1197
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
1201 adding callbacks.
1202 @cindex libguile - step by step
1203
1204 @cartouche
1205 @enumerate
1206 @item
1207 @code{#include <guile/gh.h>}
1208 @item
1209 You need to invoke the initialization routine @code{gh_enter()}. This
1210 starts up a Scheme interpreter, handling many details.
1211 @item
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
1216 @code{gh_enter()}.
1217 @item
1218 You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
1219 routine.
1220 @item
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.
1224 @item
1225 You pass strings to the Scheme interpreter with the
1226 @code{gh_eval_str()} routine.
1227 @item
1228 You link your program with @code{-lguile}.
1229 @end enumerate
1230 @end cartouche
1231
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}.
1235
1236
1237 @node Compiling and running learn1
1238 @subsection Compiling and running learn1
1239
1240 @smallexample
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
1244 @end smallexample
1245
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},
1249 @code{v-t}).
1250
1251 @smallexample
1252 <shell-prompt> ./learn1
1253 welcome to Guile
1254 hello Guile
1255 learn1> (display (c-factorial 6))
1256 720
1257 learn1> (display (c-factorial 20))
1258 2192834560
1259 learn1> (display (c-factorial 100))
1260 0
1261 learn1> (display (c-sin 1.5))
1262 0.997494986604054
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)
1269 learn1> (quit)
1270 <shell-prompt>
1271 @end smallexample
1272
1273 As you see, taking @code{(c-factorial 100)} does not use bignumbers and
1274 returns a bogus answer.
1275
1276 @node Further examples
1277 @section Further examples
1278
1279 Further ``idealized'' examples are included in the @code{doc/examples/c}
1280 distribution. They include programs to:
1281
1282 @c [FIXME: still have to write some of these; then I will revise the list.]
1283
1284 @itemize @bullet
1285 @item
1286 Parse a startup file (C is the master world).
1287 @item
1288 Set up initial conditions for an n-body simulation (C is the master
1289 world).
1290 @item
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).
1294 @end itemize
1295
1296 @node Regular Expression Support
1297 @chapter Regular Expression Support
1298
1299 @node UNIX System Programming
1300 @chapter UNIX System Programming
1301
1302 @node Where to find more Guile/Scheme resources
1303 @chapter Where to find more Guile/Scheme resources
1304
1305
1306 @node Concept Index
1307 @unnumbered Concept Index
1308
1309 @printindex cp
1310
1311 @node Procedure and Macro Index
1312 @unnumbered Procedure and Macro Index
1313
1314 This is an alphabetical list of all the procedures and macros in Dominion.
1315
1316 @printindex fn
1317
1318 @node Variable Index
1319 @unnumbered Variable Index
1320
1321 This is an alphabetical list of the major global variables in Dominion.
1322
1323 @printindex vr
1324
1325 @node Type Index
1326 @unnumbered Type Index
1327
1328 This is an alphabetical list of the major data structures in Dominion.
1329
1330 @printindex tp
1331
1332 @contents
1333
1334 @bye