1
This is guile-tut.info, produced by makeinfo version 4.8 from
4
INFO-DIR-SECTION The Algorithmic Language Scheme
6
* Guile Tutorial: (guile-tut). The Guile tutorial.
10
File: guile-tut.info, Node: Top, Next: Jump Start, Up: (dir)
15
This file gives a tutorial introduction to Guile.
17
Copyright (C) 1997, 2004, 2006 Free Software Foundation
19
Permission is granted to make and distribute verbatim copies of this
20
manual provided the copyright notice and this permission notice are
21
preserved on all copies.
23
Permission is granted to copy and distribute modified versions of this
24
manual under the conditions for verbatim copying, provided that the
25
entire resulting derived work is distributed under the terms of a
26
permission notice identical to this one.
28
Permission is granted to copy and distribute translations of this
29
manual into another language, under the above conditions for modified
30
versions, except that this permission notice may be stated in a
31
translation approved by the author.
37
* Using Guile to program in Scheme::
38
* Guile in a Library::
39
* Regular Expression Support::
40
* UNIX System Programming::
41
* Where to find more Guile/Scheme resources::
43
* Procedure and Macro Index::
48
File: guile-tut.info, Node: Jump Start, Next: Introduction, Prev: Top, Up: Top
53
Before giving an overview of Guile, I present some simple commands and
54
programs that you can type to get going immediately.
56
Start by invoking the Guile interpreter. Usually you do this by just
57
typing `guile'. Then type (or paste) the following expressions at the
58
prompt; the interpreter's response is preceded (in this manual) by =>.
64
(define (recursive-factorial n)
67
(* n (recursive-factorial (- n 1)))))
68
(recursive-factorial 5)
72
In this example we did some simple arithmetic `(+ 20 35)' and got the
73
answer `55'. Then we coded the classic (and rather wasteful) factorial
74
algorithm and computed the factorial of `55'. Finally we quit with
77
We can find out about some of Scheme's nice features by asking for the
78
factorial of some big number, say `500'. On some systems the correct
79
answer will be returned (I do not indicate calling and leaving the
80
guile session anymore).
82
(recursive-factorial 500)
83
=> 1220136825991110068701238785423046926253574342803192842192413588
84
3858453731538819976054964475022032818630136164771482035841633787
85
2207817720048078520515932928547790757193933060377296085908627042
86
9174547882424912726344305670173270769461062802310452644218878789
87
4657547771498634943677810376442740338273653974713864778784954384
88
8959553753799042324106127132698432774571554630997720278101456108
89
1188373709531016356324432987029563896628911658974769572087926928
90
8712817800702651745077684107196243903943225364226052349458501299
91
1857150124870696156814162535905669342381300885624924689156412677
92
5654481886506593847951775360894005745238940335798476363944905313
93
0623237490664450488246650759467358620746379251842004593696929810
94
2226397195259719094521782333175693458150855233282076282002340262
95
6907898342451712006207714640979456116127629145951237229913340169
96
5523638509428855920187274337951730145863575708283557801587354327
97
6888868012039988238470215146760544540766353598417443048012893831
98
3896881639487469658817504506926365338175055478128640000000000000
99
0000000000000000000000000000000000000000000000000000000000000000
100
00000000000000000000000000000000000000000000000
102
The result is an example of Scheme's _bignumbers_. However, there
103
are operating environments that provide (by default) too little stack
104
space. They will instead produce an error message like this:
106
(recursive-factorial 500)
108
ERROR: Stack overflow
109
ABORT: (stack-overflow)
111
Rather than enlarging the system's stack, we can implement the
112
algorithm such that it does not consume increasing stack space. This
113
is called a _tail recursive_ implementation. The following definition
114
is tail recursive and so should work on all systems.
116
(define (tail-recursive-factorial n)
119
(loop (- k 1) (* k l))))
122
(tail-recursive-factorial 500)
123
=> 1220136825991110068701238785423046926253574342803192842192413588
126
This is the most basic use of Guile: a simple Scheme interpreter. In
127
the rest of this tutorial I will show you how Guile has many facets: it
128
is also an _extensible_ interpreter (to which many features can be
129
easilly added) and an _embeddable_ interpreter (which can be invoked
130
from your C programs).
133
File: guile-tut.info, Node: Introduction, Next: Using Guile to program in Scheme, Prev: Jump Start, Up: Top
138
"Guile" (which can stand for _GNU Ubiquitous Intelligent Language
139
Extension_) is the GNU extension language. It started out as an
140
embeddable Scheme interpreter, and has rapidly evolved into a
141
kitchen-sink package including a standalone Scheme interpreter, an
142
embeddable Scheme interpreter, several graphics options, other languages
143
that can be used along with Scheme (for now just _ctax_ and _Tcl_), and
148
* What are scripting and extension languages::
149
* History of Guile and its motivations::
150
* How to characterize Guile::
153
File: guile-tut.info, Node: What are scripting and extension languages, Next: History of Guile and its motivations, Up: Introduction
155
2.1 What are scripting and extension languages
156
==============================================
158
A "scripting language" is a programming language which serves as glue
159
between other system programs. In the UNIX world, the traditional
160
scripting language is the _Bourne shell_, which allows many UNIX
161
commands to be executed in sequence, or in a pipeline. Traditional UNIX
162
commands are cleverly written to work well when put together in a
165
Other examples of UNIX scripting languages are AWK, Perl, Scsh (the
166
Scheme Shell: a Scheme interpreter enhanced to do good scripting),
167
Python, Tcl, Java ...
169
UNIX programmers noticed, more than 25 years ago, that scripting
170
languages can do serious work, so the Bourne shell was written to have
171
variables, operators and control structures, just like a full-featured
172
programming language.
174
What scripting languages have, that traditional programming languages
175
do not, is the ability to easily run an external program (or a pipeline
176
of external programs) and use the returned values and output from that
177
program in useful ways.
179
An "extension language" is a programming language interpreter offered
180
by an application program, so that users can write macros or even
181
full-fledged programs to extend the original application. Extension
182
languages have a C interface (it is usually C, but it could be any
183
other compiled language), and can be given access to the C data
184
structures. Likewise, there are C routines to access the extension
185
language data structures.
187
Extension languages abound in the software world, even though the name
188
_extension language_ is seldom used. Examples are:
190
* Emacs Lisp, the language used to program and customize GNU Emacs.
192
* Tcl, John Ousterhout's general-purpose scripting and extension
195
* The Lotus 1-2-3 macro language (any spreadsheet macro language,
196
really). I mention this one first because it is a classic, even
197
though it is seldom used any more.
199
* Other spreadsheet and database macro languages.
201
* The Dominion empire-style game's _exec_ files.
203
* Any syntax for a ".*rc" file you might have used. Almost all
204
programs end up parsing some kind of startup or configuration
205
file. The syntax for those can get pretty involved, thus
206
justifying calling them "extension languages". The _fvwm_ window
207
manager, for example, parses a rather elaborate `.fvwmrc' file.
209
* Brent Benson's libscheme.a, an embeddable Scheme interpreter.
211
* Guile, the GNU extension language, which is the subject of this
215
One lesson we can learn from looking at classical large software
216
applications is that "writers of large programs" always end up throwing
217
in some kind of parser for configuration or scripting.
219
Of the examples listed above, Emacs Lisp, Tcl, Libscheme and Guile
220
have an important property: they are not added as an afterthought for a
221
specific application. They are general-purpose languages which a user
222
can learn (even in college courses) and then use to customize the
225
This is a recent and (in my opinion) very exciting direction in
226
large-program software engineering: program designers can link in the
227
Guile or Tcl library from the very beginning, and tell their users "You
228
want to customize this program? Just use Scheme (or Tcl, or whatever
229
language), which you already know!"
232
File: guile-tut.info, Node: History of Guile and its motivations, Next: How to characterize Guile, Prev: What are scripting and extension languages, Up: Introduction
234
2.2 History of Guile and its motivations
235
========================================
237
A few separate threads of events led to the development of Guile.
239
In the fall of 1994, Richard Stallman, director of the GNU project,
240
posted an article with the subject "Why you should not use Tcl", in
241
which he argued that Tcl is inadequate as an extension language. This
242
generated a flurry of flames (available in the hypermail archive
243
(`http://www.vanderburg.org/Tcl/war/') *The Tcl War*).
245
The result was that Stallman then proposed his design for the GNU
246
Extension Language, first called GEL and then renamed Guile. The
247
discussion triggered by that article is also available in a hypermail
248
archive, `http://www.vanderburg.org/Tcl/war2/'.
250
One interesting feature of this GNU Extension Language plan was that
251
users should have a _choice_ of languages to use in extending their
252
program. The basic language would be a slightly modified Scheme, and
253
translators would be written to convert other languages (like Tcl,
254
Python, Perl, C-like languages ...) into Scheme.
256
Tom Lord started working on this project immediately, taking Aubrey
257
Jaffer's small and portable implementation of Scheme, SCM, and making it
258
into an embeddable interpreter: callable from C and allowing new Scheme
259
procedures to be written in C.
261
In the spring of 1995, the guile-ii snapshot was released. This made
262
it possible to start writing code in C and Scheme using the guile
265
The guile-iii snapshot was released the summer of 1995, and it had
266
fixed enough problems so that the access to Scheme data structures from
267
C was almost complete.
269
After this, Cygnus Support added many features to Guile and finished
270
implementing others, so that Guile acquired thread support, a regular
271
expression matcher, a Tk interface, an interface to the SGI OpenGL
272
graphics system, an _applet_ formalism, and some other packages. This
273
was all in the Cygnus Guile r0.3 and r0.4 releases.
275
Meanwhile, Tom Lord left the project after having produced a divergent
276
version of Guile: 1.0b2. The Free Software Foundation hired Jim Blandy
277
to coordinate Guile development. The FSF released its first version of
278
Guile in January 1997. In the future, many of the Cygnus packages will
279
be re-integrated into Guile.
282
File: guile-tut.info, Node: How to characterize Guile, Prev: History of Guile and its motivations, Up: Introduction
284
2.3 How to characterize Guile
285
=============================
287
I have already mentioned that Guile has become a kitchen sink package;
288
here you can see how Guile freely takes new commands and constructs from
289
the portable Scheme library _slib_, the _Tk_ widget set, a posix
290
library (useful for UNIX systems programming), the regular expression
291
library _rx_, and many more ...
293
So Guile has many more primitive procedures available to it than those
294
specified in *Note Revised(5) Report on the Algorithmic Language
295
Scheme: (r5rs)Standard Procedures. On top of that, Guile will interpret
296
almost all standard Scheme programs. The only incompatible difference
297
between the basic Guile language and R5RS Scheme is that Guile is case
298
sensitive, whereas R5RS is case insensitive. We hope that few people
299
have written Scheme programs that depend on case insensitivity.
301
Here is a possible view of the _sum of the parts_ in Guile:
302
guile = standard Scheme (R5RS)
303
PLUS extensions to R5RS offered by SCM
304
PLUS some extra primitives offered by Guile (catch/throw)
305
PLUS portable Scheme library (SLIB)
306
PLUS embeddable Scheme interpreter library (libguile)
310
PLUS Regular expression library (rx)
314
File: guile-tut.info, Node: Using Guile to program in Scheme, Next: Guile in a Library, Prev: Introduction, Up: Top
316
3 Using Guile to program in Scheme
317
**********************************
319
In this section I give a tutorial introduction to programming in Scheme,
320
with a slant toward the interesting things that can be done in Guile.
322
This section will try to touch on many of the interesting and cool
323
aspects of Guile, showing you how new types of problems can be solved
324
with Guile. Note that using Guile as a library with `libguile.a' is
325
described in its own chapter (*note Guile in a Library::). Also note
326
that some small examples are given in *Note Jump Start::.
328
To get started you need to know how to program in "Scheme" (a dialect
329
of LISP). Fortunately Scheme is a small, clean language and is not
330
hard to learn. It is also used in many undergraduate courses to
331
introduce computer programming.
333
I will not try to teach you Scheme here (although you might end up
334
learning by example), since there are many good books on the subject,
335
listed in *Note Where to find more Guile/Scheme resources::. (1)
340
Our first program is the typical Scheme "hello world" program. Put the
341
following code in a file called `hello.scm' (this can be find in
342
`examples/scheme/hello.scm').
344
#!/usr/local/bin/guile -s
347
(display "hello world")
350
Then run guile on it. One way to do so is to start up guile and load
354
guile> (load "hello")
356
Another way is to make the file executable and execute it directly.
357
Notice how Guile recognizes a `-s' option which tells it to run a
358
script and then exit. Guile also has a new type of block comment
359
enclosed by `#!' and `!#', so that you can make executable Scheme
360
scripts with the standard UNIX `#!' mechanism.
362
In the given example, the first line is used to invoke the Guile
363
interpreter (make sure you correct the path if you installed Guile in
364
something other than /usr/local/bin). Once Guile is invoked on this
365
file, it will understand that the first line is a comment. The comment
366
is then terminated with `!#' on the second line so as to not interfere
367
with the execution mechanism.
369
3.0.2 A bunch of operations in Scheme
370
-------------------------------------
372
Here is some code you can type at the `guile>' prompt to see some of
373
the Scheme data types at work (mostly lists and vectors). I have
374
inserted brief comments _before_ each line of code explaining what
377
;; make a list and bind it to the symbol `ls'
378
guile> (define ls (list 1 2 3 4 5 6 7))
383
;; ask if `ls' is a vector; `#f' means it is not
386
;; ask if `ls' is a list; `#t' means it is
389
;; ask for the length of `ls'
392
;; pick out the first element of the list
395
;; pick the rest of the list without the first element
398
;; this should pick out the 3rd element of the list
399
guile> (car (cdr (cdr ls)))
401
;; a shorthand for doing the same thing
404
;; append the given list onto `ls', print the result
405
;; *NOTE_* the original list `ls' is _not_ modified
406
guile> (append ls (list 8 9 10))
407
=> (1 2 3 4 5 6 7 8 9 10)
410
;; ask if 12 is in the list -- it obviously is not
413
;; ask if 4 is in the list -- returns the list from 4 on.
414
;; Notice that the result will behave as true in conditionals
417
;; an `if' statement using the aforementioned result
418
guile> (if (memq 4 ls)
419
(display "hey, it's true!\n")
420
(display "dude, it's false\n"))
423
guile> (if (memq 12 ls)
424
(display "hey, it's true!\n")
425
(display "dude, it's false\n"))
428
guile> (memq 4 (reverse ls))
430
;; make a smaller list `ls2' to work with
431
guile> (define ls2 (list 2 3 4))
432
;; make a list in which the function `sin' has been
433
;; applied to all elements of `ls2'
435
=> (0.909297426825682 0.141120008059867 -0.756802495307928)
436
;; make a list in which the squaring function has been
437
;; applied to all elements of `ls'
438
guile> (map (lambda (n) (* n n)) ls)
439
=> (1 4 9 16 25 36 49)
441
;; make a vector and bind it to the symbol `v'
442
guile> (define v '#(1 2 3 4 5 6 7))
449
guile> (vector-length v)
451
;; vector-ref allows you to pick out elements by index
452
guile> (vector-ref v 2)
454
;; play around with the vector: make it into a list, reverse
455
;; the list, go back to a vector and take the second element
456
guile> (vector-ref (list->vector (reverse (vector->list v))) 2)
458
;; this demonstrates that the entries in a vector do not have
459
;; to be of uniform type
460
guile> (vector-set! v 4 "hi there")
463
=> #(1 2 3 4 "hi there" 6 7)
465
3.0.3 Using recursion to process lists
466
--------------------------------------
468
Here are some typical examples of using recursion to process a list.
470
;; this is a rather trivial way of reversing a list
471
(define (my-reverse l)
474
(append (my-reverse (cdr l)) (list (car l)))))
475
(my-reverse '(27 32 33 40))
478
3.0.4 Processing matrices
479
-------------------------
481
Suppose you have a matrix represented as a list of lists:
485
(list 7 2 1 3 2 8 5 3 6)
486
(list 4 1 1 1 3 8 9 8 1)
487
(list 5 5 4 8 1 8 2 2 4)))
489
Then you could apply a certain function to each element of the matrix
490
in the following manner:
491
;; apply the function func to the matrix m element-by-element;
492
;; return a matrix with the result.
493
(define (process-matrix m func)
497
Notice that I have used the Scheme `map' procedure because I am
498
interested in the matrix that results from the application of `func',
499
rather than in the side effects associated with applying `func'.
501
This could be invoked with `(process-matrix m sin)' or
502
`(process-matrix m (lambda (x) (* x x)))'; for example:
504
(process-matrix m (lambda (x) (* x x)))
505
=> ((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))
507
To print a representation of the matrix, we could define a generalized
509
;; proc is a procedure to represent the single element,
510
;; row-proc is a procedure that is invoked after each row.
511
;; Example: proc could be (lambda (x) (begin (display x) (display " ")))
512
;; and row-proc could be (lambda (l) (display "\n"))
513
(define (represent-matrix m proc row-proc)
514
(for-each (lambda (l)
520
And then invoke it with
522
(lambda (x) (begin (display x) (display " ")))
523
(lambda (l) (begin (display "\n"))))
528
Now we write a helper routine that uses Scheme "closures" to make
529
objects with state that then receive messages to draw little squares.
531
But let us take it one step at a time. I will start by showing you a
532
simple example of object in Scheme. The object I make here represents a
533
cell, which could be a cell in a matrix. The cell responds to commands
534
to draw itself, to return the next cell, and so forth. _Guile does not
535
currently have a Tk interface, so I will leave the hooks for graphical
536
rendering. In a future release of Guile I will add graphical rendering
537
messages to the cell object._
539
;; cell-object.scm: routines for creating and manipulating cell objects
541
;; (the-x, the-y) is the initial position of the cell.
542
;; the-color is a string representing a color; must be something Tk can grok.
543
;; square-size is the size of the square that gets drawn.
544
;; (sizex, sizey) is the size of the matrix.
545
(define (MAKE-CELL the-x the-y the-color square-size sizex sizey)
546
(define (get-x) the-x)
547
(define (get-y) the-y)
549
(define (set-x! new-x)
552
(define (set-y! new-y)
555
(define (get-color) the-color)
556
(define (set-color! new-color)
557
(set! the-color new-color)
560
(set! the-x (+ the-x 1))
564
(set! the-y (+ the-y 1))))
567
(display "CELL next!: value of y is too big; not changing it\n")
568
(set! the-y (- the-y 1))))
571
(let* ((x0 (* the-x square-size))
572
(y0 (* the-y square-size))
573
(x1 (+ x0 square-size))
574
(y1 (+ y0 square-size)))
575
(display "I should draw a ")
577
(display " rectangle with corners at ")
578
(display x0) (display y0) (display x1) (display y1)
581
;; self is the dispatch procedure
582
(define (self message)
589
((set-color!) set-color!)
592
(else (error "CELL: Unknown message -> " message))))
593
;; and now return the dispatch procedure
597
What does this procedure do? It returns another procedure (`self')
598
which receives a message (x, y, set-x!, set-y!, ...) and takes an
599
action to return or modify its state. The state consists of the values
600
of variables `the-x', `the-y', `the-color' and so forth.
602
Here are some examples of how to use MAKE-CELL and the cell object it
604
(define c (MAKE-CELL 0 0 "red" 10 7 9))
606
;; retrieve the x and y coordinates
611
;; change the x coordinate
619
((c 'set-color!) "green")
623
;; now use the next! message to move to the next cell
630
;; now make things wrap around
642
You will notice that expressions like `(c 'next)' return procedures
643
that do the job, so we have to use extra parentheses to make the job
644
happen. This syntax is rather awkward; one way around it is to define a
647
;; send makes object syntax a bit easier; instead of saying
648
;; ((my-cell 'set-x!) 4)
650
;; (send my-cell 'set-x! 4)
651
(define (send obj . args)
652
(let ((first-eval (apply obj (list (car args)))))
653
(if (null? (cdr args))
655
(apply first-eval (cdr args)))))
657
You can see that `send' passes the message to the object, making sure
658
that things are evaluated the proper number of times. You can now type:
660
(define c2 (MAKE-CELL 0 0 "red" 10 7 9))
667
(send c2 'set-color! "green")
676
This is the simplest way of implementing objects in Scheme, but it
677
does not really allow for full _object-oriented programming_ (for
678
example, there is no inheritance). But it is useful for _object-based
681
Guile comes with a couple more complete object-oriented extensions to
682
Scheme: these are part of slib (*note Object: (slib)Object. and *note
683
Yasos: (slib)Yasos.).
685
---------- Footnotes ----------
687
(1) To get started, look at the books `Simply Scheme' and `The Little
688
Schemer' from that list.
691
File: guile-tut.info, Node: Guile in a Library, Next: Regular Expression Support, Prev: Using Guile to program in Scheme, Up: Top
696
In the previous chapters Guile was used to write programs entirely in
697
Scheme, and no C code was seen; but I have been claiming _ad nauseam_
698
that Guile is an _extension_ language. Here we see how that is done,
699
and how that can be useful.
705
* How to get started with libguile::
706
* More interesting programming with libguile::
710
File: guile-tut.info, Node: Two world views, Next: What is libguile, Up: Guile in a Library
715
In this manual, I usually jump into examples and explain them as you
716
type in the code; here I will digress and ramble for a few paragraphs to
717
set some concepts straight, and then let you type (or paste) in fun
720
In 1995, I implemented a large program, "Gnudl", using Guile quite
721
extensively. In the design phase of Gnudl, I found I had to make a
722
choice: should the fundamental data structures be C or Scheme data
725
Guile allows C to see its data structures (scalar types, lists,
726
vectors, strings ...). C also allows Guile to see its data structures.
727
As a large program designer, you have to decide which of those
728
capabilities to use. You have two main choices:
730
1. You can write your software mostly in Scheme. In this case, your C
731
software will mostly parse the Scheme code with Guile calls, and
732
provide some new primitive procedures to be used by Scheme. This
735
2. You can write your software mostly in C, occasionally allowing
736
Scheme code to be parsed by Guile, either to allow the user to
737
modify data structures, or to parse a configuration file, ...
739
Mixing the two approaches seems unwise: the overall layout would be
740
confusing. But who knows? There might be problems that are best solved
741
by a hybrid approach. Please let me know if you think of such a
744
If you use the former approach, we will say that the "master world"
745
is Scheme, and the C routines serve Scheme and access Scheme data
746
structures. In the latter case, the master world is C, and Scheme
747
routines serve the C code and access C data structures.
749
In both approaches the `libguile.a' library is the same, but a
750
predominantly different set of routines will be used. When we go
751
through examples of libguile use, we will point out which is the master
752
world in order to clarify these two approaches.
755
File: guile-tut.info, Node: What is libguile, Next: How to get started with libguile, Prev: Two world views, Up: Guile in a Library
760
"Libguile" is the library which allows C programs to start a Scheme
761
interpreter and execute Scheme code. There are also facilities in
762
libguile to make C data structures available to Scheme, and vice versa.
764
The interface provided by the libguile C library is somewhat specific
765
to the implementation of the Scheme interpreter. This low-level
766
libguile interface is usually referred to as the `scm_' interface,
767
since its public calls (API) all have the `scm_' prefix.
769
There is also a higher-level libguile interface, which is usually
770
referred to as the `gh_' interface (libGuile High). Its public calls
771
all have the `gh_' prefix. The `gh_' library interface is designed to
772
hide the implementation details, thus making it easier to assimilate
773
and portable to other underlying Scheme implementations.
775
People extending Guile by adding bindings to C libraries (like OpenGL
776
or Rx) are encouraged to use the `gh_' interface, so their work will be
777
portable to other Scheme systems. The `gh_' interface should be more
778
stable, because it is simpler.
780
The `scm_' interface is necessary if you want to poke into the
781
innards of Scheme data structures, or do anything else that is not
782
offered by the `gh_' interface. It is not covered in this tutorial,
783
but is covered extensively in *Note Data Representation in Guile:
784
(guile)Data representation.
786
This chapter gives a gentle introduction to the `gh_' interface,
787
presenting some _hello world_-style programs which I wrote while
788
teaching myself to use libguile.
790
The `Guile Programmer's Manual' gives more examples of programs
791
written using libguile, illustrating diverse applications. You can also
792
consult my _Gnudl_ documentation at
793
`http://nis-www.lanl.gov/~rosalia/mydocs/' to see a large scale project
794
that uses C and Scheme code together.
797
File: guile-tut.info, Node: How to get started with libguile, Next: More interesting programming with libguile, Prev: What is libguile, Up: Guile in a Library
799
4.3 How to get started with libguile
800
====================================
802
Here is an elementary first program, `learn0', to get going with
803
libguile. The program (which uses Scheme as a master world) is in a
804
single source file, `learn0.c':
806
/* test the new libgh.a (Guile High-level library) with a trivial
811
#include <guile/gh.h>
813
void main_prog(int argc, char *argv[]);
815
main(int argc, char *argv[])
817
gh_enter(argc, argv, main_prog);
820
void main_prog(int argc, char *argv[])
825
gh_eval_str("(display \"hello Guile\")");
826
gh_eval_str("(newline)");
828
/* for fun, evaluate some simple Scheme expressions here */
829
gh_eval_str("(define (square x) (* x x))");
830
gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
831
gh_eval_str("(square 9)");
833
/* now sit in a Scheme eval loop: I input the expressions, have
834
Guile evaluate them, and then get another expression. */
836
fputs("learn0> ", stdout);
837
while (fgets(input_str, 199, stdin) != NULL) {
838
gh_eval_str(input_str);
839
fputs("\nlearn0> ", stdout);
845
If you name this program `learn0.c', it can now be compiled with:
846
gcc -g -c learn0.c -o learn0.o
847
gcc -o learn0 learn0.o -lguile -lm
849
The program is simple: it creates a Scheme interpreter, passes a
850
couple of strings to it that define new Scheme functions `square' and
851
`factorial', and then a couple of strings that invoke those functions.
853
It then goes into a read-eval-print-loop (REPL), so you could type
854
one-line Scheme expressions to it and have them evaluated. For example:
855
<shell-prompt> ./learn0
857
learn0> (display (sin 1.3))
859
learn0> (display (fact 10))
864
You should notice the key steps involved in this `learn0' program:
866
1. `#include <guile/gh.h>'
868
2. You need to invoke the initialization routine `gh_enter()'. This
869
starts up a Scheme interpreter, handling many
870
implementation-specific details.
872
3. Your main() function should be almost empty: the real main program
873
goes in a separate function main_prog() which is passed to
874
gh_enter(). This rather arcane convention is due to the way
875
Guile's garbage collector works: the whole program has to run in
876
the dynamic context of `gh_enter()'.
878
4. You pass strings to the Scheme interpreter with the `gh_eval_str()'
881
5. You link your program with `-lguile'.
884
File: guile-tut.info, Node: More interesting programming with libguile, Next: Further examples, Prev: How to get started with libguile, Up: Guile in a Library
886
4.4 More interesting programming with libguile
887
==============================================
889
The `learn0' program shows how you can invoke Scheme commands from a C
890
program. This is not such a great achievement: the same could have
891
been done by opening a pipe to SCM or any other Scheme interpreter.
893
A true extension language must allow "callbacks". Callbacks allow
894
you to write C routines that can be invoked as Scheme procedures, thus
895
adding new primitive procedures to Scheme. This also means that a
896
Scheme procedure can modify a C data structure.
898
Guile allows you to define new Scheme procedures in C, and provides a
899
mechanism to go back and forth between C and Scheme data types.
901
Here is a second program, `learn1', which demonstrates these
902
features. It is split into three source files: `learn1.c',
903
`c_builtins.h' and `c_builtins.c'. I am including the code here.
905
Notice that `learn1' uses a Scheme master world, and the C routines
906
in `c_builtins.c' are simply adding new primitives to Scheme.
913
* What learn1 is doing::
914
* Compiling and running learn1::
917
File: guile-tut.info, Node: learn1.c, Next: c_builtins.h, Up: More interesting programming with libguile
925
#include <guile/gh.h>
927
#include "c_builtins.h"
929
void main_prog(int argc, char *argv[]);
931
main(int argc, char *argv[])
933
gh_enter(argc, argv, main_prog);
936
void main_prog(int argc, char *argv[])
938
char input_str[200]; /* ugly hack: assume strlen(line) < 200 */
941
/* for fun, evaluate some simple Scheme expressions here */
942
gh_eval_str("(define (square x) (* x x))");
943
gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
944
gh_eval_str("(square 9)");
945
gh_eval_str("(fact 100)");
947
/* now try to define some new builtins, coded in C, so that they are
948
available in Scheme. */
949
gh_new_procedure1_0("c-factorial", c_factorial);
950
gh_new_procedure1_0("c-sin", c_sin);
951
gh_new_procedure1_0("v-t", vector_test);
953
/* now sit in a Scheme eval loop: I input the expressions, have
954
Guile evaluate them, and then get another expression. */
956
fputs("learn1> ", stdout);
958
if (gets(input_str) == NULL) {
961
gh_eval_str(input_str);
962
fputs("learn1> ", stdout);
970
File: guile-tut.info, Node: c_builtins.h, Next: c_builtins.c, Prev: learn1.c, Up: More interesting programming with libguile
975
Here is `c_builtins.h':
976
/* builtin function prototypes */
978
#include <guile/gh.h>
980
SCM c_factorial(SCM n);
982
SCM vector_test(SCM s_length);
985
File: guile-tut.info, Node: c_builtins.c, Next: What learn1 is doing, Prev: c_builtins.h, Up: More interesting programming with libguile
990
Here is `c_builtins.c':
994
#include <guile/gh.h>
996
#include "c_builtins.h"
998
/* this is a factorial routine in C, made to be callable by Scheme */
999
SCM c_factorial(SCM s_n)
1002
unsigned long result = 1, n;
1004
n = gh_scm2ulong(s_n);
1007
for (i = 1; i <= n; ++i) {
1011
return gh_ulong2scm(result);
1014
/* a sin routine in C, callable from Scheme. it is named c_sin() to
1015
distinguish it from the default Scheme sin function */
1018
double x = gh_scm2double(s_x);
1020
return gh_double2scm(sin(x));
1023
/* play around with vectors in Guile: this routine creates a vector of
1024
the given length, initializes it all to zero except element 2 which
1026
SCM vector_test(SCM s_length)
1030
c_length = gh_scm2ulong(s_length);
1031
printf("requested length for vector: %ld\n", gh_scm2ulong(s_length));
1033
/* create a vector */
1034
xvec = gh_make_vector(s_length, gh_double2scm(0.0));
1035
/* set the second element in it */
1036
gh_vector_set_x(xvec, gh_int2scm(2), gh_double2scm(1.9));
1042
File: guile-tut.info, Node: What learn1 is doing, Next: Compiling and running learn1, Prev: c_builtins.c, Up: More interesting programming with libguile
1044
4.4.4 What learn1 is doing
1045
--------------------------
1047
If you compare learn1 to learn0, you will find that learn1 uses a new
1048
Guile construct: the function `gh_new_procedure()', and its siblings:
1050
/* now try to define some new builtins, coded in C, so that they are
1051
available in Scheme. */
1052
gh_new_procedure1_0("c-factorial", c_factorial);
1053
gh_new_procedure1_0("c-sin", c_sin);
1054
gh_new_procedure1_0("v-t", vector_test);
1056
It is clear that `gh_new_procedure()' adds a new builtin routine
1057
written in C which can be invoked from Scheme. We can now revise our
1058
checklist for programming with libguile, so it includes adding
1061
1. `#include <guile/gh.h>'
1063
2. You need to invoke the initialization routine `gh_enter()'. This
1064
starts up a Scheme interpreter, handling many details.
1066
3. Your main() function should be almost empty: the real main program
1067
goes in a separate function main_prog() which is passed to
1068
gh_enter(). This rather arcane convention is due to the way
1069
Guile's garbage collector works: the whole program has to run in
1070
the dynamic context of `gh_enter()'.
1072
4. You pass strings to the Scheme interpreter with the `gh_eval_str()'
1075
5. *[new]* You can now define new builtin Scheme functions; i.e.
1076
define new builtin Scheme functions, with the `gh_new_procedure()'
1079
6. You pass strings to the Scheme interpreter with the
1080
`gh_eval_str()' routine.
1082
7. You link your program with `-lguile'.
1084
I breezed by the issue of how to write your C routines that are
1085
registered to be called from Scheme. This is non-trivial, and is
1086
discussed at length in the `Guile Programmer's Manual'.
1089
File: guile-tut.info, Node: Compiling and running learn1, Prev: What learn1 is doing, Up: More interesting programming with libguile
1091
4.4.5 Compiling and running learn1
1092
----------------------------------
1094
gcc -g -c learn1.c -o learn1.o
1095
gcc -g -c c_builtins.c -o c_builtins.o
1096
gcc -o learn1 learn1.o c_builtins.o -lguile -lm
1098
If you run `learn1', it will prompt you for a one-line Scheme
1099
expression, just as `learn0' did. The difference is that you can use
1100
the new C builtin procedures (`c-factorial', `c-sin', `v-t').
1102
<shell-prompt> ./learn1
1105
learn1> (display (c-factorial 6))
1107
learn1> (display (c-factorial 20))
1109
learn1> (display (c-factorial 100))
1111
learn1> (display (c-sin 1.5))
1113
learn1> (display (v-t 10))
1114
requested length for vector: 10
1115
#(0.0 0.0 1.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0)
1116
learn1> (display (v-t 15))
1117
requested length for vector: 15
1118
#(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)
1122
As you see, taking `(c-factorial 100)' does not use bignumbers and
1123
returns a bogus answer.
1126
File: guile-tut.info, Node: Further examples, Prev: More interesting programming with libguile, Up: Guile in a Library
1128
4.5 Further examples
1129
====================
1131
Further "idealized" examples are included in the `doc/examples/c'
1132
distribution. They include programs to:
1134
* Parse a startup file (C is the master world).
1136
* Set up initial conditions for an n-body simulation (C is the master
1139
* Implement a Scheme interpreter with all of Guile's goodies, _plus_
1140
the readline library _and_ a fast Fourier transform routine
1141
provided in C (Scheme is the master world).
1144
File: guile-tut.info, Node: Regular Expression Support, Next: UNIX System Programming, Prev: Guile in a Library, Up: Top
1146
5 Regular Expression Support
1147
****************************
1150
File: guile-tut.info, Node: UNIX System Programming, Next: Where to find more Guile/Scheme resources, Prev: Regular Expression Support, Up: Top
1152
6 UNIX System Programming
1153
*************************
1156
File: guile-tut.info, Node: Where to find more Guile/Scheme resources, Next: Concept Index, Prev: UNIX System Programming, Up: Top
1158
7 Where to find more Guile/Scheme resources
1159
*******************************************
1162
File: guile-tut.info, Node: Concept Index, Next: Procedure and Macro Index, Prev: Where to find more Guile/Scheme resources, Up: Top