guile-tut.texi 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. \input texinfo @c -*-texinfo-*-
  2. @c %**start of header
  3. @setfilename guile-tut.info
  4. @settitle Guile Tutorial
  5. @set guile-tut
  6. @include version.texi
  7. @dircategory The Algorithmic Language Scheme
  8. @direntry
  9. * Guile Tutorial: (guile-tut). The Guile tutorial.
  10. @end direntry
  11. @setchapternewpage off
  12. @c Choices for setchapternewpage are {on,off,odd}.
  13. @paragraphindent 2
  14. @c %**end of header
  15. @iftex
  16. @finalout
  17. @c DL: lose the egregious vertical whitespace, esp. around examples
  18. @c but paras in @defun-like things don't have parindent
  19. @parskip 4pt plus 1pt
  20. @end iftex
  21. @titlepage
  22. @title Guile Tutorial
  23. @subtitle For use with Guile @value{VERSION}
  24. @subtitle Last updated @value{UPDATED}
  25. @author Mark Galassi
  26. @author Cygnus Solutions and Los Alamos National Laboratory
  27. @author @email{rosalia@@nis.lanl.gov}
  28. @page
  29. @vskip 0pt plus 1filll
  30. Copyright @copyright{} 1997, 1998, 2004, 2006 Free Software Foundation
  31. Permission is granted to make and distribute verbatim copies of
  32. this manual provided the copyright notice and this permission notice
  33. are preserved on all copies.
  34. Permission is granted to copy and distribute modified versions of this
  35. manual under the conditions for verbatim copying, provided that the entire
  36. resulting derived work is distributed under the terms of a permission
  37. notice identical to this one.
  38. Permission is granted to copy and distribute translations of this manual
  39. into another language, under the above conditions for modified versions,
  40. except that this permission notice may be stated in a translation approved
  41. by the author.
  42. @end titlepage
  43. @ifnottex
  44. @node Top
  45. @top Guile Tutorial
  46. @end ifnottex
  47. @ifinfo
  48. This file gives a tutorial introduction to Guile.
  49. Copyright (C) 1997, 2004, 2006 Free Software Foundation
  50. Permission is granted to make and distribute verbatim copies of
  51. this manual provided the copyright notice and this permission notice
  52. are preserved on all copies.
  53. @ignore
  54. Permission is granted to process this file through TeX and print the
  55. results, provided the printed document carries copying permission
  56. notice identical to this one except for the removal of this paragraph
  57. (this paragraph not being relevant to the printed manual).
  58. @end ignore
  59. Permission is granted to copy and distribute modified versions of this
  60. manual under the conditions for verbatim copying, provided that the entire
  61. resulting derived work is distributed under the terms of a permission
  62. notice identical to this one.
  63. Permission is granted to copy and distribute translations of this manual
  64. into another language, under the above conditions for modified versions,
  65. except that this permission notice may be stated in a translation approved
  66. by the author.
  67. @end ifinfo
  68. @menu
  69. * Jump Start::
  70. * Introduction::
  71. * Using Guile to program in Scheme::
  72. * Guile in a Library::
  73. * Regular Expression Support::
  74. * UNIX System Programming::
  75. * Where to find more Guile/Scheme resources::
  76. * Concept Index::
  77. * Procedure and Macro Index::
  78. * Variable Index::
  79. * Type Index::
  80. @end menu
  81. @node Jump Start
  82. @chapter Jump Start
  83. @noindent
  84. Before giving an overview of Guile, I present some simple commands and
  85. programs that you can type to get going immediately.
  86. Start by invoking the Guile interpreter. Usually you do this by just
  87. typing @code{guile}. Then type (or paste) the following expressions at
  88. the prompt; the interpreter's response is preceded (in this manual) by
  89. @result{}.
  90. @example
  91. <shell-prompt> guile
  92. @end example
  93. @lisp
  94. (+ 20 35)
  95. @result{} 55
  96. (define (recursive-factorial n)
  97. (if (zero? n)
  98. 1
  99. (* n (recursive-factorial (- n 1)))))
  100. (recursive-factorial 5)
  101. @result{} 120
  102. (quit)
  103. @end lisp
  104. In this example we did some simple arithmetic @code{(+ 20 35)} and got
  105. the answer @code{55}. Then we coded the classic (and rather wasteful)
  106. factorial algorithm and computed the factorial of @code{55}. Finally we
  107. quit with @code{(quit)}.
  108. @cindex bignumbers
  109. We can find out about some of Scheme's nice features by asking for the
  110. factorial of some big number, say @code{500}. On some systems the
  111. correct answer will be returned (I do not indicate calling and leaving
  112. the guile session anymore).
  113. @lisp
  114. (recursive-factorial 500)
  115. @result{} 1220136825991110068701238785423046926253574342803192842192413588
  116. 3858453731538819976054964475022032818630136164771482035841633787
  117. 2207817720048078520515932928547790757193933060377296085908627042
  118. 9174547882424912726344305670173270769461062802310452644218878789
  119. 4657547771498634943677810376442740338273653974713864778784954384
  120. 8959553753799042324106127132698432774571554630997720278101456108
  121. 1188373709531016356324432987029563896628911658974769572087926928
  122. 8712817800702651745077684107196243903943225364226052349458501299
  123. 1857150124870696156814162535905669342381300885624924689156412677
  124. 5654481886506593847951775360894005745238940335798476363944905313
  125. 0623237490664450488246650759467358620746379251842004593696929810
  126. 2226397195259719094521782333175693458150855233282076282002340262
  127. 6907898342451712006207714640979456116127629145951237229913340169
  128. 5523638509428855920187274337951730145863575708283557801587354327
  129. 6888868012039988238470215146760544540766353598417443048012893831
  130. 3896881639487469658817504506926365338175055478128640000000000000
  131. 0000000000000000000000000000000000000000000000000000000000000000
  132. 00000000000000000000000000000000000000000000000
  133. @end lisp
  134. The result is an example of Scheme's @emph{bignumbers}. However, there
  135. are operating environments that provide (by default) too little stack
  136. space. They will instead produce an error message like this:
  137. @lisp
  138. (recursive-factorial 500)
  139. @print{}
  140. ERROR: Stack overflow
  141. ABORT: (stack-overflow)
  142. @end lisp
  143. Rather than enlarging the system's stack, we can implement the algorithm
  144. such that it does not consume increasing stack space. This is called a
  145. @emph{tail recursive} implementation. The following definition is tail
  146. recursive and so should work on all systems.
  147. @lisp
  148. (define (tail-recursive-factorial n)
  149. (define (loop k l)
  150. (if (zero? k) l
  151. (loop (- k 1) (* k l))))
  152. (loop n 1))
  153. (tail-recursive-factorial 500)
  154. @result{} 1220136825991110068701238785423046926253574342803192842192413588
  155. ;; ... skipped
  156. @end lisp
  157. This is the most basic use of Guile: a simple Scheme interpreter. In
  158. the rest of this tutorial I will show you how Guile has many facets: it
  159. is also an @emph{extensible} interpreter (to which many features can be
  160. easilly added) and an @emph{embeddable} interpreter (which can be
  161. invoked from your C programs).
  162. @node Introduction
  163. @chapter Introduction
  164. @noindent
  165. @dfn{Guile} (which can stand for @emph{GNU Ubiquitous Intelligent
  166. Language Extension}) is the GNU extension language. It started out as
  167. an embeddable Scheme interpreter, and has rapidly evolved into a
  168. kitchen-sink package including a standalone Scheme interpreter, an
  169. embeddable Scheme interpreter, several graphics options, other languages
  170. that can be used along with Scheme (for now just @emph{ctax} and
  171. @emph{Tcl}), and hooks for much more.
  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. @node What are scripting and extension languages
  178. @section What are scripting and extension languages
  179. @cindex scripting languages
  180. @cindex extension languages
  181. A @dfn{scripting language} is a programming language which serves as
  182. glue between other system programs. In the UNIX world, the traditional
  183. scripting language is the @emph{Bourne shell}, which allows many UNIX
  184. commands to be executed in sequence, or in a pipeline. Traditional UNIX
  185. commands are cleverly written to work well when put together in a
  186. script.
  187. Other examples of UNIX scripting languages are AWK, Perl, Scsh (the
  188. Scheme Shell: a Scheme interpreter enhanced to do good scripting),
  189. Python, Tcl, Java @dots{}
  190. @cindex scripting languages - examples
  191. UNIX programmers noticed, more than 25 years ago, that scripting
  192. languages can do serious work, so the Bourne shell was written to have
  193. variables, operators and control structures, just like a full-featured
  194. programming language.
  195. @cindex Bourne shell
  196. What scripting languages have, that traditional programming languages do
  197. not, is the ability to easily run an external program (or a pipeline of
  198. external programs) and use the returned values and output from that
  199. program in useful ways.
  200. An @dfn{extension language} is a programming language interpreter
  201. offered by an application program, so that users can write macros or
  202. even full-fledged programs to extend the original application.
  203. Extension languages have a C interface (it is usually C, but it could be
  204. any other compiled language), and can be given access to the C data
  205. structures. Likewise, there are C routines to access the extension
  206. language data structures.
  207. Extension languages abound in the software world, even though the name
  208. @emph{extension language} is seldom used. Examples are:
  209. @cindex extension languages - examples
  210. @itemize @bullet
  211. @item
  212. Emacs Lisp, the language used to program and customize GNU Emacs.
  213. @cindex Emacs Lisp
  214. @item
  215. Tcl, John Ousterhout's general-purpose scripting and extension language.
  216. @cindex Tcl
  217. @item
  218. The Lotus 1-2-3 macro language (any spreadsheet macro language,
  219. really). I mention this one first because it is a classic, even though
  220. it is seldom used any more.
  221. @cindex Lotus 1-2-3
  222. @item
  223. Other spreadsheet and database macro languages.
  224. @item
  225. The Dominion empire-style game's @emph{exec} files.
  226. @cindex Dominion
  227. @item
  228. Any syntax for a ".*rc" file you might have used. Almost all programs
  229. end up parsing some kind of startup or configuration file. The syntax
  230. for those can get pretty involved, thus justifying calling them
  231. "extension languages". The @emph{fvwm} window manager, for example,
  232. parses a rather elaborate @file{.fvwmrc} file.
  233. @item
  234. Brent Benson's libscheme.a, an embeddable Scheme interpreter.
  235. @cindex Benson, Brent
  236. @cindex libscheme
  237. @item
  238. Guile, the GNU extension language, which is the subject of this
  239. tutorial.
  240. @end itemize
  241. One lesson we can learn from looking at classical large software
  242. applications is that "writers of large programs" always end up throwing
  243. in some kind of parser for configuration or scripting.
  244. Of the examples listed above, Emacs Lisp, Tcl, Libscheme and Guile have
  245. an important property: they are not added as an afterthought for a
  246. specific application. They are general-purpose languages which a user
  247. can learn (even in college courses) and then use to customize the
  248. application program.
  249. This is a recent and (in my opinion) very exciting direction in
  250. large-program software engineering: program designers can link in the
  251. Guile or Tcl library from the very beginning, and tell their users "You
  252. want to customize this program? Just use Scheme (or Tcl, or whatever
  253. language), which you already know!"
  254. @cindex large programs
  255. @node History of Guile and its motivations
  256. @section History of Guile and its motivations
  257. A few separate threads of events led to the development of Guile.
  258. In the fall of 1994, Richard Stallman, director of the GNU project,
  259. posted an article with the subject "Why you should not use Tcl", in
  260. which he argued that Tcl is inadequate as an extension language. This
  261. generated a flurry of flames (available in the hypermail archive
  262. (@url{http://www.vanderburg.org/Tcl/war/}) @strong{The Tcl War}).
  263. @cindex Stallman, Richard
  264. @cindex GNU project
  265. @cindex Tcl
  266. The result was that Stallman then proposed his design for the GNU
  267. Extension Language, first called GEL and then renamed Guile. The
  268. discussion triggered by that article is also available in a hypermail
  269. archive, @url{http://www.vanderburg.org/Tcl/war2/}.
  270. One interesting feature of this GNU Extension Language plan was that
  271. users should have a @emph{choice} of languages to use in extending their
  272. program. The basic language would be a slightly modified Scheme, and
  273. translators would be written to convert other languages (like Tcl,
  274. Python, Perl, C-like languages @dots{}) into Scheme.
  275. Tom Lord started working on this project immediately, taking Aubrey
  276. Jaffer's small and portable implementation of Scheme, SCM, and making it
  277. into an embeddable interpreter: callable from C and allowing new Scheme
  278. procedures to be written in C.
  279. @cindex Lord, Tom
  280. @cindex Jaffer, Aubrey
  281. In the spring of 1995, the guile-ii snapshot was released. This made it
  282. possible to start writing code in C and Scheme using the guile
  283. facilities.
  284. The guile-iii snapshot was released the summer of 1995, and it had fixed
  285. enough problems so that the access to Scheme data structures from C was
  286. almost complete.
  287. After this, Cygnus Support added many features to Guile and finished
  288. implementing others, so that Guile acquired thread support, a regular
  289. expression matcher, a Tk interface, an interface to the SGI OpenGL
  290. graphics system, an @emph{applet} formalism, and some other packages.
  291. This was all in the Cygnus Guile r0.3 and r0.4 releases.
  292. @cindex Cygnus Support
  293. Meanwhile, Tom Lord left the project after having produced a divergent
  294. version of Guile: 1.0b2. The Free Software Foundation hired Jim Blandy
  295. to coordinate Guile development. The FSF released its first version of
  296. Guile in January 1997. In the future, many of the Cygnus packages will
  297. be re-integrated into Guile.
  298. @cindex Blandy, Jim
  299. @cindex Free Software Foundation
  300. @node How to characterize Guile
  301. @section How to characterize Guile
  302. I have already mentioned that Guile has become a kitchen sink package;
  303. here you can see how Guile freely takes new commands and constructs from
  304. the portable Scheme library @emph{slib}, the @emph{Tk} widget set, a
  305. posix library (useful for UNIX systems programming), the regular
  306. expression library @emph{rx}, and many more @dots{}
  307. @cindex slib
  308. @cindex Tk
  309. @cindex POSIX
  310. @c @cindex OpenGL
  311. @cindex rx
  312. So Guile has many more primitive procedures available to it than those
  313. specified in @ref{Standard Procedures, Revised(5) Report on the
  314. Algorithmic Language Scheme, , r5rs, Revised(5) Report on the
  315. Algorithmic Language Scheme}. On top of that, Guile will interpret
  316. almost all standard Scheme programs. The only incompatible difference
  317. between the basic Guile language and R5RS Scheme is that Guile is case
  318. sensitive, whereas R5RS is case insensitive. We hope that few people
  319. have written Scheme programs that depend on case insensitivity.
  320. @cindex case sensitivity
  321. @cindex Revised(5) Report on the Algorithmic Language Scheme
  322. @cindex report on Scheme
  323. @cindex Scheme language - report
  324. @cindex Scheme language - definition
  325. Here is a possible view of the @emph{sum of the parts} in Guile:
  326. @cindex extensions to standard Scheme
  327. @cindex extensions to R5RS
  328. @cindex Scheme extensions
  329. @example
  330. guile = standard Scheme (R5RS)
  331. PLUS extensions to R5RS offered by SCM
  332. PLUS some extra primitives offered by Guile (catch/throw)
  333. PLUS portable Scheme library (SLIB)
  334. PLUS embeddable Scheme interpreter library (libguile)
  335. PLUS Tk toolkit
  336. PLUS threads
  337. PLUS Posix library
  338. @c PLUS OpenGL library (mesa)
  339. @c PLUS OpenGL toolkit (glut)
  340. PLUS Regular expression library (rx)
  341. @c PLUS Applet formalism
  342. PLUS Tcl library
  343. @end example
  344. @node Using Guile to program in Scheme
  345. @chapter Using Guile to program in Scheme
  346. @cindex Scheme programming tutorial
  347. @cindex tutorial on Scheme programming
  348. In this section I give a tutorial introduction to programming in Scheme,
  349. with a slant toward the interesting things that can be done in Guile.
  350. @c Applets are so @emph{chic} that they get their own section, but this
  351. This section will try to touch on many of the interesting and cool
  352. aspects of Guile, showing you how new types of problems can be solved
  353. with Guile. Note that using Guile as a library with @code{libguile.a}
  354. is described in its own chapter (@pxref{Guile in a Library}). Also note
  355. that some small examples are given in @ref{Jump Start}.
  356. To get started you need to know how to program in @dfn{Scheme} (a
  357. dialect of LISP). Fortunately Scheme is a small, clean language and is
  358. not hard to learn. It is also used in many undergraduate courses to
  359. introduce computer programming.
  360. @cindex lisp dialects
  361. I will not try to teach you Scheme here (although you might end up
  362. learning by example), since there are many good books on the subject,
  363. listed in @ref{Where to find more Guile/Scheme resources}. @footnote{To
  364. get started, look at the books @cite{Simply Scheme} and @cite{The Little
  365. Schemer} from that list.}
  366. @subsection Hello World
  367. @cindex hello world
  368. Our first program is the typical Scheme "hello world" program. Put the
  369. following code in a file called @code{hello.scm} (this can be find in
  370. @file{examples/scheme/hello.scm}).
  371. @smalllisp
  372. #!/usr/local/bin/guile -s
  373. !#
  374. (display "hello world")
  375. (newline)
  376. @end smalllisp
  377. Then run guile on it. One way to do so is to start up guile and load
  378. this file:
  379. @smallexample
  380. <shell-prompt> @kbd{guile}
  381. guile> @kbd{(load "hello")}
  382. @end smallexample
  383. Another way is to make the file executable and execute it directly.
  384. Notice how Guile recognizes a @code{-s} option which tells it to run a
  385. script and then exit. Guile also has a new type of block comment
  386. enclosed by @code{#!} and @code{!#}, so that you can make executable
  387. Scheme scripts with the standard UNIX @code{#!} mechanism.
  388. In the given example, the first line is used to invoke the Guile
  389. interpreter (make sure you correct the path if you installed Guile in
  390. something other than /usr/local/bin). Once Guile is invoked on this
  391. file, it will understand that the first line is a comment. The comment
  392. is then terminated with @code{!#} on the second line so as to not
  393. interfere with the execution mechanism.
  394. @subsection A bunch of operations in Scheme
  395. Here is some code you can type at the @code{guile>} prompt to see some
  396. of the Scheme data types at work (mostly lists and vectors). I have
  397. inserted brief comments @emph{before} each line of code explaining what
  398. happens.
  399. @smalllisp
  400. ;; @r{make a list and bind it to the symbol @code{ls}}
  401. guile> @kbd{(define ls (list 1 2 3 4 5 6 7))}
  402. @result{}
  403. ;; @r{display the list}
  404. guile> @kbd{ls}
  405. @result{} (1 2 3 4 5 6 7)
  406. ;; @r{ask if @code{ls} is a vector; @code{#f} means it is not}
  407. guile> @kbd{(vector? ls)}
  408. @result{} #f
  409. ;; @r{ask if @code{ls} is a list; @code{#t} means it is}
  410. guile> @kbd{(list? ls)}
  411. @result{} #t
  412. ;; @r{ask for the length of @code{ls}}
  413. guile> @kbd{(length ls)}
  414. @result{} 7
  415. ;; @r{pick out the first element of the list}
  416. guile> @kbd{(car ls)}
  417. @result{} 1
  418. ;; @r{pick the rest of the list without the first element}
  419. guile> @kbd{(cdr ls)}
  420. @result{} (2 3 4 5 6 7)
  421. ;; @r{this should pick out the 3rd element of the list}
  422. guile> @kbd{(car (cdr (cdr ls)))}
  423. @result{} 3
  424. ;; @r{a shorthand for doing the same thing}
  425. guile> @kbd{(caddr ls)}
  426. @result{} 3
  427. ;; @r{append the given list onto @code{ls}, print the result}
  428. ;; @r{@strong{NOTE:} the original list @code{ls} is @emph{not} modified}
  429. guile> @kbd{(append ls (list 8 9 10))}
  430. @result{} (1 2 3 4 5 6 7 8 9 10)
  431. guile> @kbd{(reverse ls)}
  432. @result{} (7 6 5 4 3 2 1)
  433. ;; @r{ask if 12 is in the list --- it obviously is not}
  434. guile> @kbd{(memq 12 ls)}
  435. @result{} #f
  436. ;; @r{ask if 4 is in the list --- returns the list from 4 on.}
  437. ;; @r{Notice that the result will behave as true in conditionals}
  438. guile> @kbd{(memq 4 ls)}
  439. @result{} (4 5 6 7)
  440. ;; @r{an @code{if} statement using the aforementioned result}
  441. guile> @kbd{(if (memq 4 ls)
  442. (display "hey, it's true!\n")
  443. (display "dude, it's false\n"))}
  444. @print{hey, it's true!}
  445. @result{}
  446. guile> @kbd{(if (memq 12 ls)
  447. (display "hey, it's true!\n")
  448. (display "dude, it's false\n"))}
  449. @print{dude, it's false}
  450. @result{}
  451. guile> @kbd{(memq 4 (reverse ls))}
  452. @result{} (4 3 2 1)
  453. ;; @r{make a smaller list @code{ls2} to work with}
  454. guile> @kbd{(define ls2 (list 2 3 4))}
  455. ;; @r{make a list in which the function @code{sin} has been}
  456. ;; @r{applied to all elements of @code{ls2}}
  457. guile> @kbd{(map sin ls2)}
  458. @result{} (0.909297426825682 0.141120008059867 -0.756802495307928)
  459. ;; @r{make a list in which the squaring function has been}
  460. ;; @r{applied to all elements of @code{ls}}
  461. guile> @kbd{(map (lambda (n) (* n n)) ls)}
  462. @result{} (1 4 9 16 25 36 49)
  463. @end smalllisp
  464. @smalllisp
  465. ;; @r{make a vector and bind it to the symbol @code{v}}
  466. guile> @kbd{(define v '#(1 2 3 4 5 6 7))}
  467. guile> @kbd{v}
  468. @result{} #(1 2 3 4 5 6 7)
  469. guile> @kbd{(vector? v)}
  470. @result{} #t
  471. guile> @kbd{(list? v)}
  472. @result{} #f
  473. guile> @kbd{(vector-length v)}
  474. @result{} 7
  475. ;; @r{vector-ref allows you to pick out elements by index}
  476. guile> @kbd{(vector-ref v 2)}
  477. @result{} 3
  478. ;; @r{play around with the vector: make it into a list, reverse}
  479. ;; @r{the list, go back to a vector and take the second element}
  480. guile> @kbd{(vector-ref (list->vector (reverse (vector->list v))) 2)}
  481. @result{} 5
  482. ;; @r{this demonstrates that the entries in a vector do not have}
  483. ;; @r{to be of uniform type}
  484. guile> @kbd{(vector-set! v 4 "hi there")}
  485. @result{} "hi there"
  486. guile> @kbd{v}
  487. @result{} #(1 2 3 4 "hi there" 6 7)
  488. @end smalllisp
  489. @subsection Using recursion to process lists
  490. @cindex recursion
  491. @cindex list processing
  492. Here are some typical examples of using recursion to process a list.
  493. @smalllisp
  494. ;; @r{this is a rather trivial way of reversing a list}
  495. (define (my-reverse l)
  496. (if (null? l)
  497. l
  498. (append (my-reverse (cdr l)) (list (car l)))))
  499. (my-reverse '(27 32 33 40))
  500. @result{} (40 33 32 27)
  501. @end smalllisp
  502. @subsection Processing matrices
  503. Suppose you have a matrix represented as a list of lists:
  504. @smalllisp
  505. (define m
  506. (list
  507. (list 7 2 1 3 2 8 5 3 6)
  508. (list 4 1 1 1 3 8 9 8 1)
  509. (list 5 5 4 8 1 8 2 2 4)))
  510. @end smalllisp
  511. Then you could apply a certain function to each element of the matrix in
  512. the following manner:
  513. @smalllisp
  514. ;; @r{apply the function func to the matrix m element-by-element;}
  515. ;; @r{return a matrix with the result.}
  516. (define (process-matrix m func)
  517. (map (lambda (l)
  518. (map func l))
  519. m))
  520. @end smalllisp
  521. Notice that I have used the Scheme @code{map} procedure because I am
  522. interested in the matrix that results from the application of
  523. @code{func}, rather than in the side effects associated with applying
  524. @code{func}.
  525. This could be invoked with @code{(process-matrix m sin)} or
  526. @code{(process-matrix m (lambda (x) (* x x)))}; for example:
  527. @smalllisp
  528. (process-matrix m (lambda (x) (* x x)))
  529. @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))
  530. @end smalllisp
  531. To print a representation of the matrix, we could define a generalized
  532. routine:
  533. @smalllisp
  534. ;; @r{proc is a procedure to represent the single element,}
  535. ;; @r{row-proc is a procedure that is invoked after each row.}
  536. ;; @r{Example: proc could be (lambda (x) (begin (display x) (display " ")))}
  537. ;; @r{and row-proc could be (lambda (l) (display "\n"))}
  538. (define (represent-matrix m proc row-proc)
  539. (for-each (lambda (l)
  540. (begin
  541. (for-each proc l)
  542. (row-proc l)))
  543. m))
  544. @end smalllisp
  545. @findex represent-matrix
  546. And then invoke it with
  547. @smalllisp
  548. (represent-matrix m
  549. (lambda (x) (begin (display x) (display " ")))
  550. (lambda (l) (begin (display "\n"))))
  551. @print{7 2 1 3 2 8 5 3 6}
  552. @print{4 1 1 1 3 8 9 8 1}
  553. @print{5 5 4 8 1 8 2 2 4}
  554. @end smalllisp
  555. @cindex objects
  556. Now we write a helper routine that uses Scheme @dfn{closures} to make
  557. objects with state that then receive messages to draw little squares.
  558. @cindex closures
  559. @cindex syntactic closures
  560. But let us take it one step at a time. I will start by showing you a
  561. simple example of object in Scheme. The object I make here represents a
  562. cell, which could be a cell in a matrix. The cell responds to commands
  563. to draw itself, to return the next cell, and so forth. @emph{Guile does
  564. not currently have a Tk interface, so I will leave the hooks for
  565. graphical rendering. In a future release of Guile I will add graphical
  566. rendering messages to the cell object.}
  567. @smallexample
  568. ;; @r{cell-object.scm: routines for creating and manipulating cell objects}
  569. ;; @r{(the-x, the-y) is the initial position of the cell.}
  570. ;; @r{the-color is a string representing a color; must be something Tk can grok.}
  571. ;; @r{square-size is the size of the square that gets drawn.}
  572. ;; @r{(sizex, sizey) is the size of the matrix.}
  573. (define (MAKE-CELL the-x the-y the-color square-size sizex sizey)
  574. (define (get-x) the-x)
  575. (define (get-y) the-y)
  576. (define (set-x! new-x)
  577. (set! the-x new-x)
  578. the-x)
  579. (define (set-y! new-y)
  580. (set! the-y new-y)
  581. the-y)
  582. (define (get-color) the-color)
  583. (define (set-color! new-color)
  584. (set! the-color new-color)
  585. the-color)
  586. (define (next!)
  587. (set! the-x (+ the-x 1))
  588. (if (>= the-x sizex)
  589. (begin
  590. (set! the-x 0)
  591. (set! the-y (+ the-y 1))))
  592. (if (>= the-y sizey)
  593. (begin
  594. (display "CELL next!: value of y is too big; not changing it\n")
  595. (set! the-y (- the-y 1))))
  596. (cons the-x the-y))
  597. (define (draw)
  598. (let* ((x0 (* the-x square-size))
  599. (y0 (* the-y square-size))
  600. (x1 (+ x0 square-size))
  601. (y1 (+ y0 square-size)))
  602. (display "I should draw a ")
  603. (display the-color)
  604. (display " rectangle with corners at ")
  605. (display x0) (display y0) (display x1) (display y1)
  606. ))
  607. ;; self is the dispatch procedure
  608. (define (self message)
  609. (case message
  610. ((x) get-x)
  611. ((y) get-y)
  612. ((set-x!) set-x!)
  613. ((set-y!) set-y!)
  614. ((color) get-color)
  615. ((set-color!) set-color!)
  616. ((next!) next!)
  617. ((draw) draw)
  618. (else (error "CELL: Unknown message -> " message))))
  619. ;; and now return the dispatch procedure
  620. self
  621. )
  622. @end smallexample
  623. @cindex cell-object
  624. @findex MAKE-CELL
  625. What does this procedure do? It returns another procedure
  626. (@code{self}) which receives a message (x, y, set-x!, set-y!, @dots{})
  627. and takes an action to return or modify its state. The state consists
  628. of the values of variables @code{the-x}, @code{the-y}, @code{the-color}
  629. and so forth.
  630. Here are some examples of how to use MAKE-CELL and the cell object it
  631. creates:
  632. @smallexample
  633. (define c (MAKE-CELL 0 0 "red" 10 7 9))
  634. ;; @r{retrieve the x and y coordinates}
  635. ((c 'x))
  636. @result{} 0
  637. ((c 'y))
  638. @result{} 0
  639. ;; @r{change the x coordinate}
  640. ((c 'set-x!) 5)
  641. @result{} 5
  642. ((c 'x))
  643. @result{} 5
  644. ;; @r{change the color}
  645. ((c 'color))
  646. @result{} "red"
  647. ((c 'set-color!) "green")
  648. @result{} "green"
  649. ((c 'color))
  650. @result{} "green"
  651. ;; @r{now use the next! message to move to the next cell}
  652. ((c 'next!))
  653. @result{} (6 . 0)
  654. ((c 'x))
  655. @result{} 6
  656. ((c 'y))
  657. @result{} 0
  658. ;; @r{now make things wrap around}
  659. ((c 'next!))
  660. @result{} (0 . 1)
  661. ((c 'next!))
  662. @result{} (1 . 1)
  663. ((c 'next!))
  664. @result{} (2 . 1)
  665. ((c 'x))
  666. @result{} 2
  667. ((c 'y))
  668. @result{} 1
  669. @end smallexample
  670. You will notice that expressions like @code{(c 'next)} return procedures
  671. that do the job, so we have to use extra parentheses to make the job
  672. happen. This syntax is rather awkward; one way around it is to define a
  673. @code{send} procedure:
  674. @smallexample
  675. ;; @r{send makes object syntax a bit easier; instead of saying}
  676. ;; @r{ ((my-cell 'set-x!) 4)}
  677. ;; @r{you can say}
  678. ;; @r{ (send my-cell 'set-x! 4)}
  679. (define (send obj . args)
  680. (let ((first-eval (apply obj (list (car args)))))
  681. (if (null? (cdr args))
  682. (first-eval)
  683. (apply first-eval (cdr args)))))
  684. @end smallexample
  685. @findex send
  686. You can see that @code{send} passes the message to the object, making
  687. sure that things are evaluated the proper number of times. You can now
  688. type:
  689. @smallexample
  690. (define c2 (MAKE-CELL 0 0 "red" 10 7 9))
  691. (send c2 'x)
  692. @result{} 0
  693. (send c2 'set-x! 5)
  694. @result{} 5
  695. (send c2 'color)
  696. @result{} "red"
  697. (send c2 'set-color! "green")
  698. @result{} "green"
  699. (send c2 'next!)
  700. @result{} (1 . 0)
  701. (send c2 'x)
  702. @result{} 1
  703. (send c2 'y)
  704. @result{} 0
  705. @end smallexample
  706. @cindex object-based programming
  707. @cindex object-oriented programming
  708. This is the simplest way of implementing objects in Scheme, but it does
  709. not really allow for full @emph{object-oriented programming} (for
  710. example, there is no inheritance). But it is useful for
  711. @emph{object-based programming}.
  712. Guile comes with a couple more complete object-oriented extensions to
  713. Scheme: these are part of slib (@pxref{Object, , , slib, SLIB: the
  714. portable Scheme library} and @pxref{Yasos, , , slib, SLIB: the portable
  715. Scheme library}).
  716. @node Guile in a Library
  717. @chapter Guile in a Library
  718. @iftex
  719. @nobreak
  720. @end iftex
  721. In the previous chapters Guile was used to write programs entirely in
  722. Scheme, and no C code was seen; but I have been claiming @emph{ad
  723. nauseam} that Guile is an @emph{extension} language. Here we see how
  724. that is done, and how that can be useful.
  725. @cindex libguile
  726. @cindex extending C programs
  727. @menu
  728. * Two world views::
  729. * What is libguile::
  730. * How to get started with libguile::
  731. * More interesting programming with libguile::
  732. * Further examples::
  733. @end menu
  734. @node Two world views
  735. @section Two world views
  736. @cindex master world
  737. In this manual, I usually jump into examples and explain them as you
  738. type in the code; here I will digress and ramble for a few paragraphs to
  739. set some concepts straight, and then let you type (or paste) in fun
  740. examples.
  741. In 1995, I implemented a large program, @dfn{Gnudl}, using Guile quite
  742. extensively. In the design phase of Gnudl, I found I had to make a
  743. choice: should the fundamental data structures be C or Scheme data
  744. structures?
  745. @cindex gnudl
  746. @cindex GNU Data Language
  747. @cindex Galassi, Mark
  748. Guile allows C to see its data structures (scalar types, lists, vectors,
  749. strings @dots{}). C also allows Guile to see its data structures. As a
  750. large program designer, you have to decide which of those capabilities
  751. to use. You have two main choices:
  752. @enumerate 1
  753. @item
  754. You can write your software mostly in Scheme. In this case, your C
  755. software will mostly parse the Scheme code with Guile calls, and provide
  756. some new primitive procedures to be used by Scheme. This is what Gnudl
  757. does.
  758. @item
  759. You can write your software mostly in C, occasionally allowing Scheme
  760. code to be parsed by Guile, either to allow the user to modify data
  761. structures, or to parse a configuration file, @dots{}
  762. @end enumerate
  763. Mixing the two approaches seems unwise: the overall layout would be
  764. confusing. But who knows? There might be problems that are best solved
  765. by a hybrid approach. Please let me know if you think of such a
  766. problem.
  767. If you use the former approach, we will say that the @dfn{master world}
  768. is Scheme, and the C routines serve Scheme and access Scheme data
  769. structures. In the latter case, the master world is C, and Scheme
  770. routines serve the C code and access C data structures.
  771. In both approaches the @code{libguile.a} library is the same, but a
  772. predominantly different set of routines will be used. When we go
  773. through examples of libguile use, we will point out which is the master
  774. world in order to clarify these two approaches.
  775. @node What is libguile
  776. @section What is libguile
  777. @cindex libguile
  778. @cindex gh interface
  779. @cindex scm interface
  780. @dfn{Libguile} is the library which allows C programs to start a Scheme
  781. interpreter and execute Scheme code. There are also facilities in
  782. libguile to make C data structures available to Scheme, and vice versa.
  783. The interface provided by the libguile C library is somewhat specific to
  784. the implementation of the Scheme interpreter. This low-level libguile
  785. interface is usually referred to as the @code{scm_} interface, since its
  786. public calls (API) all have the @code{scm_} prefix.
  787. There is also a higher-level libguile interface, which is usually
  788. referred to as the @code{gh_} interface (libGuile High). Its public
  789. calls all have the @code{gh_} prefix. The @code{gh_} library interface
  790. is designed to hide the implementation details, thus making it easier to
  791. assimilate and portable to other underlying Scheme implementations.
  792. People extending Guile by adding bindings to C libraries (like OpenGL or
  793. Rx) are encouraged to use the @code{gh_} interface, so their work will
  794. be portable to other Scheme systems. The @code{gh_} interface should be
  795. more stable, because it is simpler.
  796. The @code{scm_} interface is necessary if you want to poke into the
  797. innards of Scheme data structures, or do anything else that is not
  798. offered by the @code{gh_} interface. It is not covered in this
  799. tutorial, but is covered extensively in @ref{Data representation,, Data
  800. Representation in Guile, guile, Guile Reference Manual}.
  801. This chapter gives a gentle introduction to the @code{gh_} interface,
  802. presenting some @emph{hello world}-style programs which I wrote while
  803. teaching myself to use libguile.
  804. @cindex hello world
  805. The @cite{Guile Programmer's Manual} gives more examples of programs
  806. written using libguile, illustrating diverse applications. You can also
  807. consult my @emph{Gnudl} documentation at
  808. @url{http://nis-www.lanl.gov/~rosalia/mydocs/} to see a large scale
  809. project that uses C and Scheme code together.
  810. @node How to get started with libguile
  811. @section How to get started with libguile
  812. @cindex learn0
  813. Here is an elementary first program, @code{learn0}, to get going with
  814. libguile. The program (which uses Scheme as a master world) is in a
  815. single source file, @code{learn0.c}:
  816. @smallexample
  817. /* @r{test the new libgh.a (Guile High-level library) with a trivial
  818. program} */
  819. #include <stdio.h>
  820. #include <guile/gh.h>
  821. void main_prog(int argc, char *argv[]);
  822. main(int argc, char *argv[])
  823. @{
  824. gh_enter(argc, argv, main_prog);
  825. @}
  826. void main_prog(int argc, char *argv[])
  827. @{
  828. int done;
  829. char input_str[200];
  830. gh_eval_str("(display \"hello Guile\")");
  831. gh_eval_str("(newline)");
  832. /* @r{for fun, evaluate some simple Scheme expressions here} */
  833. gh_eval_str("(define (square x) (* x x))");
  834. gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
  835. gh_eval_str("(square 9)");
  836. /* @r{now sit in a Scheme eval loop: I input the expressions, have
  837. Guile evaluate them, and then get another expression.} */
  838. done = 0;
  839. fputs("learn0> ", stdout);
  840. while (fgets(input_str, 199, stdin) != NULL) @{
  841. gh_eval_str(input_str);
  842. fputs("\nlearn0> ", stdout);
  843. @}
  844. exit(0);
  845. @}
  846. @end smallexample
  847. If you name this program @code{learn0.c}, it can now be compiled with:
  848. @smallexample
  849. gcc -g -c learn0.c -o learn0.o
  850. gcc -o learn0 learn0.o -lguile -lm
  851. @end smallexample
  852. @c @emph{NOTE: If you are in the Guile development tree, you can simply do
  853. @c ``cd doc/examples/c; make; ./learn0''.}
  854. The program is simple: it creates a Scheme interpreter, passes a couple
  855. of strings to it that define new Scheme functions @code{square} and
  856. @code{factorial}, and then a couple of strings that invoke those
  857. functions.
  858. It then goes into a read-eval-print-loop (REPL), so you could type
  859. one-line Scheme expressions to it and have them evaluated. For example:
  860. @smallexample
  861. <shell-prompt> ./learn0
  862. hello Guile
  863. learn0> (display (sin 1.3))
  864. 963.558185417193e-3
  865. learn0> (display (fact 10))
  866. 3628800
  867. learn0> (quit)
  868. <shell-prompt>
  869. @end smallexample
  870. You should notice the key steps involved in this @code{learn0} program:
  871. @cartouche
  872. @enumerate
  873. @item
  874. @code{#include <guile/gh.h>}
  875. @item
  876. You need to invoke the initialization routine @code{gh_enter()}. This
  877. starts up a Scheme interpreter, handling many implementation-specific
  878. details.
  879. @item
  880. Your main() function should be almost empty: the real main program goes
  881. in a separate function main_prog() which is passed to gh_enter(). This
  882. rather arcane convention is due to the way Guile's garbage collector
  883. works: the whole program has to run in the dynamic context of
  884. @code{gh_enter()}.
  885. @item
  886. You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
  887. routine.
  888. @item
  889. You link your program with @code{-lguile}.
  890. @end enumerate
  891. @end cartouche
  892. @node More interesting programming with libguile
  893. @section More interesting programming with libguile
  894. @cindex learn1
  895. @cindex callback
  896. @cindex builtin functions
  897. The @code{learn0} program shows how you can invoke Scheme commands from
  898. a C program. This is not such a great achievement: the same could have
  899. been done by opening a pipe to SCM or any other Scheme interpreter.
  900. A true extension language must allow @dfn{callbacks}. Callbacks allow
  901. you to write C routines that can be invoked as Scheme procedures, thus
  902. adding new primitive procedures to Scheme. This also means that a
  903. Scheme procedure can modify a C data structure.
  904. Guile allows you to define new Scheme procedures in C, and provides a
  905. mechanism to go back and forth between C and Scheme data types.
  906. Here is a second program, @code{learn1}, which demonstrates these
  907. features. It is split into three source files: @code{learn1.c},
  908. @code{c_builtins.h} and @code{c_builtins.c}. I am including the code
  909. here.
  910. @c , but you might just want to look at the online source code and the
  911. @c Makefile.am that come with Guile in the
  912. @c @file{doc/examples/c} directory.
  913. Notice that @code{learn1} uses a Scheme master world, and the C routines
  914. in @code{c_builtins.c} are simply adding new primitives to Scheme.
  915. @menu
  916. * learn1.c::
  917. * c_builtins.h::
  918. * c_builtins.c::
  919. * What learn1 is doing::
  920. * Compiling and running learn1::
  921. @end menu
  922. @node learn1.c
  923. @subsection learn1.c
  924. Here is @file{learn1.c}:
  925. @smallexample
  926. #include <stdio.h>
  927. #include <guile/gh.h>
  928. #include "c_builtins.h"
  929. void main_prog(int argc, char *argv[]);
  930. main(int argc, char *argv[])
  931. @{
  932. gh_enter(argc, argv, main_prog);
  933. @}
  934. void main_prog(int argc, char *argv[])
  935. @{
  936. char input_str[200]; /* @r{ugly hack: assume strlen(line) < 200} */
  937. int done;
  938. /* @r{for fun, evaluate some simple Scheme expressions here} */
  939. gh_eval_str("(define (square x) (* x x))");
  940. gh_eval_str("(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))");
  941. gh_eval_str("(square 9)");
  942. gh_eval_str("(fact 100)");
  943. /* @r{now try to define some new builtins, coded in C, so that they are
  944. available in Scheme.} */
  945. gh_new_procedure1_0("c-factorial", c_factorial);
  946. gh_new_procedure1_0("c-sin", c_sin);
  947. gh_new_procedure1_0("v-t", vector_test);
  948. /* @r{now sit in a Scheme eval loop: I input the expressions, have
  949. Guile evaluate them, and then get another expression.} */
  950. done = 0;
  951. fputs("learn1> ", stdout);
  952. while (!done) @{
  953. if (gets(input_str) == NULL) @{
  954. done = 1;
  955. @} else @{
  956. gh_eval_str(input_str);
  957. fputs("learn1> ", stdout);
  958. @}
  959. @}
  960. exit(0);
  961. @}
  962. @end smallexample
  963. @node c_builtins.h
  964. @subsection c_builtins.h
  965. Here is @file{c_builtins.h}:
  966. @smallexample
  967. /* @r{builtin function prototypes} */
  968. #include <guile/gh.h>
  969. SCM c_factorial(SCM n);
  970. SCM c_sin(SCM n);
  971. SCM vector_test(SCM s_length);
  972. @end smallexample
  973. @node c_builtins.c
  974. @subsection c_builtins.c
  975. Here is @file{c_builtins.c}:
  976. @smallexample
  977. #include <stdio.h>
  978. #include <math.h>
  979. #include <guile/gh.h>
  980. #include "c_builtins.h"
  981. /* @r{this is a factorial routine in C, made to be callable by Scheme} */
  982. SCM c_factorial(SCM s_n)
  983. @{
  984. int i;
  985. unsigned long result = 1, n;
  986. n = gh_scm2ulong(s_n);
  987. gh_defer_ints();
  988. for (i = 1; i <= n; ++i) @{
  989. result = result*i;
  990. @}
  991. gh_allow_ints();
  992. return gh_ulong2scm(result);
  993. @}
  994. /* @r{a sin routine in C, callable from Scheme. it is named c_sin() to
  995. distinguish it from the default Scheme sin function} */
  996. SCM c_sin(SCM s_x)
  997. @{
  998. double x = gh_scm2double(s_x);
  999. return gh_double2scm(sin(x));
  1000. @}
  1001. /* @r{play around with vectors in Guile: this routine creates a vector of
  1002. the given length, initializes it all to zero except element 2 which
  1003. is set to 1.9.} */
  1004. SCM vector_test(SCM s_length)
  1005. @{
  1006. SCM xvec;
  1007. c_length = gh_scm2ulong(s_length);
  1008. printf("requested length for vector: %ld\n", gh_scm2ulong(s_length));
  1009. /* create a vector */
  1010. xvec = gh_make_vector(s_length, gh_double2scm(0.0));
  1011. /* set the second element in it */
  1012. gh_vector_set_x(xvec, gh_int2scm(2), gh_double2scm(1.9));
  1013. return xvec;
  1014. @}
  1015. @end smallexample
  1016. @node What learn1 is doing
  1017. @subsection What learn1 is doing
  1018. @cindex registering callbacks
  1019. @cindex registering C functions
  1020. @cindex primitive procedures
  1021. If you compare learn1 to learn0, you will find that learn1 uses a new
  1022. Guile construct: the function @code{gh_new_procedure()}, and its
  1023. siblings:
  1024. @smallexample
  1025. /* @r{now try to define some new builtins, coded in C, so that they are
  1026. available in Scheme.} */
  1027. gh_new_procedure1_0("c-factorial", c_factorial);
  1028. gh_new_procedure1_0("c-sin", c_sin);
  1029. gh_new_procedure1_0("v-t", vector_test);
  1030. @end smallexample
  1031. It is clear that @code{gh_new_procedure()} adds a new builtin
  1032. routine written in C which can be invoked from Scheme. We can now
  1033. revise our checklist for programming with libguile, so it includes
  1034. adding callbacks.
  1035. @cindex libguile - step by step
  1036. @cartouche
  1037. @enumerate
  1038. @item
  1039. @code{#include <guile/gh.h>}
  1040. @item
  1041. You need to invoke the initialization routine @code{gh_enter()}. This
  1042. starts up a Scheme interpreter, handling many details.
  1043. @item
  1044. Your main() function should be almost empty: the real main program goes
  1045. in a separate function main_prog() which is passed to gh_enter(). This
  1046. rather arcane convention is due to the way Guile's garbage collector
  1047. works: the whole program has to run in the dynamic context of
  1048. @code{gh_enter()}.
  1049. @item
  1050. You pass strings to the Scheme interpreter with the @code{gh_eval_str()}
  1051. routine.
  1052. @item
  1053. @strong{[new]} You can now define new builtin Scheme functions;
  1054. i.e. define new builtin Scheme functions, with the
  1055. @code{gh_new_procedure()} routine.
  1056. @item
  1057. You pass strings to the Scheme interpreter with the
  1058. @code{gh_eval_str()} routine.
  1059. @item
  1060. You link your program with @code{-lguile}.
  1061. @end enumerate
  1062. @end cartouche
  1063. I breezed by the issue of how to write your C routines that are
  1064. registered to be called from Scheme. This is non-trivial, and is
  1065. discussed at length in the @cite{Guile Programmer's Manual}.
  1066. @node Compiling and running learn1
  1067. @subsection Compiling and running learn1
  1068. @smallexample
  1069. gcc -g -c learn1.c -o learn1.o
  1070. gcc -g -c c_builtins.c -o c_builtins.o
  1071. gcc -o learn1 learn1.o c_builtins.o -lguile -lm
  1072. @end smallexample
  1073. If you run @code{learn1}, it will prompt you for a one-line Scheme
  1074. expression, just as @code{learn0} did. The difference is that you can
  1075. use the new C builtin procedures (@code{c-factorial}, @code{c-sin},
  1076. @code{v-t}).
  1077. @smallexample
  1078. <shell-prompt> ./learn1
  1079. welcome to Guile
  1080. hello Guile
  1081. learn1> (display (c-factorial 6))
  1082. 720
  1083. learn1> (display (c-factorial 20))
  1084. 2192834560
  1085. learn1> (display (c-factorial 100))
  1086. 0
  1087. learn1> (display (c-sin 1.5))
  1088. 0.997494986604054
  1089. learn1> (display (v-t 10))
  1090. requested length for vector: 10
  1091. #(0.0 0.0 1.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0)
  1092. learn1> (display (v-t 15))
  1093. requested length for vector: 15
  1094. #(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)
  1095. learn1> (quit)
  1096. <shell-prompt>
  1097. @end smallexample
  1098. As you see, taking @code{(c-factorial 100)} does not use bignumbers and
  1099. returns a bogus answer.
  1100. @node Further examples
  1101. @section Further examples
  1102. Further ``idealized'' examples are included in the @code{doc/examples/c}
  1103. distribution. They include programs to:
  1104. @c [FIXME: still have to write some of these; then I will revise the list.]
  1105. @itemize @bullet
  1106. @item
  1107. Parse a startup file (C is the master world).
  1108. @item
  1109. Set up initial conditions for an n-body simulation (C is the master
  1110. world).
  1111. @item
  1112. Implement a Scheme interpreter with all of Guile's goodies, @emph{plus}
  1113. the readline library @emph{and} a fast Fourier transform routine
  1114. provided in C (Scheme is the master world).
  1115. @end itemize
  1116. @node Regular Expression Support
  1117. @chapter Regular Expression Support
  1118. @node UNIX System Programming
  1119. @chapter UNIX System Programming
  1120. @node Where to find more Guile/Scheme resources
  1121. @chapter Where to find more Guile/Scheme resources
  1122. @node Concept Index
  1123. @unnumbered Concept Index
  1124. @printindex cp
  1125. @node Procedure and Macro Index
  1126. @unnumbered Procedure and Macro Index
  1127. This is an alphabetical list of all the procedures and macros in Dominion.
  1128. @printindex fn
  1129. @node Variable Index
  1130. @unnumbered Variable Index
  1131. This is an alphabetical list of the major global variables in Dominion.
  1132. @printindex vr
  1133. @node Type Index
  1134. @unnumbered Type Index
  1135. This is an alphabetical list of the major data structures in Dominion.
  1136. @printindex tp
  1137. @contents
  1138. @bye