scheme-ideas.texi 55 KB

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