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