scheme-ideas.texi 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2012
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Hello Scheme!
  7. @chapter Hello Scheme!
  8. In this chapter, we introduce the basic concepts that underpin the
  9. elegance and power of the Scheme language.
  10. Readers who already possess a background knowledge of Scheme may happily
  11. skip this chapter. For the reader who is new to the language, however,
  12. the following discussions on data, procedures, expressions and closure
  13. are designed to provide a minimum level of Scheme understanding that is
  14. more or less assumed by the chapters that follow.
  15. The style of this introductory material aims about halfway between the terse
  16. precision of R5RS and the discursiveness of existing Scheme tutorials. For
  17. pointers to useful Scheme resources on the web, please see @ref{Further
  18. Reading}.
  19. @menu
  20. * About Data:: Latent typing, types, values and variables.
  21. * About Procedures:: The representation and use of procedures.
  22. * About Expressions:: All kinds of expressions and their meaning.
  23. * About Closure:: Closure, scoping and environments.
  24. * Further Reading:: Where to find out more about Scheme.
  25. @end menu
  26. @node About Data
  27. @section Data Types, Values and Variables
  28. This section discusses the representation of data types and values, what
  29. it means for Scheme to be a @dfn{latently typed} language, and the role
  30. of variables. We conclude by introducing the Scheme syntaxes for
  31. defining a new variable, and for changing the value of an existing
  32. variable.
  33. @menu
  34. * Latent Typing:: Scheme as a "latently typed" language.
  35. * Values and Variables:: About data types, values and variables.
  36. * Definition:: Defining variables and setting their values.
  37. @end menu
  38. @node Latent Typing
  39. @subsection Latent Typing
  40. The term @dfn{latent typing} is used to describe a computer language,
  41. such as Scheme, for which you cannot, @emph{in general}, simply look at
  42. a program's source code and determine what type of data will be
  43. associated with a particular variable, or with the result of a
  44. particular expression.
  45. Sometimes, of course, you @emph{can} tell from the code what the type of
  46. an expression will be. If you have a line in your program that sets the
  47. variable @code{x} to the numeric value 1, you can be certain that,
  48. immediately after that line has executed (and in the absence of multiple
  49. threads), @code{x} has the numeric value 1. Or if you write a procedure
  50. that is designed to concatenate two strings, it is likely that the rest
  51. of your application will always invoke this procedure with two string
  52. parameters, and quite probable that the procedure would go wrong in some
  53. way if it was ever invoked with parameters that were not both strings.
  54. Nevertheless, the point is that there is nothing in Scheme which
  55. requires the procedure parameters always to be strings, or @code{x}
  56. always to hold a numeric value, and there is no way of declaring in your
  57. program that such constraints should always be obeyed. In the same
  58. vein, there is no way to declare the expected type of a procedure's
  59. return value.
  60. Instead, the types of variables and expressions are only known -- in
  61. general -- at run time. If you @emph{need} to check at some point that
  62. a value has the expected type, Scheme provides run time procedures that
  63. you can invoke to do so. But equally, it can be perfectly valid for two
  64. separate invocations of the same procedure to specify arguments with
  65. different types, and to return values with different types.
  66. The next subsection explains what this means in practice, for the ways
  67. that Scheme programs use data types, values and variables.
  68. @node Values and Variables
  69. @subsection Values and Variables
  70. Scheme provides many data types that you can use to represent your data.
  71. Primitive types include characters, strings, numbers and procedures.
  72. Compound types, which allow a group of primitive and compound values to
  73. be stored together, include lists, pairs, vectors and multi-dimensional
  74. arrays. In addition, Guile allows applications to define their own data
  75. types, with the same status as the built-in standard Scheme types.
  76. As a Scheme program runs, values of all types pop in and out of
  77. existence. Sometimes values are stored in variables, but more commonly
  78. they pass seamlessly from being the result of one computation to being
  79. one of the parameters for the next.
  80. Consider an example. A string value is created because the interpreter
  81. reads in a literal string from your program's source code. Then a
  82. numeric value is created as the result of calculating the length of the
  83. string. A second numeric value is created by doubling the calculated
  84. length. Finally the program creates a list with two elements -- the
  85. doubled length and the original string itself -- and stores this list in
  86. a program variable.
  87. All of the values involved here -- in fact, all values in Scheme --
  88. carry their type with them. In other words, every value ``knows,'' at
  89. runtime, what kind of value it is. A number, a string, a list,
  90. whatever.
  91. A variable, on the other hand, has no fixed type. A variable --
  92. @code{x}, say -- is simply the name of a location -- a box -- in which
  93. you can store any kind of Scheme value. So the same variable in a
  94. program may hold a number at one moment, a list of procedures the next,
  95. and later a pair of strings. The ``type'' of a variable -- insofar as
  96. the idea is meaningful at all -- is simply the type of whatever value
  97. the variable happens to be storing at a particular moment.
  98. @node Definition
  99. @subsection Defining and Setting Variables
  100. To define a new variable, you use Scheme's @code{define} syntax like
  101. this:
  102. @lisp
  103. (define @var{variable-name} @var{value})
  104. @end lisp
  105. This makes a new variable called @var{variable-name} and stores
  106. @var{value} in it as the variable's initial value. For example:
  107. @lisp
  108. ;; Make a variable `x' with initial numeric value 1.
  109. (define x 1)
  110. ;; Make a variable `organization' with an initial string value.
  111. (define organization "Free Software Foundation")
  112. @end lisp
  113. (In Scheme, a semicolon marks the beginning of a comment that continues
  114. until the end of the line. So the lines beginning @code{;;} are
  115. comments.)
  116. Changing the value of an already existing variable is very similar,
  117. except that @code{define} is replaced by the Scheme syntax @code{set!},
  118. like this:
  119. @lisp
  120. (set! @var{variable-name} @var{new-value})
  121. @end lisp
  122. Remember that variables do not have fixed types, so @var{new-value} may
  123. have a completely different type from whatever was previously stored in
  124. the location named by @var{variable-name}. Both of the following
  125. examples are therefore correct.
  126. @lisp
  127. ;; Change the value of `x' to 5.
  128. (set! x 5)
  129. ;; Change the value of `organization' to the FSF's street number.
  130. (set! organization 545)
  131. @end lisp
  132. In these examples, @var{value} and @var{new-value} are literal numeric
  133. or string values. In general, however, @var{value} and @var{new-value}
  134. can be any Scheme expression. Even though we have not yet covered the
  135. forms that Scheme expressions can take (@pxref{About Expressions}), you
  136. can probably guess what the following @code{set!} example does@dots{}
  137. @lisp
  138. (set! x (+ x 1))
  139. @end lisp
  140. (Note: this is not a complete description of @code{define} and
  141. @code{set!}, because we need to introduce some other aspects of Scheme
  142. before the missing pieces can be filled in. If, however, you are
  143. already familiar with the structure of Scheme, you may like to read
  144. about those missing pieces immediately by jumping ahead to the following
  145. references.
  146. @itemize @bullet
  147. @item
  148. @ref{Lambda Alternatives}, to read about an alternative form of the
  149. @code{define} syntax that can be used when defining new procedures.
  150. @item
  151. @ref{Procedures with Setters}, to read about an alternative form of the
  152. @code{set!} syntax that helps with changing a single value in the depths
  153. of a compound data structure.)
  154. @item
  155. @xref{Internal Definitions}, to read about using @code{define} other
  156. than at top level in a Scheme program, including a discussion of when it
  157. works to use @code{define} rather than @code{set!} to change the value
  158. of an existing variable.
  159. @end itemize
  160. @node About Procedures
  161. @section The Representation and Use of Procedures
  162. This section introduces the basics of using and creating Scheme
  163. procedures. It discusses the representation of procedures as just
  164. another kind of Scheme value, and shows how procedure invocation
  165. expressions are constructed. We then explain how @code{lambda} is used
  166. to create new procedures, and conclude by presenting the various
  167. shorthand forms of @code{define} that can be used instead of writing an
  168. explicit @code{lambda} expression.
  169. @menu
  170. * Procedures as Values:: Procedures are values like everything else.
  171. * Simple Invocation:: How to write a simple procedure invocation.
  172. * Creating a Procedure:: How to create your own procedures.
  173. * Lambda Alternatives:: Other ways of writing procedure definitions.
  174. @end menu
  175. @node Procedures as Values
  176. @subsection Procedures as Values
  177. One of the great simplifications of Scheme is that a procedure is just
  178. another type of value, and that procedure values can be passed around
  179. and stored in variables in exactly the same way as, for example, strings
  180. and lists. When we talk about a built-in standard Scheme procedure such
  181. as @code{open-input-file}, what we actually mean is that there is a
  182. pre-defined top level variable called @code{open-input-file}, whose
  183. value is a procedure that implements what R5RS says that
  184. @code{open-input-file} should do.
  185. Note that this is quite different from many dialects of Lisp ---
  186. including Emacs Lisp --- in which a program can use the same name with
  187. two quite separate meanings: one meaning identifies a Lisp function,
  188. while the other meaning identifies a Lisp variable, whose value need
  189. have nothing to do with the function that is associated with the first
  190. meaning. In these dialects, functions and variables are said to live in
  191. different @dfn{namespaces}.
  192. In Scheme, on the other hand, all names belong to a single unified
  193. namespace, and the variables that these names identify can hold any kind
  194. of Scheme value, including procedure values.
  195. One consequence of the ``procedures as values'' idea is that, if you
  196. don't happen to like the standard name for a Scheme procedure, you can
  197. change it.
  198. For example, @code{call-with-current-continuation} is a very important
  199. standard Scheme procedure, but it also has a very long name! So, many
  200. programmers use the following definition to assign the same procedure
  201. value to the more convenient name @code{call/cc}.
  202. @lisp
  203. (define call/cc call-with-current-continuation)
  204. @end lisp
  205. Let's understand exactly how this works. The definition creates a new
  206. variable @code{call/cc}, and then sets its value to the value of the
  207. variable @code{call-with-current-continuation}; the latter value is a
  208. procedure that implements the behaviour that R5RS specifies under the
  209. name ``call-with-current-continuation''. So @code{call/cc} ends up
  210. holding this value as well.
  211. Now that @code{call/cc} holds the required procedure value, you could
  212. choose to use @code{call-with-current-continuation} for a completely
  213. different purpose, or just change its value so that you will get an
  214. error if you accidentally use @code{call-with-current-continuation} as a
  215. procedure in your program rather than @code{call/cc}. For example:
  216. @lisp
  217. (set! call-with-current-continuation "Not a procedure any more!")
  218. @end lisp
  219. Or you could just leave @code{call-with-current-continuation} as it was.
  220. It's perfectly fine for more than one variable to hold the same
  221. procedure value.
  222. @node Simple Invocation
  223. @subsection Simple Procedure Invocation
  224. A procedure invocation in Scheme is written like this:
  225. @lisp
  226. (@var{procedure} [@var{arg1} [@var{arg2} @dots{}]])
  227. @end lisp
  228. In this expression, @var{procedure} can be any Scheme expression whose
  229. value is a procedure. Most commonly, however, @var{procedure} is simply
  230. the name of a variable whose value is a procedure.
  231. For example, @code{string-append} is a standard Scheme procedure whose
  232. behaviour is to concatenate together all the arguments, which are
  233. expected to be strings, that it is given. So the expression
  234. @lisp
  235. (string-append "/home" "/" "andrew")
  236. @end lisp
  237. @noindent
  238. is a procedure invocation whose result is the string value
  239. @code{"/home/andrew"}.
  240. Similarly, @code{string-length} is a standard Scheme procedure that
  241. returns the length of a single string argument, so
  242. @lisp
  243. (string-length "abc")
  244. @end lisp
  245. @noindent
  246. is a procedure invocation whose result is the numeric value 3.
  247. Each of the parameters in a procedure invocation can itself be any
  248. Scheme expression. Since a procedure invocation is itself a type of
  249. expression, we can put these two examples together to get
  250. @lisp
  251. (string-length (string-append "/home" "/" "andrew"))
  252. @end lisp
  253. @noindent
  254. --- a procedure invocation whose result is the numeric value 12.
  255. (You may be wondering what happens if the two examples are combined the
  256. other way round. If we do this, we can make a procedure invocation
  257. expression that is @emph{syntactically} correct:
  258. @lisp
  259. (string-append "/home" (string-length "abc"))
  260. @end lisp
  261. @noindent
  262. but when this expression is executed, it will cause an error, because
  263. the result of @code{(string-length "abc")} is a numeric value, and
  264. @code{string-append} is not designed to accept a numeric value as one of
  265. its arguments.)
  266. @node Creating a Procedure
  267. @subsection Creating and Using a New Procedure
  268. Scheme has lots of standard procedures, and Guile provides all of these
  269. via predefined top level variables. All of these standard procedures
  270. are documented in the later chapters of this reference manual.
  271. Before very long, though, you will want to create new procedures that
  272. encapsulate aspects of your own applications' functionality. To do
  273. this, you can use the famous @code{lambda} syntax.
  274. For example, the value of the following Scheme expression
  275. @lisp
  276. (lambda (name address) @var{expression} @dots{})
  277. @end lisp
  278. @noindent
  279. is a newly created procedure that takes two arguments:
  280. @code{name} and @code{address}. The behaviour of the
  281. new procedure is determined by the sequence of @var{expression}s in the
  282. @dfn{body} of the procedure definition. (Typically, these
  283. @var{expression}s would use the arguments in some way, or else there
  284. wouldn't be any point in giving them to the procedure.) When invoked,
  285. the new procedure returns a value that is the value of the last
  286. @var{expression} in the procedure body.
  287. To make things more concrete, let's suppose that the two arguments are
  288. both strings, and that the purpose of this procedure is to form a
  289. combined string that includes these arguments. Then the full lambda
  290. expression might look like this:
  291. @lisp
  292. (lambda (name address)
  293. (string-append "Name=" name ":Address=" address))
  294. @end lisp
  295. We noted in the previous subsection that the @var{procedure} part of a
  296. procedure invocation expression can be any Scheme expression whose value
  297. is a procedure. But that's exactly what a lambda expression is! So we
  298. can use a lambda expression directly in a procedure invocation, like
  299. this:
  300. @lisp
  301. ((lambda (name address)
  302. (string-append "Name=" name ":Address=" address))
  303. "FSF"
  304. "Cambridge")
  305. @end lisp
  306. @noindent
  307. This is a valid procedure invocation expression, and its result is the
  308. string:
  309. @lisp
  310. "Name=FSF:Address=Cambridge"
  311. @end lisp
  312. It is more common, though, to store the procedure value in a variable ---
  313. @lisp
  314. (define make-combined-string
  315. (lambda (name address)
  316. (string-append "Name=" name ":Address=" address)))
  317. @end lisp
  318. @noindent
  319. --- and then to use the variable name in the procedure invocation:
  320. @lisp
  321. (make-combined-string "FSF" "Cambridge")
  322. @end lisp
  323. @noindent
  324. Which has exactly the same result.
  325. It's important to note that procedures created using @code{lambda} have
  326. exactly the same status as the standard built in Scheme procedures, and
  327. can be invoked, passed around, and stored in variables in exactly the
  328. same ways.
  329. @node Lambda Alternatives
  330. @subsection Lambda Alternatives
  331. Since it is so common in Scheme programs to want to create a procedure
  332. and then store it in a variable, there is an alternative form of the
  333. @code{define} syntax that allows you to do just that.
  334. A @code{define} expression of the form
  335. @lisp
  336. (define (@var{name} [@var{arg1} [@var{arg2} @dots{}]])
  337. @var{expression} @dots{})
  338. @end lisp
  339. @noindent
  340. is exactly equivalent to the longer form
  341. @lisp
  342. (define @var{name}
  343. (lambda ([@var{arg1} [@var{arg2} @dots{}]])
  344. @var{expression} @dots{}))
  345. @end lisp
  346. So, for example, the definition of @code{make-combined-string} in the
  347. previous subsection could equally be written:
  348. @lisp
  349. (define (make-combined-string name address)
  350. (string-append "Name=" name ":Address=" address))
  351. @end lisp
  352. This kind of procedure definition creates a procedure that requires
  353. exactly the expected number of arguments. There are two further forms
  354. of the @code{lambda} expression, which create a procedure that can
  355. accept a variable number of arguments:
  356. @lisp
  357. (lambda (@var{arg1} @dots{} . @var{args}) @var{expression} @dots{})
  358. (lambda @var{args} @var{expression} @dots{})
  359. @end lisp
  360. @noindent
  361. The corresponding forms of the alternative @code{define} syntax are:
  362. @lisp
  363. (define (@var{name} @var{arg1} @dots{} . @var{args}) @var{expression} @dots{})
  364. (define (@var{name} . @var{args}) @var{expression} @dots{})
  365. @end lisp
  366. @noindent
  367. For details on how these forms work, see @xref{Lambda}.
  368. Prior to Guile 2.0, Guile provided an extension to @code{define} syntax
  369. that allowed you to nest the previous extension up to an arbitrary
  370. depth. These are no longer provided by default, and instead have been
  371. moved to @ref{Curried Definitions}
  372. (It could be argued that the alternative @code{define} forms are rather
  373. confusing, especially for newcomers to the Scheme language, as they hide
  374. both the role of @code{lambda} and the fact that procedures are values
  375. that are stored in variables in the some way as any other kind of value.
  376. On the other hand, they are very convenient, and they are also a good
  377. example of another of Scheme's powerful features: the ability to specify
  378. arbitrary syntactic transformations at run time, which can be applied to
  379. subsequently read input.)
  380. @node About Expressions
  381. @section Expressions and Evaluation
  382. So far, we have met expressions that @emph{do} things, such as the
  383. @code{define} expressions that create and initialize new variables, and
  384. we have also talked about expressions that have @emph{values}, for
  385. example the value of the procedure invocation expression:
  386. @lisp
  387. (string-append "/home" "/" "andrew")
  388. @end lisp
  389. @noindent
  390. but we haven't yet been precise about what causes an expression like
  391. this procedure invocation to be reduced to its ``value'', or how the
  392. processing of such expressions relates to the execution of a Scheme
  393. program as a whole.
  394. This section clarifies what we mean by an expression's value, by
  395. introducing the idea of @dfn{evaluation}. It discusses the side effects
  396. that evaluation can have, explains how each of the various types of
  397. Scheme expression is evaluated, and describes the behaviour and use of
  398. the Guile REPL as a mechanism for exploring evaluation. The section
  399. concludes with a very brief summary of Scheme's common syntactic
  400. expressions.
  401. @menu
  402. * Evaluating:: How a Scheme program is executed.
  403. * Tail Calls:: Space-safe recursion.
  404. * The REPL:: Interacting with the Guile interpreter.
  405. * Syntax Summary:: Common syntactic expressions -- in brief.
  406. @end menu
  407. @node Evaluating
  408. @subsection Evaluating Expressions and Executing Programs
  409. In Scheme, the process of executing an expression is known as
  410. @dfn{evaluation}. Evaluation has two kinds of result:
  411. @itemize @bullet
  412. @item
  413. the @dfn{value} of the evaluated expression
  414. @item
  415. the @dfn{side effects} of the evaluation, which consist of any effects of
  416. evaluating the expression that are not represented by the value.
  417. @end itemize
  418. Of the expressions that we have met so far, @code{define} and
  419. @code{set!} expressions have side effects --- the creation or
  420. modification of a variable --- but no value; @code{lambda} expressions
  421. have values --- the newly constructed procedures --- but no side
  422. effects; and procedure invocation expressions, in general, have either
  423. values, or side effects, or both.
  424. It is tempting to try to define more intuitively what we mean by
  425. ``value'' and ``side effects'', and what the difference between them is.
  426. In general, though, this is extremely difficult. It is also
  427. unnecessary; instead, we can quite happily define the behaviour of a
  428. Scheme program by specifying how Scheme executes a program as a whole,
  429. and then by describing the value and side effects of evaluation for each
  430. type of expression individually.
  431. @noindent
  432. So, some@footnote{These definitions are approximate. For the whole
  433. and detailed truth, see @ref{Formal syntax and semantics,R5RS
  434. syntax,,r5rs,The Revised(5) Report on the Algorithmic Language
  435. Scheme}.} definitions@dots{}
  436. @itemize @bullet
  437. @item
  438. A Scheme program consists of a sequence of expressions.
  439. @item
  440. A Scheme interpreter executes the program by evaluating these
  441. expressions in order, one by one.
  442. @item
  443. An expression can be
  444. @itemize @bullet
  445. @item
  446. a piece of literal data, such as a number @code{2.3} or a string
  447. @code{"Hello world!"}
  448. @item
  449. a variable name
  450. @item
  451. a procedure invocation expression
  452. @item
  453. one of Scheme's special syntactic expressions.
  454. @end itemize
  455. @end itemize
  456. @noindent
  457. The following subsections describe how each of these types of expression
  458. is evaluated.
  459. @menu
  460. * Eval Literal:: Evaluating literal data.
  461. * Eval Variable:: Evaluating variable references.
  462. * Eval Procedure:: Evaluating procedure invocation expressions.
  463. * Eval Special:: Evaluating special syntactic expressions.
  464. @end menu
  465. @node Eval Literal
  466. @subsubsection Evaluating Literal Data
  467. When a literal data expression is evaluated, the value of the expression
  468. is simply the value that the expression describes. The evaluation of a
  469. literal data expression has no side effects.
  470. @noindent
  471. So, for example,
  472. @itemize @bullet
  473. @item
  474. the value of the expression @code{"abc"} is the string value
  475. @code{"abc"}
  476. @item
  477. the value of the expression @code{3+4i} is the complex number 3 + 4i
  478. @item
  479. the value of the expression @code{#(1 2 3)} is a three-element vector
  480. containing the numeric values 1, 2 and 3.
  481. @end itemize
  482. For any data type which can be expressed literally like this, the syntax
  483. of the literal data expression for that data type --- in other words,
  484. what you need to write in your code to indicate a literal value of that
  485. type --- is known as the data type's @dfn{read syntax}. This manual
  486. specifies the read syntax for each such data type in the section that
  487. describes that data type.
  488. Some data types do not have a read syntax. Procedures, for example,
  489. cannot be expressed as literal data; they must be created using a
  490. @code{lambda} expression (@pxref{Creating a Procedure}) or implicitly
  491. using the shorthand form of @code{define} (@pxref{Lambda Alternatives}).
  492. @node Eval Variable
  493. @subsubsection Evaluating a Variable Reference
  494. When an expression that consists simply of a variable name is evaluated,
  495. the value of the expression is the value of the named variable. The
  496. evaluation of a variable reference expression has no side effects.
  497. So, after
  498. @lisp
  499. (define key "Paul Evans")
  500. @end lisp
  501. @noindent
  502. the value of the expression @code{key} is the string value @code{"Paul
  503. Evans"}. If @var{key} is then modified by
  504. @lisp
  505. (set! key 3.74)
  506. @end lisp
  507. @noindent
  508. the value of the expression @code{key} is the numeric value 3.74.
  509. If there is no variable with the specified name, evaluation of the
  510. variable reference expression signals an error.
  511. @node Eval Procedure
  512. @subsubsection Evaluating a Procedure Invocation Expression
  513. This is where evaluation starts getting interesting! As already noted,
  514. a procedure invocation expression has the form
  515. @lisp
  516. (@var{procedure} [@var{arg1} [@var{arg2} @dots{}]])
  517. @end lisp
  518. @noindent
  519. where @var{procedure} must be an expression whose value, when evaluated,
  520. is a procedure.
  521. The evaluation of a procedure invocation expression like this proceeds
  522. by
  523. @itemize @bullet
  524. @item
  525. evaluating individually the expressions @var{procedure}, @var{arg1},
  526. @var{arg2}, and so on
  527. @item
  528. calling the procedure that is the value of the @var{procedure}
  529. expression with the list of values obtained from the evaluations of
  530. @var{arg1}, @var{arg2} etc. as its parameters.
  531. @end itemize
  532. For a procedure defined in Scheme, ``calling the procedure with the list
  533. of values as its parameters'' means binding the values to the
  534. procedure's formal parameters and then evaluating the sequence of
  535. expressions that make up the body of the procedure definition. The
  536. value of the procedure invocation expression is the value of the last
  537. evaluated expression in the procedure body. The side effects of calling
  538. the procedure are the combination of the side effects of the sequence of
  539. evaluations of expressions in the procedure body.
  540. For a built-in procedure, the value and side-effects of calling the
  541. procedure are best described by that procedure's documentation.
  542. Note that the complete side effects of evaluating a procedure invocation
  543. expression consist not only of the side effects of the procedure call,
  544. but also of any side effects of the preceding evaluation of the
  545. expressions @var{procedure}, @var{arg1}, @var{arg2}, and so on.
  546. To illustrate this, let's look again at the procedure invocation
  547. expression:
  548. @lisp
  549. (string-length (string-append "/home" "/" "andrew"))
  550. @end lisp
  551. In the outermost expression, @var{procedure} is @code{string-length} and
  552. @var{arg1} is @code{(string-append "/home" "/" "andrew")}.
  553. @itemize @bullet
  554. @item
  555. Evaluation of @code{string-length}, which is a variable, gives a
  556. procedure value that implements the expected behaviour for
  557. ``string-length''.
  558. @item
  559. Evaluation of @code{(string-append "/home" "/" "andrew")}, which is
  560. another procedure invocation expression, means evaluating each of
  561. @itemize @bullet
  562. @item
  563. @code{string-append}, which gives a procedure value that implements the
  564. expected behaviour for ``string-append''
  565. @item
  566. @code{"/home"}, which gives the string value @code{"/home"}
  567. @item
  568. @code{"/"}, which gives the string value @code{"/"}
  569. @item
  570. @code{"andrew"}, which gives the string value @code{"andrew"}
  571. @end itemize
  572. and then invoking the procedure value with this list of string values as
  573. its arguments. The resulting value is a single string value that is the
  574. concatenation of all the arguments, namely @code{"/home/andrew"}.
  575. @end itemize
  576. In the evaluation of the outermost expression, the interpreter can now
  577. invoke the procedure value obtained from @var{procedure} with the value
  578. obtained from @var{arg1} as its arguments. The resulting value is a
  579. numeric value that is the length of the argument string, which is 12.
  580. @node Eval Special
  581. @subsubsection Evaluating Special Syntactic Expressions
  582. When a procedure invocation expression is evaluated, the procedure and
  583. @emph{all} the argument expressions must be evaluated before the
  584. procedure can be invoked. Special syntactic expressions are special
  585. because they are able to manipulate their arguments in an unevaluated
  586. form, and can choose whether to evaluate any or all of the argument
  587. expressions.
  588. Why is this needed? Consider a program fragment that asks the user
  589. whether or not to delete a file, and then deletes the file if the user
  590. answers yes.
  591. @lisp
  592. (if (string=? (read-answer "Should I delete this file?")
  593. "yes")
  594. (delete-file file))
  595. @end lisp
  596. If the outermost @code{(if @dots{})} expression here was a procedure
  597. invocation expression, the expression @code{(delete-file file)}, whose
  598. side effect is to actually delete a file, would already have been
  599. evaluated before the @code{if} procedure even got invoked! Clearly this
  600. is no use --- the whole point of an @code{if} expression is that the
  601. @dfn{consequent} expression is only evaluated if the condition of the
  602. @code{if} expression is ``true''.
  603. Therefore @code{if} must be special syntax, not a procedure. Other
  604. special syntaxes that we have already met are @code{define}, @code{set!}
  605. and @code{lambda}. @code{define} and @code{set!} are syntax because
  606. they need to know the variable @emph{name} that is given as the first
  607. argument in a @code{define} or @code{set!} expression, not that
  608. variable's value. @code{lambda} is syntax because it does not
  609. immediately evaluate the expressions that define the procedure body;
  610. instead it creates a procedure object that incorporates these
  611. expressions so that they can be evaluated in the future, when that
  612. procedure is invoked.
  613. The rules for evaluating each special syntactic expression are specified
  614. individually for each special syntax. For a summary of standard special
  615. syntax, see @xref{Syntax Summary}.
  616. @node Tail Calls
  617. @subsection Tail calls
  618. @cindex tail calls
  619. @cindex recursion
  620. Scheme is ``properly tail recursive'', meaning that tail calls or
  621. recursions from certain contexts do not consume stack space or other
  622. resources and can therefore be used on arbitrarily large data or for
  623. an arbitrarily long calculation. Consider for example,
  624. @example
  625. (define (foo n)
  626. (display n)
  627. (newline)
  628. (foo (1+ n)))
  629. (foo 1)
  630. @print{}
  631. 1
  632. 2
  633. 3
  634. @dots{}
  635. @end example
  636. @code{foo} prints numbers infinitely, starting from the given @var{n}.
  637. It's implemented by printing @var{n} then recursing to itself to print
  638. @math{@var{n}+1} and so on. This recursion is a tail call, it's the
  639. last thing done, and in Scheme such tail calls can be made without
  640. limit.
  641. Or consider a case where a value is returned, a version of the SRFI-1
  642. @code{last} function (@pxref{SRFI-1 Selectors}) returning the last
  643. element of a list,
  644. @example
  645. (define (my-last lst)
  646. (if (null? (cdr lst))
  647. (car lst)
  648. (my-last (cdr lst))))
  649. (my-last '(1 2 3)) @result{} 3
  650. @end example
  651. If the list has more than one element, @code{my-last} applies itself
  652. to the @code{cdr}. This recursion is a tail call, there's no code
  653. after it, and the return value is the return value from that call. In
  654. Scheme this can be used on an arbitrarily long list argument.
  655. @sp 1
  656. A proper tail call is only available from certain contexts, namely the
  657. following special form positions,
  658. @itemize @bullet
  659. @item
  660. @code{and} --- last expression
  661. @item
  662. @code{begin} --- last expression
  663. @item
  664. @code{case} --- last expression in each clause
  665. @item
  666. @code{cond} --- last expression in each clause, and the call to a
  667. @code{=>} procedure is a tail call
  668. @item
  669. @code{do} --- last result expression
  670. @item
  671. @code{if} --- ``true'' and ``false'' leg expressions
  672. @item
  673. @code{lambda} --- last expression in body
  674. @item
  675. @code{let}, @code{let*}, @code{letrec}, @code{let-syntax},
  676. @code{letrec-syntax} --- last expression in body
  677. @item
  678. @code{or} --- last expression
  679. @end itemize
  680. @noindent
  681. The following core functions make tail calls,
  682. @itemize @bullet
  683. @item
  684. @code{apply} --- tail call to given procedure
  685. @item
  686. @code{call-with-current-continuation} --- tail call to the procedure
  687. receiving the new continuation
  688. @item
  689. @code{call-with-values} --- tail call to the values-receiving
  690. procedure
  691. @item
  692. @code{eval} --- tail call to evaluate the form
  693. @item
  694. @code{string-any}, @code{string-every} --- tail call to predicate on
  695. the last character (if that point is reached)
  696. @end itemize
  697. @sp 1
  698. The above are just core functions and special forms. Tail calls in
  699. other modules are described with the relevant documentation, for
  700. example SRFI-1 @code{any} and @code{every} (@pxref{SRFI-1 Searching}).
  701. It will be noted there are a lot of places which could potentially be
  702. tail calls, for instance the last call in a @code{for-each}, but only
  703. those explicitly described are guaranteed.
  704. @node The REPL
  705. @subsection Using the Guile REPL
  706. If you start Guile without specifying a particular program for it to
  707. execute, Guile enters its standard Read Evaluate Print Loop --- or
  708. @dfn{REPL} for short. In this mode, Guile repeatedly reads in the next
  709. Scheme expression that the user types, evaluates it, and prints the
  710. resulting value.
  711. The REPL is a useful mechanism for exploring the evaluation behaviour
  712. described in the previous subsection. If you type @code{string-append},
  713. for example, the REPL replies @code{#<primitive-procedure
  714. string-append>}, illustrating the relationship between the variable
  715. @code{string-append} and the procedure value stored in that variable.
  716. In this manual, the notation @result{} is used to mean ``evaluates
  717. to''. Wherever you see an example of the form
  718. @lisp
  719. @var{expression}
  720. @result{}
  721. @var{result}
  722. @end lisp
  723. @noindent
  724. feel free to try it out yourself by typing @var{expression} into the
  725. REPL and checking that it gives the expected @var{result}.
  726. @node Syntax Summary
  727. @subsection Summary of Common Syntax
  728. This subsection lists the most commonly used Scheme syntactic
  729. expressions, simply so that you will recognize common special syntax
  730. when you see it. For a full description of each of these syntaxes,
  731. follow the appropriate reference.
  732. @code{lambda} (@pxref{Lambda}) is used to construct procedure objects.
  733. @code{define} (@pxref{Top Level}) is used to create a new variable and
  734. set its initial value.
  735. @code{set!} (@pxref{Top Level}) is used to modify an existing variable's
  736. value.
  737. @code{let}, @code{let*} and @code{letrec} (@pxref{Local Bindings})
  738. create an inner lexical environment for the evaluation of a sequence of
  739. expressions, in which a specified set of local variables is bound to the
  740. values of a corresponding set of expressions. For an introduction to
  741. environments, see @xref{About Closure}.
  742. @code{begin} (@pxref{begin}) executes a sequence of expressions in order
  743. and returns the value of the last expression. Note that this is not the
  744. same as a procedure which returns its last argument, because the
  745. evaluation of a procedure invocation expression does not guarantee to
  746. evaluate the arguments in order.
  747. @code{if} and @code{cond} (@pxref{Conditionals}) provide conditional
  748. evaluation of argument expressions depending on whether one or more
  749. conditions evaluate to ``true'' or ``false''.
  750. @code{case} (@pxref{Conditionals}) provides conditional evaluation of
  751. argument expressions depending on whether a variable has one of a
  752. specified group of values.
  753. @code{and} (@pxref{and or}) executes a sequence of expressions in order
  754. until either there are no expressions left, or one of them evaluates to
  755. ``false''.
  756. @code{or} (@pxref{and or}) executes a sequence of expressions in order
  757. until either there are no expressions left, or one of them evaluates to
  758. ``true''.
  759. @node About Closure
  760. @section The Concept of Closure
  761. @cindex closure
  762. The concept of @dfn{closure} is the idea that a lambda expression
  763. ``captures'' the variable bindings that are in lexical scope at the
  764. point where the lambda expression occurs. The procedure created by the
  765. lambda expression can refer to and mutate the captured bindings, and the
  766. values of those bindings persist between procedure calls.
  767. This section explains and explores the various parts of this idea in
  768. more detail.
  769. @menu
  770. * About Environments:: Names, locations, values and environments.
  771. * Local Variables:: Local variables and local environments.
  772. * Chaining:: Environment chaining.
  773. * Lexical Scope:: The meaning of lexical scoping.
  774. * Closure:: Explaining the concept of closure.
  775. * Serial Number:: Example 1: a serial number generator.
  776. * Shared Variable:: Example 2: a shared persistent variable.
  777. * Callback Closure:: Example 3: the callback closure problem.
  778. * OO Closure:: Example 4: object orientation.
  779. @end menu
  780. @node About Environments
  781. @subsection Names, Locations, Values and Environments
  782. @cindex location
  783. @cindex environment
  784. @cindex vcell
  785. @cindex top level environment
  786. @cindex environment, top level
  787. We said earlier that a variable name in a Scheme program is associated
  788. with a location in which any kind of Scheme value may be stored.
  789. (Incidentally, the term ``vcell'' is often used in Lisp and Scheme
  790. circles as an alternative to ``location''.) Thus part of what we mean
  791. when we talk about ``creating a variable'' is in fact establishing an
  792. association between a name, or identifier, that is used by the Scheme
  793. program code, and the variable location to which that name refers.
  794. Although the value that is stored in that location may change, the
  795. location to which a given name refers is always the same.
  796. We can illustrate this by breaking down the operation of the
  797. @code{define} syntax into three parts: @code{define}
  798. @itemize @bullet
  799. @item
  800. creates a new location
  801. @item
  802. establishes an association between that location and the name specified
  803. as the first argument of the @code{define} expression
  804. @item
  805. stores in that location the value obtained by evaluating the second
  806. argument of the @code{define} expression.
  807. @end itemize
  808. A collection of associations between names and locations is called an
  809. @dfn{environment}. When you create a top level variable in a program
  810. using @code{define}, the name-location association for that variable is
  811. added to the ``top level'' environment. The ``top level'' environment
  812. also includes name-location associations for all the procedures that are
  813. supplied by standard Scheme.
  814. It is also possible to create environments other than the top level one,
  815. and to create variable bindings, or name-location associations, in those
  816. environments. This ability is a key ingredient in the concept of
  817. closure; the next subsection shows how it is done.
  818. @node Local Variables
  819. @subsection Local Variables and Environments
  820. @cindex local variable
  821. @cindex variable, local
  822. @cindex local environment
  823. @cindex environment, local
  824. We have seen how to create top level variables using the @code{define}
  825. syntax (@pxref{Definition}). It is often useful to create variables
  826. that are more limited in their scope, typically as part of a procedure
  827. body. In Scheme, this is done using the @code{let} syntax, or one of
  828. its modified forms @code{let*} and @code{letrec}. These syntaxes are
  829. described in full later in the manual (@pxref{Local Bindings}). Here
  830. our purpose is to illustrate their use just enough that we can see how
  831. local variables work.
  832. For example, the following code uses a local variable @code{s} to
  833. simplify the computation of the area of a triangle given the lengths of
  834. its three sides.
  835. @lisp
  836. (define a 5.3)
  837. (define b 4.7)
  838. (define c 2.8)
  839. (define area
  840. (let ((s (/ (+ a b c) 2)))
  841. (sqrt (* s (- s a) (- s b) (- s c)))))
  842. @end lisp
  843. The effect of the @code{let} expression is to create a new environment
  844. and, within this environment, an association between the name @code{s}
  845. and a new location whose initial value is obtained by evaluating
  846. @code{(/ (+ a b c) 2)}. The expressions in the body of the @code{let},
  847. namely @code{(sqrt (* s (- s a) (- s b) (- s c)))}, are then evaluated
  848. in the context of the new environment, and the value of the last
  849. expression evaluated becomes the value of the whole @code{let}
  850. expression, and therefore the value of the variable @code{area}.
  851. @node Chaining
  852. @subsection Environment Chaining
  853. @cindex shadowing an imported variable binding
  854. @cindex chaining environments
  855. In the example of the previous subsection, we glossed over an important
  856. point. The body of the @code{let} expression in that example refers not
  857. only to the local variable @code{s}, but also to the top level variables
  858. @code{a}, @code{b}, @code{c} and @code{sqrt}. (@code{sqrt} is the
  859. standard Scheme procedure for calculating a square root.) If the body
  860. of the @code{let} expression is evaluated in the context of the
  861. @emph{local} @code{let} environment, how does the evaluation get at the
  862. values of these top level variables?
  863. The answer is that the local environment created by a @code{let}
  864. expression automatically has a reference to its containing environment
  865. --- in this case the top level environment --- and that the Scheme
  866. interpreter automatically looks for a variable binding in the containing
  867. environment if it doesn't find one in the local environment. More
  868. generally, every environment except for the top level one has a
  869. reference to its containing environment, and the interpreter keeps
  870. searching back up the chain of environments --- from most local to top
  871. level --- until it either finds a variable binding for the required
  872. identifier or exhausts the chain.
  873. This description also determines what happens when there is more than
  874. one variable binding with the same name. Suppose, continuing the
  875. example of the previous subsection, that there was also a pre-existing
  876. top level variable @code{s} created by the expression:
  877. @lisp
  878. (define s "Some beans, my lord!")
  879. @end lisp
  880. Then both the top level environment and the local @code{let} environment
  881. would contain bindings for the name @code{s}. When evaluating code
  882. within the @code{let} body, the interpreter looks first in the local
  883. @code{let} environment, and so finds the binding for @code{s} created by
  884. the @code{let} syntax. Even though this environment has a reference to
  885. the top level environment, which also has a binding for @code{s}, the
  886. interpreter doesn't get as far as looking there. When evaluating code
  887. outside the @code{let} body, the interpreter looks up variable names in
  888. the top level environment, so the name @code{s} refers to the top level
  889. variable.
  890. Within the @code{let} body, the binding for @code{s} in the local
  891. environment is said to @dfn{shadow} the binding for @code{s} in the top
  892. level environment.
  893. @node Lexical Scope
  894. @subsection Lexical Scope
  895. The rules that we have just been describing are the details of how
  896. Scheme implements ``lexical scoping''. This subsection takes a brief
  897. diversion to explain what lexical scope means in general and to present
  898. an example of non-lexical scoping.
  899. ``Lexical scope'' in general is the idea that
  900. @itemize @bullet
  901. @item
  902. an identifier at a particular place in a program always refers to the
  903. same variable location --- where ``always'' means ``every time that the
  904. containing expression is executed'', and that
  905. @item
  906. the variable location to which it refers can be determined by static
  907. examination of the source code context in which that identifier appears,
  908. without having to consider the flow of execution through the program as
  909. a whole.
  910. @end itemize
  911. In practice, lexical scoping is the norm for most programming languages,
  912. and probably corresponds to what you would intuitively consider to be
  913. ``normal''. You may even be wondering how the situation could possibly
  914. --- and usefully --- be otherwise. To demonstrate that another kind of
  915. scoping is possible, therefore, and to compare it against lexical
  916. scoping, the following subsection presents an example of non-lexical
  917. scoping and examines in detail how its behavior differs from the
  918. corresponding lexically scoped code.
  919. @menu
  920. * Scoping Example:: An example of non-lexical scoping.
  921. @end menu
  922. @node Scoping Example
  923. @subsubsection An Example of Non-Lexical Scoping
  924. To demonstrate that non-lexical scoping does exist and can be useful, we
  925. present the following example from Emacs Lisp, which is a ``dynamically
  926. scoped'' language.
  927. @lisp
  928. (defvar currency-abbreviation "USD")
  929. (defun currency-string (units hundredths)
  930. (concat currency-abbreviation
  931. (number-to-string units)
  932. "."
  933. (number-to-string hundredths)))
  934. (defun french-currency-string (units hundredths)
  935. (let ((currency-abbreviation "FRF"))
  936. (currency-string units hundredths)))
  937. @end lisp
  938. The question to focus on here is: what does the identifier
  939. @code{currency-abbreviation} refer to in the @code{currency-string}
  940. function? The answer, in Emacs Lisp, is that all variable bindings go
  941. onto a single stack, and that @code{currency-abbreviation} refers to the
  942. topmost binding from that stack which has the name
  943. ``currency-abbreviation''. The binding that is created by the
  944. @code{defvar} form, to the value @code{"USD"}, is only relevant if none
  945. of the code that calls @code{currency-string} rebinds the name
  946. ``currency-abbreviation'' in the meanwhile.
  947. The second function @code{french-currency-string} works precisely by
  948. taking advantage of this behaviour. It creates a new binding for the
  949. name ``currency-abbreviation'' which overrides the one established by
  950. the @code{defvar} form.
  951. @lisp
  952. ;; Note! This is Emacs Lisp evaluation, not Scheme!
  953. (french-currency-string 33 44)
  954. @result{}
  955. "FRF33.44"
  956. @end lisp
  957. Now let's look at the corresponding, @emph{lexically scoped} Scheme
  958. code:
  959. @lisp
  960. (define currency-abbreviation "USD")
  961. (define (currency-string units hundredths)
  962. (string-append currency-abbreviation
  963. (number->string units)
  964. "."
  965. (number->string hundredths)))
  966. (define (french-currency-string units hundredths)
  967. (let ((currency-abbreviation "FRF"))
  968. (currency-string units hundredths)))
  969. @end lisp
  970. According to the rules of lexical scoping, the
  971. @code{currency-abbreviation} in @code{currency-string} refers to the
  972. variable location in the innermost environment at that point in the code
  973. which has a binding for @code{currency-abbreviation}, which is the
  974. variable location in the top level environment created by the preceding
  975. @code{(define currency-abbreviation @dots{})} expression.
  976. In Scheme, therefore, the @code{french-currency-string} procedure does
  977. not work as intended. The variable binding that it creates for
  978. ``currency-abbreviation'' is purely local to the code that forms the
  979. body of the @code{let} expression. Since this code doesn't directly use
  980. the name ``currency-abbreviation'' at all, the binding is pointless.
  981. @lisp
  982. (french-currency-string 33 44)
  983. @result{}
  984. "USD33.44"
  985. @end lisp
  986. This begs the question of how the Emacs Lisp behaviour can be
  987. implemented in Scheme. In general, this is a design question whose
  988. answer depends upon the problem that is being addressed. In this case,
  989. the best answer may be that @code{currency-string} should be
  990. redesigned so that it can take an optional third argument. This third
  991. argument, if supplied, is interpreted as a currency abbreviation that
  992. overrides the default.
  993. It is possible to change @code{french-currency-string} so that it mostly
  994. works without changing @code{currency-string}, but the fix is inelegant,
  995. and susceptible to interrupts that could leave the
  996. @code{currency-abbreviation} variable in the wrong state:
  997. @lisp
  998. (define (french-currency-string units hundredths)
  999. (set! currency-abbreviation "FRF")
  1000. (let ((result (currency-string units hundredths)))
  1001. (set! currency-abbreviation "USD")
  1002. result))
  1003. @end lisp
  1004. The key point here is that the code does not create any local binding
  1005. for the identifier @code{currency-abbreviation}, so all occurrences of
  1006. this identifier refer to the top level variable.
  1007. @node Closure
  1008. @subsection Closure
  1009. Consider a @code{let} expression that doesn't contain any
  1010. @code{lambda}s:
  1011. @lisp
  1012. (let ((s (/ (+ a b c) 2)))
  1013. (sqrt (* s (- s a) (- s b) (- s c))))
  1014. @end lisp
  1015. @noindent
  1016. When the Scheme interpreter evaluates this, it
  1017. @itemize @bullet
  1018. @item
  1019. creates a new environment with a reference to the environment that was
  1020. current when it encountered the @code{let}
  1021. @item
  1022. creates a variable binding for @code{s} in the new environment, with
  1023. value given by @code{(/ (+ a b c) 2)}
  1024. @item
  1025. evaluates the expression in the body of the @code{let} in the context of
  1026. the new local environment, and remembers the value @code{V}
  1027. @item
  1028. forgets the local environment
  1029. @item
  1030. continues evaluating the expression that contained the @code{let}, using
  1031. the value @code{V} as the value of the @code{let} expression, in the
  1032. context of the containing environment.
  1033. @end itemize
  1034. After the @code{let} expression has been evaluated, the local
  1035. environment that was created is simply forgotten, and there is no longer
  1036. any way to access the binding that was created in this environment. If
  1037. the same code is evaluated again, it will follow the same steps again,
  1038. creating a second new local environment that has no connection with the
  1039. first, and then forgetting this one as well.
  1040. If the @code{let} body contains a @code{lambda} expression, however, the
  1041. local environment is @emph{not} forgotten. Instead, it becomes
  1042. associated with the procedure that is created by the @code{lambda}
  1043. expression, and is reinstated every time that that procedure is called.
  1044. In detail, this works as follows.
  1045. @itemize @bullet
  1046. @item
  1047. When the Scheme interpreter evaluates a @code{lambda} expression, to
  1048. create a procedure object, it stores the current environment as part of
  1049. the procedure definition.
  1050. @item
  1051. Then, whenever that procedure is called, the interpreter reinstates the
  1052. environment that is stored in the procedure definition and evaluates the
  1053. procedure body within the context of that environment.
  1054. @end itemize
  1055. The result is that the procedure body is always evaluated in the context
  1056. of the environment that was current when the procedure was created.
  1057. This is what is meant by @dfn{closure}. The next few subsections
  1058. present examples that explore the usefulness of this concept.
  1059. @node Serial Number
  1060. @subsection Example 1: A Serial Number Generator
  1061. This example uses closure to create a procedure with a variable binding
  1062. that is private to the procedure, like a local variable, but whose value
  1063. persists between procedure calls.
  1064. @lisp
  1065. (define (make-serial-number-generator)
  1066. (let ((current-serial-number 0))
  1067. (lambda ()
  1068. (set! current-serial-number (+ current-serial-number 1))
  1069. current-serial-number)))
  1070. (define entry-sn-generator (make-serial-number-generator))
  1071. (entry-sn-generator)
  1072. @result{}
  1073. 1
  1074. (entry-sn-generator)
  1075. @result{}
  1076. 2
  1077. @end lisp
  1078. When @code{make-serial-number-generator} is called, it creates a local
  1079. environment with a binding for @code{current-serial-number} whose
  1080. initial value is 0, then, within this environment, creates a procedure.
  1081. The local environment is stored within the created procedure object and
  1082. so persists for the lifetime of the created procedure.
  1083. Every time the created procedure is invoked, it increments the value of
  1084. the @code{current-serial-number} binding in the captured environment and
  1085. then returns the current value.
  1086. Note that @code{make-serial-number-generator} can be called again to
  1087. create a second serial number generator that is independent of the
  1088. first. Every new invocation of @code{make-serial-number-generator}
  1089. creates a new local @code{let} environment and returns a new procedure
  1090. object with an association to this environment.
  1091. @node Shared Variable
  1092. @subsection Example 2: A Shared Persistent Variable
  1093. This example uses closure to create two procedures, @code{get-balance}
  1094. and @code{deposit}, that both refer to the same captured local
  1095. environment so that they can both access the @code{balance} variable
  1096. binding inside that environment. The value of this variable binding
  1097. persists between calls to either procedure.
  1098. Note that the captured @code{balance} variable binding is private to
  1099. these two procedures: it is not directly accessible to any other code.
  1100. It can only be accessed indirectly via @code{get-balance} or
  1101. @code{deposit}, as illustrated by the @code{withdraw} procedure.
  1102. @lisp
  1103. (define get-balance #f)
  1104. (define deposit #f)
  1105. (let ((balance 0))
  1106. (set! get-balance
  1107. (lambda ()
  1108. balance))
  1109. (set! deposit
  1110. (lambda (amount)
  1111. (set! balance (+ balance amount))
  1112. balance)))
  1113. (define (withdraw amount)
  1114. (deposit (- amount)))
  1115. (get-balance)
  1116. @result{}
  1117. 0
  1118. (deposit 50)
  1119. @result{}
  1120. 50
  1121. (withdraw 75)
  1122. @result{}
  1123. -25
  1124. @end lisp
  1125. An important detail here is that the @code{get-balance} and
  1126. @code{deposit} variables must be set up by @code{define}ing them at top
  1127. level and then @code{set!}ing their values inside the @code{let} body.
  1128. Using @code{define} within the @code{let} body would not work: this
  1129. would create variable bindings within the local @code{let} environment
  1130. that would not be accessible at top level.
  1131. @node Callback Closure
  1132. @subsection Example 3: The Callback Closure Problem
  1133. A frequently used programming model for library code is to allow an
  1134. application to register a callback function for the library to call when
  1135. some particular event occurs. It is often useful for the application to
  1136. make several such registrations using the same callback function, for
  1137. example if several similar library events can be handled using the same
  1138. application code, but the need then arises to distinguish the callback
  1139. function calls that are associated with one callback registration from
  1140. those that are associated with different callback registrations.
  1141. In languages without the ability to create functions dynamically, this
  1142. problem is usually solved by passing a @code{user_data} parameter on the
  1143. registration call, and including the value of this parameter as one of
  1144. the parameters on the callback function. Here is an example of
  1145. declarations using this solution in C:
  1146. @example
  1147. typedef void (event_handler_t) (int event_type,
  1148. void *user_data);
  1149. void register_callback (int event_type,
  1150. event_handler_t *handler,
  1151. void *user_data);
  1152. @end example
  1153. In Scheme, closure can be used to achieve the same functionality without
  1154. requiring the library code to store a @code{user-data} for each callback
  1155. registration.
  1156. @lisp
  1157. ;; In the library:
  1158. (define (register-callback event-type handler-proc)
  1159. @dots{})
  1160. ;; In the application:
  1161. (define (make-handler event-type user-data)
  1162. (lambda ()
  1163. @dots{}
  1164. <code referencing event-type and user-data>
  1165. @dots{}))
  1166. (register-callback event-type
  1167. (make-handler event-type @dots{}))
  1168. @end lisp
  1169. As far as the library is concerned, @code{handler-proc} is a procedure
  1170. with no arguments, and all the library has to do is call it when the
  1171. appropriate event occurs. From the application's point of view, though,
  1172. the handler procedure has used closure to capture an environment that
  1173. includes all the context that the handler code needs ---
  1174. @code{event-type} and @code{user-data} --- to handle the event
  1175. correctly.
  1176. @node OO Closure
  1177. @subsection Example 4: Object Orientation
  1178. Closure is the capture of an environment, containing persistent variable
  1179. bindings, within the definition of a procedure or a set of related
  1180. procedures. This is rather similar to the idea in some object oriented
  1181. languages of encapsulating a set of related data variables inside an
  1182. ``object'', together with a set of ``methods'' that operate on the
  1183. encapsulated data. The following example shows how closure can be used
  1184. to emulate the ideas of objects, methods and encapsulation in Scheme.
  1185. @lisp
  1186. (define (make-account)
  1187. (let ((balance 0))
  1188. (define (get-balance)
  1189. balance)
  1190. (define (deposit amount)
  1191. (set! balance (+ balance amount))
  1192. balance)
  1193. (define (withdraw amount)
  1194. (deposit (- amount)))
  1195. (lambda args
  1196. (apply
  1197. (case (car args)
  1198. ((get-balance) get-balance)
  1199. ((deposit) deposit)
  1200. ((withdraw) withdraw)
  1201. (else (error "Invalid method!")))
  1202. (cdr args)))))
  1203. @end lisp
  1204. Each call to @code{make-account} creates and returns a new procedure,
  1205. created by the expression in the example code that begins ``(lambda
  1206. args''.
  1207. @lisp
  1208. (define my-account (make-account))
  1209. my-account
  1210. @result{}
  1211. #<procedure args>
  1212. @end lisp
  1213. This procedure acts as an account object with methods
  1214. @code{get-balance}, @code{deposit} and @code{withdraw}. To apply one of
  1215. the methods to the account, you call the procedure with a symbol
  1216. indicating the required method as the first parameter, followed by any
  1217. other parameters that are required by that method.
  1218. @lisp
  1219. (my-account 'get-balance)
  1220. @result{}
  1221. 0
  1222. (my-account 'withdraw 5)
  1223. @result{}
  1224. -5
  1225. (my-account 'deposit 396)
  1226. @result{}
  1227. 391
  1228. (my-account 'get-balance)
  1229. @result{}
  1230. 391
  1231. @end lisp
  1232. Note how, in this example, both the current balance and the helper
  1233. procedures @code{get-balance}, @code{deposit} and @code{withdraw}, used
  1234. to implement the guts of the account object's methods, are all stored in
  1235. variable bindings within the private local environment captured by the
  1236. @code{lambda} expression that creates the account object procedure.
  1237. @c Local Variables:
  1238. @c TeX-master: "guile.texi"
  1239. @c End: