32-way branching in intmap.scm, not 16-way
[bpt/guile.git] / doc / r5rs / r5rs.texi
CommitLineData
a0e07ba4
NJ
1\input texinfo @c -*-texinfo-*-
2@c %**start of header
3@setfilename r5rs.info
4@settitle Revised(5) Scheme
5
6@c This copy of r5rs.texi differs from Aubrey Jaffer's master copy
7@c by a set of changes to allow the building of r5rs.dvi from r5rs.texi.
8@c Aubrey Jaffer's view - which I agree with - is that, given that
9@c people have the option of building r5rs.dvi from the original
10@c LaTeX distribution for R5RS, it is not worth fixing his master
11@c copy of r5rs.texi and the tool which autogenerates it. On the
12@c other hand, it is a marginal convenience for people to be able to
13@c build hardcopy from r5rs.texi, even if the results are less good
14@c than with the original LaTeX. Hence the following fixes.
15@c (lines 714, 725, 728, 1614, 2258): Remove invalid parentheses from
16@c @deffn statements.
17@c (line 2316): Change @deffnx to @deffn, and insert `@end deffn' to
18@c terminate preceding @deffn.
19@c (line 7320): Insert `@c ' at beginning of lines that are intended
20@c to be @ignore'd.
21@c
22@c NJ 2001/1/26
23
24@c \documentclass[twoside]{algol60}
25
26@c \pagestyle{headings}
27@c \showboxdepth=0
28
29
30
31@c \def\headertitle{Revised$^{5}$ Scheme}
32@c \def\integerversion{5}
33
34@c Sizes and dimensions
35
36@c \topmargin -.375in % Nominal distance from top of page to top of
37
38@c box containing running head.
39@c \headsep 15pt % Space between running head and text.
40
41@c \textheight 663pt % Height of text (including footnotes and figures,
42
43@c excluding running head and foot).
44
45@c \textwidth 523pt % Width of text line.
46@c \columnsep 15pt % Space between columns
47@c \columnseprule 0pt % Width of rule between columns.
48
49@c \parskip 5pt plus 2pt minus 2pt % Extra vertical space between paragraphs.
50@c \parindent 0pt % Width of paragraph indentation.
51@c \topsep 0pt plus 2pt % Extra vertical space, in addition to
52
53@c \parskip, added above and below list and
54
55@c paragraphing environments.
56
57@c \oddsidemargin -.5in % Left margin on odd-numbered pages.
58@c \evensidemargin -.5in % Left margin on even-numbered pages.
59
60@c % End of sizes and dimensions
61
62@paragraphindent 0
63@c %**end of header
64@c syncodeindex fn cp
65
66@ifinfo
67@dircategory The Algorithmic Language Scheme
68@direntry
69* R5RS: (r5rs). The Revised(5) Report on Scheme.
70@end direntry
71@end ifinfo
72
73
74@c \parindent 0pt %!! 15pt % Width of paragraph indentation.
75
76 @b{20 February 1998}
77@c \hfil \today{}
78
79@c @include{first}
80@titlepage
81
82@c HTML first page
83@title Scheme
84@subtitle Revised(5) Report on the Algorithmic Language Scheme
85@c First page
86
87@c \thispagestyle{empty}
88
89@c \todo{"another" report?}
90
91
92@author R@sc{ICHARD} K@sc{ELSEY}, W@sc{ILLIAM} C@sc{LINGER, AND} J@sc{ONATHAN} R@sc{EES} (@i{Editors})
93@author H. A@sc{BELSON}
94@author R. K. D@sc{YBVIG}
95@author C. T. H@sc{AYNES}
96@author G. J. R@sc{OZAS}
97@author N. I. A@sc{DAMS IV}
98@author D. P. F@sc{RIEDMAN}
99@author E. K@sc{OHLBECKER}
100@author G. L. S@sc{TEELE} J@sc{R}.
101@author D. H. B@sc{ARTLEY}
102@author R. H@sc{ALSTEAD}
103@author D. O@sc{XLEY}
104@author G. J. S@sc{USSMAN}
105@author G. B@sc{ROOKS}
106@author C. H@sc{ANSON}
107@author K. M. P@sc{ITMAN}
108@author M. W@sc{AND}
a0e07ba4
NJ
109
110
111@c {\it Dedicated to the Memory of ALGOL 60}
112@i{Dedicated to the Memory of Robert Hieb}
113@c [For the macros in R5RS -RK]
114
115
116
117
0c8a2c38 118@majorheading Summary
a0e07ba4
NJ
119
120
121The report gives a defining description of the programming language
122Scheme. Scheme is a statically scoped and properly tail-recursive
123dialect of the Lisp programming language invented by Guy Lewis
124Steele Jr.@: and Gerald Jay Sussman. It was designed to have an
125exceptionally clear and simple semantics and few different ways to
126form expressions. A wide variety of programming paradigms, including
127imperative, functional, and message passing styles, find convenient
128expression in Scheme.
129
130The introduction offers a brief history of the language and of
131the report.
132
133The first three chapters present the fundamental ideas of the
134language and describe the notational conventions used for describing the
135language and for writing programs in the language.
136
137Chapters @ref{Expressions} and @ref{Program structure} describe
138the syntax and semantics of expressions, programs, and definitions.
139
140Chapter @ref{Standard procedures} describes Scheme's built-in
141procedures, which include all of the language's data manipulation and
142input/output primitives.
143
144Chapter @ref{Formal syntax and semantics} provides a formal syntax for Scheme
145written in extended BNF, along with a formal denotational semantics.
146An example of the use of the language follows the formal syntax and
147semantics.
148
149The report concludes with a list of references and an
150alphabetic index.
151
152@ignore todo
153expand the summary so that it fills up the column.
154@end ignore
155
156
157@c \vfill
158@c \begin{center}
159@c {\large \bf
160@c *** DRAFT*** \\
161@c %August 31, 1989
162@c \today
163@c }\end{center}
164
165
166
167
168
169@c \addvspace{3.5pt} % don't shrink this gap
170@c \renewcommand{\tocshrink}{-3.5pt} % value determined experimentally
171
172
173
174
175
176
177@page
178
179@end titlepage
180
181@c INFO first page
6e4de0cc 182@ifnottex
a0e07ba4
NJ
183
184@c First page
185
186@c \thispagestyle{empty}
187
188@c \todo{"another" report?}
189
190
191@node top, Introduction, (dir), (dir)
192@top Revised(5) Report on the Algorithmic Language Scheme
193
194@sp 1
195
196
a0e07ba4 197@quotation
6e4de0cc
MV
198R@sc{ichard} K@sc{elsey}, W@sc{illiam} C@sc{linger, and} J@sc{onathan} R@sc{ees} (@i{Editors})
199@sp 1
a0e07ba4 200@multitable @columnfractions 0.25 0.25 0.25 0.25
6e4de0cc
MV
201@item H. A@sc{belson} @tab R. K. D@sc{ybvig} @tab C. T. H@sc{aynes} @tab G. J. R@sc{ozas}
202@item N. I. A@sc{dams IV} @tab D. P. F@sc{riedman} @tab E. K@sc{ohlbecker} @tab G. L. S@sc{teele} J@sc{r}.
203@item D. H. B@sc{artley} @tab R. H@sc{alstead} @tab D. O@sc{xley} @tab G. J. S@sc{ussman}
204@item G. B@sc{rooks} @tab C. H@sc{anson} @tab K. M. P@sc{itman} @tab M. W@sc{and}
a0e07ba4
NJ
205@item
206@end multitable
207@end quotation
208
209
210@sp 2
211
212@c {\it Dedicated to the Memory of ALGOL 60}
213@i{Dedicated to the Memory of Robert Hieb}
214@c [For the macros in R5RS -RK]
215
216@sp 3
217
218
219
220
221@majorheading Summary
222
223
224The report gives a defining description of the programming language
225Scheme. Scheme is a statically scoped and properly tail-recursive
226dialect of the Lisp programming language invented by Guy Lewis
227Steele Jr.@: and Gerald Jay Sussman. It was designed to have an
228exceptionally clear and simple semantics and few different ways to
229form expressions. A wide variety of programming paradigms, including
230imperative, functional, and message passing styles, find convenient
231expression in Scheme.
232
233The introduction offers a brief history of the language and of
234the report.
235
236The first three chapters present the fundamental ideas of the
237language and describe the notational conventions used for describing the
238language and for writing programs in the language.
239
240Chapters @ref{Expressions} and @ref{Program structure} describe
241the syntax and semantics of expressions, programs, and definitions.
242
243Chapter @ref{Standard procedures} describes Scheme's built-in
244procedures, which include all of the language's data manipulation and
245input/output primitives.
246
247Chapter @ref{Formal syntax and semantics} provides a formal syntax for Scheme
248written in extended BNF, along with a formal denotational semantics.
249An example of the use of the language follows the formal syntax and
250semantics.
251
252The report concludes with a list of references and an
253alphabetic index.
254
255@ignore todo
256expand the summary so that it fills up the column.
257@end ignore
258
259
260@c \vfill
261@c \begin{center}
262@c {\large \bf
263@c *** DRAFT*** \\
264@c %August 31, 1989
265@c \today
266@c }\end{center}
267
268
269
270
271
272@c \addvspace{3.5pt} % don't shrink this gap
273@c \renewcommand{\tocshrink}{-3.5pt} % value determined experimentally
274
275@unnumbered Contents
276
277@menu
278* Introduction::
279* Overview of Scheme::
280* Lexical conventions::
281* Basic concepts::
282* Expressions::
283* Program structure::
284* Standard procedures::
285* Formal syntax and semantics::
286* Notes::
287* Additional material::
288* Example::
289* Bibliography::
290* Index::
291@end menu
292
293
294
295
296
297@page
298
6e4de0cc 299@end ifnottex
a0e07ba4
NJ
300
301
302@c @include{intro}
303@node Introduction, Overview of Scheme, top, top
304@unnumbered Introduction
305
306@menu
307* Background::
308* Acknowledgements::
309@end menu
310
311
312
313
314Programming languages should be designed not by piling feature on top of
315feature, but by removing the weaknesses and restrictions that make additional
316features appear necessary. Scheme demonstrates that a very small number
317of rules for forming expressions, with no restrictions on how they are
318composed, suffice to form a practical and efficient programming language
319that is flexible enough to support most of the major programming
320paradigms in use today.
321
322@c Scheme has influenced the evolution of Lisp.
323Scheme
324was one of the first programming languages to incorporate first class
325procedures as in the lambda calculus, thereby proving the usefulness of
326static scope rules and block structure in a dynamically typed language.
327Scheme was the first major dialect of Lisp to distinguish procedures
328from lambda expressions and symbols, to use a single lexical
329environment for all variables, and to evaluate the operator position
330of a procedure call in the same way as an operand position. By relying
331entirely on procedure calls to express iteration, Scheme emphasized the
332fact that tail-recursive procedure calls are essentially goto's that
333pass arguments. Scheme was the first widely used programming language to
334embrace first class escape procedures, from which all previously known
335sequential control structures can be synthesized. A subsequent
336version of Scheme introduced the concept of exact and inexact numbers,
337an extension of Common Lisp's generic arithmetic.
338More recently, Scheme became the first programming language to support
339hygienic macros, which permit the syntax of a block-structured language
340to be extended in a consistent and reliable manner.
341@c A few
342@c of these innovations have recently been incorporated into Common Lisp, while
343@c others remain to be adopted.
344
345@ignore todo
346Ramsdell:
347I would like to make a few comments on presentation. The most
348important comment is about section organization. Newspaper writers
349spend most of their time writing the first three paragraphs of any
350article. This part of the article is often the only part read by
351readers, and is important in enticing readers to continue. In the
352same way, The first page is most likely to be the only page read by
353many SIGPLAN readers. If I had my choice of what I would ask them to
354read, it would be the material in section 1.1, the Semantics section
355that notes that scheme is lexically scoped, tail recursive, weakly
356typed, ... etc. I would expand on the discussion on continuations,
357as they represent one important difference between Scheme and other
358languages. The introduction, with its history of scheme, its history
359of scheme reports and meetings, and acknowledgements giving names of
360people that the reader will not likely know, is not that one page I
361would like all to read. I suggest moving the history to the back of
362the report, and use the first couple of pages to convince the reader
363that the language documented in this report is worth studying.
364
365@end ignore
366
367
368@node Background, Acknowledgements, Introduction, Introduction
369@unnumberedsec Background
370
371
372The first description of Scheme was written in
3731975 [Scheme75]. A revised report [Scheme78]
374@ignore todo
375italicize or not?
376@end ignore
377 appeared in 1978, which described the evolution
378of the language as its MIT implementation was upgraded to support an
379innovative compiler [Rabbit]. Three distinct projects began in
3801981 and 1982 to use variants of Scheme for courses at MIT, Yale, and
381Indiana University [Rees82], [MITScheme], [Scheme311]. An introductory
382computer science textbook using Scheme was published in
3831984 [SICP].
384
385@c \vest As might be expected of a language used primarily for education and
386@c research, Scheme has always evolved rapidly. This was no problem when
387@c Scheme was used only within MIT, but
388As Scheme became more widespread,
389local dialects began to diverge until students and researchers
390occasionally found it difficult to understand code written at other
391sites.
392Fifteen representatives of the major implementations of Scheme therefore
393met in October 1984 to work toward a better and more widely accepted
394standard for Scheme.
395@c Participating in this workshop were Hal Abelson, Norman Adams, David
396@c Bartley, Gary Brooks, William Clinger, Daniel Friedman, Robert Halstead,
397@c Chris Hanson, Christopher Haynes, Eugene Kohlbecker, Don Oxley, Jonathan Rees,
398@c Guillermo Rozas, Gerald Jay Sussman, and Mitchell Wand. Kent Pitman
399@c made valuable contributions to the agenda for the workshop but was
400@c unable to attend the sessions.
401
402@c Subsequent electronic mail discussions and committee work completed the
403@c definition of the language.
404@c Gerry Sussman drafted the section on numbers, Chris Hanson drafted the
405@c sections on characters and strings, and Gary Brooks and William Clinger
406@c drafted the sections on input and output.
407@c William Clinger recorded the decisions of the workshop and
408@c compiled the pieces into a coherent document.
409@c The ``Revised revised report on Scheme''~\cite{RRRS}
410Their report [RRRS]
411was published at MIT and Indiana University in the summer of 1985.
412Further revision took place in the spring of 1986 [R3RS],
413@c , again accomplished
414@c almost entirely by electronic mail, resulted in the present report.
415and in the spring of 1988 [R4RS].
416The present report reflects further revisions agreed upon in a meeting
417at Xerox PARC in June 1992.
418
419@c \vest The number 3 in the title is part of the title, not a reference to
420@c a footnote. The word ``revised'' is raised to the third power because
421@c the report is a revision of a report that was already twice revised.
422
423@ignore todo
424Write an editors' note?
425@end ignore
426
427
428
429@sp 3
430
431We intend this report to belong to the entire Scheme community, and so
432we grant permission to copy it in whole or in part without fee. In
433particular, we encourage implementors of Scheme to use this report as
434a starting point for manuals and other documentation, modifying it as
435necessary.
436
437
438
439
440@node Acknowledgements, , Background, Introduction
441@unnumberedsec Acknowledgements
442
443
444We would like to thank the following people for their help: Alan Bawden, Michael
445Blair, George Carrette, Andy Cromarty, Pavel Curtis, Jeff Dalton, Olivier Danvy,
446Ken Dickey, Bruce Duba, Marc Feeley,
447Andy Freeman, Richard Gabriel, Yekta G"ursel, Ken Haase, Robert
448Hieb, Paul Hudak, Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim Philbin,
449John Ramsdell, Mike Shaff, Jonathan Shapiro, Julie Sussman,
450Perry Wagle, Daniel Weise, Henry Wu, and Ozan Yigit.
451We thank Carol Fessenden, Daniel
452Friedman, and Christopher Haynes for permission to use text from the Scheme 311
453version 4 reference manual. We thank Texas Instruments, Inc. for permission to
454use text from the @emph{TI Scheme Language Reference Manual}[TImanual85].
455We gladly acknowledge the influence of manuals for MIT Scheme[MITScheme],
456T[Rees84], Scheme 84[Scheme84],Common Lisp[CLtL],
457and Algol 60[Naur63].
458
459We also thank Betty Dexter for the extreme effort she put into
460setting this report in @TeX{}, and Donald Knuth for designing the program
461that caused her troubles.
462
463The Artificial Intelligence Laboratory of the
464Massachusetts Institute of Technology, the Computer Science
465Department of Indiana University, the Computer and Information
466Sciences Department of the University of Oregon, and the NEC Research
467Institute supported the preparation of this report. Support for the MIT
468work was provided in part by
469the Advanced Research Projects Agency of the Department of Defense under Office
470of Naval Research contract N00014-80-C-0505. Support for the Indiana
471University work was provided by NSF grants NCS 83-04567 and NCS
47283-03325.
473
474
475
476
477@sp 2
478
479@c \clearchapterstar{Description of the language} %\unskip\vskip -2ex
480@c @include{struct}
481
482@c 1. Structure of the language
483
484@node Overview of Scheme, Lexical conventions, Introduction, top
485@chapter Overview of Scheme
486
487@menu
488* Semantics::
489* Syntax::
490* Notation and terminology::
491@end menu
492
493
494@node Semantics, Syntax, Overview of Scheme, Overview of Scheme
495@section Semantics
496
497
498
499This section gives an overview of Scheme's semantics. A
500detailed informal semantics is the subject of
501chapters @ref{Basic concepts} through @ref{Standard procedures}. For reference
502purposes, section @ref{Formal semantics} provides a formal
503semantics of Scheme.
504
505Following Algol, Scheme is a statically scoped programming
506language. Each use of a variable is associated with a lexically
507apparent binding of that variable.
508
509Scheme has latent as opposed to manifest types. Types
510are associated with values (also called objects) rather than
511@cindex @w{object}
512with variables. (Some authors refer to languages with latent types as
513weakly typed or dynamically typed languages.) Other languages with
514latent types are APL, Snobol, and other dialects of Lisp. Languages
515with manifest types (sometimes referred to as strongly typed or
516statically typed languages) include Algol 60, Pascal, and C.
517
518All objects created in the course of a Scheme computation, including
519procedures and continuations, have unlimited extent.
520No Scheme object is ever destroyed. The reason that
521implementations of Scheme do not (usually!) run out of storage is that
522they are permitted to reclaim the storage occupied by an object if
523they can prove that the object cannot possibly matter to any future
524computation. Other languages in which most objects have unlimited
525extent include APL and other Lisp dialects.
526
527Implementations of Scheme are required to be properly tail-recursive.
528This allows the execution of an iterative computation in constant space,
529even if the iterative computation is described by a syntactically
530recursive procedure. Thus with a properly tail-recursive implementation,
531iteration can be expressed using the ordinary procedure-call
532mechanics, so that special iteration constructs are useful only as
533syntactic sugar. See section @ref{Proper tail recursion}.
534
535Scheme procedures are objects in their own right. Procedures can be
536created dynamically, stored in data structures, returned as results of
537procedures, and so on. Other languages with these properties include
538Common Lisp and ML.
539@ignore todo
540Rozas: Scheme had them first.
541@end ignore
542
543
544One distinguishing feature of Scheme is that continuations, which
545in most other languages only operate behind the scenes, also have
546``first-class'' status. Continuations are useful for implementing a
547wide variety of advanced control constructs, including non-local exits,
548backtracking, and coroutines. See section @ref{Control features}.
549
550Arguments to Scheme procedures are always passed by value, which
551means that the actual argument expressions are evaluated before the
552procedure gains control, whether the procedure needs the result of the
553evaluation or not. ML, C, and APL are three other languages that always
554pass arguments by value.
555This is distinct from the lazy-evaluation semantics of Haskell,
556or the call-by-name semantics of Algol 60, where an argument
557expression is not evaluated unless its value is needed by the
558procedure.
559
560@ignore todo
561Lisp's call by value should be explained more
562accurately. What's funny is that all values are references.
563@end ignore
564
565
566Scheme's model of arithmetic is designed to remain as independent as
567possible of the particular ways in which numbers are represented within a
568computer. In Scheme, every integer is a rational number, every rational is a
569real, and every real is a complex number. Thus the distinction between integer
570and real arithmetic, so important to many programming languages, does not
571appear in Scheme. In its place is a distinction between exact arithmetic,
572which corresponds to the mathematical ideal, and inexact arithmetic on
573approximations. As in Common Lisp, exact arithmetic is not limited to
574integers.
575
576@node Syntax, Notation and terminology, Semantics, Overview of Scheme
577@section Syntax
578
579
580Scheme, like most dialects of Lisp, employs a fully parenthesized prefix
581notation for programs and (other) data; the grammar of Scheme generates a
582sublanguage of the language used for data. An important
583consequence of this simple, uniform representation is the susceptibility of
584Scheme programs and data to uniform treatment by other Scheme programs.
585For example, the @samp{eval} procedure evaluates a Scheme program expressed
586as data.
587
588The @samp{read} procedure performs syntactic as well as lexical decomposition of
589the data it reads. The @samp{read} procedure parses its input as data
590(section @pxref{External representation}), not as program.
591
592The formal syntax of Scheme is described in section @ref{Formal syntax}.
593
594
595@node Notation and terminology, , Syntax, Overview of Scheme
596@section Notation and terminology
597
598@menu
599* Primitive; library; and optional features::
600* Error situations and unspecified behavior::
601* Entry format::
602* Evaluation examples::
603* Naming conventions::
604@end menu
605
606
607
608@node Primitive; library; and optional features, Error situations and unspecified behavior, Notation and terminology, Notation and terminology
609@subsection Primitive; library; and optional features
610
611
612
613It is required that every implementation of Scheme support all
614features that are not marked as being @dfn{optional}. Implementations are
615@cindex @w{optional}
616free to omit optional features of Scheme or to add extensions,
617provided the extensions are not in conflict with the language reported
618here. In particular, implementations must support portable code by
619providing a syntactic mode that preempts no lexical conventions of this
620report.
621
622To aid in understanding and implementing Scheme, some features are marked
623as @dfn{library}. These can be easily implemented in terms of the other,
624@cindex @w{library}
625primitive, features. They are redundant in the strict sense of
626the word, but they capture common patterns of usage, and are therefore
627provided as convenient abbreviations.
628
629@node Error situations and unspecified behavior, Entry format, Primitive; library; and optional features, Notation and terminology
630@subsection Error situations and unspecified behavior
631
632
633
634@cindex @w{error}
635When speaking of an error situation, this report uses the phrase ``an
636error is signalled'' to indicate that implementations must detect and
637report the error. If such wording does not appear in the discussion of
638an error, then implementations are not required to detect or report the
639error, though they are encouraged to do so. An error situation that
640implementations are not required to detect is usually referred to simply
641as ``an error.''
642
643For example, it is an error for a procedure to be passed an argument that
644the procedure is not explicitly specified to handle, even though such
645domain errors are seldom mentioned in this report. Implementations may
646extend a procedure's domain of definition to include such arguments.
647
648This report uses the phrase ``may report a violation of an
649implementation restriction'' to indicate circumstances under which an
650implementation is permitted to report that it is unable to continue
651execution of a correct program because of some restriction imposed by the
652implementation. Implementation restrictions are of course discouraged,
653but implementations are encouraged to report violations of implementation
654restrictions.
655@cindex @w{implementation restriction}
656
657For example, an implementation may report a violation of an
658implementation restriction if it does not have enough storage to run a
659program.
660
661If the value of an expression is said to be ``unspecified,'' then
662the expression must evaluate to some object without signalling an error,
663but the value depends on the implementation; this report explicitly does
664not say what value should be returned.
665@cindex @w{unspecified}
666
667@ignore todo
668Talk about unspecified behavior vs. unspecified values.
669@end ignore
670
671
672@ignore todo
673Look at KMP's situations paper.
674@end ignore
675
676
677
678@node Entry format, Evaluation examples, Error situations and unspecified behavior, Notation and terminology
679@subsection Entry format
680
681
682Chapters @ref{Expressions} and @ref{Standard procedures} are organized
683into entries. Each entry describes one language feature or a group of
684related features, where a feature is either a syntactic construct or a
685built-in procedure. An entry begins with one or more header lines of the form
686
687
688@noindent
689@deffn {@var{category}} @var{template}
690
691@end deffn
692
693for required, primitive features, or
694
695
696@noindent
697@deffn {@var{qualifier} @var{category}} @var{template}
698
699@end deffn
700
701where @var{qualifier} is either ``library'' or ``optional'' as defined
702 in section @ref{Primitive; library; and optional features}.
703
704If @var{category} is ``syntax'', the entry describes an expression
705type, and the template gives the syntax of the expression type.
706Components of expressions are designated by syntactic variables, which
707are written using angle brackets, for example, @r{<expression>},
708@r{<variable>}. Syntactic variables should be understood to denote segments of
709program text; for example, @r{<expression>} stands for any string of
710characters which is a syntactically valid expression. The notation
711
712@format
713 @r{<thing1>} @dots{}
714@end format
715
716indicates zero or more occurrences of a @r{<thing>}, and
717
718@format
719 @r{<thing1>} @r{<thing2>} @dots{}
720@end format
721
722indicates one or more occurrences of a @r{<thing>}.
723
724If @var{category} is ``procedure'', then the entry describes a procedure, and
725the header line gives a template for a call to the procedure. Argument
726names in the template are @var{italicized}. Thus the header line
727
728
729@noindent
730@deffn {procedure} vector-ref @var{vector} @var{k}
731
732@end deffn
733
734indicates that the built-in procedure @t{vector-ref} takes
735two arguments, a vector @var{vector} and an exact non-negative integer
736@var{k} (see below). The header lines
737
738
739@noindent
740
741@deffn {procedure} make-vector @var{k}
742
743
744@deffnx {procedure} make-vector @var{k} @var{fill}
745
746@end deffn
747
748indicate that the @t{make-vector} procedure must be defined to take
749either one or two arguments.
750
751
752It is an error for an operation to be presented with an argument that it
753is not specified to handle. For succinctness, we follow the convention
754that if an argument name is also the name of a type listed in
755section @ref{Disjointness of types}, then that argument must be of the named type.
756For example, the header line for @t{vector-ref} given above dictates that the
757first argument to @t{vector-ref} must be a vector. The following naming
758conventions also imply type restrictions:
759@c \newcommand{\foo}[1]{\vr{#1}, \vri{#1}, $\ldots$ \vrj{#1}, $\ldots$}
760
761
762@center @c begin-tabular
763@quotation
764@table @asis
765@item @var{obj}
766any object
767@item @var{list}, @var{list1}, @dots{} @var{listj}, @dots{}
768list (see section @pxref{Pairs and lists})
769@item @var{z}, @var{z1}, @dots{} @var{zj}, @dots{}
770complex number
771@item @var{x}, @var{x1}, @dots{} @var{xj}, @dots{}
772real number
773@item @var{y}, @var{y1}, @dots{} @var{yj}, @dots{}
774real number
775@item @var{q}, @var{q1}, @dots{} @var{qj}, @dots{}
776rational number
777@item @var{n}, @var{n1}, @dots{} @var{nj}, @dots{}
778integer
779@item @var{k}, @var{k1}, @dots{} @var{kj}, @dots{}
780exact non-negative integer
781@item
782@end table
783@end quotation
784
785
786
787
788@ignore todo
789Provide an example entry??
790@end ignore
791
792
793
794@node Evaluation examples, Naming conventions, Entry format, Notation and terminology
795@subsection Evaluation examples
796
797
798The symbol ``@result{}'' used in program examples should be read
799``evaluates to.'' For example,
800
801
802@example
803
804(* 5 8) ==> 40
805
806@end example
807
808
809means that the expression @t{(* 5 8)} evaluates to the object @t{40}.
810Or, more precisely: the expression given by the sequence of characters
811``@t{(* 5 8)}'' evaluates, in the initial environment, to an object
812that may be represented externally by the sequence of characters ``@t{40}''. See section @ref{External representations} for a discussion of external
813representations of objects.
814
815@node Naming conventions, , Evaluation examples, Notation and terminology
816@subsection Naming conventions
817
818
819By convention, the names of procedures that always return a boolean
820value usually end
821in ``@code{?}''. Such procedures are called predicates.
822@vindex @w{?}
823
824By convention, the names of procedures that store values into previously
825allocated locations (see section @pxref{Storage model}) usually end in
826``@code{!}''.
827@vindex @w{!}
828Such procedures are called mutation procedures.
829By convention, the value returned by a mutation procedure is unspecified.
830
831By convention, ``@code{->}'' appears within the names of procedures that
832@vindex @w{->}
833take an object of one type and return an analogous object of another type.
834For example, @samp{list->vector} takes a list and returns a vector whose
835elements are the same as those of the list.
836
837
838
839@ignore todo
840Terms that need defining: thunk, command (what else?).
841@end ignore
842
843
844@c @include{lex}
845
846@c Lexical structure
847
848@c %\vfill\eject
849@node Lexical conventions, Basic concepts, Overview of Scheme, top
850@chapter Lexical conventions
851
852@menu
853* Identifiers::
854* Whitespace and comments::
855* Other notations::
856@end menu
857
858
859This section gives an informal account of some of the lexical
860conventions used in writing Scheme programs. For a formal syntax of
861Scheme, see section @ref{Formal syntax}.
862
863Upper and lower case forms of a letter are never distinguished
864except within character and string constants. For example, @samp{Foo} is
865the same identifier as @samp{FOO}, and @t{#x1AB} is the same number as
866@t{#X1ab}.
867
868@node Identifiers, Whitespace and comments, Lexical conventions, Lexical conventions
869@section Identifiers
870
871
872
873Most identifiers allowed by other programming
874@cindex @w{identifier}
875languages are also acceptable to Scheme. The precise rules for forming
876identifiers vary among implementations of Scheme, but in all
877implementations a sequence of letters, digits, and ``extended alphabetic
878characters'' that begins with a character that cannot begin a number is
879an identifier. In addition, @code{+}, @code{-}, and @code{...} are identifiers.
880@vindex @w{...}
881@vindex @w{-}
882@vindex @w{+}
883Here are some examples of identifiers:
884
885
886@example
887
888lambda q
889list->vector soup
890+ V17a
891<=? a34kTMNs
892the-word-recursion-has-many-meanings
893
894@end example
895
896
897Extended alphabetic characters may be used within identifiers as if
898they were letters. The following are extended alphabetic characters:
899
900
901@example
902
903! $ % & * + - . / : < = > ? @@ ^ _ ~
904@end example
905
906
907See section @ref{Lexical structure} for a formal syntax of identifiers.
908
909Identifiers have two uses within Scheme programs:
910
911
912@itemize @bullet
913
914@item
915Any identifier may be used as a variable
916or as a syntactic keyword
917(see sections @pxref{Variables; syntactic keywords; and regions} and @pxref{Macros}).
918
919@item
920When an identifier appears as a literal or within a literal
921(see section @pxref{Literal expressions}), it is being used to denote a @emph{symbol}
922(see section @pxref{Symbols}).
923
924
925@end itemize
926
927@cindex @w{syntactic keyword}
928@cindex @w{variable}
929
930@c \label{keywordsection}
931@c The following identifiers are syntactic keywords, and should not be used
932@c as variables:
933
934@c \begin{scheme}
935@c => do or
936@c and else quasiquote
937@c begin if quote
938@c case lambda set!
939@c cond let unquote
940@c define let* unquote-splicing
941@c delay letrec%
942@c \end{scheme}
943
944@c Some implementations allow all identifiers, including syntactic
945@c keywords, to be used as variables. This is a compatible extension to
946@c the language, but ambiguities in the language result when the
947@c restriction is relaxed, and the ways in which these ambiguities are
948@c resolved vary between implementations.
949
950
951@node Whitespace and comments, Other notations, Identifiers, Lexical conventions
952@section Whitespace and comments
953
954
955@dfn{Whitespace} characters are spaces and newlines.
956@cindex @w{Whitespace}
957(Implementations typically provide additional whitespace characters such
958as tab or page break.) Whitespace is used for improved readability and
959as necessary to separate tokens from each other, a token being an
960indivisible lexical unit such as an identifier or number, but is
961otherwise insignificant. Whitespace may occur between any two tokens,
962but not within a token. Whitespace may also occur inside a string,
963where it is significant.
964
965A semicolon (@t{;}) indicates the start of a
966comment. The comment continues to the
967@cindex @w{;}
968@cindex @w{comment}
969end of the line on which the semicolon appears. Comments are invisible
970to Scheme, but the end of the line is visible as whitespace. This
971prevents a comment from appearing in the middle of an identifier or
972number.
973
974
975@example
976
977;;; The FACT procedure computes the factorial
978;;; of a non-negative integer.
979(define fact
980 (lambda (n)
981 (if (= n 0)
982 1 ;Base case: return 1
983 (* n (fact (- n 1))))))
984
985@end example
986
987
988
989@node Other notations, , Whitespace and comments, Lexical conventions
990@section Other notations
991
992
993@ignore todo
994Rewrite?
995@end ignore
996
997
998For a description of the notations used for numbers, see
999section @ref{Numbers}.
1000
1001
1002@table @t
1003
1004
1005@item @t{.@: + -}
1006These are used in numbers, and may also occur anywhere in an identifier
1007except as the first character. A delimited plus or minus sign by itself
1008is also an identifier.
1009A delimited period (not occurring within a number or identifier) is used
1010in the notation for pairs (section @pxref{Pairs and lists}), and to indicate a
1011rest-parameter in a formal parameter list (section @pxref{Procedures}).
1012A delimited sequence of three successive periods is also an identifier.
1013
1014@item @t{( )}
1015Parentheses are used for grouping and to notate lists
1016(section @pxref{Pairs and lists}).
1017
1018@item @t{'}
1019The single quote character is used to indicate literal data (section @pxref{Literal expressions}).
1020
1021@item @t{`}
1022The backquote character is used to indicate almost-constant
1023data (section @pxref{Quasiquotation}).
1024
1025@item @t{, ,@@}
1026The character comma and the sequence comma at-sign are used in conjunction
1027with backquote (section @pxref{Quasiquotation}).
1028
1029@item @t{"}
1030The double quote character is used to delimit strings (section @pxref{Strings}).
1031
1032@item \
1033Backslash is used in the syntax for character constants
1034(section @pxref{Characters}) and as an escape character within string
1035constants (section @pxref{Strings}).
1036
1037@c A box used because \verb is not allowed in command arguments.
1038
1039@item @w{@t{[ ] @{ @} |}}
1040Left and right square brackets and curly braces and vertical bar
1041are reserved for possible future extensions to the language.
1042
1043@item #
1044 Sharp sign is used for a variety of purposes depending on
1045the character that immediately follows it:
1046
1047@item @t{#t} @t{#f}
1048These are the boolean constants (section @pxref{Booleans}).
1049
1050@item #\
1051This introduces a character constant (section @pxref{Characters}).
1052
1053@item #@t{(}
1054This introduces a vector constant (section @pxref{Vectors}). Vector constants
1055are terminated by @t{)} .
1056
1057@item @t{#e #i #b #o #d #x}
1058These are used in the notation for numbers (section @pxref{Syntax of numerical constants}).
1059
1060@end table
1061
1062
1063@c @include{basic}
1064
1065@c \vfill\eject
1066@node Basic concepts, Expressions, Lexical conventions, top
1067@chapter Basic concepts
1068
1069@menu
1070* Variables; syntactic keywords; and regions::
1071* Disjointness of types::
1072* External representations::
1073* Storage model::
1074* Proper tail recursion::
1075@end menu
1076
1077
1078
1079@node Variables; syntactic keywords; and regions, Disjointness of types, Basic concepts, Basic concepts
1080@section Variables; syntactic keywords; and regions
1081
1082
1083
1084
1085An identifier may name a type of syntax, or it may name
1086@cindex @w{identifier}
1087a location where a value can be stored. An identifier that names a type
1088of syntax is called a @emph{syntactic keyword}
1089@cindex @w{syntactic keyword}
1090and is said to be @emph{bound} to that syntax. An identifier that names a
1091location is called a @emph{variable} and is said to be
1092@cindex @w{variable}
1093@emph{bound} to that location. The set of all visible
1094bindings in effect at some point in a program is
1095@cindex @w{binding}
1096known as the @emph{environment} in effect at that point. The value
1097stored in the location to which a variable is bound is called the
1098variable's value. By abuse of terminology, the variable is sometimes
1099said to name the value or to be bound to the value. This is not quite
1100accurate, but confusion rarely results from this practice.
1101
1102@ignore todo
1103Define ``assigned'' and ``unassigned'' perhaps?
1104@end ignore
1105
1106
1107@ignore todo
1108In programs without side effects, one can safely pretend that the
1109variables are bound directly to the arguments. Or:
1110In programs without @code{set!}, one can safely pretend that the
1111@vindex @w{set!}
1112variable is bound directly to the value.
1113@end ignore
1114
1115
1116Certain expression types are used to create new kinds of syntax
1117and bind syntactic keywords to those new syntaxes, while other
1118expression types create new locations and bind variables to those
1119locations. These expression types are called @emph{binding constructs}.
1120
1121@cindex @w{binding construct}
1122Those that bind syntactic keywords are listed in section @ref{Macros}.
1123The most fundamental of the variable binding constructs is the
1124@samp{lambda} expression, because all other variable binding constructs
1125can be explained in terms of @samp{lambda} expressions. The other
1126variable binding constructs are @samp{let}, @samp{let*}, @samp{letrec},
1127and @samp{do} expressions (see sections @pxref{Procedures}, @pxref{Binding constructs}, and
1128@pxref{Iteration}).
1129
1130@c Note: internal definitions not mentioned here.
1131
1132Like Algol and Pascal, and unlike most other dialects of Lisp
1133except for Common Lisp, Scheme is a statically scoped language with
1134block structure. To each place where an identifier is bound in a program
1135there corresponds a @dfn{region} of the program text within which
1136@cindex @w{region}
1137the binding is visible. The region is determined by the particular
1138binding construct that establishes the binding; if the binding is
1139established by a @samp{lambda} expression, for example, then its region
1140is the entire @samp{lambda} expression. Every mention of an identifier
1141refers to the binding of the identifier that established the
1142innermost of the regions containing the use. If there is no binding of
1143the identifier whose region contains the use, then the use refers to the
1144binding for the variable in the top level environment, if any
1145(chapters @pxref{Expressions} and @pxref{Standard procedures}); if there is no
1146binding for the identifier,
1147it is said to be @dfn{unbound}.
1148@cindex @w{top level environment}
1149@cindex @w{bound}
1150@cindex @w{unbound}
1151
1152@ignore todo
1153Mention that some implementations have multiple top level environments?
1154@end ignore
1155
1156
1157@ignore todo
1158Pitman sez: needs elaboration in case of @t{(let ...)}
1159@end ignore
1160
1161
1162@ignore todo
1163Pitman asks: say something about vars created after scheme starts?
1164@t{(define x 3) (define (f) x) (define (g) y) (define y 4)}
1165Clinger replies: The language was explicitly
1166designed to permit a view in which no variables are created after
1167Scheme starts. In files, you can scan out the definitions beforehand.
1168I think we're agreed on the principle that interactive use should
1169approximate that behavior as closely as possible, though we don't yet
1170agree on which programming environment provides the best approximation.
1171@end ignore
1172
1173
1174@node Disjointness of types, External representations, Variables; syntactic keywords; and regions, Basic concepts
1175@section Disjointness of types
1176
1177
1178
1179No object satisfies more than one of the following predicates:
1180
1181
1182@example
1183
1184boolean? pair?
1185symbol? number?
1186char? string?
1187vector? port?
1188procedure?
1189
1190@end example
1191
1192
1193These predicates define the types @emph{boolean}, @emph{pair}, @emph{symbol}, @emph{number}, @emph{char} (or @emph{character}), @emph{string}, @emph{vector}, @emph{port}, and @emph{procedure}. The empty list is a special
1194object of its own type; it satisfies none of the above predicates.
1195
1196@vindex symbol?
1197@vindex pair?
1198@vindex boolean?
1199@cindex @w{type}
1200
1201@vindex vector?
1202@vindex string?
1203@vindex char?
1204@vindex number?
1205
1206@cindex @w{empty list}
1207@vindex procedure?
1208@vindex port?
1209
1210Although there is a separate boolean type,
1211any Scheme value can be used as a boolean value for the purpose of a
1212conditional test. As explained in section @ref{Booleans}, all
1213values count as true in such a test except for @t{#f}.
1214@c and possibly the empty list.
1215@c The only value that is guaranteed to count as
1216@c false is \schfalse{}. It is explicitly unspecified whether the empty list
1217@c counts as true or as false.
1218This report uses the word ``true'' to refer to any
1219Scheme value except @t{#f}, and the word ``false'' to refer to
1220@t{#f}.
1221@cindex @w{false}
1222@cindex @w{true}
1223
1224@node External representations, Storage model, Disjointness of types, Basic concepts
1225@section External representations
1226
1227
1228
1229An important concept in Scheme (and Lisp) is that of the @emph{external
1230representation} of an object as a sequence of characters. For example,
1231an external representation of the integer 28 is the sequence of
1232characters ``@t{28}'', and an external representation of a list consisting
1233of the integers 8 and 13 is the sequence of characters ``@t{(8 13)}''.
1234
1235The external representation of an object is not necessarily unique. The
1236integer 28 also has representations ``@t{#e28.000}'' and ``@t{#x1c}'', and the
1237list in the previous paragraph also has the representations ``@t{( 08 13
1238)}'' and ``@t{(8 .@: (13 .@: ()))}'' (see section @pxref{Pairs and lists}).
1239
1240Many objects have standard external representations, but some, such as
1241procedures, do not have standard representations (although particular
1242implementations may define representations for them).
1243
1244An external representation may be written in a program to obtain the
1245corresponding object (see @samp{quote}, section @pxref{Literal expressions}).
1246
1247External representations can also be used for input and output. The
1248procedure @samp{read} (section @pxref{Input}) parses external
1249representations, and the procedure @samp{write} (section @pxref{Output})
1250generates them. Together, they provide an elegant and powerful
1251input/output facility.
1252
1253Note that the sequence of characters ``@t{(+ 2 6)}'' is @emph{not} an
1254external representation of the integer 8, even though it @emph{is} an
1255expression evaluating to the integer 8; rather, it is an external
1256representation of a three-element list, the elements of which are the symbol
1257@t{+} and the integers 2 and 6. Scheme's syntax has the property that
1258any sequence of characters that is an expression is also the external
1259representation of some object. This can lead to confusion, since it may
1260not be obvious out of context whether a given sequence of characters is
1261intended to denote data or program, but it is also a source of power,
1262since it facilitates writing programs such as interpreters and
1263compilers that treat programs as data (or vice versa).
1264
1265The syntax of external representations of various kinds of objects
1266accompanies the description of the primitives for manipulating the
1267objects in the appropriate sections of chapter @ref{Standard procedures}.
1268
1269@node Storage model, Proper tail recursion, External representations, Basic concepts
1270@section Storage model
1271
1272
1273
1274Variables and objects such as pairs, vectors, and strings implicitly
1275denote locations or sequences of locations. A string, for
1276@cindex @w{location}
1277example, denotes as many locations as there are characters in the string.
1278(These locations need not correspond to a full machine word.) A new value may be
1279stored into one of these locations using the @t{string-set!} procedure, but
1280the string continues to denote the same locations as before.
1281
1282An object fetched from a location, by a variable reference or by
1283a procedure such as @samp{car}, @samp{vector-ref}, or @samp{string-ref}, is
1284equivalent in the sense of @code{eqv?}
1285@c and \ide{eq?} ??
1286(section @pxref{Equivalence predicates})
1287@vindex @w{eqv?}
1288to the object last stored in the location before the fetch.
1289
1290Every location is marked to show whether it is in use.
1291No variable or object ever refers to a location that is not in use.
1292Whenever this report speaks of storage being allocated for a variable
1293or object, what is meant is that an appropriate number of locations are
1294chosen from the set of locations that are not in use, and the chosen
1295locations are marked to indicate that they are now in use before the variable
1296or object is made to denote them.
1297
1298In many systems it is desirable for constants (i.e. the values of
1299@cindex @w{constant}
1300literal expressions) to reside in read-only-memory. To express this, it is
1301convenient to imagine that every object that denotes locations is associated
1302with a flag telling whether that object is mutable or
1303@cindex @w{mutable}
1304immutable. In such systems literal constants and the strings
1305@cindex @w{immutable}
1306returned by @code{symbol->string} are immutable objects, while all objects
1307@vindex @w{symbol->string}
1308created by the other procedures listed in this report are mutable. It is an
1309error to attempt to store a new value into a location that is denoted by an
1310immutable object.
1311
1312@node Proper tail recursion, , Storage model, Basic concepts
1313@section Proper tail recursion
1314
1315
1316
1317Implementations of Scheme are required to be
1318@emph{properly tail-recursive}.
1319@cindex @w{proper tail recursion}
1320Procedure calls that occur in certain syntactic
1321contexts defined below are `tail calls'. A Scheme implementation is
1322properly tail-recursive if it supports an unbounded number of active
1323tail calls. A call is @emph{active} if the called procedure may still
1324return. Note that this includes calls that may be returned from either
1325by the current continuation or by continuations captured earlier by
1326@samp{call-with-current-continuation} that are later invoked.
1327In the absence of captured continuations, calls could
1328return at most once and the active calls would be those that had not
1329yet returned.
1330A formal definition of proper tail recursion can be found
1331in [propertailrecursion].
1332
1333
1334@quotation
1335@emph{Rationale:}
1336
1337Intuitively, no space is needed for an active tail call because the
1338continuation that is used in the tail call has the same semantics as the
1339continuation passed to the procedure containing the call. Although an improper
1340implementation might use a new continuation in the call, a return
1341to this new continuation would be followed immediately by a return
1342to the continuation passed to the procedure. A properly tail-recursive
1343implementation returns to that continuation directly.
1344
1345Proper tail recursion was one of the central ideas in Steele and
1346Sussman's original version of Scheme. Their first Scheme interpreter
1347implemented both functions and actors. Control flow was expressed using
1348actors, which differed from functions in that they passed their results
1349on to another actor instead of returning to a caller. In the terminology
1350of this section, each actor finished with a tail call to another actor.
1351
1352Steele and Sussman later observed that in their interpreter the code
1353for dealing with actors was identical to that for functions and thus
1354there was no need to include both in the language.
1355
1356@end quotation
1357
1358
1359A @emph{tail call} is a procedure call that occurs
1360@cindex @w{tail call}
1361in a @emph{tail context}. Tail contexts are defined inductively. Note
1362that a tail context is always determined with respect to a particular lambda
1363expression.
1364
1365
1366
1367@itemize @bullet
1368
1369@item
1370The last expression within the body of a lambda expression,
1371shown as @r{<tail expression>} below, occurs in a tail context.
1372
1373@format
1374@t{(lambda <formals>
1375 <definition>* <expression>* <tail expression>)
1376}
1377
1378@end format
1379
1380
1381
1382@item
1383If one of the following expressions is in a tail context,
1384then the subexpressions shown as <tail expression> are in a tail context.
1385These were derived from rules in the grammar given in
1386chapter @ref{Formal syntax and semantics} by replacing some occurrences of <expression>
1387with <tail expression>. Only those rules that contain tail contexts
1388are shown here.
1389
1390
1391@format
1392@t{(if <expression> <tail expression> <tail expression>)
1393(if <expression> <tail expression>)
1394
1395(cond <cond clause>+)
1396(cond <cond clause>* (else <tail sequence>))
1397
1398(case <expression>
1399 <case clause>+)
1400(case <expression>
1401 <case clause>*
1402 (else <tail sequence>))
1403
1404(and <expression>* <tail expression>)
1405(or <expression>* <tail expression>)
1406
1407(let (<binding spec>*) <tail body>)
1408(let <variable> (<binding spec>*) <tail body>)
1409(let* (<binding spec>*) <tail body>)
1410(letrec (<binding spec>*) <tail body>)
1411
1412(let-syntax (<syntax spec>*) <tail body>)
1413(letrec-syntax (<syntax spec>*) <tail body>)
1414
1415(begin <tail sequence>)
1416
1417(do (<iteration spec>*)
1418 (<test> <tail sequence>)
1419 <expression>*)
1420
1421@r{where}
1422
1423<cond clause> --> (<test> <tail sequence>)
1424<case clause> --> ((<datum>*) <tail sequence>)
1425
1426<tail body> --> <definition>* <tail sequence>
1427<tail sequence> --> <expression>* <tail expression>
1428}
1429
1430@end format
1431
1432
1433
1434@item
1435If a @samp{cond} expression is in a tail context, and has a clause of
1436the form @samp{(@r{<expression1>} => @r{<expression2>})}
1437then the (implied) call to
1438the procedure that results from the evaluation of @r{<expression2>} is in a
1439tail context. @r{<expression2>} itself is not in a tail context.
1440
1441
1442@end itemize
1443
1444
1445Certain built-in procedures are also required to perform tail calls.
1446The first argument passed to @code{apply} and to
1447@vindex @w{apply}
1448@code{call-with-current-continuation}, and the second argument passed to
1449@vindex @w{call-with-current-continuation}
1450@code{call-with-values}, must be called via a tail call.
1451@vindex @w{call-with-values}
1452Similarly, @code{eval} must evaluate its argument as if it
1453@vindex @w{eval}
1454were in tail position within the @code{eval} procedure.
1455@vindex @w{eval}
1456
1457In the following example the only tail call is the call to @samp{f}.
1458None of the calls to @samp{g} or @samp{h} are tail calls. The reference to
1459@samp{x} is in a tail context, but it is not a call and thus is not a
1460tail call.
1461
1462@example
1463
1464(lambda ()
1465 (if (g)
1466 (let ((x (h)))
1467 x)
1468 (and (g) (f))))
1469
1470@end example
1471
1472
1473
1474@quotation
1475@emph{Note:}
1476Implementations are allowed, but not required, to
1477recognize that some non-tail calls, such as the call to @samp{h}
1478above, can be evaluated as though they were tail calls.
1479In the example above, the @samp{let} expression could be compiled
1480as a tail call to @samp{h}. (The possibility of @samp{h} returning
1481an unexpected number of values can be ignored, because in that
1482case the effect of the @samp{let} is explicitly unspecified and
1483implementation-dependent.)
1484@end quotation
1485
1486
1487
1488@c @include{expr}
1489
1490@c \vfill\eject
1491@node Expressions, Program structure, Basic concepts, top
1492@chapter Expressions
1493
1494@menu
1495* Primitive expression types::
1496* Derived expression types::
1497* Macros::
1498@end menu
1499
1500
1501
1502@c \newcommand{\syntax}{{\em Syntax: }}
1503@c \newcommand{\semantics}{{\em Semantics: }}
1504
1505@c [Deleted for R5RS because of multiple-value returns. -RK]
1506@c A Scheme expression is a construct that returns a value, such as a
1507@c variable reference, literal, procedure call, or conditional.
1508
1509Expression types are categorized as @emph{primitive} or @emph{derived}.
1510Primitive expression types include variables and procedure calls.
1511Derived expression types are not semantically primitive, but can instead
1512be defined as macros.
1513With the exception of @samp{quasiquote}, whose macro definition is complex,
1514the derived expressions are classified as library features.
1515Suitable definitions are given in section @ref{Derived expression type}.
1516
1517@node Primitive expression types, Derived expression types, Expressions, Expressions
1518@section Primitive expression types
1519
1520@menu
1521* Variable references::
1522* Literal expressions::
1523* Procedure calls::
1524* Procedures::
1525* Conditionals::
1526* Assignments::
1527@end menu
1528
1529
1530
1531@node Variable references, Literal expressions, Primitive expression types, Primitive expression types
1532@subsection Variable references
1533
1534
1535
1536@deffn {syntax} @r{<variable>}
1537
1538
1539An expression consisting of a variable
1540@cindex @w{variable}
1541(section @pxref{Variables; syntactic keywords; and regions}) is a variable reference. The value of
1542the variable reference is the value stored in the location to which the
1543variable is bound. It is an error to reference an
1544unbound variable.
1545@cindex @w{unbound}
1546
1547
1548@format
1549@t{(define x 28)
1550x ==> 28
1551}
1552@end format
1553
1554@end deffn
1555
1556@node Literal expressions, Procedure calls, Variable references, Primitive expression types
1557@subsection Literal expressions
1558
1559
1560
1561
1562@deffn {syntax} quote @r{<datum>}
1563
1564@deffnx {syntax} @t{'}@r{<datum>}
1565
1566
1567@deffnx {syntax} @r{<constant>}
1568
1569
1570@samp{(quote @r{<datum>})} evaluates to @r{<datum>}.
1571@cindex @w{'}
1572@r{<Datum>}
1573may be any external representation of a Scheme object (see
1574section @pxref{External representations}). This notation is used to include literal
1575constants in Scheme code.
1576
1577
1578@format
1579@t{
1580(quote a) ==> a
1581(quote #(a b c)) ==> #(a b c)
1582(quote (+ 1 2)) ==> (+ 1 2)
1583}
1584@end format
1585
1586
1587@samp{(quote @r{<datum>})} may be abbreviated as
1588@t{'}@r{<datum>}. The two notations are equivalent in all
1589respects.
1590
1591
1592@format
1593@t{'a ==> a
1594'#(a b c) ==> #(a b c)
1595'() ==> ()
1596'(+ 1 2) ==> (+ 1 2)
1597'(quote a) ==> (quote a)
1598''a ==> (quote a)
1599}
1600@end format
1601
1602
1603Numerical constants, string constants, character constants, and boolean
1604constants evaluate ``to themselves''; they need not be quoted.
1605
1606
1607@format
1608@t{'"abc" ==> "abc"
1609"abc" ==> "abc"
1610'145932 ==> 145932
1611145932 ==> 145932
1612'#t ==> #t
1613#t ==> #t
1614}
1615@end format
1616
1617
1618As noted in section @ref{Storage model}, it is an error to alter a constant
1619(i.e. the value of a literal expression) using a mutation procedure like
1620@samp{set-car!} or @samp{string-set!}.
1621
1622@end deffn
1623
1624
1625@node Procedure calls, Procedures, Literal expressions, Primitive expression types
1626@subsection Procedure calls
1627
1628
1629
1630@deffn {syntax} @r{<operator>} @r{<operand1>} @dots{},
1631
1632
1633A procedure call is written by simply enclosing in parentheses
1634expressions for the procedure to be called and the arguments to be
1635passed to it. The operator and operand expressions are evaluated (in an
1636unspecified order) and the resulting procedure is passed the resulting
1637arguments.
1638@cindex @w{procedure call}
1639@cindex @w{call}
1640
1641@format
1642@t{
1643(+ 3 4) ==> 7
1644((if #f + *) 3 4) ==> 12
1645}
1646@end format
1647
1648
1649A number of procedures are available as the values of variables in the
1650initial environment; for example, the addition and multiplication
1651procedures in the above examples are the values of the variables @samp{+}
1652and @samp{*}. New procedures are created by evaluating lambda expressions
1653(see section @pxref{Procedures}).
1654@ignore todo
1655At Friedman's request, flushed mention of other ways.
1656@end ignore
1657
1658@c or definitions (see section~\ref{define}).
1659
1660Procedure calls may return any number of values (see @code{values} in
1661@vindex @w{values}
1662section @pxref{Control features}). With the exception of @samp{values}
1663the procedures available in the initial environment return one
1664value or, for procedures such as @samp{apply}, pass on the values returned
1665by a call to one of their arguments.
1666
1667Procedure calls are also called @emph{combinations}.
1668
1669@cindex @w{combination}
1670
1671
1672@quotation
1673@emph{Note:} In contrast to other dialects of Lisp, the order of
1674evaluation is unspecified, and the operator expression and the operand
1675expressions are always evaluated with the same evaluation rules.
1676@end quotation
1677
1678
1679
1680@quotation
1681@emph{Note:}
1682Although the order of evaluation is otherwise unspecified, the effect of
1683any concurrent evaluation of the operator and operand expressions is
1684constrained to be consistent with some sequential order of evaluation.
1685The order of evaluation may be chosen differently for each procedure call.
1686@end quotation
1687
1688
1689
1690@quotation
1691@emph{Note:} In many dialects of Lisp, the empty combination, @t{()}, is a legitimate expression. In Scheme, combinations must have at
1692least one subexpression, so @t{()} is not a syntactically valid
1693expression.
1694@ignore todo
1695Dybvig: ``it should be obvious from the syntax.''
1696@end ignore
1697
1698@end quotation
1699
1700
1701@ignore todo
1702Freeman:
1703I think an explanation as to why evaluation order is not specified
1704should be included. It should not include any reference to parallel
1705evaluation. Does any existing compiler generate better code because
1706the evaluation order is unspecified? Clinger: yes: T3, MacScheme v2,
1707probably MIT Scheme and Chez Scheme. But that's not the main reason
1708for leaving the order unspecified.
1709@end ignore
1710
1711
1712@end deffn
1713
1714
1715@node Procedures, Conditionals, Procedure calls, Primitive expression types
1716@subsection Procedures
1717
1718
1719
1720
1721@deffn {syntax} lambda @r{<formals>} @r{<body>}
1722
1723@emph{Syntax:}
1724@r{<Formals>} should be a formal arguments list as described below,
1725and @r{<body>} should be a sequence of one or more expressions.
1726
1727@emph{Semantics:}
1728A lambda expression evaluates to a procedure. The environment in
1729effect when the lambda expression was evaluated is remembered as part of the
1730procedure. When the procedure is later called with some actual
1731arguments, the environment in which the lambda expression was evaluated will
1732be extended by binding the variables in the formal argument list to
1733fresh locations, the corresponding actual argument values will be stored
1734in those locations, and the expressions in the body of the lambda expression
1735will be evaluated sequentially in the extended environment.
1736The result(s) of the last expression in the body will be returned as
1737the result(s) of the procedure call.
1738
1739
1740@format
1741@t{(lambda (x) (+ x x)) ==> @emph{}a procedure
1742((lambda (x) (+ x x)) 4) ==> 8
1743
1744(define reverse-subtract
1745 (lambda (x y) (- y x)))
1746(reverse-subtract 7 10) ==> 3
1747
1748(define add4
1749 (let ((x 4))
1750 (lambda (y) (+ x y))))
1751(add4 6) ==> 10
1752}
1753@end format
1754
1755
1756@r{<Formals>} should have one of the following forms:
1757
1758
1759
1760@itemize @bullet
1761
1762@item
1763@t{(@r{<variable1>} @dots{},)}:
1764The procedure takes a fixed number of arguments; when the procedure is
1765called, the arguments will be stored in the bindings of the
1766corresponding variables.
1767
1768@item
1769@r{<variable>}:
1770The procedure takes any number of arguments; when the procedure is
1771called, the sequence of actual arguments is converted into a newly
1772allocated list, and the list is stored in the binding of the
1773@r{<variable>}.
1774
1775@item
1776@t{(@r{<variable1>} @dots{}, @r{<variable_n>} @b{.}
1777@r{<variable_n+1>})}:
1778If a space-delimited period precedes the last variable, then
1779the procedure takes n or more arguments, where n is the
1780number of formal arguments before the period (there must
1781be at least one).
1782The value stored in the binding of the last variable will be a
1783newly allocated
1784list of the actual arguments left over after all the other actual
1785arguments have been matched up against the other formal arguments.
1786
1787@end itemize
1788
1789
1790It is an error for a @r{<variable>} to appear more than once in
1791@r{<formals>}.
1792
1793
1794@format
1795@t{((lambda x x) 3 4 5 6) ==> (3 4 5 6)
1796((lambda (x y . z) z)
1797 3 4 5 6) ==> (5 6)
1798}
1799@end format
1800
1801
1802Each procedure created as the result of evaluating a lambda expression is
1803(conceptually) tagged
1804with a storage location, in order to make @code{eqv?} and
1805@vindex @w{eqv?}
1806@code{eq?} work on procedures (see section @pxref{Equivalence predicates}).
1807@vindex @w{eq?}
1808
1809@end deffn
1810
1811
1812@node Conditionals, Assignments, Procedures, Primitive expression types
1813@subsection Conditionals
1814
1815
1816
1817@deffn {syntax} if @r{<test>} @r{<consequent>} @r{<alternate>}
1818@deffnx {syntax} if @r{<test>} @r{<consequent>}
1819@c \/ if hyper = italic
1820
1821@emph{Syntax:}
1822@r{<Test>}, @r{<consequent>}, and @r{<alternate>} may be arbitrary
1823expressions.
1824
1825@emph{Semantics:}
1826An @samp{if} expression is evaluated as follows: first,
1827@r{<test>} is evaluated. If it yields a true value (see
1828@cindex @w{true}
1829section @pxref{Booleans}), then @r{<consequent>} is evaluated and
1830its value(s) is(are) returned. Otherwise @r{<alternate>} is evaluated and its
1831value(s) is(are) returned. If @r{<test>} yields a false value and no
1832@r{<alternate>} is specified, then the result of the expression is
1833unspecified.
1834
1835
1836@format
1837@t{(if (> 3 2) 'yes 'no) ==> yes
1838(if (> 2 3) 'yes 'no) ==> no
1839(if (> 3 2)
1840 (- 3 2)
1841 (+ 3 2)) ==> 1
1842}
1843@end format
1844
1845
1846@end deffn
1847
1848
1849@node Assignments, , Conditionals, Primitive expression types
1850@subsection Assignments
1851
1852
1853
1854
1855@deffn {syntax} set! @r{<variable>} @r{<expression>}
1856
1857@r{<Expression>} is evaluated, and the resulting value is stored in
1858the location to which @r{<variable>} is bound. @r{<Variable>} must
1859be bound either in some region enclosing the @samp{set!} expression
1860@cindex @w{region}
1861or at top level. The result of the @samp{set!} expression is
1862unspecified.
1863
1864
1865@format
1866@t{(define x 2)
1867(+ x 1) ==> 3
1868(set! x 4) ==> @emph{unspecified}
1869(+ x 1) ==> 5
1870}
1871@end format
1872
1873
1874@end deffn
1875
1876
1877@node Derived expression types, Macros, Primitive expression types, Expressions
1878@section Derived expression types
1879
1880@menu
1881* Conditional::
1882* Binding constructs::
1883* Sequencing::
1884* Iteration::
1885* Delayed evaluation::
1886* Quasiquotation::
1887@end menu
1888
1889
1890
1891The constructs in this section are hygienic, as discussed in
1892section @ref{Macros}.
1893For reference purposes, section @ref{Derived expression type} gives macro definitions
1894that will convert most of the constructs described in this section
1895into the primitive constructs described in the previous section.
1896
1897@ignore todo
1898Mention that no definition of backquote is provided?
1899@end ignore
1900
1901
1902@node Conditional, Binding constructs, Derived expression types, Derived expression types
1903@subsection Conditionals
1904
1905
1906
1907@deffn {library syntax} cond <clause1> <clause2> @dots{},
1908
1909@emph{Syntax:}
1910Each @r{<clause>} should be of the form
1911
1912@format
1913@t{(@r{<test>} @r{<expression1>} @dots{},)
1914}
1915@end format
1916
1917where @r{<test>} is any expression. Alternatively, a @r{<clause>} may be
1918of the form
1919
1920@format
1921@t{(@r{<test>} => @r{<expression>})
1922}
1923@end format
1924
1925The last @r{<clause>} may be
1926an ``else clause,'' which has the form
1927
1928@format
1929@t{(else @r{<expression1>} @r{<expression2>} @dots{},)@r{.}
1930}
1931@end format
1932
1933
1934@cindex @w{else}
1935
1936@cindex @w{=>}
1937
1938@emph{Semantics:}
1939A @samp{cond} expression is evaluated by evaluating the @r{<test>}
1940expressions of successive @r{<clause>}s in order until one of them
1941evaluates to a true value (see
1942@cindex @w{true}
1943section @pxref{Booleans}). When a @r{<test>} evaluates to a true
1944value, then the remaining @r{<expression>}s in its @r{<clause>} are
1945evaluated in order, and the result(s) of the last @r{<expression>} in the
1946@r{<clause>} is(are) returned as the result(s) of the entire @samp{cond}
1947expression. If the selected @r{<clause>} contains only the
1948@r{<test>} and no @r{<expression>}s, then the value of the
1949@r{<test>} is returned as the result. If the selected @r{<clause>} uses the
1950@code{=>} alternate form, then the @r{<expression>} is evaluated.
1951@vindex @w{=>}
1952Its value must be a procedure that accepts one argument; this procedure is then
1953called on the value of the @r{<test>} and the value(s) returned by this
1954procedure is(are) returned by the @samp{cond} expression.
1955If all @r{<test>}s evaluate
1956to false values, and there is no else clause, then the result of
1957the conditional expression is unspecified; if there is an else
1958clause, then its @r{<expression>}s are evaluated, and the value(s) of
1959the last one is(are) returned.
1960
1961
1962@format
1963@t{(cond ((> 3 2) 'greater)
1964 ((< 3 2) 'less)) ==> greater
1965
1966(cond ((> 3 3) 'greater)
1967 ((< 3 3) 'less)
1968 (else 'equal)) ==> equal
1969
1970(cond ((assv 'b '((a 1) (b 2))) => cadr)
1971 (else #f)) ==> 2
1972}
1973@end format
1974
1975
1976
1977@end deffn
1978
1979
1980
1981@deffn {library syntax} case @r{<key>} <clause1> <clause2> @dots{},
1982
1983@emph{Syntax:}
1984@r{<Key>} may be any expression. Each @r{<clause>} should have
1985the form
1986
1987@format
1988@t{((@r{<datum1>} @dots{},) @r{<expression1>} @r{<expression2>} @dots{},)@r{,}
1989}
1990@end format
1991
1992where each @r{<datum>} is an external representation of some object.
1993All the @r{<datum>}s must be distinct.
1994The last @r{<clause>} may be an ``else clause,'' which has the form
1995
1996@format
1997@t{(else @r{<expression1>} @r{<expression2>} @dots{},)@r{.}
1998}
1999@end format
2000
2001
2002@vindex else
2003
2004@emph{Semantics:}
2005A @samp{case} expression is evaluated as follows. @r{<Key>} is
2006evaluated and its result is compared against each @r{<datum>}. If the
2007result of evaluating @r{<key>} is equivalent (in the sense of
2008@samp{eqv?}; see section @pxref{Equivalence predicates}) to a @r{<datum>}, then the
2009expressions in the corresponding @r{<clause>} are evaluated from left
2010to right and the result(s) of the last expression in the @r{<clause>} is(are)
2011returned as the result(s) of the @samp{case} expression. If the result of
2012evaluating @r{<key>} is different from every @r{<datum>}, then if
2013there is an else clause its expressions are evaluated and the
2014result(s) of the last is(are) the result(s) of the @samp{case} expression;
2015otherwise the result of the @samp{case} expression is unspecified.
2016
2017
2018@format
2019@t{(case (* 2 3)
2020 ((2 3 5 7) 'prime)
2021 ((1 4 6 8 9) 'composite)) ==> composite
2022(case (car '(c d))
2023 ((a) 'a)
2024 ((b) 'b)) ==> @emph{unspecified}
2025(case (car '(c d))
2026 ((a e i o u) 'vowel)
2027 ((w y) 'semivowel)
2028 (else 'consonant)) ==> consonant
2029}
2030@end format
2031
2032
2033@end deffn
2034
2035
2036
2037@deffn {library syntax} and <test1> @dots{},
2038
2039The @r{<test>} expressions are evaluated from left to right, and the
2040value of the first expression that evaluates to a false value (see
2041section @pxref{Booleans}) is returned. Any remaining expressions
2042are not evaluated. If all the expressions evaluate to true values, the
2043value of the last expression is returned. If there are no expressions
2044then @t{#t} is returned.
2045
2046
2047@format
2048@t{(and (= 2 2) (> 2 1)) ==> #t
2049(and (= 2 2) (< 2 1)) ==> #f
2050(and 1 2 'c '(f g)) ==> (f g)
2051(and) ==> #t
2052}
2053@end format
2054
2055
2056@end deffn
2057
2058
2059
2060@deffn {library syntax} or <test1> @dots{},
2061
2062The @r{<test>} expressions are evaluated from left to right, and the value of the
2063first expression that evaluates to a true value (see
2064section @pxref{Booleans}) is returned. Any remaining expressions
2065are not evaluated. If all expressions evaluate to false values, the
2066value of the last expression is returned. If there are no
2067expressions then @t{#f} is returned.
2068
2069
2070@format
2071@t{(or (= 2 2) (> 2 1)) ==> #t
2072(or (= 2 2) (< 2 1)) ==> #t
2073(or #f #f #f) ==> #f
2074(or (memq 'b '(a b c))
2075 (/ 3 0)) ==> (b c)
2076}
2077@end format
2078
2079
2080@end deffn
2081
2082
2083@node Binding constructs, Sequencing, Conditional, Derived expression types
2084@subsection Binding constructs
2085
2086
2087The three binding constructs @samp{let}, @samp{let*}, and @samp{letrec}
2088give Scheme a block structure, like Algol 60. The syntax of the three
2089constructs is identical, but they differ in the regions they establish
2090@cindex @w{region}
2091for their variable bindings. In a @samp{let} expression, the initial
2092values are computed before any of the variables become bound; in a
2093@samp{let*} expression, the bindings and evaluations are performed
2094sequentially; while in a @samp{letrec} expression, all the bindings are in
2095effect while their initial values are being computed, thus allowing
2096mutually recursive definitions.
2097
2098
2099@deffn {library syntax} let @r{<bindings>} @r{<body>}
2100
2101@emph{Syntax:}
2102@r{<Bindings>} should have the form
2103
2104@format
2105@t{((@r{<variable1>} @r{<init1>}) @dots{},)@r{,}
2106}
2107@end format
2108
2109where each @r{<init>} is an expression, and @r{<body>} should be a
2110sequence of one or more expressions. It is
2111an error for a @r{<variable>} to appear more than once in the list of variables
2112being bound.
2113
2114@emph{Semantics:}
2115The @r{<init>}s are evaluated in the current environment (in some
2116unspecified order), the @r{<variable>}s are bound to fresh locations
2117holding the results, the @r{<body>} is evaluated in the extended
2118environment, and the value(s) of the last expression of @r{<body>}
2119is(are) returned. Each binding of a @r{<variable>} has @r{<body>} as its
2120region.
2121@cindex @w{region}
2122
2123
2124@format
2125@t{(let ((x 2) (y 3))
2126 (* x y)) ==> 6
2127
2128(let ((x 2) (y 3))
2129 (let ((x 7)
2130 (z (+ x y)))
2131 (* z x))) ==> 35
2132}
2133@end format
2134
2135
2136See also named @samp{let}, section @ref{Iteration}.
2137
2138@end deffn
2139
2140
2141
2142@deffn {library syntax} let* @r{<bindings>} @r{<body>}
2143
2144
2145@emph{Syntax:}
2146@r{<Bindings>} should have the form
2147
2148@format
2149@t{((@r{<variable1>} @r{<init1>}) @dots{},)@r{,}
2150}
2151@end format
2152
2153and @r{<body>} should be a sequence of
2154one or more expressions.
2155
2156@emph{Semantics:}
7fb9c4af 2157@samp{Let*} is similar to @samp{let}, but the bindings are performed
a0e07ba4
NJ
2158sequentially from left to right, and the region of a binding indicated
2159@cindex @w{region}
2160by @samp{(@r{<variable>} @r{<init>})} is that part of the @samp{let*}
2161expression to the right of the binding. Thus the second binding is done
2162in an environment in which the first binding is visible, and so on.
2163
2164
2165@format
2166@t{(let ((x 2) (y 3))
2167 (let* ((x 7)
2168 (z (+ x y)))
2169 (* z x))) ==> 70
2170}
2171@end format
2172
2173
2174@end deffn
2175
2176
2177
2178@deffn {library syntax} letrec @r{<bindings>} @r{<body>}
2179
2180@emph{Syntax:}
2181@r{<Bindings>} should have the form
2182
2183@format
2184@t{((@r{<variable1>} @r{<init1>}) @dots{},)@r{,}
2185}
2186@end format
2187
2188and @r{<body>} should be a sequence of
2189one or more expressions. It is an error for a @r{<variable>} to appear more
2190than once in the list of variables being bound.
2191
2192@emph{Semantics:}
2193The @r{<variable>}s are bound to fresh locations holding undefined
2194values, the @r{<init>}s are evaluated in the resulting environment (in
2195some unspecified order), each @r{<variable>} is assigned to the result
2196of the corresponding @r{<init>}, the @r{<body>} is evaluated in the
2197resulting environment, and the value(s) of the last expression in
2198@r{<body>} is(are) returned. Each binding of a @r{<variable>} has the
2199entire @samp{letrec} expression as its region, making it possible to
2200@cindex @w{region}
2201define mutually recursive procedures.
2202
2203
2204@format
2205@t{(letrec ((even?
2206 (lambda (n)
2207 (if (zero? n)
2208 #t
2209 (odd? (- n 1)))))
2210 (odd?
2211 (lambda (n)
2212 (if (zero? n)
2213 #f
2214 (even? (- n 1))))))
2215 (even? 88))
2216 ==> #t
2217}
2218@end format
2219
2220
2221One restriction on @samp{letrec} is very important: it must be possible
2222to evaluate each @r{<init>} without assigning or referring to the value of any
2223@r{<variable>}. If this restriction is violated, then it is an error. The
2224restriction is necessary because Scheme passes arguments by value rather than by
2225name. In the most common uses of @samp{letrec}, all the @r{<init>}s are
2226lambda expressions and the restriction is satisfied automatically.
2227
2228@c \todo{use or uses? --- Jinx.}
2229
2230@end deffn
2231
2232
2233@node Sequencing, Iteration, Binding constructs, Derived expression types
2234@subsection Sequencing
2235
2236
2237
2238@deffn {library syntax} begin <expression1> <expression2> @dots{},
2239
2240The @r{<expression>}s are evaluated sequentially from left to right,
2241and the value(s) of the last @r{<expression>} is(are) returned. This
2242expression type is used to sequence side effects such as input and
2243output.
2244
2245
2246@format
2247@t{(define x 0)
2248
2249(begin (set! x 5)
2250 (+ x 1)) ==> 6
2251
2252(begin (display "4 plus 1 equals ")
2253 (display (+ 4 1))) ==> @emph{unspecified}
2254 @emph{and prints} 4 plus 1 equals 5
2255}
2256@end format
2257
2258
2259@end deffn
2260
2261
2262@node Iteration, Delayed evaluation, Sequencing, Derived expression types
2263@subsection Iteration
2264
2265@c \unsection
2266
2267
2268@noindent
2269
2270@deffn {library syntax} do ((@r{<variable1>} @r{<init1>} @r{<step1>}) @dots{}) (@r{<test>} @r{<expression>} @dots{}) @r{<command>} @dots{}
2271@cindex @w{do}
2272
7fb9c4af 2273@samp{Do} is an iteration construct. It specifies a set of variables to
a0e07ba4
NJ
2274be bound, how they are to be initialized at the start, and how they are
2275to be updated on each iteration. When a termination condition is met,
2276the loop exits after evaluating the @r{<expression>}s.
2277
7fb9c4af 2278@samp{Do} expressions are evaluated as follows:
a0e07ba4
NJ
2279The @r{<init>} expressions are evaluated (in some unspecified order),
2280the @r{<variable>}s are bound to fresh locations, the results of the
2281@r{<init>} expressions are stored in the bindings of the
2282@r{<variable>}s, and then the iteration phase begins.
2283
2284Each iteration begins by evaluating @r{<test>}; if the result is
2285false (see section @pxref{Booleans}), then the @r{<command>}
2286expressions are evaluated in order for effect, the @r{<step>}
2287expressions are evaluated in some unspecified order, the
2288@r{<variable>}s are bound to fresh locations, the results of the
2289@r{<step>}s are stored in the bindings of the
2290@r{<variable>}s, and the next iteration begins.
2291
2292If @r{<test>} evaluates to a true value, then the
2293@r{<expression>}s are evaluated from left to right and the value(s) of
2294the last @r{<expression>} is(are) returned. If no @r{<expression>}s
2295are present, then the value of the @samp{do} expression is unspecified.
2296
2297The region of the binding of a @r{<variable>}
2298@cindex @w{region}
2299consists of the entire @samp{do} expression except for the @r{<init>}s.
2300It is an error for a @r{<variable>} to appear more than once in the
2301list of @samp{do} variables.
2302
2303A @r{<step>} may be omitted, in which case the effect is the
2304same as if @samp{(@r{<variable>} @r{<init>} @r{<variable>})} had
2305been written instead of @samp{(@r{<variable>} @r{<init>})}.
2306
2307
2308@format
2309@t{(do ((vec (make-vector 5))
2310 (i 0 (+ i 1)))
2311 ((= i 5) vec)
2312 (vector-set! vec i i)) ==> #(0 1 2 3 4)
2313
2314(let ((x '(1 3 5 7 9)))
2315 (do ((x x (cdr x))
2316 (sum 0 (+ sum (car x))))
2317 ((null? x) sum))) ==> 25
2318}
2319@end format
2320
2321
2322@c \end{entry}
2323@end deffn
2324
2325
2326@deffn {library syntax} let @r{<variable>} @r{<bindings>} @r{<body>}
2327
2328
2329``Named @samp{let}'' is a variant on the syntax of @code{let} which provides
2330@vindex @w{let}
2331a more general looping construct than @samp{do} and may also be used to express
2332recursions.
2333It has the same syntax and semantics as ordinary @samp{let}
2334except that @r{<variable>} is bound within @r{<body>} to a procedure
2335whose formal arguments are the bound variables and whose body is
2336@r{<body>}. Thus the execution of @r{<body>} may be repeated by
2337invoking the procedure named by @r{<variable>}.
2338
2339@c | <-- right margin
2340
2341@format
2342@t{(let loop ((numbers '(3 -2 1 6 -5))
2343 (nonneg '())
2344 (neg '()))
2345 (cond ((null? numbers) (list nonneg neg))
2346 ((>= (car numbers) 0)
2347 (loop (cdr numbers)
2348 (cons (car numbers) nonneg)
2349 neg))
2350 ((< (car numbers) 0)
2351 (loop (cdr numbers)
2352 nonneg
2353 (cons (car numbers) neg)))))
2354 ==> ((6 1 3) (-5 -2))
2355}
2356@end format
2357
2358
2359@end deffn
2360
2361
2362@node Delayed evaluation, Quasiquotation, Iteration, Derived expression types
2363@subsection Delayed evaluation
2364
2365
2366
2367@deffn {library syntax} delay @r{<expression>}
2368
2369@ignore todo
2370Fix.
2371@end ignore
2372
2373
2374The @samp{delay} construct is used together with the procedure @code{force} to
2375@vindex @w{force}
2376implement @dfn{lazy evaluation} or @dfn{call by need}.
2377@cindex @w{call by need}
2378@cindex @w{lazy evaluation}
2379@t{(delay @r{<expression>})} returns an object called a
2380@dfn{promise} which at some point in the future may be asked (by
2381@cindex @w{promise}
2382the @samp{force} procedure)
2383@ignore todo
2384Bartley's white lie; OK?
2385@end ignore
2386 to evaluate
2387@r{<expression>}, and deliver the resulting value.
2388The effect of @r{<expression>} returning multiple values
2389is unspecified.
2390
2391See the description of @samp{force} (section @pxref{Control features}) for a
2392more complete description of @samp{delay}.
2393
2394@end deffn
2395
2396
2397@node Quasiquotation, , Delayed evaluation, Derived expression types
2398@subsection Quasiquotation
2399
2400
2401
2402
2403@deffn {syntax} quasiquote @r{<qq template>}
2404
2405@deffnx {syntax} @t{`}@r{<qq template>}
2406
2407
2408``Backquote'' or ``quasiquote'' expressions are useful
2409@cindex @w{backquote}
2410for constructing a list or vector structure when most but not all of the
2411desired structure is known in advance. If no
2412commas appear within the @r{<qq template>}, the result of
2413@cindex @w{comma}
2414evaluating
2415@t{`}@r{<qq template>} is equivalent to the result of evaluating
2416@t{'}@r{<qq template>}. If a comma appears within the
2417@cindex @w{,}
2418@r{<qq template>}, however, the expression following the comma is
2419evaluated (``unquoted'') and its result is inserted into the structure
2420instead of the comma and the expression. If a comma appears followed
2421immediately by an at-sign (@@), then the following
2422@cindex @w{,@@}
2423expression must evaluate to a list; the opening and closing parentheses
2424of the list are then ``stripped away'' and the elements of the list are
2425inserted in place of the comma at-sign expression sequence. A comma
2426at-sign should only appear within a list or vector @r{<qq template>}.
2427
2428@c struck: "(in the sense of {\cf equal?})" after "equivalent"
2429
2430
2431@format
2432@t{`(list ,(+ 1 2) 4) ==> (list 3 4)
2433(let ((name 'a)) `(list ,name ',name))
2434 ==> (list a (quote a))
2435`(a ,(+ 1 2) ,@@(map abs '(4 -5 6)) b)
2436 ==> (a 3 4 5 6 b)
2437`((@samp{foo} ,(- 10 3)) ,@@(cdr '(c)) . ,(car '(cons)))
2438 ==> ((foo 7) . cons)
2439`#(10 5 ,(sqrt 4) ,@@(map sqrt '(16 9)) 8)
2440 ==> #(10 5 2 4 3 8)
2441}
2442@end format
2443
2444
2445Quasiquote forms may be nested. Substitutions are made only for
2446unquoted components appearing at the same nesting level
2447as the outermost backquote. The nesting level increases by one inside
2448each successive quasiquotation, and decreases by one inside each
2449unquotation.
2450
2451
2452@format
2453@t{`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
2454 ==> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
2455(let ((name1 'x)
2456 (name2 'y))
2457 `(a `(b ,,name1 ,',name2 d) e))
2458 ==> (a `(b ,x ,'y d) e)
2459}
2460@end format
2461
2462
2463The two notations
2464 @t{`}@r{<qq template>} and @t{(quasiquote @r{<qq template>})}
2465 are identical in all respects.
2466 @samp{,@r{<expression>}} is identical to @samp{(unquote @r{<expression>})},
2467 and
2468 @samp{,@@@r{<expression>}} is identical to @samp{(unquote-splicing @r{<expression>})}.
2469The external syntax generated by @code{write} for two-element lists whose
2470@vindex @w{write}
2471car is one of these symbols may vary between implementations.
2472
2473@cindex @w{`}
2474
2475
2476@format
2477@t{(quasiquote (list (unquote (+ 1 2)) 4))
2478 ==> (list 3 4)
2479'(quasiquote (list (unquote (+ 1 2)) 4))
2480 ==> `(list ,(+ 1 2) 4)
2481 @emph{}i.e., (quasiquote (list (unquote (+ 1 2)) 4))
2482}
2483@end format
2484
2485
2486Unpredictable behavior can result if any of the symbols
2487@code{quasiquote}, @code{unquote}, or @code{unquote-splicing} appear in
2488@vindex @w{unquote-splicing}
2489@vindex @w{unquote}
2490@vindex @w{quasiquote}
2491positions within a @r{<qq template>} otherwise than as described above.
2492
2493@end deffn
2494
2495@node Macros, , Derived expression types, Expressions
2496@section Macros
2497
2498@menu
2499* Binding constructs for syntactic keywords::
2500* Pattern language::
2501@end menu
2502
2503
2504
2505Scheme programs can define and use new derived expression types,
2506 called @emph{macros}.
2507@cindex @w{macro}
2508Program-defined expression types have the syntax
2509
2510@example
2511
2512(@r{<keyword>} @r{<datum>} ...)
2513
2514@end example
2515
2516where @r{<keyword>} is an identifier that uniquely determines the
2517expression type. This identifier is called the @emph{syntactic
2518keyword}, or simply @emph{keyword}, of the macro. The
2519@cindex @w{macro keyword}
2520@cindex @w{keyword}
2521@cindex @w{syntactic keyword}
2522number of the @r{<datum>}s, and their syntax, depends on the
2523expression type.
2524
2525Each instance of a macro is called a @emph{use}
2526@cindex @w{macro use}
2527of the macro.
2528The set of rules that specifies
2529how a use of a macro is transcribed into a more primitive expression
2530is called the @emph{transformer}
2531@cindex @w{macro transformer}
2532of the macro.
2533
2534The macro definition facility consists of two parts:
2535
2536
2537
2538@itemize @bullet
2539
2540@item
2541A set of expressions used to establish that certain identifiers
2542are macro keywords, associate them with macro transformers, and control
2543the scope within which a macro is defined, and
2544
2545@item
2546a pattern language for specifying macro transformers.
2547
2548@end itemize
2549
2550
2551The syntactic keyword of a macro may shadow variable bindings, and local
2552variable bindings may shadow keyword bindings. All macros
2553@cindex @w{keyword}
2554defined using the pattern language are ``hygienic'' and ``referentially
2555transparent'' and thus preserve Scheme's lexical scoping [Kohlbecker86], [
2556hygienic], [Bawden88], [macrosthatwork], [syntacticabstraction]:
2557
2558@cindex @w{hygienic}
2559
2560@cindex @w{referentially transparent}
2561
2562
2563
2564
2565@itemize @bullet
2566
2567
2568@item
2569If a macro transformer inserts a binding for an identifier
2570(variable or keyword), the identifier will in effect be renamed
2571throughout its scope to avoid conflicts with other identifiers.
2572Note that a @code{define} at top level may or may not introduce a binding;
2573see section @ref{Definitions}.
2574
2575@item
2576If a macro transformer inserts a free reference to an
2577identifier, the reference refers to the binding that was visible
2578where the transformer was specified, regardless of any local
2579bindings that may surround the use of the macro.
2580
2581
2582@end itemize
2583
2584@vindex @w{define}
2585
2586@c The low-level facility permits non-hygienic macros to be written,
2587@c and may be used to implement the high-level pattern language.
2588
2589@c The fourth section describes some features that would make the
2590@c low-level macro facility easier to use directly.
2591
2592@node Binding constructs for syntactic keywords, Pattern language, Macros, Macros
2593@subsection Binding constructs for syntactic keywords
2594
2595
2596
7fb9c4af 2597@samp{Let-syntax} and @samp{letrec-syntax} are
a0e07ba4
NJ
2598analogous to @samp{let} and @samp{letrec}, but they bind
2599syntactic keywords to macro transformers instead of binding variables
2600to locations that contain values. Syntactic keywords may also be
2601bound at top level; see section @ref{Syntax definitions}.
2602
2603
2604@deffn {syntax} let-syntax @r{<bindings>} @r{<body>}
2605
2606@emph{Syntax:}
2607@r{<Bindings>} should have the form
2608
2609@format
2610@t{((@r{<keyword>} @r{<transformer spec>}) @dots{},)
2611}
2612@end format
2613
2614Each @r{<keyword>} is an identifier,
2615each @r{<transformer spec>} is an instance of @samp{syntax-rules}, and
2616@r{<body>} should be a sequence of one or more expressions. It is an error
2617for a @r{<keyword>} to appear more than once in the list of keywords
2618being bound.
2619
2620@emph{Semantics:}
2621The @r{<body>} is expanded in the syntactic environment
2622obtained by extending the syntactic environment of the
2623@samp{let-syntax} expression with macros whose keywords are
2624the @r{<keyword>}s, bound to the specified transformers.
2625Each binding of a @r{<keyword>} has @r{<body>} as its region.
2626
2627
2628@format
2629@t{(let-syntax ((when (syntax-rules ()
2630 ((when test stmt1 stmt2 ...)
2631 (if test
2632 (begin stmt1
2633 stmt2 ...))))))
2634 (let ((if #t))
2635 (when if (set! if 'now))
2636 if)) ==> now
2637
2638(let ((x 'outer))
2639 (let-syntax ((m (syntax-rules () ((m) x))))
2640 (let ((x 'inner))
2641 (m)))) ==> outer
2642}
2643@end format
2644
2645
2646@end deffn
2647
2648
2649@deffn {syntax} letrec-syntax @r{<bindings>} @r{<body>}
2650
2651@emph{Syntax:}
2652Same as for @samp{let-syntax}.
2653
2654@emph{Semantics:}
2655 The @r{<body>} is expanded in the syntactic environment obtained by
2656extending the syntactic environment of the @samp{letrec-syntax}
2657expression with macros whose keywords are the
2658@r{<keyword>}s, bound to the specified transformers.
2659Each binding of a @r{<keyword>} has the @r{<bindings>}
2660as well as the @r{<body>} within its region,
2661so the transformers can
2662transcribe expressions into uses of the macros
2663introduced by the @samp{letrec-syntax} expression.
2664
2665
2666@format
2667@t{(letrec-syntax
2668 ((my-or (syntax-rules ()
2669 ((my-or) #f)
2670 ((my-or e) e)
2671 ((my-or e1 e2 ...)
2672 (let ((temp e1))
2673 (if temp
2674 temp
2675 (my-or e2 ...)))))))
2676 (let ((x #f)
2677 (y 7)
2678 (temp 8)
2679 (let odd?)
2680 (if even?))
2681 (my-or x
2682 (let temp)
2683 (if y)
2684 y))) ==> 7
2685}
2686@end format
2687
2688
2689@end deffn
2690
2691@node Pattern language, , Binding constructs for syntactic keywords, Macros
2692@subsection Pattern language
2693
2694
2695
2696A @r{<transformer spec>} has the following form:
2697
2698
2699@deffn {} syntax-rules @r{<literals>} @r{<syntax rule>} @dots{},
2700
2701@emph{Syntax:}
2702@r{<Literals>} is a list of identifiers and each @r{<syntax rule>}
2703should be of the form
2704
2705@format
2706@t{(@r{<pattern>} @r{<template>})
2707}
2708@end format
2709
2710The @r{<pattern>} in a @r{<syntax rule>} is a list @r{<pattern>}
2711that begins with the keyword for the macro.
2712
2713A @r{<pattern>} is either an identifier, a constant, or one of the
2714following
2715
2716@format
2717@t{(@r{<pattern>} @dots{})
2718(@r{<pattern>} @r{<pattern>} @dots{} . @r{<pattern>})
2719(@r{<pattern>} @dots{} @r{<pattern>} @r{<ellipsis>})
2720#(@r{<pattern>} @dots{})
2721#(@r{<pattern>} @dots{} @r{<pattern>} @r{<ellipsis>})
2722}
2723@end format
2724
2725and a template is either an identifier, a constant, or one of the following
2726
2727@format
2728@t{(@r{<element>} @dots{})
2729(@r{<element>} @r{<element>} @dots{} . @r{<template>})
2730#(@r{<element>} @dots{})
2731}
2732@end format
2733
2734where an @r{<element>} is a @r{<template>} optionally
2735followed by an @r{<ellipsis>} and
2736an @r{<ellipsis>} is the identifier ``@samp{...}'' (which cannot be used as
2737an identifier in either a template or a pattern).
2738@vindex ...
2739
2740@emph{Semantics:} An instance of @samp{syntax-rules} produces a new macro
2741transformer by specifying a sequence of hygienic rewrite rules. A use
2742of a macro whose keyword is associated with a transformer specified by
2743@samp{syntax-rules} is matched against the patterns contained in the
2744@r{<syntax rule>}s, beginning with the leftmost @r{<syntax rule>}.
2745When a match is found, the macro use is transcribed hygienically
2746according to the template.
2747
2748An identifier that appears in the pattern of a @r{<syntax rule>} is
2749a @emph{pattern variable}, unless it is the keyword that begins the pattern,
2750is listed in @r{<literals>}, or is the identifier ``@samp{...}''.
2751Pattern variables match arbitrary input elements and
2752are used to refer to elements of the input in the template. It is an
2753error for the same pattern variable to appear more than once in a
2754@r{<pattern>}.
2755
2756The keyword at the beginning of the pattern in a
2757@r{<syntax rule>} is not involved in the matching and
2758is not considered a pattern variable or literal identifier.
2759
2760
2761@quotation
2762@emph{Rationale:}
2763The scope of the keyword is determined by the expression or syntax
2764definition that binds it to the associated macro transformer.
2765If the keyword were a pattern variable or literal
2766identifier, then
2767the template that follows the pattern would be within its scope
2768regardless of whether the keyword were bound by @samp{let-syntax}
2769or by @samp{letrec-syntax}.
2770@end quotation
2771
2772
2773Identifiers that appear in @r{<literals>} are interpreted as literal
2774identifiers to be matched against corresponding subforms of the input.
2775A subform
2776in the input matches a literal identifier if and only if it is an
2777identifier
2778and either both its occurrence in the macro expression and its
2779occurrence in the macro definition have the same lexical binding, or
2780the two identifiers are equal and both have no lexical binding.
2781
2782@c [Bill Rozas suggested the term "noise word" for these literal
2783@c identifiers, but in their most interesting uses, such as a setf
2784@c macro, they aren't noise words at all. -- Will]
2785
2786A subpattern followed by @samp{...} can match zero or more elements of the
2787input. It is an error for @samp{...} to appear in @r{<literals>}.
2788Within a pattern the identifier @samp{...} must follow the last element of
2789a nonempty sequence of subpatterns.
2790
2791More formally, an input form F matches a pattern P if and only if:
2792
2793
2794
2795@itemize @bullet
2796
2797@item
2798P is a non-literal identifier; or
2799
2800@item
2801P is a literal identifier and F is an identifier with the same
2802binding; or
2803
2804@item
2805P is a list @samp{(P_1 @dots{} P_n)} and F is a
2806list of n
2807forms that match P_1 through P_n, respectively; or
2808
2809@item
2810P is an improper list
2811@samp{(P_1 P_2 @dots{} P_n . P_n+1)}
2812and F is a list or
2813improper list of n or more forms that match P_1 through P_n,
2814respectively, and whose nth ``cdr'' matches P_n+1; or
2815
2816@item
2817P is of the form
2818@samp{(P_1 @dots{} P_n P_n+1 <ellipsis>)}
2819where <ellipsis> is the identifier @samp{...}
2820and F is
2821a proper list of at least n forms, the first n of which match
2822P_1 through P_n, respectively, and each remaining element of F
2823matches P_n+1; or
2824
2825@item
2826P is a vector of the form @samp{#(P_1 @dots{} P_n)}
2827and F is a vector
2828of n forms that match P_1 through P_n; or
2829
2830@item
2831P is of the form
2832@samp{#(P_1 @dots{} P_n P_n+1 <ellipsis>)}
2833where <ellipsis> is the identifier @samp{...}
2834and F is a vector of n
2835or more forms the first n of which match
2836P_1 through P_n, respectively, and each remaining element of F
2837matches P_n+1; or
2838
2839@item
2840P is a datum and F is equal to P in the sense of
2841the @samp{equal?} procedure.
2842
2843@end itemize
2844
2845
2846It is an error to use a macro keyword, within the scope of its
2847binding, in an expression that does not match any of the patterns.
2848
2849When a macro use is transcribed according to the template of the
2850matching @r{<syntax rule>}, pattern variables that occur in the
2851template are replaced by the subforms they match in the input.
2852Pattern variables that occur in subpatterns followed by one or more
2853instances of the identifier
2854@samp{...} are allowed only in subtemplates that are
2855followed by as many instances of @samp{...}.
2856They are replaced in the
2857output by all of the subforms they match in the input, distributed as
2858indicated. It is an error if the output cannot be built up as
2859specified.
2860
2861@c %% This description of output construction is very vague. It should
2862@c %% probably be formalized, but that is not easy...
2863
2864Identifiers that appear in the template but are not pattern variables
2865or the identifier
2866@samp{...} are inserted into the output as literal identifiers. If a
2867literal identifier is inserted as a free identifier then it refers to the
2868binding of that identifier within whose scope the instance of
2869@samp{syntax-rules} appears.
2870If a literal identifier is inserted as a bound identifier then it is
2871in effect renamed to prevent inadvertent captures of free identifiers.
2872
2873As an example, if @code{let} and @code{cond} are defined as in
2874@vindex @w{cond}
2875@vindex @w{let}
2876section @ref{Derived expression type} then they are hygienic (as required) and
2877the following is not an error.
2878
2879
2880@format
2881@t{(let ((=> #f))
2882 (cond (#t => 'ok))) ==> ok
2883}
2884@end format
2885
2886
2887The macro transformer for @samp{cond} recognizes @samp{=>}
2888as a local variable, and hence an expression, and not as the
2889top-level identifier @samp{=>}, which the macro transformer treats
2890as a syntactic keyword. Thus the example expands into
2891
2892
2893@format
2894@t{(let ((=> #f))
2895 (if #t (begin => 'ok)))
2896}
2897@end format
2898
2899
2900instead of
2901
2902
2903@format
2904@t{(let ((=> #f))
2905 (let ((temp #t))
2906 (if temp ('ok temp))))
2907}
2908@end format
2909
2910
2911which would result in an invalid procedure call.
2912
2913@end deffn
2914
2915
2916@page
2917
2918@c @include{prog}
2919@node Program structure, Standard procedures, Expressions, top
2920@chapter Program structure
2921
2922@menu
2923* Programs::
2924* Definitions::
2925* Syntax definitions::
2926@end menu
2927
2928
2929
2930@node Programs, Definitions, Program structure, Program structure
2931@section Programs
2932
2933
2934A Scheme program consists of a sequence of expressions, definitions,
2935and syntax definitions.
2936Expressions are described in chapter @ref{Expressions};
2937definitions and syntax definitions are the subject of the rest of the
2938present chapter.
2939
2940Programs are typically stored in files or entered interactively to a
2941running Scheme system, although other paradigms are possible;
2942questions of user interface lie outside the scope of this report.
2943(Indeed, Scheme would still be useful as a notation for expressing
2944computational methods even in the absence of a mechanical
2945implementation.)
2946
2947Definitions and syntax definitions occurring at the top level of a program
2948can be interpreted
2949declaratively.
2950They cause bindings to be created in the top level
2951environment or modify the value of existing top-level bindings.
2952Expressions occurring at the top level of a program are
2953interpreted imperatively; they are executed in order when the program is
2954invoked or loaded, and typically perform some kind of initialization.
2955
2956At the top level of a program @t{(begin @r{<form1>} @dots{},)} is
2957equivalent to the sequence of expressions, definitions, and syntax definitions
2958that form the body of the @code{begin}.
2959@vindex @w{begin}
2960
2961@ignore todo
2962Cromarty, etc.: disclaimer about top level?
2963@end ignore
2964
2965
2966@node Definitions, Syntax definitions, Programs, Program structure
2967@section Definitions
2968
2969@menu
2970* Top level definitions::
2971* Internal definitions::
2972@end menu
2973
2974
2975
2976Definitions are valid in some, but not all, contexts where expressions
2977are allowed. They are valid only at the top level of a @r{<program>}
2978and at the beginning of a @r{<body>}.
2979
2980@cindex @w{definition}
2981
2982A definition should have one of the following forms:
2983@cindex @w{define}
2984
2985
2986
2987@itemize @bullet
2988
2989
2990@item @t{(define @r{<variable>} @r{<expression>})}
2991
2992@item @t{(define (@r{<variable>} @r{<formals>}) @r{<body>})}
2993
2994@r{<Formals>} should be either a
2995sequence of zero or more variables, or a sequence of one or more
2996variables followed by a space-delimited period and another variable (as
2997in a lambda expression). This form is equivalent to
2998
2999@example
3000
3001(define @r{<variable>}
3002 (lambda (@r{<formals>}) @r{<body>}))@r{.}
3003
3004@end example
3005
3006
3007@item @t{(define (@r{<variable>} .@: @r{<formal>}) @r{<body>})}
3008
3009@r{<Formal>} should be a single
3010variable. This form is equivalent to
3011
3012@example
3013
3014(define @r{<variable>}
3015 (lambda @r{<formal>} @r{<body>}))@r{.}
3016
3017@end example
3018
3019
3020
3021@end itemize
3022
3023
3024@node Top level definitions, Internal definitions, Definitions, Definitions
3025@subsection Top level definitions
3026
3027
3028At the top level of a program, a definition
3029
3030@example
3031
3032(define @r{<variable>} @r{<expression>})
3033
3034@end example
3035
3036has essentially the same effect as the assignment expression
3037
3038@example
3039
3040(set! @r{<variable>} @r{<expression>})
3041
3042@end example
3043
3044if @r{<variable>} is bound. If @r{<variable>} is not bound,
3045however, then the definition will bind @r{<variable>} to a new
3046location before performing the assignment, whereas it would be an error
3047to perform a @samp{set!} on an unbound variable.
3048@cindex @w{unbound}
3049
3050
3051@example
3052
3053(define add3
3054 (lambda (x) (+ x 3)))
3055(add3 3) ==> 6
3056(define first car)
3057(first '(1 2)) ==> 1
3058
3059@end example
3060
3061
3062Some implementations of Scheme use an initial environment in
3063which all possible variables are bound to locations, most of
3064which contain undefined values. Top level definitions in
3065such an implementation are truly equivalent to assignments.
3066
3067@ignore todo
3068Rozas: equal time for opposition semantics?
3069@end ignore
3070
3071
3072
3073@node Internal definitions, , Top level definitions, Definitions
3074@subsection Internal definitions
3075
3076
3077
3078Definitions may occur at the
3079beginning of a @r{<body>} (that is, the body of a @code{lambda},
3080@vindex @w{lambda}
3081@code{let}, @code{let*}, @code{letrec}, @code{let-syntax}, or @code{letrec-syntax}
3082@vindex @w{letrec-syntax}
3083@vindex @w{let-syntax}
3084@vindex @w{letrec}
3085@vindex @w{let*}
3086@vindex @w{let}
3087expression or that of a definition of an appropriate form).
3088Such definitions are known as @emph{internal definitions} as opposed to the top level definitions described above.
3089@cindex @w{internal definition}
3090The variable defined by an internal definition is local to the
3091@r{<body>}. That is, @r{<variable>} is bound rather than assigned,
3092and the region of the binding is the entire @r{<body>}. For example,
3093
3094
3095@example
3096
3097(let ((x 5))
3098 (define foo (lambda (y) (bar x y)))
3099 (define bar (lambda (a b) (+ (* a b) a)))
3100 (foo (+ x 3))) ==> 45
3101
3102@end example
3103
3104
3105A @r{<body>} containing internal definitions can always be converted
3106into a completely equivalent @samp{letrec} expression. For example, the
3107@samp{let} expression in the above example is equivalent to
3108
3109
3110@example
3111
3112(let ((x 5))
3113 (letrec ((foo (lambda (y) (bar x y)))
3114 (bar (lambda (a b) (+ (* a b) a))))
3115 (foo (+ x 3))))
3116
3117@end example
3118
3119
3120Just as for the equivalent @samp{letrec} expression, it must be
3121possible to evaluate each @r{<expression>} of every internal
3122definition in a @r{<body>} without assigning or referring to
3123the value of any @r{<variable>} being defined.
3124
3125Wherever an internal definition may occur
3126@t{(begin @r{<definition1>} @dots{},)}
3127is equivalent to the sequence of definitions
3128that form the body of the @code{begin}.
3129@vindex @w{begin}
3130
3131@node Syntax definitions, , Definitions, Program structure
3132@section Syntax definitions
3133
3134
3135Syntax definitions are valid only at the top level of a @r{<program>}.
3136
3137@cindex @w{syntax definition}
3138They have the following form:
3139@cindex @w{define-syntax}
3140
3141@t{(define-syntax @r{<keyword>} @r{<transformer spec>})}
3142
3143@r{<Keyword>} is an identifier, and
3144the @r{<transformer spec>} should be an instance of @code{syntax-rules}.
3145@vindex @w{syntax-rules}
3146The top-level syntactic environment is extended by binding the
3147@r{<keyword>} to the specified transformer.
3148
3149There is no @samp{define-syntax} analogue of internal definitions.
3150
3151@c [Rationale flushed because it may or may not be true and isn't the
3152@c real rationale anyway. -RK]
3153@c \begin{rationale}
3154@c As discussed below, the syntax and scope rules for syntax definitions
3155@c can give rise to syntactic ambiguities when syntactic keywords are
3156@c shadowed.
3157@c Further ambiguities would arise if {\cf define-syntax}
3158@c were permitted at the beginning of a \meta{body}, with scope
3159@c rules analogous to those for internal definitions.
3160@c \end{rationale}
3161
3162@c It is an error for a program to contain more than one top-level
3163@c \meta{definition} or \meta{syntax definition} of any identifier.
3164
3165@c [I flushed this because it isn't an error for a program to
3166@c contain more than one top-level definition of an identifier,
3167@c and I didn't want to introduce any gratuitous incompatibilities
3168@c with the existing Scheme language. -- Will]
3169
3170Although macros may expand into definitions and syntax definitions in
3171any context that permits them, it is an error for a definition or syntax
3172definition to shadow a syntactic keyword whose meaning is needed to
3173determine whether some form in the group of forms that contains the
3174shadowing definition is in fact a definition, or, for internal definitions,
3175is needed to determine the boundary between the group and the expressions
3176that follow the group. For example, the following are errors:
3177
3178
3179@example
3180
3181(define define 3)
3182
3183(begin (define begin list))
3184
3185(let-syntax
3186 ((foo (syntax-rules ()
3187 ((foo (proc args ...) body ...)
3188 (define proc
3189 (lambda (args ...)
3190 body ...))))))
3191 (let ((x 3))
3192 (foo (plus x y) (+ x y))
3193 (define foo x)
3194 (plus foo x)))
3195
3196@end example
3197
3198
3199
3200
3201@c @include{procs}
3202
3203@c Initial environment
3204
3205@c \vfill\eject
3206@node Standard procedures, Formal syntax and semantics, Program structure, top
3207@chapter Standard procedures
3208
3209@menu
3210* Equivalence predicates::
3211* Numbers::
3212* Other data types::
3213* Control features::
3214* Eval::
3215* Input and output::
3216@end menu
3217
3218
3219
3220
3221
3222@cindex @w{initial environment}
3223
3224@cindex @w{top level environment}
3225
3226@cindex @w{library procedure}
3227
3228This chapter describes Scheme's built-in procedures. The initial (or
3229``top level'') Scheme environment starts out with a number of variables
3230bound to locations containing useful values, most of which are primitive
3231procedures that manipulate data. For example, the variable @samp{abs} is
3232bound to (a location initially containing) a procedure of one argument
3233that computes the absolute value of a number, and the variable @samp{+}
3234is bound to a procedure that computes sums. Built-in procedures that
3235can easily be written in terms of other built-in procedures are identified as
3236``library procedures''.
3237
3238A program may use a top-level definition to bind any variable. It may
3239subsequently alter any such binding by an assignment (see @pxref{Assignments}).
3240These operations do not modify the behavior of Scheme's built-in
3241procedures. Altering any top-level binding that has not been introduced by a
3242definition has an unspecified effect on the behavior of the built-in procedures.
3243
3244@node Equivalence predicates, Numbers, Standard procedures, Standard procedures
3245@section Equivalence predicates
3246
3247
3248
3249A @dfn{predicate} is a procedure that always returns a boolean
3250@cindex @w{predicate}
3251value (@t{#t} or @t{#f}). An @dfn{equivalence predicate} is
3252@cindex @w{equivalence predicate}
3253the computational analogue of a mathematical equivalence relation (it is
3254symmetric, reflexive, and transitive). Of the equivalence predicates
3255described in this section, @samp{eq?} is the finest or most
7fb9c4af 3256discriminating, and @samp{equal?} is the coarsest. @samp{Eqv?} is
a0e07ba4
NJ
3257slightly less discriminating than @samp{eq?}.
3258@ignore todo
3259Pitman doesn't like
3260this paragraph. Lift the discussion from the Maclisp manual. Explain
3261why there's more than one predicate.
3262@end ignore
3263
3264
3265
3266
3267@deffn {procedure} eqv? obj1 obj2
3268
3269The @samp{eqv?} procedure defines a useful equivalence relation on objects.
3270Briefly, it returns @t{#t} if @var{obj1} and @var{obj2} should
3271normally be regarded as the same object. This relation is left slightly
3272open to interpretation, but the following partial specification of
3273@samp{eqv?} holds for all implementations of Scheme.
3274
3275The @samp{eqv?} procedure returns @t{#t} if:
3276
3277
3278
3279@itemize @bullet
3280
3281@item
3282@var{obj1} and @var{obj2} are both @t{#t} or both @t{#f}.
3283
3284@item
3285@var{obj1} and @var{obj2} are both symbols and
3286
3287
3288@format
3289@t{(string=? (symbol->string obj1)
3290 (symbol->string obj2))
3291 ==> #t
3292}
3293@end format
3294
3295
3296
3297@quotation
3298@emph{Note:}
3299This assumes that neither @var{obj1} nor @var{obj2} is an ``uninterned
3300symbol'' as alluded to in section @ref{Symbols}. This report does
3301not presume to specify the behavior of @samp{eqv?} on implementation-dependent
3302extensions.
3303@end quotation
3304
3305
3306@item
3307@var{obj1} and @var{obj2} are both numbers, are numerically
3308equal (see @samp{=}, section @pxref{Numbers}), and are either both
3309exact or both inexact.
3310
3311@item
3312@var{obj1} and @var{obj2} are both characters and are the same
3313character according to the @samp{char=?} procedure
3314(section @pxref{Characters}).
3315
3316@item
3317both @var{obj1} and @var{obj2} are the empty list.
3318
3319@item
3320@var{obj1} and @var{obj2} are pairs, vectors, or strings that denote the
3321same locations in the store (section @pxref{Storage model}).
3322
3323@item
3324@var{obj1} and @var{obj2} are procedures whose location tags are
3325equal (section @pxref{Procedures}).
3326
3327@end itemize
3328
3329@cindex @w{inexact}
3330@cindex @w{exact}
3331
3332The @samp{eqv?} procedure returns @t{#f} if:
3333
3334
3335
3336@itemize @bullet
3337
3338@item
3339@var{obj1} and @var{obj2} are of different types
3340(section @pxref{Disjointness of types}).
3341
3342@item
3343one of @var{obj1} and @var{obj2} is @t{#t} but the other is
3344@t{#f}.
3345
3346@item
3347@var{obj1} and @var{obj2} are symbols but
3348
3349
3350@format
3351@t{(string=? (symbol->string @var{obj1})
3352 (symbol->string @var{obj2}))
3353 ==> #f
3354}
3355@end format
3356
3357
3358@item
3359one of @var{obj1} and @var{obj2} is an exact number but the other
3360is an inexact number.
3361
3362@item
3363@var{obj1} and @var{obj2} are numbers for which the @samp{=}
3364procedure returns @t{#f}.
3365
3366@item
3367@var{obj1} and @var{obj2} are characters for which the @samp{char=?}
3368procedure returns @t{#f}.
3369
3370@item
3371one of @var{obj1} and @var{obj2} is the empty list but the other
3372is not.
3373
3374@item
3375@var{obj1} and @var{obj2} are pairs, vectors, or strings that denote
3376distinct locations.
3377
3378@item
3379@var{obj1} and @var{obj2} are procedures that would behave differently
3380(return different value(s) or have different side effects) for some arguments.
3381
3382
3383@end itemize
3384
3385
3386
3387@format
3388@t{(eqv? 'a 'a) ==> #t
3389(eqv? 'a 'b) ==> #f
3390(eqv? 2 2) ==> #t
3391(eqv? '() '()) ==> #t
3392(eqv? 100000000 100000000) ==> #t
3393(eqv? (cons 1 2) (cons 1 2)) ==> #f
3394(eqv? (lambda () 1)
3395 (lambda () 2)) ==> #f
3396(eqv? #f 'nil) ==> #f
3397(let ((p (lambda (x) x)))
3398 (eqv? p p)) ==> #t
3399}
3400@end format
3401
3402
3403The following examples illustrate cases in which the above rules do
3404not fully specify the behavior of @samp{eqv?}. All that can be said
3405about such cases is that the value returned by @samp{eqv?} must be a
3406boolean.
3407
3408
3409@format
3410@t{(eqv? "" "") ==> @emph{unspecified}
3411(eqv? '#() '#()) ==> @emph{unspecified}
3412(eqv? (lambda (x) x)
3413 (lambda (x) x)) ==> @emph{unspecified}
3414(eqv? (lambda (x) x)
3415 (lambda (y) y)) ==> @emph{unspecified}
3416}
3417@end format
3418
3419
3420The next set of examples shows the use of @samp{eqv?} with procedures
7fb9c4af 3421that have local state. @samp{Gen-counter} must return a distinct
a0e07ba4 3422procedure every time, since each procedure has its own internal counter.
7fb9c4af 3423@samp{Gen-loser}, however, returns equivalent procedures each time, since
a0e07ba4
NJ
3424the local state does not affect the value or side effects of the
3425procedures.
3426
3427
3428@format
3429@t{(define gen-counter
3430 (lambda ()
3431 (let ((n 0))
3432 (lambda () (set! n (+ n 1)) n))))
3433(let ((g (gen-counter)))
3434 (eqv? g g)) ==> #t
3435(eqv? (gen-counter) (gen-counter))
3436 ==> #f
3437(define gen-loser
3438 (lambda ()
3439 (let ((n 0))
3440 (lambda () (set! n (+ n 1)) 27))))
3441(let ((g (gen-loser)))
3442 (eqv? g g)) ==> #t
3443(eqv? (gen-loser) (gen-loser))
3444 ==> @emph{unspecified}
3445
3446(letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
3447 (g (lambda () (if (eqv? f g) 'both 'g))))
3448 (eqv? f g))
3449 ==> @emph{unspecified}
3450
3451(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
3452 (g (lambda () (if (eqv? f g) 'g 'both))))
3453 (eqv? f g))
3454 ==> #f
3455}
3456@end format
3457
3458
3459@c Objects of distinct types must never be regarded as the same object,
3460@c except that \schfalse{} and the empty list\index{empty list} are permitted to
3461@c be identical.
3462
3463@c \begin{scheme}
3464@c (eqv? '() \schfalse) \ev \unspecified%
3465@c \end{scheme}
3466
3467Since it is an error to modify constant objects (those returned by
3468literal expressions), implementations are permitted, though not
3469required, to share structure between constants where appropriate. Thus
3470the value of @samp{eqv?} on constants is sometimes
3471implementation-dependent.
3472
3473
3474@format
3475@t{(eqv? '(a) '(a)) ==> @emph{unspecified}
3476(eqv? "a" "a") ==> @emph{unspecified}
3477(eqv? '(b) (cdr '(a b))) ==> @emph{unspecified}
3478(let ((x '(a)))
3479 (eqv? x x)) ==> #t
3480}
3481@end format
3482
3483
3484
3485@quotation
3486@emph{Rationale:}
3487The above definition of @samp{eqv?} allows implementations latitude in
3488their treatment of procedures and literals: implementations are free
3489either to detect or to fail to detect that two procedures or two literals
3490are equivalent to each other, and can decide whether or not to
3491merge representations of equivalent objects by using the same pointer or
3492bit pattern to represent both.
3493@end quotation
3494
3495
3496@end deffn
3497
3498
3499
3500@deffn {procedure} eq? obj1 obj2
3501
7fb9c4af 3502@samp{Eq?} is similar to @samp{eqv?} except that in some cases it is
a0e07ba4
NJ
3503capable of discerning distinctions finer than those detectable by
3504@samp{eqv?}.
3505
7fb9c4af 3506@samp{Eq?} and @samp{eqv?} are guaranteed to have the same
a0e07ba4
NJ
3507behavior on symbols, booleans, the empty list, pairs, procedures,
3508and non-empty
7fb9c4af 3509strings and vectors. @samp{Eq?}'s behavior on numbers and characters is
a0e07ba4
NJ
3510implementation-dependent, but it will always return either true or
3511false, and will return true only when @samp{eqv?} would also return
7fb9c4af 3512true. @samp{Eq?} may also behave differently from @samp{eqv?} on empty
a0e07ba4
NJ
3513vectors and empty strings.
3514
3515
3516@format
3517@t{(eq? 'a 'a) ==> #t
3518(eq? '(a) '(a)) ==> @emph{unspecified}
3519(eq? (list 'a) (list 'a)) ==> #f
3520(eq? "a" "a") ==> @emph{unspecified}
3521(eq? "" "") ==> @emph{unspecified}
3522(eq? '() '()) ==> #t
3523(eq? 2 2) ==> @emph{unspecified}
3524(eq? #\A #\A) ==> @emph{unspecified}
3525(eq? car car) ==> #t
3526(let ((n (+ 2 3)))
3527 (eq? n n)) ==> @emph{unspecified}
3528(let ((x '(a)))
3529 (eq? x x)) ==> #t
3530(let ((x '#()))
3531 (eq? x x)) ==> #t
3532(let ((p (lambda (x) x)))
3533 (eq? p p)) ==> #t
3534}
3535@end format
3536
3537
3538@ignore todo
3539Needs to be explained better above. How can this be made to be
3540not confusing? A table maybe?
3541@end ignore
3542
3543
3544
3545@quotation
3546@emph{Rationale:} It will usually be possible to implement @samp{eq?} much
3547more efficiently than @samp{eqv?}, for example, as a simple pointer
3548comparison instead of as some more complicated operation. One reason is
3549that it may not be possible to compute @samp{eqv?} of two numbers in
3550constant time, whereas @samp{eq?} implemented as pointer comparison will
7fb9c4af 3551always finish in constant time. @samp{Eq?} may be used like @samp{eqv?}
a0e07ba4
NJ
3552in applications using procedures to implement objects with state since
3553it obeys the same constraints as @samp{eqv?}.
3554@end quotation
3555
3556
3557@end deffn
3558
3559
3560
3561@deffn {library procedure} equal? obj1 obj2
3562
7fb9c4af 3563@samp{Equal?} recursively compares the contents of pairs, vectors, and
a0e07ba4
NJ
3564strings, applying @samp{eqv?} on other objects such as numbers and symbols.
3565A rule of thumb is that objects are generally @samp{equal?} if they print
7fb9c4af 3566the same. @samp{Equal?} may fail to terminate if its arguments are
a0e07ba4
NJ
3567circular data structures.
3568
3569
3570@format
3571@t{(equal? 'a 'a) ==> #t
3572(equal? '(a) '(a)) ==> #t
3573(equal? '(a (b) c)
3574 '(a (b) c)) ==> #t
3575(equal? "abc" "abc") ==> #t
3576(equal? 2 2) ==> #t
3577(equal? (make-vector 5 'a)
3578 (make-vector 5 'a)) ==> #t
3579(equal? (lambda (x) x)
3580 (lambda (y) y)) ==> @emph{unspecified}
3581}
3582@end format
3583
3584
3585@end deffn
3586
3587
3588@node Numbers, Other data types, Equivalence predicates, Standard procedures
3589@section Numbers
3590
3591@menu
3592* Numerical types::
3593* Exactness::
3594* Implementation restrictions::
3595* Syntax of numerical constants::
3596* Numerical operations::
3597* Numerical input and output::
3598@end menu
3599
3600
3601
3602@cindex @w{number}
3603
3604@c %R4%% The excessive use of the code font in this section was
3605@c confusing, somewhat obnoxious, and inconsistent with the rest
3606@c of the report and with parts of the section itself. I added
3607@c a \tupe no-op, and changed most old uses of \type to \tupe,
3608@c to make it easier to change the fonts back if people object
3609@c to the change.
3610
3611@c \newcommand{\type}[1]{{\it#1}}
3612@c \newcommand{\tupe}[1]{{#1}}
3613
3614Numerical computation has traditionally been neglected by the Lisp
3615community. Until Common Lisp there was no carefully thought out
3616strategy for organizing numerical computation, and with the exception of
3617the MacLisp system [Pitman83] little effort was made to
3618execute numerical code efficiently. This report recognizes the excellent work
3619of the Common Lisp committee and accepts many of their recommendations.
3620In some ways this report simplifies and generalizes their proposals in a manner
3621consistent with the purposes of Scheme.
3622
3623It is important to distinguish between the mathematical numbers, the
3624Scheme numbers that attempt to model them, the machine representations
3625used to implement the Scheme numbers, and notations used to write numbers.
3626This report uses the types @i{number}, @i{complex}, @i{real},
3627@i{rational}, and @i{integer} to refer to both mathematical numbers
3628and Scheme numbers. Machine representations such as fixed point and
3629floating point are referred to by names such as @i{fixnum} and
3630@i{flonum}.
3631
3632@c %R4%% I did some reorganizing here to move the discussion of mathematical
3633@c numbers before the discussion of the Scheme numbers, hoping that this
3634@c would help to motivate the discussion of representation independence.
3635
3636@node Numerical types, Exactness, Numbers, Numbers
3637@subsection Numerical types
3638
3639
3640
3641@cindex @w{numerical types}
3642
3643@c %R4%% A Scheme system provides data of type \type{number}, which is the most
3644@c general numerical type supported by that system.
3645@c \type{Number} is
3646@c likely to be a complicated union type implemented in terms of
3647@c \type{fixnum}s, \type{bignum}s, \type{flonum}s, and so forth, but this
3648@c should not be apparent to a naive user. What the user should see is
3649@c that the usual operations on numbers produce the mathematically
3650@c expected results, within the limits of the implementation.
3651
3652@c %R4%% I rewrote the following paragraph to make the various levels of
3653@c the tower into subsets of each other, instead of relating them by
3654@c injections. I think the injections tended to put people in the frame
3655@c of mind of thinking about coercions between non-overlapping numeric
3656@c types in mainstream programming languages.
3657
3658Mathematically, numbers may be arranged into a tower of subtypes
3659@c %R4%% with injections relating adjacent levels of the tower:
3660in which each level is a subset of the level above it:
3661
3662@format
3663 @r{number}
3664 @r{complex}
3665 @r{real}
3666 @r{rational}
3667 @r{integer}
3668@end format
3669
3670
3671For example, 3 is an integer. Therefore 3 is also a rational,
3672a real, and a complex. The same is true of the Scheme numbers
3673that model 3. For Scheme numbers, these types are defined by the
3674predicates @code{number?}, @code{complex?}, @code{real?}, @code{rational?},
3675@vindex @w{rational?}
3676@vindex @w{real?}
3677@vindex @w{complex?}
3678@vindex @w{number?}
3679and @code{integer?}.
3680@vindex @w{integer?}
3681
3682There is no simple relationship between a number's type and its
3683representation inside a computer. Although most implementations of
3684Scheme will offer at least two different representations of 3, these
3685different representations denote the same integer.
3686
3687@c %R4%% I moved "Implementations of Scheme are not required to implement
3688@c the whole tower..." to the subsection on implementation restrictions.
3689
3690Scheme's numerical operations treat numbers as abstract data, as
3691independent of their representation as possible. Although an implementation
3692of Scheme may use fixnum, flonum, and perhaps other representations for
3693numbers, this should not be apparent to a casual programmer writing
3694simple programs.
3695
3696It is necessary, however, to distinguish between numbers that are
3697represented exactly and those that may not be. For example, indexes
3698into data structures must be known exactly, as must some polynomial
3699coefficients in a symbolic algebra system. On the other hand, the
3700results of measurements are inherently inexact, and irrational numbers
3701may be approximated by rational and therefore inexact approximations.
3702In order to catch uses of inexact numbers where exact numbers are
3703required, Scheme explicitly distinguishes exact from inexact numbers.
3704This distinction is orthogonal to the dimension of type.
3705
3706@node Exactness, Implementation restrictions, Numerical types, Numbers
3707@subsection Exactness
3708
3709
3710@c %R4%% I tried to direct the following paragraph away from philosophizing
3711@c about the exactness of mathematical numbers, and toward philosophizing
3712@c about the exactness of Scheme numbers.
3713
3714
3715@cindex @w{exactness}
3716Scheme numbers are either @i{exact} or @i{inexact}. A number is
3717@r{exact} if it was written as an exact constant or was derived from
3718@r{exact} numbers using only @r{exact} operations. A number is
3719@r{inexact} if it was written as an inexact constant,
3720@c %R4%% models a quantity (e.g., a measurement) known only approximately,
3721if it was
3722derived using @r{inexact} ingredients, or if it was derived using
3723@r{inexact} operations. Thus @r{inexact}ness is a contagious
3724property of a number.
3725@c %R4%% The rest of this paragraph (from R3RS) has been dropped.
3726
3727If two implementations produce @r{exact} results for a
3728computation that did not involve @r{inexact} intermediate results,
3729the two ultimate results will be mathematically equivalent. This is
3730generally not true of computations involving @r{inexact} numbers
3731since approximate methods such as floating point arithmetic may be used,
3732but it is the duty of each implementation to make the result as close as
3733practical to the mathematically ideal result.
3734
3735Rational operations such as @samp{+} should always produce
3736@r{exact} results when given @r{exact} arguments.
3737@c %R4%%If an implementation is
3738@c unable to represent an \tupe{exact} result (for example, if it does not
3739@c support infinite precision integers and rationals)
3740If the operation is unable to produce an @r{exact} result,
3741then it may either report the violation of an implementation restriction
3742or it may silently coerce its
3743result to an @r{inexact} value.
3744@c %R4%%Such a coercion may cause an error later.
3745See section @ref{Implementation restrictions}.
3746
3747With the exception of @code{inexact->exact}, the operations described in
3748@vindex @w{inexact->exact}
3749this section must generally return inexact results when given any inexact
3750arguments. An operation may, however, return an @r{exact} result if it can
3751prove that the value of the result is unaffected by the inexactness of its
3752arguments. For example, multiplication of any number by an @r{exact} zero
3753may produce an @r{exact} zero result, even if the other argument is
3754@r{inexact}.
3755
3756@node Implementation restrictions, Syntax of numerical constants, Exactness, Numbers
3757@subsection Implementation restrictions
3758
3759
3760
3761@cindex @w{implementation restriction}
3762
3763Implementations of Scheme are not required to implement the whole
3764tower of subtypes given in section @ref{Numerical types},
3765but they must implement a coherent subset consistent with both the
3766purposes of the implementation and the spirit of the Scheme language.
3767For example, an implementation in which all numbers are @r{real}
3768may still be quite useful.
3769
3770Implementations may also support only a limited range of numbers of
3771any type, subject to the requirements of this section. The supported
3772range for @r{exact} numbers of any type may be different from the
3773supported range for @r{inexact} numbers of that type. For example,
3774an implementation that uses flonums to represent all its
3775@r{inexact} @r{real} numbers may
3776support a practically unbounded range of @r{exact} @r{integer}s
3777and @r{rational}s
3778while limiting the range of @r{inexact} @r{real}s (and therefore
3779the range of @r{inexact} @r{integer}s and @r{rational}s)
3780to the dynamic range of the flonum format.
3781Furthermore
3782the gaps between the representable @r{inexact} @r{integer}s and
3783@r{rational}s are
3784likely to be very large in such an implementation as the limits of this
3785range are approached.
3786
3787An implementation of Scheme must support exact integers
3788throughout the range of numbers that may be used for indexes of
3789lists, vectors, and strings or that may result from computing the length of a
3790list, vector, or string. The @code{length}, @code{vector-length},
3791@vindex @w{vector-length}
3792@vindex @w{length}
3793and @code{string-length} procedures must return an exact
3794@vindex @w{string-length}
3795integer, and it is an error to use anything but an exact integer as an
3796index. Furthermore any integer constant within the index range, if
3797expressed by an exact integer syntax, will indeed be read as an exact
3798integer, regardless of any implementation restrictions that may apply
3799outside this range. Finally, the procedures listed below will always
3800return an exact integer result provided all their arguments are exact integers
3801and the mathematically expected result is representable as an exact integer
3802within the implementation:
3803
3804
3805@example
3806
3807+ - *
3808quotient remainder modulo
3809max min abs
3810numerator denominator gcd
3811lcm floor ceiling
3812truncate round rationalize
3813expt
3814
3815@end example
3816
3817
3818Implementations are encouraged, but not required, to support
3819@r{exact} @r{integer}s and @r{exact} @r{rational}s of
3820practically unlimited size and precision, and to implement the
3821above procedures and the @samp{/} procedure in
3822such a way that they always return @r{exact} results when given @r{exact}
3823arguments. If one of these procedures is unable to deliver an @r{exact}
3824result when given @r{exact} arguments, then it may either report a
3825violation of an
3826implementation restriction or it may silently coerce its result to an
3827@r{inexact} number. Such a coercion may cause an error later.
3828
3829@c %R4%% I moved this stuff here.
3830@c It seems to me that the only thing that this requires is that
3831@c implementations that support inexact numbers have to have both
3832@c exact and inexact representations for the integers 0 through 15.
3833@c If that's what it's saying, I'd rather say it that way.
3834@c On the other hand, letting the limit be as small as 15 sounds a
3835@c tad silly, though I think I understand how that number was arrived at.
3836@c (Or is 35 the number?)
3837
3838@c Implementations are encouraged, but not required, to support \tupe{inexact}
3839@c numbers. For any implementation that supports \tupe{inexact} numbers,
3840@c there is a subset of the integers for which there are both \tupe{exact} and
3841@c \tupe{inexact} representations. This subset must include all non-negative
3842@c integers up to some limit specified by the implementation. This limit
3843@c must be 16 or greater. The
3844@c \ide{exact\coerce{}inexact} and \ide{inexact\coerce{}exact}
3845@c procedures implement the natural one-to-one correspondence between
3846@c the \tupe{inexact} and \tupe{exact} integers within this range.
3847
3848An implementation may use floating point and other approximate
3849representation strategies for @r{inexact} numbers.
3850@c %R4%% The following sentence seemed a bit condescending as well as
3851@c awkward. It didn't seem to be very enforceable, so I flushed it.
3852
3853@c This is not to
3854@c say that implementors need not use the best known algorithms for
3855@c \tupe{inexact} computations---only that approximate methods of high
3856@c quality are allowed.
3857
3858This report recommends, but does not require, that the IEEE 32-bit
3859and 64-bit floating point standards be followed by implementations that use
3860flonum representations, and that implementations using
3861other representations should match or exceed the precision achievable
3862using these floating point standards [IEEE].
3863
3864In particular, implementations that use flonum representations
3865must follow these rules: A @r{flonum} result
3866must be represented with at least as much precision as is used to express any of
3867the inexact arguments to that operation. It is desirable (but not required) for
3868potentially inexact operations such as @samp{sqrt}, when applied to @r{exact}
3869arguments, to produce @r{exact} answers whenever possible (for example the
3870square root of an @r{exact} 4 ought to be an @r{exact} 2).
3871If, however, an
3872@r{exact} number is operated upon so as to produce an @r{inexact} result
3873(as by @samp{sqrt}), and if the result is represented as a @r{flonum}, then
3874the most precise @r{flonum} format available must be used; but if the result
3875is represented in some other way then the representation must have at least as
3876much precision as the most precise @r{flonum} format available.
3877
3878Although Scheme allows a variety of written
3879@c %R4%% representations of
3880notations for
3881numbers, any particular implementation may support only some of them.
3882@c %R4%%
3883For example, an implementation in which all numbers are @r{real}
3884need not support the rectangular and polar notations for complex
3885numbers. If an implementation encounters an @r{exact} numerical constant that
3886it cannot represent as an @r{exact} number, then it may either report a
3887violation of an implementation restriction or it may silently represent the
3888constant by an @r{inexact} number.
3889
3890
3891@node Syntax of numerical constants, Numerical operations, Implementation restrictions, Numbers
3892@subsection Syntax of numerical constants
3893
3894
3895
3896@c @@@@LOSE@@@@
3897
3898@c %R4%% I removed the following paragraph in an attempt to tighten up
3899@c this subsection. Except for its first sentence, which I moved to
3900@c the subsection on implementation restrictions, I think its content
3901@c is implied by the rest of the section.
3902
3903@c Although Scheme allows a variety of written representations of numbers,
3904@c any particular implementation may support only some of them.
3905@c These syntaxes are intended to be purely notational; any kind of number
3906@c may be written in any form that the user deems convenient. Of course,
3907@c writing 1/7 as a limited-precision decimal fraction will not express the
3908@c number exactly, but this approximate form of expression may be just what
3909@c the user wants to see.
3910
3911The syntax of the written representations for numbers is described formally in
3912section @ref{Lexical structure}. Note that case is not significant in numerical
3913constants.
3914
3915@c %R4%% See section~\ref{numberformats} for many examples.
3916
3917A number may be written in binary, octal, decimal, or
3918hexadecimal by the use of a radix prefix. The radix prefixes are @samp{#b} (binary), @samp{#o} (octal), @samp{#d} (decimal), and @samp{#x} (hexadecimal). With
3919@vindex #x
3920@vindex #d
3921@vindex #o
3922@vindex #b
3923no radix prefix, a number is assumed to be expressed in decimal.
3924
3925A
3926@c %R4%%
3927@c simple
3928numerical constant may be specified to be either @r{exact} or
3929@r{inexact} by a prefix. The prefixes are @samp{#e}
3930@vindex #e
3931for @r{exact}, and @samp{#i} for @r{inexact}. An exactness
3932@vindex #i
3933prefix may appear before or after any radix prefix that is used. If
3934the written representation of a number has no exactness prefix, the
3935constant may be either @r{inexact} or @r{exact}. It is
3936@r{inexact} if it contains a decimal point, an
3937exponent, or a ``#'' character in the place of a digit,
3938otherwise it is @r{exact}.
3939@c %R4%% With our new syntax, the following sentence is redundant:
3940
3941@c The written representation of a
3942@c compound number, such as a ratio or a complex, is exact if and only if
3943@c all of its constituents are exact.
3944
3945In systems with @r{inexact} numbers
3946of varying precisions it may be useful to specify
3947the precision of a constant. For this purpose, numerical constants
3948may be written with an exponent marker that indicates the
3949desired precision of the @r{inexact}
3950representation. The letters @samp{s}, @samp{f},
3951@samp{d}, and @samp{l} specify the use of @var{short}, @var{single},
3952@var{double}, and @var{long} precision, respectively. (When fewer
3953than four internal
3954@c %R4%%\tupe{flonum}
3955@r{inexact}
3956representations exist, the four size
3957specifications are mapped onto those available. For example, an
3958implementation with two internal representations may map short and
3959single together and long and double together.) In addition, the
3960exponent marker @samp{e} specifies the default precision for the
3961implementation. The default precision has at least as much precision
3962as @var{double}, but
3963implementations may wish to allow this default to be set by the user.
3964
3965
3966@example
3967
39683.14159265358979F0
3969 @r{Round to single ---} 3.141593
39700.6L0
3971 @r{Extend to long ---} .600000000000000
3972
3973@end example
3974
3975
3976
3977@node Numerical operations, Numerical input and output, Syntax of numerical constants, Numbers
3978@subsection Numerical operations
3979
3980
3981The reader is referred to section @ref{Entry format} for a summary
3982of the naming conventions used to specify restrictions on the types of
3983arguments to numerical routines.
3984@c %R4%% The following sentence has already been said twice, and the
3985@c term "exactness-preserving" is no longer defined by the Report.
3986
3987@c Remember that
3988@c an exactness-preserving operation may coerce its result to inexact if the
3989@c implementation is unable to represent it exactly.
3990The examples used in this section assume that any numerical constant written
3991using an @r{exact} notation is indeed represented as an @r{exact}
3992number. Some examples also assume that certain numerical constants written
3993using an @r{inexact} notation can be represented without loss of
3994accuracy; the @r{inexact} constants were chosen so that this is
3995likely to be true in implementations that use flonums to represent
3996inexact numbers.
3997
3998@ignore todo
3999Scheme provides the usual set of operations for manipulating
4000numbers, etc.
4001@end ignore
4002
4003
4004
4005@deffn {procedure} number? obj
4006@deffnx {procedure} complex? obj
4007@deffnx {procedure} real? obj
4008@deffnx {procedure} rational? obj
4009@deffnx {procedure} integer? obj
4010
4011These numerical type predicates can be applied to any kind of
4012argument, including non-numbers. They return @t{#t} if the object is
4013of the named type, and otherwise they return @t{#f}.
4014In general, if a type predicate is true of a number then all higher
4015type predicates are also true of that number. Consequently, if a type
4016predicate is false of a number, then all lower type predicates are
4017also false of that number.
4018@c %R4%% The new section on implementation restrictions subsumes:
4019@c Not every system
4020@c supports all of these types; for example, it is entirely possible to have a
4021@c Scheme system that has only \tupe{integer}s. Nonetheless every implementation
4022@c of Scheme must have all of these predicates.
4023
4024If @var{z} is an inexact complex number, then @samp{(real? @var{z})} is true if
4025and only if @samp{(zero? (imag-part @var{z}))} is true. If @var{x} is an inexact
4026real number, then @samp{(integer? @var{x})} is true if and only if
4027@samp{(= @var{x} (round @var{x}))}.
4028
4029
4030@format
4031@t{(complex? 3+4i) ==> #t
4032(complex? 3) ==> #t
4033(real? 3) ==> #t
4034(real? -2.5+0.0i) ==> #t
4035(real? #e1e10) ==> #t
4036(rational? 6/10) ==> #t
4037(rational? 6/3) ==> #t
4038(integer? 3+0i) ==> #t
4039(integer? 3.0) ==> #t
4040(integer? 8/4) ==> #t
4041}
4042@end format
4043
4044
4045
4046@quotation
4047@emph{Note:}
4048The behavior of these type predicates on @r{inexact} numbers
4049is unreliable, since any inaccuracy may affect the result.
4050@end quotation
4051
4052
4053
4054@quotation
4055@emph{Note:}
4056In many implementations the @code{rational?} procedure will be the same
4057@vindex @w{rational?}
4058as @code{real?}, and the @code{complex?} procedure will be the same as
4059@vindex @w{complex?}
4060@vindex @w{real?}
4061@code{number?}, but unusual implementations may be able to represent
4062@vindex @w{number?}
4063some irrational numbers exactly or may extend the number system to
4064support some kind of non-complex numbers.
4065@end quotation
4066
4067
4068@end deffn
4069
4070
4071@deffn {procedure} exact? @var{z}
4072@deffnx {procedure} inexact? @var{z}
4073
4074These numerical predicates provide tests for the exactness of a
4075quantity. For any Scheme number, precisely one of these predicates
4076is true.
4077
4078@end deffn
4079
4080
4081
4082@deffn {procedure} = z1 z2 z3 @dots{},
4083@deffnx {procedure} < x1 x2 x3 @dots{},
4084@deffnx {procedure} > x1 x2 x3 @dots{},
4085@deffnx {procedure} <= x1 x2 x3 @dots{},
4086@deffnx {procedure} >= x1 x2 x3 @dots{},
4087
4088@c - Some implementations allow these procedures to take many arguments, to
4089@c - facilitate range checks.
4090These procedures return @t{#t} if their arguments are (respectively):
4091equal, monotonically increasing, monotonically decreasing,
4092monotonically nondecreasing, or monotonically nonincreasing.
4093
4094These predicates are required to be transitive.
4095
4096
4097@quotation
4098@emph{Note:}
4099The traditional implementations of these predicates in Lisp-like
4100languages are not transitive.
4101@end quotation
4102
4103
4104
4105@quotation
4106@emph{Note:}
4107While it is not an error to compare @r{inexact} numbers using these
4108predicates, the results may be unreliable because a small inaccuracy
4109may affect the result; this is especially true of @code{=} and @code{zero?}.
4110@vindex @w{zero?}
4111@vindex @w{=}
4112When in doubt, consult a numerical analyst.
4113@end quotation
4114
4115
4116@end deffn
4117
4118
4119@deffn {library procedure} zero? @var{z}
4120@deffnx {library procedure} positive? @var{x}
4121@deffnx {library procedure} negative? @var{x}
4122@deffnx {library procedure} odd? @var{n}
4123@deffnx {library procedure} even? @var{n}
4124
4125These numerical predicates test a number for a particular property,
4126returning @t{#t} or @t{#f}. See note above.
4127
4128@end deffn
4129
4130
4131@deffn {library procedure} max x1 x2 @dots{},
4132@deffnx {library procedure} min x1 x2 @dots{},
4133
4134These procedures return the maximum or minimum of their arguments.
4135
4136
4137@format
4138@t{(max 3 4) ==> 4 ; exact
4139(max 3.9 4) ==> 4.0 ; inexact
4140}
4141@end format
4142
4143
4144
4145@quotation
4146@emph{Note:}
4147If any argument is inexact, then the result will also be inexact (unless
4148the procedure can prove that the inaccuracy is not large enough to affect the
4149result, which is possible only in unusual implementations). If @samp{min} or
4150@samp{max} is used to compare numbers of mixed exactness, and the numerical
4151value of the result cannot be represented as an inexact number without loss of
4152accuracy, then the procedure may report a violation of an implementation
4153restriction.
4154@end quotation
4155
4156
4157@end deffn
4158
4159
4160
4161@deffn {procedure} + z1 @dots{},
4162@deffnx {procedure} * z1 @dots{},
4163
4164These procedures return the sum or product of their arguments.
4165@c - These procedures are exactness preserving.
4166
4167
4168@format
4169@t{(+ 3 4) ==> 7
4170(+ 3) ==> 3
4171(+) ==> 0
4172(* 4) ==> 4
4173(*) ==> 1
4174}
4175@end format
4176
4177
4178@end deffn
4179
4180
4181
4182@deffn {procedure} - z1 z2
4183@deffnx {procedure} - @var{z}
4184@deffnx {optional procedure} - z1 z2 @dots{},
4185@deffnx {procedure} / z1 z2
4186@deffnx {procedure} / @var{z}
4187@deffnx {optional procedure} / z1 z2 @dots{},
4188
4189With two or more arguments, these procedures return the difference or
4190quotient of their arguments, associating to the left. With one argument,
4191however, they return the additive or multiplicative inverse of their argument.
4192@c - These procedures are exactness preserving, except that division may
4193@c - coerce its result to inexact in implementations that do not support
4194@c - \tupe{ratnum}s.
4195
4196
4197@format
4198@t{(- 3 4) ==> -1
4199(- 3 4 5) ==> -6
4200(- 3) ==> -3
4201(/ 3 4 5) ==> 3/20
4202(/ 3) ==> 1/3
4203}
4204@end format
4205
4206
4207@end deffn
4208
4209
4210
4211@deffn {library procedure} abs x
4212
7fb9c4af 4213@samp{Abs} returns the absolute value of its argument.
a0e07ba4
NJ
4214@c - {\cf Abs} is exactness preserving when its argument is real.
4215
4216@format
4217@t{(abs -7) ==> 7
4218}
4219@end format
4220
4221@end deffn
4222
4223
4224
4225@deffn {procedure} quotient n1 n2
4226@deffnx {procedure} remainder n1 n2
4227@deffnx {procedure} modulo n1 n2
4228
4229These procedures implement number-theoretic (integer)
4230division. @var{n2} should be non-zero. All three procedures
4231return integers. If @var{n1}/@var{n2} is an integer:
4232
4233@format
4234@t{ (quotient @var{n1} @var{n2}) ==> @var{n1}/@var{n2}
4235 (remainder @var{n1} @var{n2}) ==> 0
4236 (modulo @var{n1} @var{n2}) ==> 0
4237}
4238@end format
4239
4240If @var{n1}/@var{n2} is not an integer:
4241
4242@format
4243@t{ (quotient @var{n1} @var{n2}) ==> @var{n_q}
4244 (remainder @var{n1} @var{n2}) ==> @var{n_r}
4245 (modulo @var{n1} @var{n2}) ==> @var{n_m}
4246}
4247@end format
4248
4249where @var{n_q} is @var{n1}/@var{n2} rounded towards zero,
42500 < |@var{n_r}| < |@var{n2}|, 0 < |@var{n_m}| < |@var{n2}|,
4251@var{n_r} and @var{n_m} differ from @var{n1} by a multiple of @var{n2},
4252@var{n_r} has the same sign as @var{n1}, and
4253@var{n_m} has the same sign as @var{n2}.
4254
4255From this we can conclude that for integers @var{n1} and @var{n2} with
4256@var{n2} not equal to 0,
4257
4258@format
4259@t{ (= @var{n1} (+ (* @var{n2} (quotient @var{n1} @var{n2}))
4260 (remainder @var{n1} @var{n2})))
4261 ==> #t
4262}
4263@end format
4264
4265provided all numbers involved in that computation are exact.
4266
4267
4268@format
4269@t{(modulo 13 4) ==> 1
4270(remainder 13 4) ==> 1
4271
4272(modulo -13 4) ==> 3
4273(remainder -13 4) ==> -1
4274
4275(modulo 13 -4) ==> -3
4276(remainder 13 -4) ==> 1
4277
4278(modulo -13 -4) ==> -1
4279(remainder -13 -4) ==> -1
4280
4281(remainder -13 -4.0) ==> -1.0 ; inexact
4282}
4283@end format
4284
4285@end deffn
4286
4287
4288@deffn {library procedure} gcd n1 @dots{},
4289@deffnx {library procedure} lcm n1 @dots{},
4290
4291These procedures return the greatest common divisor or least common
4292multiple of their arguments. The result is always non-negative.
4293@c - These procedures are exactness preserving.
4294
4295@c %R4%% I added the inexact example.
4296
4297@format
4298@t{(gcd 32 -36) ==> 4
4299(gcd) ==> 0
4300(lcm 32 -36) ==> 288
4301(lcm 32.0 -36) ==> 288.0 ; inexact
4302(lcm) ==> 1
4303}
4304@end format
4305
4306
4307@end deffn
4308
4309
4310
4311@deffn {procedure} numerator @var{q}
4312@deffnx {procedure} denominator @var{q}
4313
4314These procedures return the numerator or denominator of their
4315argument; the result is computed as if the argument was represented as
4316a fraction in lowest terms. The denominator is always positive. The
4317denominator of 0 is defined to be 1.
4318@c - The remarks about denominators are new.
4319@c - Clearly, they are exactness-preserving procedures.
4320
4321@ignore todo
4322More description and examples needed.
4323@end ignore
4324
4325
4326@format
4327@t{(numerator (/ 6 4)) ==> 3
4328(denominator (/ 6 4)) ==> 2
4329(denominator
4330 (exact->inexact (/ 6 4))) ==> 2.0
4331}
4332@end format
4333
4334
4335@end deffn
4336
4337
4338
4339@deffn {procedure} floor x
4340@deffnx {procedure} ceiling x
4341@deffnx {procedure} truncate x
4342@deffnx {procedure} round x
4343
4344
4345These procedures return integers.
7fb9c4af
AW
4346@samp{Floor} returns the largest integer not larger than @var{x}.
4347@samp{Ceiling} returns the smallest integer not smaller than @var{x}.
4348@samp{Truncate} returns the integer closest to @var{x} whose absolute
4349value is not larger than the absolute value of @var{x}. @samp{Round} returns the
a0e07ba4
NJ
4350closest integer to @var{x}, rounding to even when @var{x} is halfway between two
4351integers.
4352
4353
4354@quotation
4355@emph{Rationale:}
7fb9c4af 4356@samp{Round} rounds to even for consistency with the default rounding
a0e07ba4
NJ
4357mode specified by the IEEE floating point standard.
4358@end quotation
4359
4360
4361
4362@quotation
4363@emph{Note:}
4364If the argument to one of these procedures is inexact, then the result
4365will also be inexact. If an exact value is needed, the
4366result should be passed to the @samp{inexact->exact} procedure.
4367@end quotation
4368
4369
4370
4371@format
4372@t{(floor -4.3) ==> -5.0
4373(ceiling -4.3) ==> -4.0
4374(truncate -4.3) ==> -4.0
4375(round -4.3) ==> -4.0
4376
4377(floor 3.5) ==> 3.0
4378(ceiling 3.5) ==> 4.0
4379(truncate 3.5) ==> 3.0
4380(round 3.5) ==> 4.0 ; inexact
4381
4382(round 7/2) ==> 4 ; exact
4383(round 7) ==> 7
4384}
4385@end format
4386
4387
4388@end deffn
4389
4390
4391@deffn {library procedure} rationalize x y
4392@c - \proto{rationalize}{ x}{procedure}
4393
4394
7fb9c4af 4395@samp{Rationalize} returns the @emph{simplest} rational number
a0e07ba4
NJ
4396differing from @var{x} by no more than @var{y}. A rational number r_1 is
4397@emph{simpler} than another rational number
4398@cindex @w{simplest rational}
4399r_2 if r_1 = p_1/q_1 and r_2 = p_2/q_2 (in lowest terms) and |p_1|<= |p_2| and |q_1| <= |q_2|. Thus 3/5 is simpler than 4/7.
4400Although not all rationals are comparable in this ordering (consider 2/7
4401and 3/5) any interval contains a rational number that is simpler than
4402every other rational number in that interval (the simpler 2/5 lies
4403between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
4404all.
4405
4406
4407@format
4408@t{(rationalize
4409 (inexact->exact .3) 1/10) ==> 1/3 ; exact
4410(rationalize .3 1/10) ==> #i1/3 ; inexact
4411}
4412@end format
4413
4414
4415@end deffn
4416
4417
4418@deffn {procedure} exp @var{z}
4419@deffnx {procedure} log @var{z}
4420@deffnx {procedure} sin @var{z}
4421@deffnx {procedure} cos @var{z}
4422@deffnx {procedure} tan @var{z}
4423@deffnx {procedure} asin @var{z}
4424@deffnx {procedure} acos @var{z}
4425@deffnx {procedure} atan @var{z}
4426@deffnx {procedure} atan @var{y} @var{x}
4427
4428These procedures are part of every implementation that supports
4429@c %R4%%
4430general
ecb87335 4431real numbers; they compute the usual transcendental functions. @samp{log}
a0e07ba4 4432computes the natural logarithm of @var{z} (not the base ten logarithm).
ecb87335 4433@samp{asin}, @samp{acos}, and @samp{atan} compute arcsine (sin^-1),
a0e07ba4
NJ
4434arccosine (cos^-1), and arctangent (tan^-1), respectively.
4435The two-argument variant of @samp{atan} computes @t{(angle
4436(make-rectangular @var{x} @var{y}))} (see below), even in implementations
4437that don't support general complex numbers.
4438
4439In general, the mathematical functions log, arcsine, arccosine, and
4440arctangent are multiply defined.
4441The value of log z is defined to be the one whose imaginary
4442part lies in the range from -pi (exclusive) to pi (inclusive).
4443log 0 is undefined.
4444With log defined this way, the values of sin^-1 z, cos^-1 z,
4445and tan^-1 z are according to the following formulae:
4446
4447
eaf2d3f2 4448@center sin^-1 z = -i log (i z + sqrt(1 - z^2))
a0e07ba4
NJ
4449
4450
4451
4452@center cos^-1 z = pi / 2 - sin^-1 z
4453
4454
4455
4456@center tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
4457
4458
4459The above specification follows [CLtL], which in turn
4460cites [Penfield81]; refer to these sources for more detailed
4461discussion of branch cuts, boundary conditions, and implementation of
4462these functions. When it is possible these procedures produce a real
4463result from a real argument.
4464
4465@c %R4%%
4466
4467@ignore todo
4468The cited references are likely to change their branch cuts
4469soon to allow for the possibility of distinct positive and negative
4470zeroes, as in IEEE floating point. We may not want to follow those
4471changes, since we may want a complex number with zero imaginary part
4472(whether positive or negative zero) to be treated as a real. I don't
4473think there are any better standards for complex arithmetic than the
4474ones cited, so we're really on our own here.
4475@end ignore
4476
4477
4478@end deffn
4479
4480
4481
4482@deffn {procedure} sqrt @var{z}
4483
4484Returns the principal square root of @var{z}. The result will have
4485either positive real part, or zero real part and non-negative imaginary
4486part.
4487@end deffn
4488
4489
4490
4491@deffn {procedure} expt z1 z2
4492
4493Returns @var{z1} raised to the power @var{z2}. For z_1 ~= 0
4494
4495
4496@center z_1^z_2 = e^z_2 log z_1
4497
44980^z is 1 if z = 0 and 0 otherwise.
4499@end deffn
4500
4501@c - \begin{entry}{%-
4502@c - \proto{approximate}{ z x}{procedure}}
4503@c -
4504@c - Returns an approximation to \vr{z} in a representation whose precision is
4505@c - the same as that
4506@c - of the representation of \vr{x}, which must be an inexact number. The
4507@c - result is always inexact.
4508@c -
4509@c - \begin{scheme}
4510@c - (approximate 3.1415926535 1F10)
4511@c - \ev 3.14159F0
4512@c - (approximate 3.1415926535 \#I65535)
4513@c - \ev \#I3
4514@c - (approximate 3.14F0 1L8)
4515@c - \ev 3.14L0
4516@c - (approximate 3.1415926535F0 1L8)
4517@c - \ev 3.14159L0
4518@c - \end{scheme}
4519@c - \end{entry}
4520
4521
4522
4523
4524@deffn {procedure} make-rectangular x1 x2
4525@deffnx {procedure} make-polar x3 x4
4526@deffnx {procedure} real-part @var{z}
4527@deffnx {procedure} imag-part @var{z}
4528@deffnx {procedure} magnitude @var{z}
4529@deffnx {procedure} angle @var{z}
4530
4531These procedures are part of every implementation that supports
4532@c %R4%%
4533general
4534complex numbers. Suppose @var{x1}, @var{x2}, @var{x3}, and @var{x4} are
4535real numbers and @var{z} is a complex number such that
4536
4537
4538@center @var{z} = @var{x1} + @var{x2}@w{i} = @var{x3} . e^@w{i} @var{x4}
4539
4540Then
4541
4542@format
4543@t{(make-rectangular @var{x1} @var{x2}) ==> @var{z}
4544(make-polar @var{x3} @var{x4}) ==> @var{z}
4545(real-part @var{z}) ==> @var{x1}
4546(imag-part @var{z}) ==> @var{x2}
4547(magnitude @var{z}) ==> |@var{x3}|
4548(angle @var{z}) ==> x_angle
4549}
4550@end format
4551
4552where -pi < x_angle <= pi with x_angle = @var{x4} + 2pi n
4553for some integer n.
4554
4555
4556@quotation
4557@emph{Rationale:}
7fb9c4af 4558@samp{Magnitude} is the same as @code{abs} for a real argument,
a0e07ba4
NJ
4559@vindex @w{abs}
4560but @samp{abs} must be present in all implementations, whereas
4561@samp{magnitude} need only be present in implementations that support
4562general complex numbers.
4563@end quotation
4564
4565
4566@end deffn
4567
4568
4569
4570@deffn {procedure} exact->inexact @var{z}
4571@deffnx {procedure} inexact->exact @var{z}
4572
7fb9c4af 4573@samp{Exact->inexact} returns an @r{inexact} representation of @var{z}.
a0e07ba4
NJ
4574The value returned is the
4575@r{inexact} number that is numerically closest to the argument.
4576@c %R4%%For
4577@c \tupe{exact} arguments which have no reasonably close \tupe{inexact} equivalent,
4578@c it is permissible to signal an error.
4579If an @r{exact} argument has no reasonably close @r{inexact} equivalent,
4580then a violation of an implementation restriction may be reported.
4581
7fb9c4af 4582@samp{Inexact->exact} returns an @r{exact} representation of
a0e07ba4
NJ
4583@var{z}. The value returned is the @r{exact} number that is numerically
4584closest to the argument.
4585@c %R4%% For \tupe{inexact} arguments which have no
4586@c reasonably close \tupe{exact} equivalent, it is permissible to signal
4587@c an error.
4588If an @r{inexact} argument has no reasonably close @r{exact} equivalent,
4589then a violation of an implementation restriction may be reported.
4590
4591@c %R%% I moved this to the section on implementation restrictions.
4592@c For any implementation that supports \tupe{inexact} quantities,
4593@c there is a subset of the integers for which there are both \tupe{exact} and
4594@c \tupe{inexact} representations. This subset must include the non-negative
4595@c integers up to a limit specified by the implementation. The limit
4596@c must be big enough to represent all digits in reasonable radices, and
4597@c may correspond to some natural word size for the implementation. For
4598@c such integers, these procedures implement the natural one-to-one
4599@c correspondence between the representations.
4600
4601These procedures implement the natural one-to-one correspondence between
4602@r{exact} and @r{inexact} integers throughout an
4603implementation-dependent range. See section @ref{Implementation restrictions}.
4604
4605@end deffn
4606
4607@sp 3
4608
4609@node Numerical input and output, , Numerical operations, Numbers
4610@subsection Numerical input and output
4611
4612
4613
4614@deffn {procedure} number->string z
4615@deffnx {procedure} number->string z radix
4616
7fb9c4af 4617@var{Radix} must be an exact integer, either 2, 8, 10, or 16. If omitted,
a0e07ba4
NJ
4618@var{radix} defaults to 10.
4619The procedure @samp{number->string} takes a
4620number and a radix and returns as a string an external representation of
4621the given number in the given radix such that
4622
4623@format
4624@t{(let ((number @var{number})
4625 (radix @var{radix}))
4626 (eqv? number
4627 (string->number (number->string number
4628 radix)
4629 radix)))
4630}
4631@end format
4632
4633is true. It is an error if no possible result makes this expression true.
4634
4635If @var{z} is inexact, the radix is 10, and the above expression
4636can be satisfied by a result that contains a decimal point,
4637then the result contains a decimal point and is expressed using the
4638minimum number of digits (exclusive of exponent and trailing
4639zeroes) needed to make the above expression
4640true [howtoprint], [howtoread];
4641otherwise the format of the result is unspecified.
4642
4643The result returned by @samp{number->string}
4644never contains an explicit radix prefix.
4645
4646
4647@quotation
4648@emph{Note:}
4649The error case can occur only when @var{z} is not a complex number
4650or is a complex number with a non-rational real or imaginary part.
4651@end quotation
4652
4653
4654
4655@quotation
4656@emph{Rationale:}
4657If @var{z} is an inexact number represented using flonums, and
4658the radix is 10, then the above expression is normally satisfied by
4659a result containing a decimal point. The unspecified case
4660allows for infinities, NaNs, and non-flonum representations.
4661@end quotation
4662
4663
4664@end deffn
4665
4666
4667
4668@deffn {procedure} string->number string
4669@deffnx {procedure} string->number string radix
4670
4671@c %R4%% I didn't include the (string->number string radix exactness)
4672@c case, since I haven't heard any resolution of the coding to be used
4673@c for the third argument.
4674
4675Returns a number of the maximally precise representation expressed by the
7fb9c4af 4676given @var{string}. @var{Radix} must be an exact integer, either 2, 8, 10,
a0e07ba4
NJ
4677or 16. If supplied, @var{radix} is a default radix that may be overridden
4678by an explicit radix prefix in @var{string} (e.g. @t{"#o177"}). If @var{radix}
4679is not supplied, then the default radix is 10. If @var{string} is not
4680a syntactically valid notation for a number, then @samp{string->number}
4681returns @t{#f}.
4682
4683
4684@format
4685@t{(string->number "100") ==> 100
4686(string->number "100" 16) ==> 256
4687(string->number "1e2") ==> 100.0
4688(string->number "15##") ==> 1500.0
4689}
4690@end format
4691
4692
4693
4694@quotation
4695@emph{Note:}
4696The domain of @samp{string->number} may be restricted by implementations
7fb9c4af 4697in the following ways. @samp{String->number} is permitted to return
a0e07ba4
NJ
4698@t{#f} whenever @var{string} contains an explicit radix prefix.
4699If all numbers supported by an implementation are real, then
4700@samp{string->number} is permitted to return @t{#f} whenever
4701@var{string} uses the polar or rectangular notations for complex
4702numbers. If all numbers are integers, then
4703@samp{string->number} may return @t{#f} whenever
4704the fractional notation is used. If all numbers are exact, then
4705@samp{string->number} may return @t{#f} whenever
4706an exponent marker or explicit exactness prefix is used, or if
4707a @t{#} appears in place of a digit. If all inexact
4708numbers are integers, then
4709@samp{string->number} may return @t{#f} whenever
4710a decimal point is used.
4711@end quotation
4712
4713
4714@end deffn
4715
4716@node Other data types, Control features, Numbers, Standard procedures
4717@section Other data types
4718
4719@menu
4720* Booleans::
4721* Pairs and lists::
4722* Symbols::
4723* Characters::
4724* Strings::
4725* Vectors::
4726@end menu
4727
4728
4729This section describes operations on some of Scheme's non-numeric data types:
4730booleans, pairs, lists, symbols, characters, strings and vectors.
4731
4732@node Booleans, Pairs and lists, Other data types, Other data types
4733@subsection Booleans
4734
4735
4736
4737The standard boolean objects for true and false are written as
4738@t{#t} and @t{#f}. What really
4739@vindex #f
4740@vindex #t
4741matters, though, are the objects that the Scheme conditional expressions
4742(@samp{if}, @samp{cond}, @samp{and}, @samp{or}, @samp{do}) treat as
4743true or false. The phrase ``a true value''
4744@cindex @w{false}
4745@cindex @w{true}
4746(or sometimes just ``true'') means any object treated as true by the
4747conditional expressions, and the phrase ``a false value'' (or
4748@cindex @w{false}
4749``false'') means any object treated as false by the conditional expressions.
4750
4751Of all the standard Scheme values, only @t{#f}
4752@c is guaranteed to count
4753counts as false in conditional expressions.
4754@c It is not
4755@c specified whether the empty list\index{empty list} counts as false
4756@c or as true in conditional expressions.
4757Except for @t{#f},
4758@c and possibly the empty list,
4759all standard Scheme values, including @t{#t},
4760pairs, the empty list, symbols, numbers, strings, vectors, and procedures,
4761count as true.
4762
4763@c \begin{note}
4764@c In some implementations the empty list counts as false, contrary
4765@c to the above.
4766@c Nonetheless a few examples in this report assume that the
4767@c empty list counts as true, as in \cite{IEEEScheme}.
4768@c \end{note}
4769
4770@c \begin{rationale}
4771@c For historical reasons some implementations regard \schfalse{} and the
4772@c empty list as the same object. These implementations therefore cannot
4773@c make the empty list count as true in conditional expressions.
4774@c \end{rationale}
4775
4776
4777@quotation
4778@emph{Note:}
4779Programmers accustomed to other dialects of Lisp should be aware that
4780Scheme distinguishes both @t{#f} and the empty list
4781@cindex @w{empty list}
4782from the symbol @code{nil}.
4783@vindex @w{nil}
4784@end quotation
4785
4786
4787Boolean constants evaluate to themselves, so they do not need to be quoted
4788in programs.
4789
4790
4791@example
4792
4793#t ==> #t
4794#f ==> #f
4795'#f ==> #f
4796
4797@end example
4798
4799
4800
4801
4802@deffn {library procedure} not obj
4803
7fb9c4af 4804@samp{Not} returns @t{#t} if @var{obj} is false, and returns
a0e07ba4
NJ
4805@t{#f} otherwise.
4806
4807
4808@format
4809@t{(not #t) ==> #f
4810(not 3) ==> #f
4811(not (list 3)) ==> #f
4812(not #f) ==> #t
4813(not '()) ==> #f
4814(not (list)) ==> #f
4815(not 'nil) ==> #f
4816}
4817@end format
4818
4819
4820@end deffn
4821
4822
4823
4824@deffn {library procedure} boolean? obj
4825
7fb9c4af 4826@samp{Boolean?} returns @t{#t} if @var{obj} is either @t{#t} or
a0e07ba4
NJ
4827@t{#f} and returns @t{#f} otherwise.
4828
4829
4830@format
4831@t{(boolean? #f) ==> #t
4832(boolean? 0) ==> #f
4833(boolean? '()) ==> #f
4834}
4835@end format
4836
4837
4838@end deffn
4839
4840
4841@node Pairs and lists, Symbols, Booleans, Other data types
4842@subsection Pairs and lists
4843
4844
4845
4846A @dfn{pair} (sometimes called a @dfn{dotted pair}) is a
4847@cindex @w{dotted pair}
4848@cindex @w{pair}
4849record structure with two fields called the car and cdr fields (for
4850historical reasons). Pairs are created by the procedure @samp{cons}.
4851The car and cdr fields are accessed by the procedures @samp{car} and
4852@samp{cdr}. The car and cdr fields are assigned by the procedures
4853@samp{set-car!} and @samp{set-cdr!}.
4854
4855Pairs are used primarily to represent lists. A list can
4856be defined recursively as either the empty list or a pair whose
4857@cindex @w{empty list}
4858cdr is a list. More precisely, the set of lists is defined as the smallest
4859set @var{X} such that
4860
4861
4862
4863@itemize @bullet
4864
4865@item
4866The empty list is in @var{X}.
4867@item
4868If @var{list} is in @var{X}, then any pair whose cdr field contains
4869@var{list} is also in @var{X}.
4870
4871@end itemize
4872
4873
4874The objects in the car fields of successive pairs of a list are the
4875elements of the list. For example, a two-element list is a pair whose car
4876is the first element and whose cdr is a pair whose car is the second element
4877and whose cdr is the empty list. The length of a list is the number of
4878elements, which is the same as the number of pairs.
4879
4880The empty list is a special object of its own type
4881@cindex @w{empty list}
4882(it is not a pair); it has no elements and its length is zero.
4883
4884
4885@quotation
4886@emph{Note:}
4887The above definitions imply that all lists have finite length and are
4888terminated by the empty list.
4889@end quotation
4890
4891
4892The most general notation (external representation) for Scheme pairs is
4893the ``dotted'' notation @w{@samp{(@var{c1} .@: @var{c2})}} where
4894@var{c1} is the value of the car field and @var{c2} is the value of the
4895cdr field. For example @samp{(4 .@: 5)} is a pair whose car is 4 and whose
4896cdr is 5. Note that @samp{(4 .@: 5)} is the external representation of a
4897pair, not an expression that evaluates to a pair.
4898
4899A more streamlined notation can be used for lists: the elements of the
4900list are simply enclosed in parentheses and separated by spaces. The
4901empty list is written @t{()} . For example,
4902@cindex @w{empty list}
4903
4904
4905@example
4906
4907(a b c d e)
4908
4909@end example
4910
4911
4912and
4913
4914
4915@example
4916
4917(a . (b . (c . (d . (e . ())))))
4918
4919@end example
4920
4921
4922are equivalent notations for a list of symbols.
4923
4924A chain of pairs not ending in the empty list is called an
4925@dfn{improper list}. Note that an improper list is not a list.
4926@cindex @w{improper list}
4927The list and dotted notations can be combined to represent
4928improper lists:
4929
4930
4931@example
4932
4933(a b c . d)
4934
4935@end example
4936
4937
4938is equivalent to
4939
4940
4941@example
4942
4943(a . (b . (c . d)))
4944
4945@end example
4946
4947
4948Whether a given pair is a list depends upon what is stored in the cdr
4949field. When the @code{set-cdr!} procedure is used, an object can be a
4950@vindex @w{set-cdr!}
4951list one moment and not the next:
4952
4953
4954@example
4955
4956(define x (list 'a 'b 'c))
4957(define y x)
4958y ==> (a b c)
4959(list? y) ==> #t
4960(set-cdr! x 4) ==> @emph{unspecified}
4961x ==> (a . 4)
4962(eqv? x y) ==> #t
4963y ==> (a . 4)
4964(list? y) ==> #f
4965(set-cdr! x x) ==> @emph{unspecified}
4966(list? x) ==> #f
4967
4968@end example
4969
4970
4971@c It is often convenient to speak of a homogeneous list of objects
4972@c of some particular data type, as for example \hbox{\cf (1 2 3)} is a list of
4973@c integers. To be more precise, suppose \var{D} is some data type. (Any
4974@c predicate defines a data type consisting of those objects of which the
4975@c predicate is true.) Then
4976
4977@c \begin{itemize}
4978@c \item The empty list is a list of \var{D}.
4979@c \item If \var{list} is a list of \var{D}, then any pair whose cdr is
4980@c \var{list} and whose car is an element of the data type \var{D} is also a
4981@c list of \var{D}.
4982@c \item There are no other lists of \var{D}.
4983@c \end{itemize}
4984
4985Within literal expressions and representations of objects read by the
4986@code{read} procedure, the forms @t{'}@r{<datum>},
4987@vindex '
4988@vindex @w{read}
4989@t{`}@r{<datum>}, @t{,}@r{<datum>}, and
4990@vindex ,
4991@t{,@@}@r{<datum>} denote two-ele@-ment lists whose first elements are
4992the symbols @code{quote}, @code{quasiquote}, @w{@code{unquote}}, and
4993@vindex @w{unquote}
4994@vindex @w{quasiquote}
4995@vindex @w{quote}
4996@code{unquote-splicing}, respectively. The second element in each case
4997@vindex @w{unquote-splicing}
4998is @r{<datum>}. This convention is supported so that arbitrary Scheme
4999programs may be represented as lists.
5000@ignore todo
5001Can or need this be stated
5002more carefully?
5003@end ignore
5004 That is, according to Scheme's grammar, every
5005<expression> is also a <datum> (see section @pxref{External representation}).
5006Among other things, this permits the use of the @samp{read} procedure to
5007parse Scheme programs. See section @ref{External representations}.
5008
5009
5010
5011@deffn {procedure} pair? obj
5012
7fb9c4af 5013@samp{Pair?} returns @t{#t} if @var{obj} is a pair, and otherwise
a0e07ba4
NJ
5014returns @t{#f}.
5015
5016
5017@format
5018@t{(pair? '(a . b)) ==> #t
5019(pair? '(a b c)) ==> #t
5020(pair? '()) ==> #f
5021(pair? '#(a b)) ==> #f
5022}
5023@end format
5024
5025@end deffn
5026
5027
5028
5029@deffn {procedure} cons obj1 obj2
5030
5031Returns a newly allocated pair whose car is @var{obj1} and whose cdr is
5032@var{obj2}. The pair is guaranteed to be different (in the sense of
5033@samp{eqv?}) from every existing object.
5034
5035
5036@format
5037@t{(cons 'a '()) ==> (a)
5038(cons '(a) '(b c d)) ==> ((a) b c d)
5039(cons "a" '(b c)) ==> ("a" b c)
5040(cons 'a 3) ==> (a . 3)
5041(cons '(a b) 'c) ==> ((a b) . c)
5042}
5043@end format
5044
5045@end deffn
5046
5047
5048
5049@deffn {procedure} car pair
5050
5051@ignore nodomain
5052@var{Pair} must be a pair.
5053@end ignore
5054
5055Returns the contents of the car field of @var{pair}. Note that it is an
5056error to take the car of the empty list.
5057@cindex @w{empty list}
5058
5059
5060@format
5061@t{(car '(a b c)) ==> a
5062(car '((a) b c d)) ==> (a)
5063(car '(1 . 2)) ==> 1
5064(car '()) ==> @emph{error}
5065}
5066@end format
5067
5068
5069@end deffn
5070
5071
5072
5073@deffn {procedure} cdr pair
5074
5075@ignore nodomain
5076@var{Pair} must be a pair.
5077@end ignore
5078
5079Returns the contents of the cdr field of @var{pair}.
5080Note that it is an error to take the cdr of the empty list.
5081
5082
5083@format
5084@t{(cdr '((a) b c d)) ==> (b c d)
5085(cdr '(1 . 2)) ==> 2
5086(cdr '()) ==> @emph{error}
5087}
5088@end format
5089
5090
5091@end deffn
5092
5093
5094
5095@deffn {procedure} set-car! pair obj
5096
5097@ignore nodomain
5098@var{Pair} must be a pair.
5099@end ignore
5100
5101Stores @var{obj} in the car field of @var{pair}.
5102The value returned by @samp{set-car!} is unspecified.
5103@c <!>
5104@c This procedure can be very confusing if used indiscriminately.
5105
5106
5107@format
5108@t{(define (f) (list 'not-a-constant-list))
5109(define (g) '(constant-list))
5110(set-car! (f) 3) ==> @emph{unspecified}
5111(set-car! (g) 3) ==> @emph{error}
5112}
5113@end format
5114
5115
5116@end deffn
5117
5118
5119
5120@deffn {procedure} set-cdr! pair obj
5121
5122@ignore nodomain
5123@var{Pair} must be a pair.
5124@end ignore
5125
5126Stores @var{obj} in the cdr field of @var{pair}.
5127The value returned by @samp{set-cdr!} is unspecified.
5128@c <!>
5129@c This procedure can be very confusing if used indiscriminately.
5130
5131@end deffn
5132
5133
5134
5135
5136
5137
5138@deffn {library procedure} caar pair
5139@deffnx {library procedure} cadr pair
5140
5141@deffnx { @w{ @dots{}}} @w{ @dots{}}
5142
5143@deffnx {library procedure} cdddar pair
5144@deffnx {library procedure} cddddr pair
5145
5146These procedures are compositions of @samp{car} and @samp{cdr}, where
5147for example @samp{caddr} could be defined by
5148
5149
5150@format
5151@t{(define caddr (lambda (x) (car (cdr (cdr x)))))@r{.}
5152}
5153@end format
5154
5155
5156Arbitrary compositions, up to four deep, are provided. There are
5157twenty-eight of these procedures in all.
5158
5159@end deffn
5160
5161
5162
5163@deffn {library procedure} null? obj
5164
5165Returns @t{#t} if @var{obj} is the empty list,
5166@cindex @w{empty list}
5167otherwise returns @t{#f}.
5168
5169@c \begin{note}
5170@c In implementations in which the empty
5171@c list is the same as \schfalse{}, {\cf null?} will return \schtrue{}
5172@c if \var{obj} is \schfalse{}.
5173@c \end{note}
5174
5175@end deffn
5176
5177
5178@deffn {library procedure} list? obj
5179
5180Returns @t{#t} if @var{obj} is a list, otherwise returns @t{#f}.
5181By definition, all lists have finite length and are terminated by
5182the empty list.
5183
5184
5185@format
5186@t{ (list? '(a b c)) ==> #t
5187 (list? '()) ==> #t
5188 (list? '(a . b)) ==> #f
5189 (let ((x (list 'a)))
5190 (set-cdr! x x)
5191 (list? x)) ==> #f
5192}
5193@end format
5194
5195@end deffn
5196
5197
5198
5199@deffn {library procedure} list @var{obj} @dots{},
5200
5201Returns a newly allocated list of its arguments.
5202
5203
5204@format
5205@t{(list 'a (+ 3 4) 'c) ==> (a 7 c)
5206(list) ==> ()
5207}
5208@end format
5209
5210@end deffn
5211
5212
5213
5214@deffn {library procedure} length list
5215
5216@ignore nodomain
5217@var{List} must be a list.
5218@end ignore
5219
5220Returns the length of @var{list}.
5221
5222
5223@format
5224@t{(length '(a b c)) ==> 3
5225(length '(a (b) (c d e))) ==> 3
5226(length '()) ==> 0
5227}
5228@end format
5229
5230@end deffn
5231
5232
5233
5234@deffn {library procedure} append list @dots{},
5235
5236@ignore nodomain
5237All @var{list}s should be lists.
5238@end ignore
5239
5240Returns a list consisting of the elements of the first @var{list}
5241followed by the elements of the other @var{list}s.
5242
5243
5244@format
5245@t{(append '(x) '(y)) ==> (x y)
5246(append '(a) '(b c d)) ==> (a b c d)
5247(append '(a (b)) '((c))) ==> (a (b) (c))
5248}
5249@end format
5250
5251
5252The resulting list is always newly allocated, except that it shares
5253structure with the last @var{list} argument. The last argument may
5254actually be any object; an improper list results if the last argument is not a
5255proper list.
5256@ignore todo
5257This is pretty awkward. I should get Bartley to fix this.
5258@end ignore
5259
5260
5261
5262@format
5263@t{(append '(a b) '(c . d)) ==> (a b c . d)
5264(append '() 'a) ==> a
5265}
5266@end format
5267
5268@end deffn
5269
5270
5271
5272@deffn {library procedure} reverse list
5273
5274@ignore nodomain
5275@var{List} must be a list.
5276@end ignore
5277
5278Returns a newly allocated list consisting of the elements of @var{list}
5279in reverse order.
5280
5281
5282@format
5283@t{(reverse '(a b c)) ==> (c b a)
5284(reverse '(a (b c) d (e (f))))
5285 ==> ((e (f)) d (b c) a)
5286}
5287@end format
5288
5289@end deffn
5290
5291
5292
5293@deffn {library procedure} list-tail list @var{k}
5294
5295Returns the sublist of @var{list} obtained by omitting the first @var{k}
5296elements. It is an error if @var{list} has fewer than @var{k} elements.
7fb9c4af 5297@samp{List-tail} could be defined by
a0e07ba4
NJ
5298
5299
5300@format
5301@t{(define list-tail
5302 (lambda (x k)
5303 (if (zero? k)
5304 x
5305 (list-tail (cdr x) (- k 1)))))
5306}
5307@end format
5308
5309@end deffn
5310
5311
5312
5313@deffn {library procedure} list-ref list @var{k}
5314
5315Returns the @var{k}th element of @var{list}. (This is the same
5316as the car of @t{(list-tail @var{list} @var{k})}.)
5317It is an error if @var{list} has fewer than @var{k} elements.
5318
5319
5320@format
5321@t{(list-ref '(a b c d) 2) ==> c
5322(list-ref '(a b c d)
5323 (inexact->exact (round 1.8)))
5324 ==> c
5325}
5326@end format
5327
5328@end deffn
5329
5330
5331@c \begin{entry}{%
5332@c \proto{last-pair}{ list}{library procedure}}
5333
5334@c Returns the last pair in the nonempty, possibly improper, list \var{list}.
5335@c {\cf Last-pair} could be defined by
5336
5337@c \begin{scheme}
5338@c (define last-pair
5339@c (lambda (x)
5340@c (if (pair? (cdr x))
5341@c (last-pair (cdr x))
5342@c x)))%
5343@c \end{scheme}
5344
5345@c \end{entry}
5346
5347
5348
5349@deffn {library procedure} memq obj list
5350@deffnx {library procedure} memv obj list
5351@deffnx {library procedure} member obj list
5352
5353These procedures return the first sublist of @var{list} whose car is
5354@var{obj}, where the sublists of @var{list} are the non-empty lists
5355returned by @t{(list-tail @var{list} @var{k})} for @var{k} less
5356than the length of @var{list}. If
5357@var{obj} does not occur in @var{list}, then @t{#f} (not the empty list) is
7fb9c4af 5358returned. @samp{Memq} uses @samp{eq?} to compare @var{obj} with the elements of
a0e07ba4
NJ
5359@var{list}, while @samp{memv} uses @samp{eqv?} and @samp{member} uses @samp{equal?}.
5360
5361
5362@format
5363@t{(memq 'a '(a b c)) ==> (a b c)
5364(memq 'b '(a b c)) ==> (b c)
5365(memq 'a '(b c d)) ==> #f
5366(memq (list 'a) '(b (a) c)) ==> #f
5367(member (list 'a)
5368 '(b (a) c)) ==> ((a) c)
5369(memq 101 '(100 101 102)) ==> @emph{unspecified}
5370(memv 101 '(100 101 102)) ==> (101 102)
5371}
5372@end format
5373
5374
5375@end deffn
5376
5377
5378
5379@deffn {library procedure} assq obj alist
5380@deffnx {library procedure} assv obj alist
5381@deffnx {library procedure} assoc obj alist
5382
7fb9c4af 5383@var{Alist} (for ``association list'') must be a list of
a0e07ba4
NJ
5384pairs. These procedures find the first pair in @var{alist} whose car field is @var{obj},
5385and returns that pair. If no pair in @var{alist} has @var{obj} as its
7fb9c4af 5386car, then @t{#f} (not the empty list) is returned. @samp{Assq} uses
a0e07ba4
NJ
5387@samp{eq?} to compare @var{obj} with the car fields of the pairs in @var{alist},
5388while @samp{assv} uses @samp{eqv?} and @samp{assoc} uses @samp{equal?}.
5389
5390
5391@format
5392@t{(define e '((a 1) (b 2) (c 3)))
5393(assq 'a e) ==> (a 1)
5394(assq 'b e) ==> (b 2)
5395(assq 'd e) ==> #f
5396(assq (list 'a) '(((a)) ((b)) ((c))))
5397 ==> #f
5398(assoc (list 'a) '(((a)) ((b)) ((c))))
5399 ==> ((a))
5400(assq 5 '((2 3) (5 7) (11 13)))
5401 ==> @emph{unspecified}
5402(assv 5 '((2 3) (5 7) (11 13)))
5403 ==> (5 7)
5404}
5405@end format
5406
5407
5408
5409
5410@quotation
5411@emph{Rationale:}
5412Although they are ordinarily used as predicates,
5413@samp{memq}, @samp{memv}, @samp{member}, @samp{assq}, @samp{assv}, and @samp{assoc} do not
5414have question marks in their names because they return useful values rather
5415than just @t{#t} or @t{#f}.
5416@end quotation
5417
5418@end deffn
5419
5420
5421@node Symbols, Characters, Pairs and lists, Other data types
5422@subsection Symbols
5423
5424
5425
5426Symbols are objects whose usefulness rests on the fact that two
5427symbols are identical (in the sense of @samp{eqv?}) if and only if their
5428names are spelled the same way. This is exactly the property needed to
5429represent identifiers in programs, and so most
5430@cindex @w{identifier}
5431implementations of Scheme use them internally for that purpose. Symbols
5432are useful for many other applications; for instance, they may be used
5433the way enumerated values are used in Pascal.
5434
5435The rules for writing a symbol are exactly the same as the rules for
5436writing an identifier; see sections @ref{Identifiers}
5437and @ref{Lexical structure}.
5438
5439It is guaranteed that any symbol that has been returned as part of
5440a literal expression, or read using the @samp{read} procedure, and
5441subsequently written out using the @samp{write} procedure, will read back
5442in as the identical symbol (in the sense of @samp{eqv?}). The
5443@samp{string->symbol} procedure, however, can create symbols for
5444which this write/read invariance may not hold because their names
5445contain special characters or letters in the non-standard case.
5446
5447
5448@quotation
5449@emph{Note:}
5450Some implementations of Scheme have a feature known as ``slashification''
5451in order to guarantee write/read invariance for all symbols, but
5452historically the most important use of this feature has been to
5453compensate for the lack of a string data type.
5454
5455Some implementations also have ``uninterned symbols'', which
5456defeat write/read invariance even in implementations with slashification,
5457and also generate exceptions to the rule that two symbols are the same
5458if and only if their names are spelled the same.
5459@end quotation
5460
5461
5462
5463
5464@deffn {procedure} symbol? obj
5465
5466Returns @t{#t} if @var{obj} is a symbol, otherwise returns @t{#f}.
5467
5468
5469@format
5470@t{(symbol? 'foo) ==> #t
5471(symbol? (car '(a b))) ==> #t
5472(symbol? "bar") ==> #f
5473(symbol? 'nil) ==> #t
5474(symbol? '()) ==> #f
5475(symbol? #f) ==> #f
5476}
5477@end format
5478
5479@end deffn
5480
5481
5482
5483@deffn {procedure} symbol->string symbol
5484
5485Returns the name of @var{symbol} as a string. If the symbol was part of
5486an object returned as the value of a literal expression
5487(section @pxref{Literal expressions}) or by a call to the @samp{read} procedure,
5488and its name contains alphabetic characters, then the string returned
5489will contain characters in the implementation's preferred standard
5490case---some implementations will prefer upper case, others lower case.
5491If the symbol was returned by @samp{string->symbol}, the case of
5492characters in the string returned will be the same as the case in the
5493string that was passed to @samp{string->symbol}. It is an error
5494to apply mutation procedures like @code{string-set!} to strings returned
5495@vindex @w{string-set!}
5496by this procedure.
5497
5498The following examples assume that the implementation's standard case is
5499lower case:
5500
5501
5502@format
5503@t{(symbol->string 'flying-fish)
5504 ==> "flying-fish"
5505(symbol->string 'Martin) ==> "martin"
5506(symbol->string
5507 (string->symbol "Malvina"))
5508 ==> "Malvina"
5509}
5510@end format
5511
5512@end deffn
5513
5514
5515
5516@deffn {procedure} string->symbol string
5517
5518Returns the symbol whose name is @var{string}. This procedure can
5519create symbols with names containing special characters or letters in
5520the non-standard case, but it is usually a bad idea to create such
5521symbols because in some implementations of Scheme they cannot be read as
5522themselves. See @samp{symbol->string}.
5523
5524The following examples assume that the implementation's standard case is
5525lower case:
5526
5527
5528@format
5529@t{(eq? 'mISSISSIppi 'mississippi)
5530 ==> #t
5531(string->symbol "mISSISSIppi")
5532 ==>
5533 @r{}the symbol with name "mISSISSIppi"
5534(eq? 'bitBlt (string->symbol "bitBlt"))
5535 ==> #f
5536(eq? 'JollyWog
5537 (string->symbol
5538 (symbol->string 'JollyWog)))
5539 ==> #t
5540(string=? "K. Harper, M.D."
5541 (symbol->string
5542 (string->symbol "K. Harper, M.D.")))
5543 ==> #t
5544}
5545@end format
5546
5547
5548@end deffn
5549
5550
5551@node Characters, Strings, Symbols, Other data types
5552@subsection Characters
5553
5554
5555
5556Characters are objects that represent printed characters such as
5557letters and digits.
5558@c There is no requirement that the data type of
5559@c characters be disjoint from other data types; implementations are
5560@c encouraged to have a separate character data type, but may choose to
5561@c represent characters as integers, strings, or some other type.
5562Characters are written using the notation #\@r{<character>}
5563or #\@r{<character name>}.
5564For example:
5565
5566
5567
5568@center @c begin-tabular
5569@quotation
5570@table @asis
5571@item @t{#\a}
5572; lower case letter
5573@item @t{#\A}
5574; upper case letter
5575@item @t{#\(}
5576; left parenthesis
5577@item @t{#\ }
5578; the space character
5579@item @t{#\space}
5580; the preferred way to write a space
5581@item @t{#\newline}
5582; the newline character
5583@item
5584@end table
5585@end quotation
5586
5587
5588
5589
5590Case is significant in #\@r{<character>}, but not in
5591#\@r{<character name>}.
5592@c \hyper doesn't
5593
5594@c allow a linebreak
5595If @r{<character>} in
5596#\@r{<character>} is alphabetic, then the character
5597following @r{<character>} must be a delimiter character such as a
5598space or parenthesis. This rule resolves the ambiguous case where, for
5599example, the sequence of characters ``@t{#\ space}''
5600could be taken to be either a representation of the space character or a
5601representation of the character ``@t{#\ s}'' followed
5602by a representation of the symbol ``@t{pace}.''
5603
5604@ignore todo
5605Fix
5606@end ignore
5607
5608Characters written in the #\ notation are self-evaluating.
5609That is, they do not have to be quoted in programs.
5610@c The \sharpsign\backwhack{}
5611@c notation is not an essential part of Scheme, however. Even implementations
5612@c that support the \sharpsign\backwhack{} notation for input do not have to
5613@c support it for output.
5614
5615Some of the procedures that operate on characters ignore the
5616difference between upper case and lower case. The procedures that
5617ignore case have @w{``@t{-ci}''} (for ``case
5618insensitive'') embedded in their names.
5619
5620
5621
5622@deffn {procedure} char? obj
5623
5624Returns @t{#t} if @var{obj} is a character, otherwise returns @t{#f}.
5625
5626@end deffn
5627
5628
5629
5630@deffn {procedure} char=? char1 char2
5631@deffnx {procedure} char<? char1 char2
5632@deffnx {procedure} char>? char1 char2
5633@deffnx {procedure} char<=? char1 char2
5634@deffnx {procedure} char>=? char1 char2
5635
5636
5637@ignore nodomain
5638Both @var{char1} and @var{char2} must be characters.
5639@end ignore
5640
5641These procedures impose a total ordering on the set of characters. It
5642is guaranteed that under this ordering:
5643
5644
5645
5646@itemize @bullet
5647
5648@item
5649The upper case characters are in order. For example, @samp{(char<? #\A #\B)} returns @t{#t}.
5650@item
5651The lower case characters are in order. For example, @samp{(char<? #\a #\b)} returns @t{#t}.
5652@item
5653The digits are in order. For example, @samp{(char<? #\0 #\9)} returns @t{#t}.
5654@item
5655Either all the digits precede all the upper case letters, or vice versa.
5656@item
5657Either all the digits precede all the lower case letters, or vice versa.
5658
5659@end itemize
5660
5661
5662Some implementations may generalize these procedures to take more than
5663two arguments, as with the corresponding numerical predicates.
5664
5665@end deffn
5666
5667
5668
5669@deffn {library procedure} char-ci=? char1 char2
5670@deffnx {library procedure} char-ci<? char1 char2
5671@deffnx {library procedure} char-ci>? char1 char2
5672@deffnx {library procedure} char-ci<=? char1 char2
5673@deffnx {library procedure} char-ci>=? char1 char2
5674
5675@ignore nodomain
5676Both @var{char1} and @var{char2} must be characters.
5677@end ignore
5678
5679These procedures are similar to @samp{char=?} et cetera, but they treat
5680upper case and lower case letters as the same. For example, @samp{(char-ci=? #\A #\a)} returns @t{#t}. Some
5681implementations may generalize these procedures to take more than two
5682arguments, as with the corresponding numerical predicates.
5683
5684@end deffn
5685
5686
5687
5688@deffn {library procedure} char-alphabetic? char
5689@deffnx {library procedure} char-numeric? char
5690@deffnx {library procedure} char-whitespace? char
5691@deffnx {library procedure} char-upper-case? letter
5692@deffnx {library procedure} char-lower-case? letter
5693
5694These procedures return @t{#t} if their arguments are alphabetic,
5695numeric, whitespace, upper case, or lower case characters, respectively,
5696otherwise they return @t{#f}. The following remarks, which are specific to
5697the ASCII character set, are intended only as a guide: The alphabetic characters
5698are the 52 upper and lower case letters. The numeric characters are the
5699ten decimal digits. The whitespace characters are space, tab, line
5700feed, form feed, and carriage return.
5701@end deffn
5702
5703
5704@c %R4%%\begin{entry}{%
5705@c \proto{char-upper-case?}{ letter}{procedure}
5706@c \proto{char-lower-case?}{ letter}{procedure}}
5707
5708@c \domain{\var{Letter} must be an alphabetic character.}
5709@c These procedures return \schtrue{} if their arguments are upper case or
5710@c lower case characters, respectively, otherwise they return \schfalse.
5711@c \end{entry}
5712
5713
5714
5715@deffn {procedure} char->integer char
5716@deffnx {procedure} integer->char @var{n}
5717
5718Given a character, @samp{char->integer} returns an exact integer
5719representation of the character. Given an exact integer that is the image of
5720a character under @samp{char->integer}, @samp{integer->char}
5721returns that character. These procedures implement order-preserving isomorphisms
5722between the set of characters under the @code{char<=?} ordering and some
5723@vindex @w{char<=?}
5724subset of the integers under the @samp{<=} ordering. That is, if
5725
5726
5727@format
5728@t{(char<=? @var{a} @var{b}) @result{} #t @r{}and (<= @var{x} @var{y}) @result{} #t
5729}
5730@end format
5731
5732
5733
5734@noindent
5735 and @var{x} and @var{y} are in the domain of
5736@samp{integer->char}, then
5737
5738
5739@format
5740@t{(<= (char->integer @var{a})
5741 (char->integer @var{b})) ==> #t
5742
5743(char<=? (integer->char @var{x})
5744 (integer->char @var{y})) ==> #t
5745}
5746@end format
5747
5748
5749@end deffn
5750
5751
5752
5753@deffn {library procedure} char-upcase char
5754@deffnx {library procedure} char-downcase char
5755
5756@ignore nodomain
5757@var{Char} must be a character.
5758@end ignore
5759
5760These procedures return a character @var{char2} such that @samp{(char-ci=? @var{char} @var{char2})}. In addition, if @var{char} is
5761alphabetic, then the result of @samp{char-upcase} is upper case and the
5762result of @samp{char-downcase} is lower case.
5763
5764@end deffn
5765
5766
5767@node Strings, Vectors, Characters, Other data types
5768@subsection Strings
5769
5770
5771
5772Strings are sequences of characters.
5773@c In some implementations of Scheme
5774@c they are immutable; other implementations provide destructive procedures
5775@c such as {\cf string-set!}\ that alter string objects.
5776Strings are written as sequences of characters enclosed within doublequotes
5777(@samp{"}). A doublequote can be written inside a string only by escaping
5778it with a backslash (\), as in
5779
5780
5781@example
5782
5783"The word \"recursion\" has many meanings."
5784
5785@end example
5786
5787
5788A backslash can be written inside a string only by escaping it with another
5789backslash. Scheme does not specify the effect of a backslash within a
5790string that is not followed by a doublequote or backslash.
5791
5792A string constant may continue from one line to the next, but
5793the exact contents of such a string are unspecified.
5794@c this is
5795@c usually a bad idea because
5796@c the exact effect may vary from one computer
5797@c system to another.
5798
5799The @emph{length} of a string is the number of characters that it
5800contains. This number is an exact, non-negative integer that is fixed when the
5801string is created. The @dfn{valid indexes} of a string are the
5802@cindex @w{valid indexes}
5803exact non-negative integers less than the length of the string. The first
5804character of a string has index 0, the second has index 1, and so on.
5805
5806In phrases such as ``the characters of @var{string} beginning with
5807index @var{start} and ending with index @var{end},'' it is understood
5808that the index @var{start} is inclusive and the index @var{end} is
5809exclusive. Thus if @var{start} and @var{end} are the same index, a null
5810substring is referred to, and if @var{start} is zero and @var{end} is
5811the length of @var{string}, then the entire string is referred to.
5812
5813Some of the procedures that operate on strings ignore the
5814difference between upper and lower case. The versions that ignore case
5815have @w{``@samp{-ci}''} (for ``case insensitive'') embedded in their
5816names.
5817
5818
5819
5820@deffn {procedure} string? obj
5821
5822Returns @t{#t} if @var{obj} is a string, otherwise returns @t{#f}.
5823@end deffn
5824
5825
5826
5827@deffn {procedure} make-string @var{k}
5828@deffnx {procedure} make-string @var{k} char
5829
5830@c \domain{\vr{k} must be a non-negative integer, and \var{char} must be
5831@c a character.}
7fb9c4af
AW
5832@samp{Make-string} returns a newly allocated string of
5833length @var{k}. If @var{char} is given, then all elements of the string
5834are initialized to @var{char}, otherwise the contents of the
5835@var{string} are unspecified.
a0e07ba4
NJ
5836
5837@end deffn
5838
5839
5840@deffn {library procedure} string char @dots{},
5841
5842Returns a newly allocated string composed of the arguments.
5843
5844@end deffn
5845
5846
5847@deffn {procedure} string-length string
5848
5849Returns the number of characters in the given @var{string}.
5850@end deffn
5851
5852
5853
5854@deffn {procedure} string-ref string @var{k}
5855
5856@var{k} must be a valid index of @var{string}.
7fb9c4af 5857@samp{String-ref} returns character @var{k} of @var{string} using zero-origin indexing.
a0e07ba4
NJ
5858@end deffn
5859
5860
5861
5862@deffn {procedure} string-set! string k char
5863
5864
5865@c \var{String} must be a string,
5866@var{k} must be a valid index of @var{string}
5867@c , and \var{char} must be a character
5868.
7fb9c4af 5869@samp{String-set!} stores @var{char} in element @var{k} of @var{string}
a0e07ba4
NJ
5870and returns an unspecified value.
5871@c <!>
5872
5873
5874@format
5875@t{(define (f) (make-string 3 #\*))
5876(define (g) "***")
5877(string-set! (f) 0 #\?) ==> @emph{unspecified}
5878(string-set! (g) 0 #\?) ==> @emph{error}
5879(string-set! (symbol->string 'immutable)
5880 0
5881 #\?) ==> @emph{error}
5882}
5883@end format
5884
5885
5886@end deffn
5887
5888
5889
5890@deffn {library procedure} string=? string1 string2
5891@deffnx {library procedure} string-ci=? string1 string2
5892
5893Returns @t{#t} if the two strings are the same length and contain the same
5894characters in the same positions, otherwise returns @t{#f}.
7fb9c4af 5895@samp{String-ci=?} treats
a0e07ba4
NJ
5896upper and lower case letters as though they were the same character, but
5897@samp{string=?} treats upper and lower case as distinct characters.
5898
5899@end deffn
5900
5901
5902
5903@deffn {library procedure} string<? string1 string2
5904@deffnx {library procedure} string>? string1 string2
5905@deffnx {library procedure} string<=? string1 string2
5906@deffnx {library procedure} string>=? string1 string2
5907@deffnx {library procedure} string-ci<? string1 string2
5908@deffnx {library procedure} string-ci>? string1 string2
5909@deffnx {library procedure} string-ci<=? string1 string2
5910@deffnx {library procedure} string-ci>=? string1 string2
5911
5912These procedures are the lexicographic extensions to strings of the
5913corresponding orderings on characters. For example, @samp{string<?} is
5914the lexicographic ordering on strings induced by the ordering
5915@samp{char<?} on characters. If two strings differ in length but
5916are the same up to the length of the shorter string, the shorter string
5917is considered to be lexicographically less than the longer string.
5918
5919Implementations may generalize these and the @samp{string=?} and
5920@samp{string-ci=?} procedures to take more than two arguments, as with
5921the corresponding numerical predicates.
5922
5923@end deffn
5924
5925
5926
5927@deffn {library procedure} substring string start end
5928
7fb9c4af 5929@var{String} must be a string, and @var{start} and @var{end}
a0e07ba4
NJ
5930must be exact integers satisfying
5931
5932
5933@center 0 <= @var{start} <= @var{end} <= @w{@t{(string-length @var{string})@r{.}}}
5934
7fb9c4af 5935@samp{Substring} returns a newly allocated string formed from the characters of
a0e07ba4
NJ
5936@var{string} beginning with index @var{start} (inclusive) and ending with index
5937@var{end} (exclusive).
5938@end deffn
5939
5940
5941
5942@deffn {library procedure} string-append @var{string} @dots{},
5943
5944Returns a newly allocated string whose characters form the concatenation of the
5945given strings.
5946
5947@end deffn
5948
5949
5950
5951@deffn {library procedure} string->list string
5952@deffnx {library procedure} list->string list
5953
7fb9c4af
AW
5954@samp{String->list} returns a newly allocated list of the
5955characters that make up the given string. @samp{List->string}
a0e07ba4 5956returns a newly allocated string formed from the characters in the list
7fb9c4af 5957@var{list}, which must be a list of characters. @samp{String->list}
a0e07ba4
NJ
5958and @samp{list->string} are
5959inverses so far as @samp{equal?} is concerned.
5960@c Implementations that provide
5961@c destructive operations on strings should ensure that the result of
5962@c {\cf list\coerce{}string} is newly allocated.
5963
5964@end deffn
5965
5966
5967
5968@deffn {library procedure} string-copy string
5969
5970Returns a newly allocated copy of the given @var{string}.
5971
5972@end deffn
5973
5974
5975
5976@deffn {library procedure} string-fill! string char
5977
5978Stores @var{char} in every element of the given @var{string} and returns an
5979unspecified value.
5980@c <!>
5981
5982@end deffn
5983
5984
5985@node Vectors, , Strings, Other data types
5986@subsection Vectors
5987
5988
5989
ecb87335 5990Vectors are heterogeneous structures whose elements are indexed
a0e07ba4
NJ
5991by integers. A vector typically occupies less space than a list
5992of the same length, and the average time required to access a randomly
5993chosen element is typically less for the vector than for the list.
5994
5995The @emph{length} of a vector is the number of elements that it
5996contains. This number is a non-negative integer that is fixed when the
5997vector is created. The @emph{valid indexes} of a
5998@cindex @w{valid indexes}
5999vector are the exact non-negative integers less than the length of the
6000vector. The first element in a vector is indexed by zero, and the last
6001element is indexed by one less than the length of the vector.
6002
6003Vectors are written using the notation @t{#(@var{obj} @dots{},)}.
6004For example, a vector of length 3 containing the number zero in element
60050, the list @samp{(2 2 2 2)} in element 1, and the string @samp{"Anna"} in
6006element 2 can be written as following:
6007
6008
6009@example
6010
6011#(0 (2 2 2 2) "Anna")
6012
6013@end example
6014
6015
6016Note that this is the external representation of a vector, not an
6017expression evaluating to a vector. Like list constants, vector
6018constants must be quoted:
6019
6020
6021@example
6022
6023'#(0 (2 2 2 2) "Anna")
6024 ==> #(0 (2 2 2 2) "Anna")
6025
6026@end example
6027
6028
6029@ignore todo
6030Pitman sez: The visual similarity to lists is bound to be confusing
6031to some. Elaborate on the distinction.
6032@end ignore
6033
6034
6035
6036
6037@deffn {procedure} vector? obj
6038
6039Returns @t{#t} if @var{obj} is a vector, otherwise returns @t{#f}.
6040@end deffn
6041
6042
6043
6044@deffn {procedure} make-vector k
6045@deffnx {procedure} make-vector k fill
6046
6047Returns a newly allocated vector of @var{k} elements. If a second
6048argument is given, then each element is initialized to @var{fill}.
6049Otherwise the initial contents of each element is unspecified.
6050
6051@end deffn
6052
6053
6054
6055@deffn {library procedure} vector obj @dots{},
6056
6057Returns a newly allocated vector whose elements contain the given
6058arguments. Analogous to @samp{list}.
6059
6060
6061@format
6062@t{(vector 'a 'b 'c) ==> #(a b c)
6063}
6064@end format
6065
6066@end deffn
6067
6068
6069
6070@deffn {procedure} vector-length vector
6071
6072Returns the number of elements in @var{vector} as an exact integer.
6073@end deffn
6074
6075
6076
6077@deffn {procedure} vector-ref vector k
6078
6079@var{k} must be a valid index of @var{vector}.
7fb9c4af 6080@samp{Vector-ref} returns the contents of element @var{k} of
a0e07ba4
NJ
6081@var{vector}.
6082
6083
6084@format
6085@t{(vector-ref '#(1 1 2 3 5 8 13 21)
6086 5)
6087 ==> 8
6088(vector-ref '#(1 1 2 3 5 8 13 21)
6089 (let ((i (round (* 2 (acos -1)))))
6090 (if (inexact? i)
6091 (inexact->exact i)
6092 i)))
6093 ==> 13
6094}
6095@end format
6096
6097@end deffn
6098
6099
6100
6101@deffn {procedure} vector-set! vector k obj
6102
6103@var{k} must be a valid index of @var{vector}.
7fb9c4af 6104@samp{Vector-set!} stores @var{obj} in element @var{k} of @var{vector}.
a0e07ba4
NJ
6105The value returned by @samp{vector-set!} is unspecified.
6106@c <!>
6107
6108
6109@format
6110@t{(let ((vec (vector 0 '(2 2 2 2) "Anna")))
6111 (vector-set! vec 1 '("Sue" "Sue"))
6112 vec)
6113 ==> #(0 ("Sue" "Sue") "Anna")
6114
6115(vector-set! '#(0 1 2) 1 "doe")
6116 ==> @emph{error} ; constant vector
6117}
6118@end format
6119
6120@end deffn
6121
6122
6123
6124@deffn {library procedure} vector->list vector
6125@deffnx {library procedure} list->vector list
6126
7fb9c4af
AW
6127@samp{Vector->list} returns a newly allocated list of the objects contained
6128in the elements of @var{vector}. @samp{List->vector} returns a newly
a0e07ba4
NJ
6129created vector initialized to the elements of the list @var{list}.
6130
6131
6132@format
6133@t{(vector->list '#(dah dah didah))
6134 ==> (dah dah didah)
6135(list->vector '(dididit dah))
6136 ==> #(dididit dah)
6137}
6138@end format
6139
6140@end deffn
6141
6142
6143
6144@deffn {library procedure} vector-fill! vector fill
6145
6146Stores @var{fill} in every element of @var{vector}.
6147The value returned by @samp{vector-fill!} is unspecified.
6148@c <!>
6149
6150@end deffn
6151
6152
6153@node Control features, Eval, Other data types, Standard procedures
6154@section Control features
6155
6156
6157
6158@c Intro flushed; not very a propos any more.
6159@c Procedures should be discussed somewhere, however.
6160
6161This chapter describes various primitive procedures which control the
6162flow of program execution in special ways.
6163The @samp{procedure?} predicate is also described here.
6164
6165@ignore todo
6166@t{Procedure?} doesn't belong in a section with the name
6167``control features.'' What to do?
6168@end ignore
6169
6170
6171
6172@deffn {procedure} procedure? obj
6173
6174Returns @t{#t} if @var{obj} is a procedure, otherwise returns @t{#f}.
6175
6176
6177@format
6178@t{(procedure? car) ==> #t
6179(procedure? 'car) ==> #f
6180(procedure? (lambda (x) (* x x)))
6181 ==> #t
6182(procedure? '(lambda (x) (* x x)))
6183 ==> #f
6184(call-with-current-continuation procedure?)
6185 ==> #t
6186}
6187@end format
6188
6189
6190@end deffn
6191
6192
6193
6194@deffn {procedure} apply proc arg1 @dots{} args
6195
7fb9c4af 6196@var{Proc} must be a procedure and @var{args} must be a list.
a0e07ba4
NJ
6197Calls @var{proc} with the elements of the list
6198@samp{(append (list @var{arg1} @dots{},) @var{args})} as the actual
6199arguments.
6200
6201
6202@format
6203@t{(apply + (list 3 4)) ==> 7
6204
6205(define compose
6206 (lambda (f g)
6207 (lambda args
6208 (f (apply g args)))))
6209
6210((compose sqrt *) 12 75) ==> 30
6211}
6212@end format
6213
6214@end deffn
6215
6216
6217
7fb9c4af 6218@deffn {library procedure} map proc list1 list2 @dots{},
a0e07ba4
NJ
6219
6220The @var{list}s must be lists, and @var{proc} must be a
6221procedure taking as many arguments as there are @i{list}s
6222and returning a single value. If more
6223than one @var{list} is given, then they must all be the same length.
7fb9c4af 6224@samp{Map} applies @var{proc} element-wise to the elements of the
a0e07ba4
NJ
6225@var{list}s and returns a list of the results, in order.
6226The dynamic order in which @var{proc} is applied to the elements of the
6227@var{list}s is unspecified.
6228
6229
6230@format
6231@t{(map cadr '((a b) (d e) (g h)))
6232 ==> (b e h)
6233
6234(map (lambda (n) (expt n n))
6235 '(1 2 3 4 5))
6236 ==> (1 4 27 256 3125)
6237
6238(map + '(1 2 3) '(4 5 6)) ==> (5 7 9)
6239
6240(let ((count 0))
6241 (map (lambda (ignored)
6242 (set! count (+ count 1))
6243 count)
6244 '(a b))) ==> (1 2) @var{or} (2 1)
6245}
6246@end format
6247
6248
6249@end deffn
6250
6251
6252
6253@deffn {library procedure} for-each proc list1 list2 @dots{},
6254
6255The arguments to @samp{for-each} are like the arguments to @samp{map}, but
6256@samp{for-each} calls @var{proc} for its side effects rather than for its
6257values. Unlike @samp{map}, @samp{for-each} is guaranteed to call @var{proc} on
6258the elements of the @var{list}s in order from the first element(s) to the
6259last, and the value returned by @samp{for-each} is unspecified.
6260
6261
6262@format
6263@t{(let ((v (make-vector 5)))
6264 (for-each (lambda (i)
6265 (vector-set! v i (* i i)))
6266 '(0 1 2 3 4))
6267 v) ==> #(0 1 4 9 16)
6268}
6269@end format
6270
6271
6272@end deffn
6273
6274
6275
6276@deffn {library procedure} force promise
6277
6278Forces the value of @var{promise} (see @code{delay},
6279@vindex @w{delay}
6280section @pxref{Delayed evaluation}). If no value has been computed for
6281@cindex @w{promise}
6282the promise, then a value is computed and returned. The value of the
6283promise is cached (or ``memoized'') so that if it is forced a second
6284time, the previously computed value is returned.
6285@c without any recomputation.
6286@c [As pointed out by Marc Feeley, the "without any recomputation"
6287@c isn't necessarily true. --Will]
6288
6289
6290@format
6291@t{(force (delay (+ 1 2))) ==> 3
6292(let ((p (delay (+ 1 2))))
6293 (list (force p) (force p)))
6294 ==> (3 3)
6295
6296(define a-stream
6297 (letrec ((next
6298 (lambda (n)
6299 (cons n (delay (next (+ n 1)))))))
6300 (next 0)))
6301(define head car)
6302(define tail
6303 (lambda (stream) (force (cdr stream))))
6304
6305(head (tail (tail a-stream)))
6306 ==> 2
6307}
6308@end format
6309
6310
7fb9c4af 6311@samp{Force} and @samp{delay} are mainly intended for programs written in
a0e07ba4
NJ
6312functional style. The following examples should not be considered to
6313illustrate good programming style, but they illustrate the property that
6314only one value is computed for a promise, no matter how many times it is
6315forced.
6316@c the value of a promise is computed at most once.
6317@c [As pointed out by Marc Feeley, it may be computed more than once,
6318@c but as I observed we can at least insist that only one value be
6319@c used! -- Will]
6320
6321
6322@format
6323@t{(define count 0)
6324(define p
6325 (delay (begin (set! count (+ count 1))
6326 (if (> count x)
6327 count
6328 (force p)))))
6329(define x 5)
6330p ==> @i{}a promise
6331(force p) ==> 6
6332p ==> @i{}a promise, still
6333(begin (set! x 10)
6334 (force p)) ==> 6
6335}
6336@end format
6337
6338
6339Here is a possible implementation of @samp{delay} and @samp{force}.
6340Promises are implemented here as procedures of no arguments,
6341and @samp{force} simply calls its argument:
6342
6343
6344@format
6345@t{(define force
6346 (lambda (object)
6347 (object)))
6348}
6349@end format
6350
6351
6352We define the expression
6353
6354
6355@format
6356@t{(delay @r{<expression>})
6357}
6358@end format
6359
6360
6361to have the same meaning as the procedure call
6362
6363
6364@format
6365@t{(make-promise (lambda () @r{<expression>}))@r{}
6366}
6367@end format
6368
6369
6370as follows
6371
6372
6373@format
6374@t{(define-syntax delay
6375 (syntax-rules ()
6376 ((delay expression)
6377 (make-promise (lambda () expression))))),
6378}
6379@end format
6380
6381
6382where @samp{make-promise} is defined as follows:
6383
6384@c \begin{scheme}
6385@c (define make-promise
6386@c (lambda (proc)
6387@c (let ((already-run? \schfalse) (result \schfalse))
6388@c (lambda ()
6389@c (cond ((not already-run?)
6390@c (set! result (proc))
6391@c (set! already-run? \schtrue)))
6392@c result))))%
6393@c \end{scheme}
6394
6395
6396@format
6397@t{(define make-promise
6398 (lambda (proc)
6399 (let ((result-ready? #f)
6400 (result #f))
6401 (lambda ()
6402 (if result-ready?
6403 result
6404 (let ((x (proc)))
6405 (if result-ready?
6406 result
6407 (begin (set! result-ready? #t)
6408 (set! result x)
6409 result))))))))
6410}
6411@end format
6412
6413
6414
6415@quotation
6416@emph{Rationale:}
6417A promise may refer to its own value, as in the last example above.
6418Forcing such a promise may cause the promise to be forced a second time
6419before the value of the first force has been computed.
6420This complicates the definition of @samp{make-promise}.
6421@end quotation
6422
6423
6424Various extensions to this semantics of @samp{delay} and @samp{force}
6425are supported in some implementations:
6426
6427
6428
6429@itemize @bullet
6430
6431@item
6432Calling @samp{force} on an object that is not a promise may simply
6433return the object.
6434
6435@item
6436It may be the case that there is no means by which a promise can be
6437operationally distinguished from its forced value. That is, expressions
6438like the following may evaluate to either @t{#t} or to @t{#f},
6439depending on the implementation:
6440
6441
6442@format
6443@t{(eqv? (delay 1) 1) ==> @emph{unspecified}
6444(pair? (delay (cons 1 2))) ==> @emph{unspecified}
6445}
6446@end format
6447
6448
6449@item
6450Some implementations may implement ``implicit forcing,'' where
6451the value of a promise is forced by primitive procedures like @samp{cdr}
6452and @samp{+}:
6453
6454
6455@format
6456@t{(+ (delay (* 3 7)) 13) ==> 34
6457}
6458@end format
6459
6460
6461@end itemize
6462
6463@end deffn
6464
6465
6466@deffn {procedure} call-with-current-continuation proc
6467
7fb9c4af 6468 @var{Proc} must be a procedure of one
a0e07ba4
NJ
6469argument. The procedure @samp{call-with-current-continuation} packages
6470up the current continuation (see the rationale below) as an ``escape
6471procedure'' and passes it as an argument to
6472@cindex @w{escape procedure}
6473@var{proc}. The escape procedure is a Scheme procedure that, if it is
6474later called, will abandon whatever continuation is in effect at that later
6475time and will instead use the continuation that was in effect
6476when the escape procedure was created. Calling the escape procedure
6477may cause the invocation of @var{before} and @var{after} thunks installed using
6478@code{dynamic-wind}.
6479@vindex @w{dynamic-wind}
6480
6481The escape procedure accepts the same number of arguments as the continuation to
6482the original call to @t{call-with-current-continuation}.
6483Except for continuations created by the @samp{call-with-values}
6484procedure, all continuations take exactly one value. The
6485effect of passing no value or more than one value to continuations
6486that were not created by @t{call-with-values} is unspecified.
6487
6488The escape procedure that is passed to @var{proc} has
6489unlimited extent just like any other procedure in Scheme. It may be stored
6490in variables or data structures and may be called as many times as desired.
6491
6492The following examples show only the most common ways in which
6493@samp{call-with-current-continuation} is used. If all real uses were as
6494simple as these examples, there would be no need for a procedure with
6495the power of @samp{call-with-current-continuation}.
6496
6497
6498@format
6499@t{(call-with-current-continuation
6500 (lambda (exit)
6501 (for-each (lambda (x)
6502 (if (negative? x)
6503 (exit x)))
6504 '(54 0 37 -3 245 19))
6505 #t)) ==> -3
6506
6507(define list-length
6508 (lambda (obj)
6509 (call-with-current-continuation
6510 (lambda (return)
6511 (letrec ((r
6512 (lambda (obj)
6513 (cond ((null? obj) 0)
6514 ((pair? obj)
6515 (+ (r (cdr obj)) 1))
6516 (else (return #f))))))
6517 (r obj))))))
6518
6519(list-length '(1 2 3 4)) ==> 4
6520
6521(list-length '(a b . c)) ==> #f
6522}
6523@end format
6524
6525
6526
6527@quotation
6528@emph{Rationale:}
6529
6530A common use of @samp{call-with-current-continuation} is for
6531structured, non-local exits from loops or procedure bodies, but in fact
6532@samp{call-with-current-continuation} is extremely useful for implementing a
6533wide variety of advanced control structures.
6534
6535Whenever a Scheme expression is evaluated there is a
6536@dfn{continuation} wanting the result of the expression. The continuation
6537@cindex @w{continuation}
6538represents an entire (default) future for the computation. If the expression is
6539evaluated at top level, for example, then the continuation might take the
6540result, print it on the screen, prompt for the next input, evaluate it, and
6541so on forever. Most of the time the continuation includes actions
6542specified by user code, as in a continuation that will take the result,
6543multiply it by the value stored in a local variable, add seven, and give
6544the answer to the top level continuation to be printed. Normally these
6545ubiquitous continuations are hidden behind the scenes and programmers do not
6546think much about them. On rare occasions, however, a programmer may
6547need to deal with continuations explicitly.
7fb9c4af 6548@samp{Call-with-current-continuation} allows Scheme programmers to do
a0e07ba4
NJ
6549that by creating a procedure that acts just like the current
6550continuation.
6551
6552Most programming languages incorporate one or more special-purpose
6553escape constructs with names like @t{exit}, @w{@samp{return}}, or
6554even @t{goto}. In 1965, however, Peter Landin [Landin65]
6555invented a general purpose escape operator called the J-operator. John
6556Reynolds [Reynolds72] described a simpler but equally powerful
6557construct in 1972. The @samp{catch} special form described by Sussman
6558and Steele in the 1975 report on Scheme is exactly the same as
6559Reynolds's construct, though its name came from a less general construct
6560in MacLisp. Several Scheme implementors noticed that the full power of the
6561@code{catch} construct could be provided by a procedure instead of by a
6562@vindex @w{catch}
6563special syntactic construct, and the name
6564@samp{call-with-current-continuation} was coined in 1982. This name is
6565descriptive, but opinions differ on the merits of such a long name, and
6566some people use the name @code{call/cc} instead.
6567@vindex @w{call/cc}
6568@end quotation
6569
6570
6571@end deffn
6572
6573
6574@deffn {procedure} values obj @dots{}
6575
6576Delivers all of its arguments to its continuation.
6577Except for continuations created by the @code{call-with-values}
6578@vindex @w{call-with-values}
6579procedure, all continuations take exactly one value.
6580@t{Values} might be defined as follows:
6581
6582@format
6583@t{(define (values . things)
6584 (call-with-current-continuation
6585 (lambda (cont) (apply cont things))))
6586}
6587@end format
6588
6589
6590@end deffn
6591
6592
6593@deffn {procedure} call-with-values producer consumer
6594
6595Calls its @var{producer} argument with no values and
6596a continuation that, when passed some values, calls the
6597@var{consumer} procedure with those values as arguments.
6598The continuation for the call to @var{consumer} is the
6599continuation of the call to @t{call-with-values}.
6600
6601
6602@format
6603@t{(call-with-values (lambda () (values 4 5))
6604 (lambda (a b) b))
6605 ==> 5
6606
6607(call-with-values * -) ==> -1
6608}
6609@end format
6610
6611
6612@end deffn
6613
6614
6615@deffn {procedure} dynamic-wind before thunk after
6616
6617Calls @var{thunk} without arguments, returning the result(s) of this call.
7fb9c4af 6618@var{Before} and @var{after} are called, also without arguments, as required
a0e07ba4
NJ
6619by the following rules (note that in the absence of calls to continuations
6620captured using @code{call-with-current-continuation} the three arguments are
6621@vindex @w{call-with-current-continuation}
7fb9c4af 6622called once each, in order). @var{Before} is called whenever execution
a0e07ba4
NJ
6623enters the dynamic extent of the call to @var{thunk} and @var{after} is called
6624whenever it exits that dynamic extent. The dynamic extent of a procedure
6625call is the period between when the call is initiated and when it
6626returns. In Scheme, because of @samp{call-with-current-continuation}, the
6627dynamic extent of a call may not be a single, connected time period.
6628It is defined as follows:
6629
6630
6631@itemize @bullet
6632
6633@item
6634The dynamic extent is entered when execution of the body of the
6635called procedure begins.
6636
6637@item
6638The dynamic extent is also entered when execution is not within
6639the dynamic extent and a continuation is invoked that was captured
6640(using @samp{call-with-current-continuation}) during the dynamic extent.
6641
6642@item
6643It is exited when the called procedure returns.
6644
6645@item
6646It is also exited when execution is within the dynamic extent and
6647a continuation is invoked that was captured while not within the
6648dynamic extent.
6649
6650@end itemize
6651
6652
6653If a second call to @samp{dynamic-wind} occurs within the dynamic extent of the
6654call to @var{thunk} and then a continuation is invoked in such a way that the
6655@var{after}s from these two invocations of @samp{dynamic-wind} are both to be
6656called, then the @var{after} associated with the second (inner) call to
6657@samp{dynamic-wind} is called first.
6658
6659If a second call to @samp{dynamic-wind} occurs within the dynamic extent of the
6660call to @var{thunk} and then a continuation is invoked in such a way that the
6661@var{before}s from these two invocations of @samp{dynamic-wind} are both to be
6662called, then the @var{before} associated with the first (outer) call to
6663@samp{dynamic-wind} is called first.
6664
6665If invoking a continuation requires calling the @var{before} from one call
6666to @samp{dynamic-wind} and the @var{after} from another, then the @var{after}
6667is called first.
6668
6669The effect of using a captured continuation to enter or exit the dynamic
6670extent of a call to @var{before} or @var{after} is undefined.
6671
6672
6673@format
6674@t{(let ((path '())
6675 (c #f))
6676 (let ((add (lambda (s)
6677 (set! path (cons s path)))))
6678 (dynamic-wind
6679 (lambda () (add 'connect))
6680 (lambda ()
6681 (add (call-with-current-continuation
6682 (lambda (c0)
6683 (set! c c0)
6684 'talk1))))
6685 (lambda () (add 'disconnect)))
6686 (if (< (length path) 4)
6687 (c 'talk2)
6688 (reverse path))))
6689
6690 ==> (connect talk1 disconnect
6691 connect talk2 disconnect)
6692}
6693@end format
6694
6695@end deffn
6696
6697@node Eval, Input and output, Control features, Standard procedures
6698@section Eval
6699
6700
6701
6702@deffn {procedure} eval expression environment-specifier
6703
6704Evaluates @var{expression} in the specified environment and returns its value.
7fb9c4af 6705@var{Expression} must be a valid Scheme expression represented as data,
a0e07ba4
NJ
6706and @var{environment-specifier} must be a value returned by one of the
6707three procedures described below.
6708Implementations may extend @samp{eval} to allow non-expression programs
6709(definitions) as the first argument and to allow other
6710values as environments, with the restriction that @samp{eval} is not
6711allowed to create new bindings in the environments associated with
6712@samp{null-environment} or @samp{scheme-report-environment}.
6713
6714
6715@format
6716@t{(eval '(* 7 3) (scheme-report-environment 5))
6717 ==> 21
6718
6719(let ((f (eval '(lambda (f x) (f x x))
6720 (null-environment 5))))
6721 (f + 10))
6722 ==> 20
6723}
6724@end format
6725
6726
6727@end deffn
6728
6729
6730@deffn {procedure} scheme-report-environment version
6731@deffnx {procedure} null-environment version
6732
7fb9c4af 6733@var{Version} must be the exact integer @samp{5},
a0e07ba4
NJ
6734corresponding to this revision of the Scheme report (the
6735Revised^5 Report on Scheme).
7fb9c4af 6736@samp{Scheme-report-environment} returns a specifier for an
a0e07ba4
NJ
6737environment that is empty except for all bindings defined in
6738this report that are either required or both optional and
7fb9c4af 6739supported by the implementation. @samp{Null-environment} returns
a0e07ba4
NJ
6740a specifier for an environment that is empty except for the
6741(syntactic) bindings for all syntactic keywords defined in
6742this report that are either required or both optional and
6743supported by the implementation.
6744
6745Other values of @var{version} can be used to specify environments
6746matching past revisions of this report, but their support is not
6747required. An implementation will signal an error if @var{version}
6748is neither @samp{5} nor another value supported by
6749the implementation.
6750
6751The effect of assigning (through the use of @samp{eval}) a variable
6752bound in a @samp{scheme-report-environment}
6753(for example @samp{car}) is unspecified. Thus the environments specified
6754by @samp{scheme-report-environment} may be immutable.
6755
6756@end deffn
6757
6758
6759@deffn {optional procedure} interaction-environment
6760
6761This procedure returns a specifier for the environment that
6762contains imple@-men@-ta@-tion-defined bindings, typically a superset of
6763those listed in the report. The intent is that this procedure
6764will return the environment in which the implementation would evaluate
6765expressions dynamically typed by the user.
6766
6767@end deffn
6768
6769@node Input and output, , Eval, Standard procedures
6770@section Input and output
6771
6772@menu
6773* Ports::
6774* Input::
6775* Output::
6776* System interface::
6777@end menu
6778
6779
6780@node Ports, Input, Input and output, Input and output
6781@subsection Ports
6782
6783
6784
6785Ports represent input and output devices. To Scheme, an input port is a
6786Scheme object that can deliver characters upon command, while an output port
6787is a Scheme object that can accept characters.
6788@cindex @w{port}
6789
6790@ignore todo
6791Haase: Mention that there are alternatives to files?
6792@end ignore
6793
6794
6795
6796@deffn {library procedure} call-with-input-file string proc
6797@deffnx {library procedure} call-with-output-file string proc
6798
7fb9c4af 6799@var{String} should be a string naming a file, and
a0e07ba4
NJ
6800@var{proc} should be a procedure that accepts one argument.
6801For @samp{call-with-input-file},
6802the file should already exist; for
6803@samp{call-with-output-file},
6804the effect is unspecified if the file
6805already exists. These procedures call @var{proc} with one argument: the
6806port obtained by opening the named file for input or output. If the
6807file cannot be opened, an error is signalled. If @var{proc} returns,
6808then the port is closed automatically and the value(s) yielded by the
6809@var{proc} is(are) returned. If @var{proc} does not return, then
6810the port will not be closed automatically unless it is possible to
6811prove that the port will never again be used for a read or write
6812operation.
6813@c Scheme
6814@c will not close the port unless it can prove that the port will never
6815@c again be used for a read or write operation.
6816
6817
6818@quotation
6819@emph{Rationale:}
6820Because Scheme's escape procedures have unlimited extent, it is
6821possible to escape from the current continuation but later to escape back in.
6822If implementations were permitted to close the port on any escape from the
6823current continuation, then it would be impossible to write portable code using
6824both @samp{call-with-current-continuation} and @samp{call-with-input-file} or
6825@samp{call-with-output-file}.
6826@ignore todo
6827Pitman wants more said here; maybe encourage users to call
6828@var{close-foo-port}; maybe talk about process switches (?).
6829@end ignore
6830
6831@end quotation
6832
6833@end deffn
6834
6835
6836
6837@deffn {procedure} input-port? obj
6838@deffnx {procedure} output-port? obj
6839
6840Returns @t{#t} if @var{obj} is an input port or output port
6841respectively, otherwise returns @t{#f}.
6842
6843@ignore todo
6844Won't necessarily return true after port is closed.
6845@end ignore
6846
6847
6848@end deffn
6849
6850
6851
6852@deffn {procedure} current-input-port
6853@deffnx {procedure} current-output-port
6854
6855Returns the current default input or output port.
6856
6857@end deffn
6858
6859
6860
6861@deffn {optional procedure} with-input-from-file string thunk
6862@deffnx {optional procedure} with-output-to-file string thunk
6863
7fb9c4af
AW
6864@var{String} should be a string naming a file, and
6865@var{proc} should be a procedure of no arguments.
a0e07ba4
NJ
6866For @samp{with-input-from-file},
6867the file should already exist; for
6868@samp{with-output-to-file},
6869the effect is unspecified if the file
6870already exists.
6871The file is opened for input or output, an input or output port
6872connected to it is made the default value returned by
6873@samp{current-input-port} or @samp{current-output-port}
6874(and is used by @t{(read)}, @t{(write @var{obj})}, and so forth),
6875and the
6876@var{thunk} is called with no arguments. When the @var{thunk} returns,
6877the port is closed and the previous default is restored.
7fb9c4af 6878@samp{With-input-from-file} and @samp{with-output-to-file} return(s) the
a0e07ba4
NJ
6879value(s) yielded by @var{thunk}.
6880If an escape procedure
6881is used to escape from the continuation of these procedures, their
6882behavior is implementation dependent.
6883
6884@ignore todo
6885OK this with authors??
6886@end ignore
6887
6888@c current continuation changes in such a way
6889@c as to make it doubtful that the \var{thunk} will ever return.
6890
6891@ignore todo
6892Freeman:
6893Throughout this section I wanted to see ``the value of @t{(current-input-port)}''
6894instead of ``the value returned by @var{current-input-port}''. (Same for
6895@var{current-output-port}.)
6896@end ignore
6897
6898
6899
6900@end deffn
6901
6902
6903
6904@deffn {procedure} open-input-file filename
6905
6906Takes a string naming an existing file and returns an input port capable of
6907delivering characters from the file. If the file cannot be opened, an error is
6908signalled.
6909
6910@end deffn
6911
6912
6913
6914@deffn {procedure} open-output-file filename
6915
6916Takes a string naming an output file to be created and returns an output
6917port capable of writing characters to a new file by that name. If the file
6918cannot be opened, an error is signalled. If a file with the given name
6919already exists, the effect is unspecified.
6920
6921@end deffn
6922
6923
6924
6925@deffn {procedure} close-input-port port
6926@deffnx {procedure} close-output-port port
6927
6928Closes the file associated with @var{port}, rendering the @var{port}
6929incapable of delivering or accepting characters.
6930@ignore todo
6931But maybe a no-op
6932on some ports, e.g. terminals or editor buffers.
6933@end ignore
6934
6935These routines have no effect if the file has already been closed.
6936The value returned is unspecified.
6937
6938@ignore todo
6939Ramsdell: Some note is needed explaining why there are two
6940different close procedures.
6941@end ignore
6942
6943
6944@ignore todo
6945A port isn't necessarily still a port after it has been closed?
6946@end ignore
6947
6948
6949@end deffn
6950
6951
6952@node Input, Output, Ports, Input and output
6953@subsection Input
6954
6955
6956
6957
6958@noindent
6959 @w{ }
6960@c ???
6961@sp 5
6962@ignore todo
6963The input routines have some things in common, maybe explain here.
6964@end ignore
6965
6966
6967
6968@deffn {library procedure} read
6969@deffnx {library procedure} read port
6970
7fb9c4af 6971@samp{Read} converts external representations of Scheme objects into the
a0e07ba4
NJ
6972objects themselves. That is, it is a parser for the nonterminal
6973<datum> (see sections @pxref{External representation} and
7fb9c4af 6974@pxref{Pairs and lists}). @samp{Read} returns the next
a0e07ba4
NJ
6975object parsable from the given input @var{port}, updating @var{port} to point to
6976the first character past the end of the external representation of the object.
6977
6978If an end of file is encountered in the input before any
6979characters are found that can begin an object, then an end of file
6980object is returned.
6981@ignore todo
6982
6983@end ignore
6984 The port remains open, and further attempts
6985to read will also return an end of file object. If an end of file is
6986encountered after the beginning of an object's external representation,
6987but the external representation is incomplete and therefore not parsable,
6988an error is signalled.
6989
6990The @var{port} argument may be omitted, in which case it defaults to the
6991value returned by @samp{current-input-port}. It is an error to read from
6992a closed port.
6993@end deffn
6994
6995
6996@deffn {procedure} read-char
6997@deffnx {procedure} read-char port
6998
6999Returns the next character available from the input @var{port}, updating
7000the @var{port} to point to the following character. If no more characters
7fb9c4af 7001are available, an end of file object is returned. @var{Port} may be
a0e07ba4
NJ
7002omitted, in which case it defaults to the value returned by @samp{current-input-port}.
7003
7004@end deffn
7005
7006
7007
7008@deffn {procedure} peek-char
7009@deffnx {procedure} peek-char port
7010
7011Returns the next character available from the input @var{port},
7012@emph{without} updating
7013the @var{port} to point to the following character. If no more characters
7fb9c4af 7014are available, an end of file object is returned. @var{Port} may be
a0e07ba4
NJ
7015omitted, in which case it defaults to the value returned by @samp{current-input-port}.
7016
7017
7018@quotation
7019@emph{Note:}
7020The value returned by a call to @samp{peek-char} is the same as the
7021value that would have been returned by a call to @samp{read-char} with the
7022same @var{port}. The only difference is that the very next call to
7023@samp{read-char} or @samp{peek-char} on that @var{port} will return the
7024value returned by the preceding call to @samp{peek-char}. In particular, a call
7025to @samp{peek-char} on an interactive port will hang waiting for input
7026whenever a call to @samp{read-char} would have hung.
7027@end quotation
7028
7029
7030@end deffn
7031
7032
7033
7034@deffn {procedure} eof-object? obj
7035
7036Returns @t{#t} if @var{obj} is an end of file object, otherwise returns
7037@t{#f}. The precise set of end of file objects will vary among
7038implementations, but in any case no end of file object will ever be an object
7039that can be read in using @samp{read}.
7040
7041@end deffn
7042
7043
7044
7045@deffn {procedure} char-ready?
7046@deffnx {procedure} char-ready? port
7047
7048Returns @t{#t} if a character is ready on the input @var{port} and
7049returns @t{#f} otherwise. If @samp{char-ready} returns @t{#t} then
7050the next @samp{read-char} operation on the given @var{port} is guaranteed
7051not to hang. If the @var{port} is at end of file then @samp{char-ready?}
7fb9c4af 7052returns @t{#t}. @var{Port} may be omitted, in which case it defaults to
a0e07ba4
NJ
7053the value returned by @samp{current-input-port}.
7054
7055
7056@quotation
7057@emph{Rationale:}
7fb9c4af 7058@samp{Char-ready?} exists to make it possible for a program to
a0e07ba4
NJ
7059accept characters from interactive ports without getting stuck waiting for
7060input. Any input editors associated with such ports must ensure that
7061characters whose existence has been asserted by @samp{char-ready?} cannot
7062be rubbed out. If @samp{char-ready?} were to return @t{#f} at end of
7063file, a port at end of file would be indistinguishable from an interactive
7064port that has no ready characters.
7065@end quotation
7066
7067@end deffn
7068
7069
7070@node Output, System interface, Input, Input and output
7071@subsection Output
7072
7073
7074
7075@c We've got to put something here to fix the indentation!!
7076
7077@noindent
7078 @w{}
7079@sp 5
7080
7081
7082@deffn {library procedure} write obj
7083@deffnx {library procedure} write obj port
7084
7085Writes a written representation of @var{obj} to the given @var{port}. Strings
7086that appear in the written representation are enclosed in doublequotes, and
7087within those strings backslash and doublequote characters are
7088escaped by backslashes.
7089Character objects are written using the @samp{#\} notation.
7fb9c4af 7090@samp{Write} returns an unspecified value. The
a0e07ba4
NJ
7091@var{port} argument may be omitted, in which case it defaults to the value
7092returned by @samp{current-output-port}.
7093
7094@end deffn
7095
7096
7097
7098@deffn {library procedure} display obj
7099@deffnx {library procedure} display obj port
7100
7101Writes a representation of @var{obj} to the given @var{port}. Strings
7102that appear in the written representation are not enclosed in
7103doublequotes, and no characters are escaped within those strings. Character
7104objects appear in the representation as if written by @samp{write-char}
7fb9c4af 7105instead of by @samp{write}. @samp{Display} returns an unspecified value.
a0e07ba4
NJ
7106The @var{port} argument may be omitted, in which case it defaults to the
7107value returned by @samp{current-output-port}.
7108
7109
7110@quotation
7111@emph{Rationale:}
7fb9c4af 7112@samp{Write} is intended
a0e07ba4
NJ
7113for producing mach@-ine-readable output and @samp{display} is for producing
7114human-readable output. Implementations that allow ``slashification''
7115within symbols will probably want @samp{write} but not @samp{display} to
7116slashify funny characters in symbols.
7117@end quotation
7118
7119@end deffn
7120
7121
7122
7123@deffn {library procedure} newline
7124@deffnx {library procedure} newline port
7125
7126Writes an end of line to @var{port}. Exactly how this is done differs
7127from one operating system to another. Returns an unspecified value.
7128The @var{port} argument may be omitted, in which case it defaults to the
7129value returned by @samp{current-output-port}.
7130
7131@end deffn
7132
7133
7134
7135@deffn {procedure} write-char char
7136@deffnx {procedure} write-char char port
7137
7138Writes the character @var{char} (not an external representation of the
7139character) to the given @var{port} and returns an unspecified value. The
7140@var{port} argument may be omitted, in which case it defaults to the value
7141returned by @samp{current-output-port}.
7142
7143@end deffn
7144
7145
7146@node System interface, , Output, Input and output
7147@subsection System interface
7148
7149
7150Questions of system interface generally fall outside of the domain of this
7151report. However, the following operations are important enough to
7152deserve description here.
7153
7154
7155
7156@deffn {optional procedure} load filename
7157
7158@ignore todo
7159Fix
7160@end ignore
7161
7162
7163@c \domain{\var{Filename} should be a string naming an existing file
7164@c containing Scheme source code.} The {\cf load} procedure reads
7fb9c4af 7165@var{Filename} should be a string naming an existing file
a0e07ba4
NJ
7166containing Scheme source code. The @samp{load} procedure reads
7167expressions and definitions from the file and evaluates them
7168sequentially. It is unspecified whether the results of the expressions
7169are printed. The @samp{load} procedure does not affect the values
7170returned by @samp{current-input-port} and @samp{current-output-port}.
7fb9c4af 7171@samp{Load} returns an unspecified value.
a0e07ba4
NJ
7172
7173
7174@quotation
7175@emph{Rationale:}
7176For portability, @samp{load} must operate on source files.
7177Its operation on other kinds of files necessarily varies among
7178implementations.
7179@end quotation
7180
7181@end deffn
7182
7183
7184
7185@deffn {optional procedure} transcript-on filename
7186@deffnx {optional procedure} transcript-off
7187
7fb9c4af 7188@var{Filename} must be a string naming an output file to be
a0e07ba4
NJ
7189created. The effect of @samp{transcript-on} is to open the named file
7190for output, and to cause a transcript of subsequent interaction between
7191the user and the Scheme system to be written to the file. The
7192transcript is ended by a call to @samp{transcript-off}, which closes the
7193transcript file. Only one transcript may be in progress at any time,
7194though some implementations may relax this restriction. The values
7195returned by these procedures are unspecified.
7196
7197@c \begin{note}
7198@c These procedures are redundant in some systems, but
7199@c systems that need them should provide them.
7200@c \end{note}
7201@end deffn
7202
7203@page
7204
7205@c @include{syn}
7206@node Formal syntax and semantics, Notes, Standard procedures, top
7207@chapter Formal syntax and semantics
7208
7209@menu
7210* Formal syntax::
7211* Formal semantics::
7212* Derived expression type::
7213@end menu
7214
7215
7216
7217This chapter provides formal descriptions of what has already been
7218described informally in previous chapters of this report.
7219
7220@ignore todo
7221Allow grammar to say that else clause needn't be last?
7222@end ignore
7223
7224
7225
7226@node Formal syntax, Formal semantics, Formal syntax and semantics, Formal syntax and semantics
7227@section Formal syntax
7228
7229@menu
7230* Lexical structure::
7231* External representation::
7232* Expression::
7233* Quasiquotations::
7234* Transformers::
7235* Programs and definitions::
7236@end menu
7237
7238
7239
7240This section provides a formal syntax for Scheme written in an extended
7241BNF.
7242
7243All spaces in the grammar are for legibility. Case is insignificant;
7244for example, @samp{#x1A} and @samp{#X1a} are equivalent. <empty>
7245stands for the empty string.
7246
7247The following extensions to BNF are used to make the description more
7248concise: <thing>* means zero or more occurrences of
7249<thing>; and <thing>+ means at least one
7250<thing>.
7251
7252
7253@node Lexical structure, External representation, Formal syntax, Formal syntax
7254@subsection Lexical structure
7255
7256
7257This section describes how individual tokens (identifiers,
7258@cindex @w{token}
7259numbers, etc.) are formed from sequences of characters. The following
7260sections describe how expressions and programs are formed from sequences
7261of tokens.
7262
7263<Intertoken space> may occur on either side of any token, but not
7264within a token.
7265
7266Tokens which require implicit termination (identifiers, numbers,
7267characters, and dot) may be terminated by any <delimiter>, but not
7268necessarily by anything else.
7269
7270The following five characters are reserved for future extensions to the
7271language: @t{[ ] @{ @} |}
7272
7273
7274@format
7275@t{<token> --> <identifier> | <boolean> | <number>
7276@cindex @w{identifier}
7277 | <character> | <string>
7278 | ( | ) | #( | @t{'} | @t{`} | , | ,@@ | @b{.}
7279<delimiter> --> <whitespace> | ( | ) | " | ;
7280<whitespace> --> <space or newline>
7281<comment> --> ; <@r{all subsequent characters up to a}
7282 @r{line break>}
7283@cindex @w{comment}
7284<atmosphere> --> <whitespace> | <comment>
7285<intertoken space> --> <atmosphere>*}
7286
7287@end format
7288
7289
7290
7291
7292
7293
7294@c This is a kludge, but \multicolumn doesn't work in tabbing environments.
7295
7296
7297
7298@format
7299@t{<identifier> --> <initial> <subsequent>*
7300 | <peculiar identifier>
7301<initial> --> <letter> | <special initial>
7302<letter> --> a | b | c | ... | z
7303
7304<special initial> --> ! | $ | % | & | * | / | : | < | =
7305 | > | ? | ^ | _ | ~
7306<subsequent> --> <initial> | <digit>
7307 | <special subsequent>
7308<digit> --> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
7309<special subsequent> --> + | - | .@: | @@
7310<peculiar identifier> --> + | - | ...
7311<syntactic keyword> --> <expression keyword>
7312@cindex @w{syntactic keyword}
7313@cindex @w{keyword}
7314 | else | => | define
7315 | unquote | unquote-splicing
7316<expression keyword> --> quote | lambda | if
7317 | set! | begin | cond | and | or | case
7318 | let | let* | letrec | do | delay
7319 | quasiquote
7320
7321@w{@samp{<variable> @result{} <}}@r{any <identifier> that isn't}
7322@cindex @w{variable}
7323 @w{ @r{also a <syntactic keyword>>}}
7324
7325<boolean> --> #t | #f
7326<character> --> #\ <any character>
7327 | #\ <character name>
7328<character name> --> space | newline
7329
7330<string> --> " <string element>* "
7331<string element> --> <any character other than " or \>
7332 | \" | \\ }
7333
7334@end format
7335
7336
7337
7338
7339
7340
7341
7342@format
7343@t{<number> --> <num 2>| <num 8>
7344 | <num 10>| <num 16>
7345}
7346
7347@end format
7348
7349
7350
7351The following rules for <num R>, <complex R>, <real
7352R>, <ureal R>, <uinteger R>, and <prefix R>
7353should be replicated for @w{R = 2, 8, 10,}
7354and 16. There are no rules for <decimal 2>, <decimal
73558>, and <decimal 16>, which means that numbers containing
7356decimal points or exponents must be in decimal radix.
7357@ignore todo
7358Mark Meyer and David Bartley want to fix this. (What? -- Will)
7359@end ignore
7360
7361
7362
7363@format
7364@t{<num R> --> <prefix R> <complex R>
7365<complex R> --> <real R> | <real R> @@ <real R>
7366 | <real R> + <ureal R> i | <real R> - <ureal R> i
7367 | <real R> + i | <real R> - i
7368 | + <ureal R> i | - <ureal R> i | + i | - i
7369<real R> --> <sign> <ureal R>
7370<ureal R> --> <uinteger R>
7371 | <uinteger R> / <uinteger R>
7372 | <decimal R>
7373<decimal 10> --> <uinteger 10> <suffix>
7374 | . <digit 10>+ #* <suffix>
7375 | <digit 10>+ . <digit 10>* #* <suffix>
7376 | <digit 10>+ #+ . #* <suffix>
7377<uinteger R> --> <digit R>+ #*
7378<prefix R> --> <radix R> <exactness>
7379 | <exactness> <radix R>
7380}
7381
7382@end format
7383
7384
7385
7386
7387@format
7388@t{<suffix> --> <empty>
7389 | <exponent marker> <sign> <digit 10>+
7390<exponent marker> --> e | s | f | d | l
7391<sign> --> <empty> | + | -
7392<exactness> --> <empty> | #i | #e
7393@vindex #e
7394@vindex #i
7395<radix 2> --> #b
7396@vindex #b
7397<radix 8> --> #o
7398@vindex #o
7399<radix 10> --> <empty> | #d
7400<radix 16> --> #x
7401@vindex #x
7402<digit 2> --> 0 | 1
7403<digit 8> --> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
7404<digit 10> --> <digit>
7405<digit 16> --> <digit 10> | a | b | c | d | e | f }
7406
7407@end format
7408
7409
7410
7411@ignore todo
7412Mark Meyer of TI sez, shouldn't we allow @t{1e3/2}?
7413@end ignore
7414
7415
7416
7417@node External representation, Expression, Lexical structure, Formal syntax
7418@subsection External representations
7419
7420
7421
7422<Datum> is what the @code{read} procedure (section @pxref{Input})
7423@vindex @w{read}
7424successfully parses. Note that any string that parses as an
7425<ex@-pres@-sion> will also parse as a <datum>.
7426
7427
7428@format
7429@t{<datum> --> <simple datum> | <compound datum>
7430<simple datum> --> <boolean> | <number>
7431 | <character> | <string> | <symbol>
7432<symbol> --> <identifier>
7433<compound datum> --> <list> | <vector>
7434<list> --> (<datum>*) | (<datum>+ .@: <datum>)
7435 | <abbreviation>
7436<abbreviation> --> <abbrev prefix> <datum>
7437<abbrev prefix> --> ' | ` | , | ,@@
7438<vector> --> #(<datum>*) }
7439
7440@end format
7441
7442
7443
7444
7445@node Expression, Quasiquotations, External representation, Formal syntax
7446@subsection Expressions
7447
7448
7449
7450@format
7451@t{<expression> --> <variable>
7452 | <literal>
7453 | <procedure call>
7454 | <lambda expression>
7455 | <conditional>
7456 | <assignment>
7457 | <derived expression>
7458 | <macro use>
7459 | <macro block>
7460
7461<literal> --> <quotation> | <self-evaluating>
7462<self-evaluating> --> <boolean> | <number>
7463 | <character> | <string>
7464<quotation> --> '<datum> | (quote <datum>)
7465<procedure call> --> (<operator> <operand>*)
7466<operator> --> <expression>
7467<operand> --> <expression>
7468
7469<lambda expression> --> (lambda <formals> <body>)
7470<formals> --> (<variable>*) | <variable>
7471 | (<variable>+ .@: <variable>)
7472<body> --> <definition>* <sequence>
7473<sequence> --> <command>* <expression>
7474<command> --> <expression>
7475
7476<conditional> --> (if <test> <consequent> <alternate>)
7477<test> --> <expression>
7478<consequent> --> <expression>
7479<alternate> --> <expression> | <empty>
7480
7481<assignment> --> (set! <variable> <expression>)
7482
7483<derived expression> -->
7484 (cond <cond clause>+)
7485 | (cond <cond clause>* (else <sequence>))
7486 | (case <expression>
7487 <case clause>+)
7488 | (case <expression>
7489 <case clause>*
7490 (else <sequence>))
7491 | (and <test>*)
7492 | (or <test>*)
7493 | (let (<binding spec>*) <body>)
7494 | (let <variable> (<binding spec>*) <body>)
7495 | (let* (<binding spec>*) <body>)
7496 | (letrec (<binding spec>*) <body>)
7497 | (begin <sequence>)
7498 | (do (<iteration spec>*)
7499 (<test> <do result>)
7500 <command>*)
7501 | (delay <expression>)
7502 | <quasiquotation>
7503
7504<cond clause> --> (<test> <sequence>)
7505 | (<test>)
7506 | (<test> => <recipient>)
7507<recipient> --> <expression>
7508<case clause> --> ((<datum>*) <sequence>)
7509<binding spec> --> (<variable> <expression>)
7510<iteration spec> --> (<variable> <init> <step>)
7511 | (<variable> <init>)
7512<init> --> <expression>
7513<step> --> <expression>
7514<do result> --> <sequence> | <empty>
7515
7516<macro use> --> (<keyword> <datum>*)
7517<keyword> --> <identifier>
7518
7519<macro block> -->
7520 (let-syntax (<syntax spec>*) <body>)
7521 | (letrec-syntax (<syntax spec>*) <body>)
7522<syntax spec> --> (<keyword> <transformer spec>)
7523
7524}
7525
7526@end format
7527
7528
7529
7530@node Quasiquotations, Transformers, Expression, Formal syntax
7531@subsection Quasiquotations
7532
7533
7534The following grammar for quasiquote expressions is not context-free.
7535It is presented as a recipe for generating an infinite number of
7536production rules. Imagine a copy of the following rules for D = 1, 2,3, @dots{}. D keeps track of the nesting depth.
7537
7538
7539@format
7540@t{<quasiquotation> --> <quasiquotation 1>
7541<qq template 0> --> <expression>
7542<quasiquotation D> --> `<qq template D>
7543 | (quasiquote <qq template D>)
7544<qq template D> --> <simple datum>
7545 | <list qq template D>
7546 | <vector qq template D>
7547 | <unquotation D>
7548<list qq template D> --> (<qq template or splice D>*)
7549 | (<qq template or splice D>+ .@: <qq template D>)
7550 | '<qq template D>
7551 | <quasiquotation D+1>
7552<vector qq template D> --> #(<qq template or splice D>*)
7553<unquotation D> --> ,<qq template D-1>
7554 | (unquote <qq template D-1>)
7555<qq template or splice D> --> <qq template D>
7556 | <splicing unquotation D>
7557<splicing unquotation D> --> ,@@<qq template D-1>
7558 | (unquote-splicing <qq template D-1>) }
7559
7560@end format
7561
7562
7563
7564In <quasiquotation>s, a <list qq template D> can sometimes
7565be confused with either an <un@-quota@-tion D> or a <splicing
7566un@-quo@-ta@-tion D>. The interpretation as an
7567<un@-quo@-ta@-tion> or <splicing
7568un@-quo@-ta@-tion D> takes precedence.
7569
7570@node Transformers, Programs and definitions, Quasiquotations, Formal syntax
7571@subsection Transformers
7572
7573
7574
7575@format
7576@t{<transformer spec> -->
7577 (syntax-rules (<identifier>*) <syntax rule>*)
7578<syntax rule> --> (<pattern> <template>)
7579<pattern> --> <pattern identifier>
7580 | (<pattern>*)
7581 | (<pattern>+ . <pattern>)
7582 | (<pattern>* <pattern> <ellipsis>)
7583 | #(<pattern>*)
7584 | #(<pattern>* <pattern> <ellipsis>)
7585 | <pattern datum>
7586<pattern datum> --> <string>
7587 | <character>
7588 | <boolean>
7589 | <number>
7590<template> --> <pattern identifier>
7591 | (<template element>*)
7592 | (<template element>+ . <template>)
7593 | #(<template element>*)
7594 | <template datum>
7595<template element> --> <template>
7596 | <template> <ellipsis>
7597<template datum> --> <pattern datum>
7598<pattern identifier> --> <any identifier except @samp{...}>
7599<ellipsis> --> <the identifier @samp{...}>
7600}
7601
7602@end format
7603
7604
7605
7606@node Programs and definitions, , Transformers, Formal syntax
7607@subsection Programs and definitions
7608
7609
7610
7611@format
7612@t{<program> --> <command or definition>*
7613<command or definition> --> <command>
7614 | <definition>
7615 | <syntax definition>
7616 | (begin <command or definition>+)
7617<definition> --> (define <variable> <expression>)
7618 | (define (<variable> <def formals>) <body>)
7619 | (begin <definition>*)
7620<def formals> --> <variable>*
7621 | <variable>* .@: <variable>
7622<syntax definition> -->
7623 (define-syntax <keyword> <transformer spec>)
7624}
7625
7626@end format
7627
7628
7629
7630@node Formal semantics, Derived expression type, Formal syntax, Formal syntax and semantics
7631@section Formal semantics
7632
7633
7634This section provides a formal denotational semantics for the primitive
7635expressions of Scheme and selected built-in procedures. The concepts
7636and notation used here are described in @sc{[Stoy77]}.
7637
7638@quotation
7639@emph{Note:} The formal semantics section was written in La@TeX{} which
7640is incompatible with @TeX{}info. See the Formal semantics section of
7641the original document from which this was derived.
7642@end quotation
7643
7644
7645@c @include{derive}
7646@node Derived expression type, , Formal semantics, Formal syntax and semantics
7647@section Derived expression types
7648
7649
7650
7651This section gives macro definitions for the derived expression types in
7652terms of the primitive expression types (literal, variable, call, @samp{lambda},
7653@samp{if}, @samp{set!}). See section @ref{Control features} for a possible
7654definition of @samp{delay}.
7655
7656
7657@example
7658
7659(define-syntax cond
7660 (syntax-rules (else =>)
7661 ((cond (else result1 result2 ...))
7662 (begin result1 result2 ...))
7663 ((cond (test => result))
7664 (let ((temp test))
7665 (if temp (result temp))))
7666 ((cond (test => result) clause1 clause2 ...)
7667 (let ((temp test))
7668 (if temp
7669 (result temp)
7670 (cond clause1 clause2 ...))))
7671 ((cond (test)) test)
7672 ((cond (test) clause1 clause2 ...)
7673 (let ((temp test))
7674 (if temp
7675 temp
7676 (cond clause1 clause2 ...))))
7677 ((cond (test result1 result2 ...))
7678 (if test (begin result1 result2 ...)))
7679 ((cond (test result1 result2 ...)
7680 clause1 clause2 ...)
7681 (if test
7682 (begin result1 result2 ...)
7683 (cond clause1 clause2 ...)))))
7684
7685@end example
7686
7687
7688
7689@example
7690
7691(define-syntax case
7692 (syntax-rules (else)
7693 ((case (key ...)
7694 clauses ...)
7695 (let ((atom-key (key ...)))
7696 (case atom-key clauses ...)))
7697 ((case key
7698 (else result1 result2 ...))
7699 (begin result1 result2 ...))
7700 ((case key
7701 ((atoms ...) result1 result2 ...))
7702 (if (memv key '(atoms ...))
7703 (begin result1 result2 ...)))
7704 ((case key
7705 ((atoms ...) result1 result2 ...)
7706 clause clauses ...)
7707 (if (memv key '(atoms ...))
7708 (begin result1 result2 ...)
7709 (case key clause clauses ...)))))
7710
7711@end example
7712
7713
7714
7715@example
7716
7717(define-syntax and
7718 (syntax-rules ()
7719 ((and) #t)
7720 ((and test) test)
7721 ((and test1 test2 ...)
7722 (if test1 (and test2 ...) #f))))
7723
7724@end example
7725
7726
7727
7728@example
7729
7730(define-syntax or
7731 (syntax-rules ()
7732 ((or) #f)
7733 ((or test) test)
7734 ((or test1 test2 ...)
7735 (let ((x test1))
7736 (if x x (or test2 ...))))))
7737
7738@end example
7739
7740
7741
7742@example
7743
7744(define-syntax let
7745 (syntax-rules ()
7746 ((let ((name val) ...) body1 body2 ...)
7747 ((lambda (name ...) body1 body2 ...)
7748 val ...))
7749 ((let tag ((name val) ...) body1 body2 ...)
7750 ((letrec ((tag (lambda (name ...)
7751 body1 body2 ...)))
7752 tag)
7753 val ...))))
7754
7755@end example
7756
7757
7758
7759@example
7760
7761(define-syntax let*
7762 (syntax-rules ()
7763 ((let* () body1 body2 ...)
7764 (let () body1 body2 ...))
7765 ((let* ((name1 val1) (name2 val2) ...)
7766 body1 body2 ...)
7767 (let ((name1 val1))
7768 (let* ((name2 val2) ...)
7769 body1 body2 ...)))))
7770
7771@end example
7772
7773
7774The following @samp{letrec} macro uses the symbol @samp{<undefined>}
7775in place of an expression which returns something that when stored in
7776a location makes it an error to try to obtain the value stored in the
7777location (no such expression is defined in Scheme).
7778A trick is used to generate the temporary names needed to avoid
7779specifying the order in which the values are evaluated.
7780This could also be accomplished by using an auxiliary macro.
7781
7782
7783@example
7784
7785(define-syntax letrec
7786 (syntax-rules ()
7787 ((letrec ((var1 init1) ...) body ...)
7788 (letrec "generate temp names"
7789 (var1 ...)
7790 ()
7791 ((var1 init1) ...)
7792 body ...))
7793 ((letrec "generate temp names"
7794 ()
7795 (temp1 ...)
7796 ((var1 init1) ...)
7797 body ...)
7798 (let ((var1 <undefined>) ...)
7799 (let ((temp1 init1) ...)
7800 (set! var1 temp1)
7801 ...
7802 body ...)))
7803 ((letrec "generate temp names"
7804 (x y ...)
7805 (temp ...)
7806 ((var1 init1) ...)
7807 body ...)
7808 (letrec "generate temp names"
7809 (y ...)
7810 (newtemp temp ...)
7811 ((var1 init1) ...)
7812 body ...))))
7813
7814@end example
7815
7816
7817
7818@example
7819
7820(define-syntax begin
7821 (syntax-rules ()
7822 ((begin exp ...)
7823 ((lambda () exp ...)))))
7824
7825@end example
7826
7827
7828The following alternative expansion for @samp{begin} does not make use of
7829the ability to write more than one expression in the body of a lambda
7830expression. In any case, note that these rules apply only if the body
7831of the @samp{begin} contains no definitions.
7832
7833
7834@example
7835
7836(define-syntax begin
7837 (syntax-rules ()
7838 ((begin exp)
7839 exp)
7840 ((begin exp1 exp2 ...)
7841 (let ((x exp1))
7842 (begin exp2 ...)))))
7843
7844@end example
7845
7846
7847The following definition
7848of @samp{do} uses a trick to expand the variable clauses.
7849As with @samp{letrec} above, an auxiliary macro would also work.
7850The expression @samp{(if #f #f)} is used to obtain an unspecific
7851value.
7852
7853
7854@example
7855
7856(define-syntax do
7857 (syntax-rules ()
7858 ((do ((var init step ...) ...)
7859 (test expr ...)
7860 command ...)
7861 (letrec
7862 ((loop
7863 (lambda (var ...)
7864 (if test
7865 (begin
7866 (if #f #f)
7867 expr ...)
7868 (begin
7869 command
7870 ...
7871 (loop (do "step" var step ...)
7872 ...))))))
7873 (loop init ...)))
7874 ((do "step" x)
7875 x)
7876 ((do "step" x y)
7877 y)))
7878
7879@end example
7880
7881
7882@c `a = Q_1[a]
7883@c `(a b c ... . z) = `(a . (b c ...))
7884@c `(a . b) = (append Q*_0[a] `b)
7885@c `(a) = Q*_0[a]
7886@c Q*_0[a] = (list 'a)
7887@c Q*_0[,a] = (list a)
7888@c Q*_0[,@a] = a
7889@c Q*_0[`a] = (list 'quasiquote Q*_1[a])
7890@c `#(a b ...) = (list->vector `(a b ...))
7891@c ugh.
7892
7893@page
7894
7895@c @include{notes}
7896@node Notes, Additional material, Formal syntax and semantics, top
7897@unnumbered Notes
7898
7899@menu
7900* Language changes::
7901@end menu
7902
7903
7904
7905@ignore todo
7906Perhaps this section should be made to disappear.
7907Can these remarks be moved somewhere else?
7908@end ignore
7909
7910
7911@node Language changes, , Notes, Notes
7912@unnumberedsec Language changes
7913
7914
7915
7916This section enumerates the changes that have been made to Scheme since
7917the ``Revised^4 report'' [R4RS] was published.
7918
7919
7920
7921@itemize @bullet
7922
7923
7924@item
7925The report is now a superset of the IEEE standard for Scheme
7926[IEEEScheme]: implementations that conform to the report will
7927also conform to the standard. This required the following changes:
7928
7929
7930@itemize @bullet
7931
7932
7933@item
7934The empty list is now required to count as true.
7935
7936@item
7937The classification of features as essential or inessential has been
7938removed. There are now three classes of built-in procedures: primitive,
7939library, and optional. The optional procedures are @samp{load},
7940@samp{with-input-from-file}, @samp{with-output-to-file},
7941@samp{transcript-on}, @samp{transcript-off}, and
7942@samp{interaction-environment},
7943and @samp{-} and @samp{/} with more than two arguments.
7944None of these are in the IEEE standard.
7945
7946@item
7947Programs are allowed to redefine built-in procedures. Doing so
7948will not change the behavior of other built-in procedures.
7949
7950@end itemize
7951
7952
7953@item
7954@emph{Port} has been added to the list of disjoint types.
7955
7956@item
7957The macro appendix has been removed. High-level macros are now part
7958of the main body of the report. The rewrite rules for derived expressions
7959have been replaced with macro definitions. There are no reserved identifiers.
7960
7961@item
7fb9c4af 7962@samp{Syntax-rules} now allows vector patterns.
a0e07ba4
NJ
7963
7964@item
7965Multiple-value returns, @samp{eval}, and @samp{dynamic-wind} have
7966been added.
7967
7968@item
7969The calls that are required to be implemented in a properly tail-recursive
7970fashion are defined explicitly.
7971
7972@item
7973`@samp{@@}' can be used within identifiers. `@samp{|}' is reserved
7974for possible future extensions.
7975
7976
7977@end itemize
7978
7979
7980@c %R4%%
7981@c \subsection*{Keywords as variable names}
7982
7983@c Some implementations allow arbitrary syntactic
7984@c keywords \index{keyword}\index{syntactic keyword}to be used as variable
7985@c names, instead of reserving them, as this report would have
7986@c it.\index{variable} But this creates ambiguities in the interpretation
7987@c of expressions: for example, in the following, it's not clear whether
7988@c the expression {\tt (if 1 2 3)} should be treated as a procedure call or
7989@c as a conditional.
7990
7991@c \begin{scheme}
7992@c (define if list)
7993@c (if 1 2 3) \ev 2 {\em{}or} (1 2 3)%
7994@c \end{scheme}
7995
7996@c These ambiguities are usually resolved in some consistent way within any
7997@c given implementation, but no particular treatment stands out as being
7998@c clearly superior to any other, so these situations were excluded for the
7999@c purposes of this report.
8000
8001@c %R4%%
8002@c \subsection*{Macros}
8003
8004@c Scheme does not have any standard facility for defining new kinds of
8005@c expressions.\index{macros}
8006
8007@c \vest The ability to alter the syntax of the language creates
8008@c numerous problems. All current implementations of Scheme have macro
8009@c facilities that solve those problems to one degree or another, but the
8010@c solutions are quite different and it isn't clear at this time which
8011@c solution is best, or indeed whether any of the solutions are truly
8012@c adequate. Rather than standardize, we are encouraging implementations
8013@c to continue to experiment with different solutions.
8014
8015@c \vest The main problems with traditional macros are: They must be
8016@c defined to the system before any code using them is loaded; this is a
8017@c common source of obscure bugs. They are usually global; macros can be
8018@c made to follow lexical scope rules \todo{flushed: ``as in Common
8019@c Lisp's {\tt macrolet}''; OK?}, but many people find the resulting scope rules
8020@c confusing. Unless they are written very carefully, macros are
8021@c vulnerable to inadvertent capture of free variables; to get around this,
8022@c for example, macros may have to generate code in which procedure values
8023@c appear as quoted constants. There is a similar problem with syntactic
8024@c keywords if the keywords of special forms are not reserved. If keywords
8025@c are reserved, then either macros introduce new reserved words,
8026@c invalidating old code, or else special forms defined by the programmer
8027@c do not have the same status as special forms defined by the system.
8028
8029@c \todo{Refer to Pitman's special forms paper.}
8030@c \todo{Pitman sez: Discuss importance of having a small number of special forms
8031@c so that programs can inspect each other.}
8032
8033@ignore todo
8034Move cwcc history back here? --- Andy Cromarty is concerned about
8035confusion over who the audience is.
8036@end ignore
8037
8038
8039@ignore todo
8040Cromarty:
804123. NOTES, p.35ff.: This material should stay somehow. We need to
8042 make it clear that R^3 Scheme is not being touted as Yet Another
8043 Ultimate Solution To The Programming Language Problem, but rather
8044 as a snapshot of a *process* of good design, for which not all
8045 answers have yet been found. We also ought to use the opportunity
8046 for publicity afforded us by SIGPLAN to advertise some of the thorny
8047 unsolved problems that need further research, and encourage
8048 language designers to work on them.
8049@end ignore
8050
8051
8052@c @include{repository}
8053@node Additional material, Example, Notes, top
8054@unnumbered Additional material
8055
8056
8057The Internet Scheme Repository at
8058
8059@center
8060@center @url{http://www.cs.indiana.edu/scheme-repository/}
8061@center
8062
8063contains an extensive Scheme bibliography, as well as papers,
8064programs, implementations, and other material related to Scheme.
8065
8066@page
8067
8068@c @include{example}
8069
8070@node Example, Bibliography, Additional material, top
8071@unnumbered Example
8072
8073@c -*- Mode: Lisp; Package: SCHEME; Syntax: Common-lisp -*-
8074
8075
7fb9c4af 8076@samp{Integrate-system} integrates the system
a0e07ba4
NJ
8077
8078
8079@center y_k^^ = f_k(y_1, y_2, @dots{}, y_n), k = 1, @dots{}, n
8080
8081of differential equations with the method of Runge-Kutta.
8082
8083The parameter @t{system-derivative} is a function that takes a system
8084state (a vector of values for the state variables y_1, @dots{}, y_n)
8085and produces a system derivative (the values y_1^^, @dots{},y_n^^). The parameter @t{initial-state} provides an initial
8086system state, and @t{h} is an initial guess for the length of the
8087integration step.
8088
8089The value returned by @samp{integrate-system} is an infinite stream of
8090system states.
8091
8092
8093@example
8094
8095(define integrate-system
8096 (lambda (system-derivative initial-state h)
8097 (let ((next (runge-kutta-4 system-derivative h)))
8098 (letrec ((states
8099 (cons initial-state
8100 (delay (map-streams next
8101 states)))))
8102 states))))
8103
8104@end example
8105
8106
7fb9c4af
AW
8107@samp{Runge-Kutta-4} takes a function, @t{f}, that produces a
8108system derivative from a system state. @samp{Runge-Kutta-4}
a0e07ba4
NJ
8109produces a function that takes a system state and
8110produces a new system state.
8111
8112
8113@example
8114
8115(define runge-kutta-4
8116 (lambda (f h)
8117 (let ((*h (scale-vector h))
8118 (*2 (scale-vector 2))
8119 (*1/2 (scale-vector (/ 1 2)))
8120 (*1/6 (scale-vector (/ 1 6))))
8121 (lambda (y)
8122 ;; y @r{}is a system state
8123 (let* ((k0 (*h (f y)))
8124 (k1 (*h (f (add-vectors y (*1/2 k0)))))
8125 (k2 (*h (f (add-vectors y (*1/2 k1)))))
8126 (k3 (*h (f (add-vectors y k2)))))
8127 (add-vectors y
8128 (*1/6 (add-vectors k0
8129 (*2 k1)
8130 (*2 k2)
8131 k3))))))))
8132@c |--------------------------------------------------|
8133
8134(define elementwise
8135 (lambda (f)
8136 (lambda vectors
8137 (generate-vector
8138 (vector-length (car vectors))
8139 (lambda (i)
8140 (apply f
8141 (map (lambda (v) (vector-ref v i))
8142 vectors)))))))
8143
8144@c |--------------------------------------------------|
8145(define generate-vector
8146 (lambda (size proc)
8147 (let ((ans (make-vector size)))
8148 (letrec ((loop
8149 (lambda (i)
8150 (cond ((= i size) ans)
8151 (else
8152 (vector-set! ans i (proc i))
8153 (loop (+ i 1)))))))
8154 (loop 0)))))
8155
8156(define add-vectors (elementwise +))
8157
8158(define scale-vector
8159 (lambda (s)
8160 (elementwise (lambda (x) (* x s)))))
8161
8162@end example
8163
8164
7fb9c4af 8165@samp{Map-streams} is analogous to @samp{map}: it applies its first
a0e07ba4
NJ
8166argument (a procedure) to all the elements of its second argument (a
8167stream).
8168
8169
8170@example
8171
8172(define map-streams
8173 (lambda (f s)
8174 (cons (f (head s))
8175 (delay (map-streams f (tail s))))))
8176
8177@end example
8178
8179
8180Infinite streams are implemented as pairs whose car holds the first
8181element of the stream and whose cdr holds a promise to deliver the rest
8182of the stream.
8183
8184
8185@example
8186
8187(define head car)
8188(define tail
8189 (lambda (stream) (force (cdr stream))))
8190
8191@end example
8192
8193
8194@sp 6
8195The following illustrates the use of @samp{integrate-system} in
8196integrating the system
8197
8198
8199@center C dv_C / dt = -i_L - v_C / R
8200
8201
8202
8203@center L di_L / dt = v_C
8204
8205which models a damped oscillator.
8206
8207
8208@example
8209
8210(define damped-oscillator
8211 (lambda (R L C)
8212 (lambda (state)
8213 (let ((Vc (vector-ref state 0))
8214 (Il (vector-ref state 1)))
8215 (vector (- 0 (+ (/ Vc (* R C)) (/ Il C)))
8216 (/ Vc L))))))
8217
8218(define the-states
8219 (integrate-system
8220 (damped-oscillator 10000 1000 .001)
8221 '#(1 0)
8222 .01))
8223
8224@end example
8225
8226
8227@ignore todo
8228Show some output?
8229@end ignore
8230
8231
8232@c (letrec ((loop (lambda (s)
8233@c (newline)
8234@c (write (head s))
8235@c (loop (tail s)))))
8236@c (loop the-states))
8237
8238@c #(1 0)
8239@c #(0.99895054 9.994835e-6)
8240@c #(0.99780226 1.9978681e-5)
8241@c #(0.9965554 2.9950552e-5)
8242@c #(0.9952102 3.990946e-5)
8243@c #(0.99376684 4.985443e-5)
8244@c #(0.99222565 5.9784474e-5)
8245@c #(0.9905868 6.969862e-5)
8246@c #(0.9888506 7.9595884e-5)
8247@c #(0.9870173 8.94753e-5)
8248
8249@page
8250
8251@c \newpage % Put bib on it's own page (it's just one)
8252@c \twocolumn[\vspace{-.18in}]% Last bib item was on a page by itself.
8253@c \renewcommand{\bibname}{References}
8254@c @include{bib}
8255
8256@c My reference for proper reference format is:
8257@c Mary-Claire van Leunen.
8258@c {\em A Handbook for Scholars.}
8259@c Knopf, 1978.
8260@c I think the references list would look better in ``open'' format,
8261@c i.e. with the three blocks for each entry appearing on separate
8262@c lines. I used the compressed format for SIGPLAN in the interest of
8263@c space. In open format, when a block runs over one line,
8264@c continuation lines should be indented; this could probably be done
8265@c using some flavor of latex list environment. Maybe the right thing
8266@c to do in the long run would be to convert to Bibtex, which probably
8267@c does the right thing, since it was implemented by one of van
8268@c Leunen's colleagues at DEC SRC.
8269@c -- Jonathan
8270
8271@c I tried to follow Jonathan's format, insofar as I understood it.
8272@c I tried to order entries lexicographically by authors (with singly
8273@c authored papers first), then by date.
8274@c In some cases I replaced a technical report or conference paper
8275@c by a subsequent journal article, but I think there are several
8276@c more such replacements that ought to be made.
8277@c -- Will, 1991.
8278
8279@c This is just a personal remark on your question on the RRRS:
8280@c The language CUCH (Curry-Church) was implemented by 1964 and
8281@c is a practical version of the lambda-calculus (call-by-name).
8282@c One reference you may find in Formal Language Description Languages
8283@c for Computer Programming T.~B.~Steele, 1965 (or so).
8284@c -- Matthias Felleisen
8285
8286@c Rather than try to keep the bibliography up-to-date, which is hopeless
8287@c given the time between updates, I replaced the bulk of the references
8288@c with a pointer to the Scheme Repository. Ozan Yigit's bibliography in
8289@c the repository is a superset of the R4RS one.
8290@c The bibliography now contains only items referenced within the report.
8291@c -- Richard, 1996.
8292
8293@node Bibliography, Index, Example, top
8294@unnumbered Bibliography
8295
8296
8297@itemize @bullet
8298@c 999
8299
8300
8301@item [SICP]
8302@pindex SICP
8303Harold Abelson and Gerald Jay Sussman with Julie Sussman.
8304@emph{Structure and Interpretation of Computer Programs, second edition.}
8305MIT Press, Cambridge, 1996.
8306
8307@item [Bawden88]
8308@c new
8309Alan Bawden and Jonathan Rees.
8310@pindex Bawden88
8311Syntactic closures.
8312In @emph{Proceedings of the 1988 ACM Symposium on Lisp and
8313 Functional Programming}, pages 86--95.
8314
8315@item [howtoprint]
8316@pindex howtoprint
8317Robert G. Burger and R. Kent Dybvig.
8318Printing floating-point numbers quickly and accurately.
8319In @emph{Proceedings of the ACM SIGPLAN '96 Conference
8320 on Programming Language Design and Implementation}, pages 108--116.
8321
8322@item [RRRS]
8323@pindex RRRS
8324William Clinger, editor.
8325The revised revised report on Scheme, or an uncommon Lisp.
8326MIT Artificial Intelligence Memo 848, August 1985.
8327Also published as Computer Science Department Technical Report 174,
8328 Indiana University, June 1985.
8329
8330@item [howtoread]
8331@c new
8332William Clinger.
8333@pindex howtoread
8334How to read floating point numbers accurately.
8335In @emph{Proceedings of the ACM SIGPLAN '90 Conference
8336 on Programming Language Design and Implementation}, pages 92--101.
8337Proceedings published as @emph{SIGPLAN Notices} 25(6), June 1990.
8338
8339@item [R4RS]
8340@pindex R4RS
8341William Clinger and Jonathan Rees, editors.
8342The revised^4 report on the algorithmic language Scheme.
8343In @emph{ACM Lisp Pointers} 4(3), pages 1--55, 1991.
8344
8345@item [macrosthatwork]
8346@c new
8347William Clinger and Jonathan Rees.
8348@pindex macrosthatwork
8349Macros that work.
8350In @emph{Proceedings of the 1991 ACM Conference on Principles of
8351 Programming Languages}, pages 155--162.
8352
8353@item [propertailrecursion]
8354@c new
8355William Clinger.
8356@pindex propertailrecursion
8357Proper Tail Recursion and Space Efficiency.
8358To appear in @emph{Proceedings of the 1998 ACM Conference on Programming
8359 Language Design and Implementation}, June 1998.
8360
8361@item [syntacticabstraction]
8362@pindex syntacticabstraction
8363R. Kent Dybvig, Robert Hieb, and Carl Bruggeman.
8364Syntactic abstraction in Scheme.
8365@emph{Lisp and Symbolic Computation} 5(4):295--326, 1993.
8366
8367@item [Scheme311]
8368@pindex Scheme311
8369Carol Fessenden, William Clinger, Daniel P. Friedman, and Christopher Haynes.
8370Scheme 311 version 4 reference manual.
8371Indiana University Computer Science Technical Report 137, February 1983.
8372Superseded by [Scheme84].
8373
8374@item [Scheme84]
8375@pindex Scheme84
8376D. Friedman, C. Haynes, E. Kohlbecker, and M. Wand.
8377Scheme 84 interim reference manual.
8378Indiana University Computer Science Technical Report 153, January 1985.
8379
8380@item [IEEE]
8381@pindex IEEE
8382@emph{IEEE Standard 754-1985. IEEE Standard for Binary Floating-Point
8383Arithmetic.} IEEE, New York, 1985.
8384
8385@item [IEEEScheme]
8386@pindex IEEEScheme
8387@emph{IEEE Standard 1178-1990. IEEE Standard for the Scheme
8388 Programming Language.} IEEE, New York, 1991.
8389
8390@item [Kohlbecker86]
8391@pindex Kohlbecker86
8392Eugene E. Kohlbecker Jr.
8393@emph{Syntactic Extensions in the Programming Language Lisp.}
8394PhD thesis, Indiana University, August 1986.
8395
8396@item [hygienic]
8397@pindex hygienic
8398Eugene E. Kohlbecker Jr., Daniel P. Friedman, Matthias Felleisen, and Bruce Duba.
8399Hygienic macro expansion.
8400In @emph{Proceedings of the 1986 ACM Conference on Lisp
8401 and Functional Programming}, pages 151--161.
8402
8403@item [Landin65]
8404@pindex Landin65
8405Peter Landin.
8406A correspondence between Algol 60 and Church's lambda notation: Part I.
8407@emph{Communications of the ACM} 8(2):89--101, February 1965.
8408
8409@item [MITScheme]
8410@pindex MITScheme
8411MIT Department of Electrical Engineering and Computer Science.
8412Scheme manual, seventh edition.
8413September 1984.
8414
8415@item [Naur63]
8416@pindex Naur63
8417Peter Naur et al.
8418Revised report on the algorithmic language Algol 60.
8419@emph{Communications of the ACM} 6(1):1--17, January 1963.
8420
8421@item [Penfield81]
8422@pindex Penfield81
8423Paul Penfield, Jr.
8424Principal values and branch cuts in complex APL.
8425In @emph{APL '81 Conference Proceedings,} pages 248--256.
8426ACM SIGAPL, San Francisco, September 1981.
8427Proceedings published as @emph{APL Quote Quad} 12(1), ACM, September 1981.
8428
8429@item [Pitman83]
8430@pindex Pitman83
8431Kent M. Pitman.
8432The revised MacLisp manual (Saturday evening edition).
8433MIT Laboratory for Computer Science Technical Report 295, May 1983.
8434
8435@item [Rees82]
8436@pindex Rees82
8437Jonathan A. Rees and Norman I. Adams IV.
8438T: A dialect of Lisp or, lambda: The ultimate software tool.
8439In @emph{Conference Record of the 1982 ACM Symposium on Lisp and
8440 Functional Programming}, pages 114--122.
8441
8442@item [Rees84]
8443@pindex Rees84
8444Jonathan A. Rees, Norman I. Adams IV, and James R. Meehan.
8445The T manual, fourth edition.
8446Yale University Computer Science Department, January 1984.
8447
8448@item [R3RS]
8449@pindex R3RS
8450Jonathan Rees and William Clinger, editors.
8451The revised^3 report on the algorithmic language Scheme.
8452In @emph{ACM SIGPLAN Notices} 21(12), pages 37--79, December 1986.
8453
8454@item [Reynolds72]
8455@pindex Reynolds72
8456John Reynolds.
8457Definitional interpreters for higher order programming languages.
8458In @emph{ACM Conference Proceedings}, pages 717--740.
8459ACM,
8460@ignore todo
8461month?
8462@end ignore
8463 1972.
8464
8465@item [Scheme78]
8466@pindex Scheme78
8467Guy Lewis Steele Jr. and Gerald Jay Sussman.
8468The revised report on Scheme, a dialect of Lisp.
8469MIT Artificial Intelligence Memo 452, January 1978.
8470
8471@item [Rabbit]
8472@pindex Rabbit
8473Guy Lewis Steele Jr.
8474Rabbit: a compiler for Scheme.
8475MIT Artificial Intelligence Laboratory Technical Report 474, May 1978.
8476
8477@item [CLtL]
8478@pindex CLtL
8479Guy Lewis Steele Jr.
8480@emph{Common Lisp: The Language, second edition.}
8481Digital Press, Burlington MA, 1990.
8482
8483@item [Scheme75]
8484@pindex Scheme75
8485Gerald Jay Sussman and Guy Lewis Steele Jr.
8486Scheme: an interpreter for extended lambda calculus.
8487MIT Artificial Intelligence Memo 349, December 1975.
8488
8489@item [Stoy77]
8490@pindex Stoy77
8491Joseph E. Stoy.
8492@emph{Denotational Semantics: The Scott-Strachey Approach to
8493 Programming Language Theory.}
8494MIT Press, Cambridge, 1977.
8495
8496@item [TImanual85]
8497@pindex TImanual85
8498Texas Instruments, Inc.
8499TI Scheme Language Reference Manual.
8500Preliminary version 1.0, November 1985.
8501
8502@end itemize
8503
8504
8505
8506
8507@page
8508
8509
8510@c Adjustment to avoid having the last index entry on a page by itself.
8511@c \addtolength{\baselineskip}{-0.1pt}
8512
8513@node Index, , Bibliography, top
8514@unnumbered Alphabetic index of definitions of concepts, keywords, and procedures
8515
8516
8517
8518The principal entry for each term, procedure, or keyword is listed
8519first, separated from the other entries by a semicolon.
8520
8521@sp 6
8522
8523@unnumberedsec Concepts
8524@printindex cp
8525@page
8526@unnumberedsec Procedures
8527@printindex fn
8528
8529@ifinfo
8530@unnumberedsec References
8531@printindex pg
8532@end ifinfo
8533
8534
8535@contents
8536@bye