commit b50284cb5e1665449fb3368e0188898fc77a782c Spenser Truex <web@spensertruex.com> 2019-11-24 14:44:35 -0800 Initialize
README.md | 8 + r6rs-complete.pdf | Bin 0 -> 1906028 bytes sources/r6rs-app.pdf | Bin 0 -> 124571 bytes sources/r6rs-lib.pdf | Bin 0 -> 629868 bytes sources/r6rs-rationale.pdf | Bin 0 -> 284718 bytes sources/r6rs.pdf | 15313 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 15321 insertions(+)
diff --git a/README.md b/README.md new file mode 100644 index 0000000..0f03065 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +This document r6rs-complete.pdf is the combination of the r6rs and supplementary +materials available on [www.r6rs.org](www.r6rs.org) as a single PDF document. +``` shell +pdfunite r6rs.pdf r6rs-lib.pdf r6rs-app.pdf r6rs-rationale.pdf r6rs-complete.pdf +``` + + + diff --git a/r6rs-complete.pdf b/r6rs-complete.pdf new file mode 100644 index 0000000..ff4d4b3 --- /dev/null +++ b/r6rs-complete.pdf @@ -0,0 +1,12177 @@ + Revised6 Report on the Algorithmic Language + Scheme + + MICHAEL SPERBER + R. KENT DYBVIG, MATTHEW FLATT, ANTON VAN STRAATEN + + (Editors ) + RICHARD KELSEY, WILLIAM CLINGER, JONATHAN REES + (Editors, Revised 5 Report on the Algorithmic Language Scheme) + + ROBERT BRUCE FINDLER, JACOB MATTHEWS + (Authors, formal semantics) + 26 September 2007 + + SUMMARY + +The report gives a defining description of the programming language Scheme. Scheme is a statically scoped and properly +tail-recursive dialect of the Lisp programming language invented by Guy Lewis Steele Jr. and Gerald Jay Sussman. It was +designed to have an exceptionally clear and simple semantics and few different ways to form expressions. A wide variety +of programming paradigms, including functional, imperative, and message passing styles, find convenient expression in +Scheme. +This report is accompanied by a report describing standard libraries [24]; references to this document are identified by +designations such as “library section” or “library chapter”. It is also accompanied by a report containing non-normative +appendices [22]. A fourth report gives some historical background and rationales for many aspects of the language and +its libraries [23]. + +The individuals listed above are not the sole authors of the text of the report. Over the years, the following individuals +were involved in discussions contributing to the design of the Scheme language, and were listed as authors of prior reports: +Hal Abelson, Norman Adams, David Bartley, Gary Brooks, William Clinger, R. Kent Dybvig, Daniel Friedman, Robert +Halstead, Chris Hanson, Christopher Haynes, Eugene Kohlbecker, Don Oxley, Kent Pitman, Jonathan Rees, Guillermo +Rozas, Guy L. Steele Jr., Gerald Jay Sussman, and Mitchell Wand. +In order to highlight recent contributions, they are not listed as authors of this version of the report. However, their +contribution and service is gratefully acknowledged. + +We intend this report to belong to the entire Scheme community, and so we grant permission to copy it in whole or in +part without fee. In particular, we encourage implementors of Scheme to use this report as a starting point for manuals +and other documentation, modifying it as necessary. + 2 Revised6 Scheme + +CONTENTS 7.1 Library form . . . . . . . . . . . . . . . . . 23 + +Introduction . . . . . . . . . . . . . . . . . . . . . . 3 7.2 Import and export levels . . . . . . . . . . . 25 + +Description of the language 7.3 Examples . . . . . . . . . . . . . . . . . . . 26 +1 Overview of Scheme . . . . . . . . . . . . . . . . . + 8 Top-level programs . . . . . . . . . . . . . . . . . 27 + 1.1 Basic types . . . . . . . . . . . . . . . . . . + 5 8.1 Top-level program syntax . . . . . . . . . . 27 + + 5 8.2 Top-level program semantics . . . . . . . . . 28 + +1.2 Expressions . . . . . . . . . . . . . . . . . . 6 9 Primitive syntax . . . . . . . . . . . . . . . . . . . 28 + +1.3 Variables and binding . . . . . . . . . . . . 6 9.1 Primitive expression types . . . . . . . . . . 28 + +1.4 Definitions . . . . . . . . . . . . . . . . . . . 6 9.2 Macros . . . . . . . . . . . . . . . . . . . . . 29 + +1.5 Forms . . . . . . . . . . . . . . . . . . . . . 7 10 Expansion process . . . . . . . . . . . . . . . . . . 29 + +1.6 Procedures . . . . . . . . . . . . . . . . . . 7 11 Base library . . . . . . . . . . . . . . . . . . . . . 31 + +1.7 Procedure calls and syntactic keywords . . . 7 11.1 Base types . . . . . . . . . . . . . . . . . . . 31 + +1.8 Assignment . . . . . . . . . . . . . . . . . . 7 11.2 Definitions . . . . . . . . . . . . . . . . . . . 31 + +1.9 Derived forms and macros . . . . . . . . . . 8 11.3 Bodies . . . . . . . . . . . . . . . . . . . . . 32 + +1.10 Syntactic data and datum values . . . . . . 8 11.4 Expressions . . . . . . . . . . . . . . . . . . 32 + +1.11 Continuations . . . . . . . . . . . . . . . . . 8 11.5 Equivalence predicates . . . . . . . . . . . . 37 + +1.12 Libraries . . . . . . . . . . . . . . . . . . . . 9 11.6 Procedure predicate . . . . . . . . . . . . . 39 + +1.13 Top-level programs . . . . . . . . . . . . . . 9 11.7 Arithmetic . . . . . . . . . . . . . . . . . . . 39 + +2 Requirement levels . . . . . . . . . . . . . . . . . 9 11.8 Booleans . . . . . . . . . . . . . . . . . . . . 47 + +3 Numbers . . . . . . . . . . . . . . . . . . . . . . . 10 11.9 Pairs and lists . . . . . . . . . . . . . . . . . 47 + +3.1 Numerical tower . . . . . . . . . . . . . . . 10 11.10Symbols . . . . . . . . . . . . . . . . . . . . 49 + +3.2 Exactness . . . . . . . . . . . . . . . . . . . 10 11.11Characters . . . . . . . . . . . . . . . . . . . 50 + +3.3 Fixnums and flonums . . . . . . . . . . . . . 10 11.12Strings . . . . . . . . . . . . . . . . . . . . . 50 + +3.4 Implementation requirements . . . . . . . . 10 11.13Vectors . . . . . . . . . . . . . . . . . . . . 51 + +3.5 Infinities and NaNs . . . . . . . . . . . . . . 11 11.14Errors and violations . . . . . . . . . . . . . 52 + +3.6 Distinguished -0.0 . . . . . . . . . . . . . . 11 11.15Control features . . . . . . . . . . . . . . . . 53 + +4 Lexical syntax and datum syntax . . . . . . . . . 11 11.16Iteration . . . . . . . . . . . . . . . . . . . . 55 + + 4.1 Notation . . . . . . . . . . . . . . . . . . . . 12 11.17Quasiquotation . . . . . . . . . . . . . . . . 55 + 4.2 Lexical syntax . . . . . . . . . . . . . . . . . 12 11.18Binding constructs for syntactic keywords . 56 + 4.3 Datum syntax . . . . . . . . . . . . . . . . . 16 11.19Macro transformers . . . . . . . . . . . . . . 57 +5 Semantic concepts . . . . . . . . . . . . . . . . . . 17 11.20Tail calls and tail contexts . . . . . . . . . . 59 + +5.1 Programs and libraries . . . . . . . . . . . . 17 Appendices + +5.2 Variables, keywords, and regions . . . . . . 17 A Formal semantics . . . . . . . . . . . . . . . . . . 61 + +5.3 Exceptional situations . . . . . . . . . . . . 18 A.1 Background . . . . . . . . . . . . . . . . . . 61 + +5.4 Argument checking . . . . . . . . . . . . . . 18 A.2 Grammar . . . . . . . . . . . . . . . . . . . 62 +5.5 Syntax violations . . . . . . . . . . . . . . . 19 A.3 Quote . . . . . . . . . . . . . . . . . . . . . 65 + +5.6 Safety . . . . . . . . . . . . . . . . . . . . . 19 A.4 Multiple values . . . . . . . . . . . . . . . . 65 + +5.7 Boolean values . . . . . . . . . . . . . . . . 19 A.5 Exceptions . . . . . . . . . . . . . . . . . . 67 + +5.8 Multiple return values . . . . . . . . . . . . 19 A.6 Arithmetic and basic forms . . . . . . . . . 69 + +5.9 Unspecified behavior . . . . . . . . . . . . . 20 A.7 Lists . . . . . . . . . . . . . . . . . . . . . . 69 + +5.10 Storage model . . . . . . . . . . . . . . . . . 20 A.8 Eqv . . . . . . . . . . . . . . . . . . . . . . 69 + +5.11 Proper tail recursion . . . . . . . . . . . . . 20 A.9 Procedures and application . . . . . . . . . 70 + +5.12 Dynamic extent and the dynamic environment 20 A.10 Call/cc and dynamic wind . . . . . . . . . . 72 + +6 Entry format . . . . . . . . . . . . . . . . . . . . . 20 A.11 Letrec . . . . . . . . . . . . . . . . . . . . . 73 + +6.1 Syntax entries . . . . . . . . . . . . . . . . . 21 A.12 Underspecification . . . . . . . . . . . . . . 74 + +6.2 Procedure entries . . . . . . . . . . . . . . . 21 B Sample definitions for derived forms . . . . . . . . 75 + +6.3 Implementation responsibilities . . . . . . . 22 C Additional material . . . . . . . . . . . . . . . . . 77 + +6.4 Other kinds of entries . . . . . . . . . . . . 22 D Example . . . . . . . . . . . . . . . . . . . . . . . 77 + +6.5 Equivalent entries . . . . . . . . . . . . . . . 22 E Language changes . . . . . . . . . . . . . . . . . . 79 + +6.6 Evaluation examples . . . . . . . . . . . . . 22 References . . . . . . . . . . . . . . . . . . . . . . . . 80 + +6.7 Naming conventions . . . . . . . . . . . . . 23 Alphabetic index of definitions of concepts, key- + +7 Libraries . . . . . . . . . . . . . . . . . . . . . . . 23 words, and procedures . . . . . . . . . . . . . . . 82 + Introduction 3 + +INTRODUCTION + +Programming languages should be designed not by piling • make procedure calls powerful enough to express any +feature on top of feature, but by removing the weaknesses form of sequential control, and allow programs to per- +and restrictions that make additional features appear nec- form non-local control operations without the use of +essary. Scheme demonstrates that a very small number of global program transformations; +rules for forming expressions, with no restrictions on how +they are composed, suffice to form a practical and efficient • allow interesting, purely functional programs to run +programming language that is flexible enough to support indefinitely without terminating or running out of +most of the major programming paradigms in use today. memory on finite-memory machines; + +Scheme was one of the first programming languages to in- • allow educators to use the language to teach program- +corporate first-class procedures as in the lambda calculus, ming effectively, at various levels and with a variety of +thereby proving the usefulness of static scope rules and pedagogical approaches; and +block structure in a dynamically typed language. Scheme +was the first major dialect of Lisp to distinguish proce- • allow researchers to use the language to explore the de- +dures from lambda expressions and symbols, to use a sin- sign, implementation, and semantics of programming +gle lexical environment for all variables, and to evaluate languages. +the operator position of a procedure call in the same way +as an operand position. By relying entirely on procedure In addition, this report is intended to: +calls to express iteration, Scheme emphasized the fact that +tail-recursive procedure calls are essentially gotos that pass • allow programmers to create and distribute substan- +arguments. Scheme was the first widely used programming tial programs and libraries, e.g., implementations of +language to embrace first-class escape procedures, from Scheme Requests for Implementation, that run with- +which all previously known sequential control structures out modification in a variety of Scheme implementa- +can be synthesized. A subsequent version of Scheme in- tions; +troduced the concept of exact and inexact number objects, +an extension of Common Lisp’s generic arithmetic. More • support procedural, syntactic, and data abstraction +recently, Scheme became the first programming language more fully by allowing programs to define hygiene- +to support hygienic macros, which permit the syntax of a bending and hygiene-breaking syntactic abstractions +block-structured language to be extended in a consistent and new unique datatypes along with procedures and +and reliable manner. hygienic macros in any scope; + +Guiding principles • allow programmers to rely on a level of automatic run- + time type and bounds checking sufficient to ensure +To help guide the standardization effort, the editors have type safety; and +adopted a set of principles, presented below. Like the +Scheme language defined in Revised5 Report on the Algo- • allow implementations to generate efficient code, with- +rithmic Language Scheme [14], the language described in out requiring programmers to use implementation- +this report is intended to: specific operators or declarations. + + • allow programmers to read each other’s code, and al- While it was possible to write portable programs in Scheme + low development of portable programs that can be ex- as described in Revised5 Report on the Algorithmic Lan- + ecuted in any conforming implementation of Scheme; guage Scheme, and indeed portable Scheme programs were + written prior to this report, many Scheme programs were + • derive its power from simplicity, a small number of not, primarily because of the lack of substantial stan- + generally useful core syntactic forms and procedures, dardized libraries and the proliferation of implementation- + and no unnecessary restrictions on how they are com- specific language additions. + posed; + In general, Scheme should include building blocks that al- + • allow programs to define new procedures and new hy- low a wide variety of libraries to be written, include com- + gienic syntactic forms; monly used user-level features to enhance portability and + readability of library and application code, and exclude fea- + • support the representation of program source code as tures that are less commonly used and easily implemented + data; in separate libraries. + + The language described in this report is intended to also be + backward compatible with programs written in Scheme as + 4 Revised6 Scheme + +described in Revised5 Report on the Algorithmic Language Julie Sussman, Perry Wagle, Daniel Weise, Henry Wu, and +Scheme to the extent possible without compromising the Ozan Yigit. +above principles and future viability of the language. With +respect to future viability, the editors have operated under We thank Carol Fessenden, Daniel Friedman, and Christo- +the assumption that many more Scheme programs will be pher Haynes for permission to use text from the Scheme +written in the future than exist in the present, so the fu- 311 version 4 reference manual. We thank Texas In- +ture programs are those with which we should be most struments, Inc. for permission to use text from the TI +concerned. Scheme Language Reference Manual [26]. We gladly ac- + knowledge the influence of manuals for MIT Scheme [20], +Acknowledgements T [21], Scheme 84 [12], Common Lisp [25], Chez Scheme [8], + PLT Scheme [11], and Algol 60 [1]. +Many people contributed significant help to this revision +of the report. Specifically, we thank Aziz Ghuloum and We also thank Betty Dexter for the extreme effort she put +Andr´e van Tonder for contributing reference implemen- into setting this report in TEX, and Donald Knuth for de- +tations of the library system. We thank Alan Bawden, signing the program that caused her troubles. +John Cowan, Sebastian Egner, Aubrey Jaffer, Shiro Kawai, +Bradley Lucier, and Andr´e van Tonder for contributing in- The Artificial Intelligence Laboratory of the Massachusetts +sights on language design. Marc Feeley, Martin Gasbichler, Institute of Technology, the Computer Science Department +Aubrey Jaffer, Lars T Hansen, Richard Kelsey, Olin Shiv- of Indiana University, the Computer and Information Sci- +ers, and Andr´e van Tonder wrote SRFIs that served as ences Department of the University of Oregon, and the +direct input to the report. Marcus Crestani, David Frese, NEC Research Institute supported the preparation of this +Aziz Ghuloum, Arthur A. Gleckler, Eric Knauel, Jonathan report. Support for the MIT work was provided in part by +Rees, and Andr´e van Tonder thoroughly proofread early the Advanced Research Projects Agency of the Department +versions of the report. of Defense under Office of Naval Research contract N00014- + 80-C-0505. Support for the Indiana University work was +We would also like to thank the following people for their provided by NSF grants NCS 83-04567 and NCS 83-03325. +help in creating this report: Lauri Alanko, Eli Barzilay, +Alan Bawden, Brian C. Barnes, Per Bothner, Trent Buck, +Thomas Bushnell, Taylor Campbell, Ludovic Court`es, Pas- +cal Costanza, John Cowan, Ray Dillinger, Jed Davis, J.A. +“Biep” Durieux, Carl Eastlund, Sebastian Egner, Tom +Emerson, Marc Feeley, Matthias Felleisen, Andy Free- +man, Ken Friedenbach, Martin Gasbichler, Arthur A. +Gleckler, Aziz Ghuloum, Dave Gurnell, Lars T Hansen, +Ben Harris, Sven Hartrumpf, Dave Herman, Nils M. +Holm, Stanislav Ievlev, James Jackson, Aubrey Jaffer, +Shiro Kawai, Alexander Kjeldaas, Eric Knauel, Michael +Lenaghan, Felix Klock, Donovan Kolbly, Marcin Kowal- +czyk, Thomas Lord, Bradley Lucier, Paulo J. Matos, Dan +Muresan, Ryan Newton, Jason Orendorff, Erich Rast, +Jeff Read, Jonathan Rees, Jorgen Scha¨fer, Paul Schlie, +Manuel Serrano, Olin Shivers, Jonathan Shapiro, Jens Axel +Søgaard, Jay Sulzberger, Pinku Surana, Mikael Tillenius, +Sam Tobin-Hochstadt, David Van Horn, Andr´e van Ton- +der, Reinder Verlinde, Alan Watson, Andrew Wilcox, Jon +Wilson, Lynn Winebarger, Keith Wright, and Chongkai +Zhu. + +We would like to thank the following people for their help +in creating the previous revisions of this report: Alan +Bawden, Michael Blair, George Carrette, Andy Cromarty, +Pavel Curtis, Jeff Dalton, Olivier Danvy, Ken Dickey, +Bruce Duba, Marc Feeley, Andy Freeman, Richard Gabriel, +Yekta Gu¨rsel, Ken Haase, Robert Hieb, Paul Hudak, +Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim +Philbin, John Ramsdell, Mike Shaff, Jonathan Shapiro, + 1. Overview of Scheme 5 + +DESCRIPTION OF THE LANGUAGE + +1. Overview of Scheme In Scheme, the argument expressions of a procedure call + are evaluated before the procedure gains control, whether +This chapter gives an overview of Scheme’s semantics. The the procedure needs the result of the evaluation or not. +purpose of this overview is to explain enough about the ba- C, C#, Common Lisp, Python, Ruby, and Smalltalk are +sic concepts of the language to facilitate understanding of other languages that always evaluate argument expressions +the subsequent chapters of the report, which are organized before invoking a procedure. This is distinct from the lazy- +as a reference manual. Consequently, this overview is not evaluation semantics of Haskell, or the call-by-name se- +a complete introduction to the language, nor is it precise mantics of Algol 60, where an argument expression is not +in all respects or normative in any way. evaluated unless its value is needed by the procedure. + +Following Algol, Scheme is a statically scoped program- Scheme’s model of arithmetic provides a rich set of numer- +ming language. Each use of a variable is associated with a ical types and operations on them. Furthermore, it distin- +lexically apparent binding of that variable. guishes exact and inexact number objects: Essentially, an + exact number object corresponds to a number exactly, and +Scheme has latent as opposed to manifest types [28]. Types an inexact number object is the result of a computation +are associated with objects (also called values) rather than that involved rounding or other errors. +with variables. (Some authors refer to languages with la- +tent types as untyped, weakly typed or dynamically typed 1.1. Basic types +languages.) Other languages with latent types are Python, +Ruby, Smalltalk, and other dialects of Lisp. Languages Scheme programs manipulate objects, which are also re- +with manifest types (sometimes referred to as strongly ferred to as values. Scheme objects are organized into sets +typed or statically typed languages) include Algol 60, C, of values called types. This section gives an overview of the +C#, Java, Haskell, and ML. fundamentally important types of the Scheme language. + More types are described in later chapters. +All objects created in the course of a Scheme computation, +including procedures and continuations, have unlimited ex- Note: As Scheme is latently typed, the use of the term type +tent. No Scheme object is ever destroyed. The reason that in this report differs from the use of the term in the context of +implementations of Scheme do not (usually!) run out of other languages, particularly those with manifest typing. +storage is that they are permitted to reclaim the storage +occupied by an object if they can prove that the object Booleans A boolean is a truth value, and can be either +cannot possibly matter to any future computation. Other true or false. In Scheme, the object for “false” is written #f. +languages in which most objects have unlimited extent in- The object for “true” is written #t. In most places where a +clude C#, Java, Haskell, most Lisp dialects, ML, Python, truth value is expected, however, any object different from +Ruby, and Smalltalk. #f counts as true. + +Implementations of Scheme must be properly tail- Numbers Scheme supports a rich variety of numerical +recursive. This allows the execution of an iterative com- data types, including objects representing integers of arbi- +putation in constant space, even if the iterative compu- trary precision, rational numbers, complex numbers, and +tation is described by a syntactically recursive procedure. inexact numbers of various kinds. Chapter 3 gives an +Thus with a properly tail-recursive implementation, iter- overview of the structure of Scheme’s numerical tower. +ation can be expressed using the ordinary procedure-call +mechanics, so that special iteration constructs are useful Characters Scheme characters mostly correspond to +only as syntactic sugar. textual characters. More precisely, they are isomorphic + to the scalar values of the Unicode standard. +Scheme was one of the first languages to support proce- +dures as objects in their own right. Procedures can be Strings Strings are finite sequences of characters with +created dynamically, stored in data structures, returned fixed length and thus represent arbitrary Unicode texts. +as results of procedures, and so on. Other languages with +these properties include Common Lisp, Haskell, ML, Ruby, +and Smalltalk. + +One distinguishing feature of Scheme is that continuations, +which in most other languages only operate behind the +scenes, also have “first-class” status. First-class continu- +ations are useful for implementing a wide variety of ad- +vanced control constructs, including non-local exits, back- +tracking, and coroutines. + 6 Revised6 Scheme + +Symbols A symbol is an object representing a string, structure. Consequently, “superfluous” parentheses, which +the symbol’s name. Unlike strings, two symbols whose are often permissible in mathematical notation and also in +names are spelled the same way are never distinguishable. many programming languages, are not allowed in Scheme. +Symbols are useful for many applications; for instance, they +may be used the way enumerated values are used in other As in many other languages, whitespace (including line +languages. endings) is not significant when it separates subexpressions + of an expression, and can be used to indicate structure. + +Pairs and lists A pair is a data structure with two com- 1.3. Variables and binding +ponents. The most common use of pairs is to represent +(singly linked) lists, where the first component (the “car”) Scheme allows identifiers to stand for locations contain- +represents the first element of the list, and the second com- ing values. These identifiers are called variables. In many +ponent (the “cdr”) the rest of the list. Scheme also has a cases, specifically when the location’s value is never mod- +distinguished empty list, which is the last cdr in a chain of ified after its creation, it is useful to think of the variable +pairs that form a list. as standing for the value directly. + +Vectors Vectors, like lists, are linear data structures rep- (let ((x 23) =⇒ 65 +resenting finite sequences of arbitrary objects. Whereas (y 42)) +the elements of a list are accessed sequentially through the +chain of pairs representing it, the elements of a vector are (+ x y)) +addressed by integer indices. Thus, vectors are more ap- +propriate than lists for random access to elements. In this case, the expression starting with let is a bind- + ing construct. The parenthesized structure following the +Procedures Procedures are values in Scheme. let lists variables alongside expressions: the variable x + alongside 23, and the variable y alongside 42. The let + expression binds x to 23, and y to 42. These bindings are + available in the body of the let expression, (+ x y), and + only there. + +1.2. Expressions + + 1.4. Definitions + +The most important elements of Scheme code are expres- The variables bound by a let expression are local, because +sions. Expressions can be evaluated, producing a value. their bindings are visible only in the let’s body. Scheme +(Actually, any number of values—see section 5.8.) The also allows creating top-level bindings for identifiers as fol- +most fundamental expressions are literal expressions: lows: + +#t =⇒ #t + +23 =⇒ 23 (define x 23) + (define y 42) +This notation means that the expression #t evaluates to (+ x y) =⇒ 65 +#t, that is, the value for “true”, and that the expression +23 evaluates to a number object representing the number (These are actually “top-level” in the body of a top-level +23. program or library; see section 1.12 below.) + +Compound expressions are formed by placing parenthe- The first two parenthesized structures are definitions; they +ses around their subexpressions. The first subexpression create top-level bindings, binding x to 23 and y to 42. Defi- +identifies an operation; the remaining subexpressions are nitions are not expressions, and cannot appear in all places +operands to the operation: where an expression can occur. Moreover, a definition has + no value. +(+ 23 42) =⇒ 65 +(+ 14 (* 23 42)) =⇒ 980 Bindings follow the lexical structure of the program: When + several bindings with the same name exist, a variable refers +In the first of these examples, + is the name of the built- to the binding that is closest to it, starting with its occur- +in operation for addition, and 23 and 42 are the operands. rence in the program and going from inside to outside, and +The expression (+ 23 42) reads as “the sum of 23 and 42”. referring to a top-level binding if no local binding can be +Compound expressions can be nested—the second example found along the way: +reads as “the sum of 14 and the product of 23 and 42”. + +As these examples indicate, compound expressions in (define x 23) +Scheme are always written using the same prefix notation. (define y 42) +As a consequence, the parentheses are needed to indicate (let ((y 43)) + 1. Overview of Scheme 7 + + (+ x y)) =⇒ 66 (define (h op x y) + =⇒ 67 (op x y)) +(let ((y 43)) + (let ((y 44)) (h + 23 42) =⇒ 65 + (+ x y))) (h * 23 42) =⇒ 966 + +1.5. Forms Procedure definitions are not the only way to create pro- + cedures. A lambda expression creates a new procedure as +While definitions are not expressions, compound ex- an object, with no need to specify a name: +pressions and definitions exhibit similar syntactic struc- +ture: ((lambda (x) (+ x 42)) 23) =⇒ 65 + + (define x 23) The entire expression in this example is a procedure call; + (* x 2) (lambda (x) (+ x 42)), evaluates to a procedure that + takes a single number object and adds 42 to it. +While the first line contains a definition, and the second +an expression, this distinction depends on the bindings for 1.7. Procedure calls and syntactic key- +define and *. At the purely syntactical level, both are words +forms, and form is the general name for a syntactic part +of a Scheme program. In particular, 23 is a subform of the Whereas (+ 23 42), (f 23), and ((lambda (x) (+ x +form (define x 23). 42)) 23) are all examples of procedure calls, lambda and + let expressions are not. This is because let, even though +1.6. Procedures it is an identifier, is not a variable, but is instead a syn- + tactic keyword . A form that has a syntactic keyword as its +Definitions can also be used to define procedures: first subexpression obeys special rules determined by the + keyword. The define identifier in a definition is also a syn- + (define (f x) tactic keyword. Hence, definitions are also not procedure + (+ x 42)) calls. + +(f 23) =⇒ 65 The rules for the lambda keyword specify that the first + subform is a list of parameters, and the remaining subforms +A procedure is, slightly simplified, an abstraction of an are the body of the procedure. In let expressions, the +expression over objects. In the example, the first defini- first subform is a list of binding specifications, and the +tion defines a procedure called f. (Note the parentheses remaining subforms constitute a body of expressions. +around f x, which indicate that this is a procedure defini- +tion.) The expression (f 23) is a procedure call, meaning, Procedure calls can generally be distinguished from these +roughly, “evaluate (+ x 42) (the body of the procedure) special forms by looking for a syntactic keyword in the first +with x bound to 23”. position of an form: if the first position does not contain + a syntactic keyword, the expression is a procedure call. +As procedures are objects, they can be passed to other (So-called identifier macros allow creating other kinds of +procedures: special forms, but are comparatively rare.) The set of syn- + tactic keywords of Scheme is fairly small, which usually +(define (f x) makes this task fairly simple. It is possible, however, to + (+ x 42)) create new bindings for syntactic keywords; see section 1.9 + below. +(define (g p x) + (p x)) + +(g f 23) =⇒ 65 + +In this example, the body of g is evaluated with p bound to 1.8. Assignment +f and x bound to 23, which is equivalent to (f 23), which +evaluates to 65. Scheme variables bound by definitions or let or lambda + expressions are not actually bound directly to the ob- +In fact, many predefined operations of Scheme are pro- jects specified in the respective bindings, but to loca- +vided not by syntax, but by variables whose values are tions containing these objects. The contents of these lo- +procedures. The + operation, for example, which receives cations can subsequently be modified destructively via as- +special syntactic treatment in many other languages, is just signment : +a regular identifier in Scheme, bound to a procedure that +adds number objects. The same holds for * and many oth- (let ((x 23)) =⇒ 42 +ers: (set! x 42) + x) + 8 Revised6 Scheme + +In this case, the body of the let expression consists of two 1.10. Syntactic data and datum values +expressions which are evaluated sequentially, with the value +of the final expression becoming the value of the entire let A subset of the Scheme objects is called datum values. +expression. The expression (set! x 42) is an assignment, These include booleans, number objects, characters, sym- +saying “replace the object in the location referenced by x bols, and strings as well as lists and vectors whose ele- +with 42”. Thus, the previous value of x, 23, is replaced by ments are data. Each datum value may be represented in +42. textual form as a syntactic datum, which can be written + out and read back in without loss of information. A da- +1.9. Derived forms and macros tum value may be represented by several different syntactic + data. Moreover, each datum value can be trivially trans- +Many of the special forms specified in this report can be lated to a literal expression in a program by prepending a +translated into more basic special forms. For example, a ’ to a corresponding syntactic datum: +let expression can be translated into a procedure call and +a lambda expression. The following two expressions are ’23 =⇒ 23 +equivalent: ’#t =⇒ #t + ’foo =⇒ foo +(let ((x 23) ’(1 2 3) =⇒ (1 2 3) + (y 42)) ’#(1 2 3) =⇒ #(1 2 3) + + (+ x y)) =⇒ 65 The ’ shown in the previous examples is not needed for rep- + resentations of number objects or booleans. The syntactic + ((lambda (x y) (+ x y)) 23 42) datum foo represents a symbol with name “foo”, and ’foo + =⇒ 65 is a literal expression with that symbol as its value. (1 2 + 3) is a syntactic datum that represents a list with elements +Special forms like let expressions are called derived forms 1, 2, and 3, and ’(1 2 3) is a literal expression with this +because their semantics can be derived from that of other list as its value. Likewise, #(1 2 3) is a syntactic datum +kinds of forms by a syntactic transformation. Some proce- that represents a vector with elements 1, 2 and 3, and ’#(1 +dure definitions are also derived forms. The following two 2 3) is the corresponding literal. +definitions are equivalent: + The syntactic data are a superset of the Scheme forms. + (define (f x) Thus, data can be used to represent Scheme forms as data + (+ x 42)) objects. In particular, symbols can be used to represent + identifiers. + (define f + (lambda (x) ’(+ 23 42) =⇒ (+ 23 42) + (+ x 42))) + ’(define (f x) (+ x 42)) +In Scheme, it is possible for a program to create its own +derived forms by binding syntactic keywords to macros: =⇒ (define (f x) (+ x 42)) + + (define-syntax def This facilitates writing programs that operate on Scheme + (syntax-rules () source code, in particular interpreters and program trans- + ((def f (p ...) body) formers. + (define (f p ...) + body)))) + + (def f (x) 1.11. Continuations + (+ x 42)) + Whenever a Scheme expression is evaluated there is a con- +The define-syntax construct specifies that a parenthe- tinuation wanting the result of the expression. The con- +sized structure matching the pattern (def f (p ...) tinuation represents an entire (default) future for the com- +body), where f, p, and body are pattern variables, is trans- putation. For example, informally the continuation of 3 in +lated to (define (f p ...) body). Thus, the def form the expression +appearing in the example gets translated to: + (+ 1 3) + (define (f x) + (+ x 42)) adds 1 to it. Normally these ubiquitous continuations + are hidden behind the scenes and programmers do not +The ability to create new syntactic keywords makes Scheme think much about them. On rare occasions, however, a +extremely flexible and expressive, allowing many of the programmer may need to deal with continuations explic- +features built into other languages to be derived forms in itly. The call-with-current-continuation procedure +Scheme. (see section 11.15) allows Scheme programmers to do that + 2. Requirement levels 9 + +by creating a procedure that reinstates the current continu- procedure from the (rnrs programs (6)) library (see +ation. The call-with-current-continuation procedure library chapter 10). It then opens the file using +accepts a procedure, calls it immediately with an argu- open-file-input-port (see library section 8.2, yielding +ment that is an escape procedure. This escape procedure a port, i.e. a connection to the file as a data source, and +can then be called with an argument that becomes the calls the get-bytes-all procedure to obtain the contents +result of the call to call-with-current-continuation. of the file as binary data. It then uses put-bytes to output +That is, the escape procedure abandons its own con- the contents of the file to standard output: +tinuation, and reinstates the continuation of the call to +call-with-current-continuation. #!r6rs + (import (rnrs base) +In the following example, an escape procedure representing +the continuation that adds 1 to its argument is bound to (rnrs io ports) +escape, and then called with 3 as an argument. The con- (rnrs programs)) +tinuation of the call to escape is abandoned, and instead (put-bytes (standard-output-port) +the 3 is passed to the continuation that adds 1: + (call-with-port + (+ 1 (call-with-current-continuation (open-file-input-port + (lambda (escape) (cadr (command-line))) + (+ 2 (escape 3))))) + =⇒ 4 get-bytes-all)) + +An escape procedure has unlimited extent: It can be 2. Requirement levels +called after the continuation it captured has been in- +voked, and it can be called multiple times. This The key words “must”, “must not”, “should”, “should +makes call-with-current-continuation significantly not”, “recommended”, “may”, and “optional” in this re- +more powerful than typical non-local control constructs port are to be interpreted as described in RFC 2119 [3]. +such as exceptions in other languages. Specifically: + +1.12. Libraries must This word means that a statement is an absolute + requirement of the specification. +Scheme code can be organized in components called li- +braries. Each library contains definitions and expressions. must not This phrase means that a statement is an ab- +It can import definitions from other libraries and export solute prohibition of the specification. +definitions to other libraries. + should This word, or the adjective “recommended”, +The following library called (hello) exports a definition means that valid reasons may exist in particular cir- +called hello-world, and imports the base library (see cumstances to ignore a statement, but that the impli- +chapter 11) and the simple I/O library (see library sec- cations must be understood and weighed before choos- +tion 8.3). The hello-world export is a procedure that ing a different course. +displays Hello World on a separate line: + should not This phrase, or the phrase “not recom- + (library (hello) mended”, means that valid reasons may exist in par- + (export hello-world) ticular circumstances when the behavior of a state- + (import (rnrs base) ment is acceptable, but that the implications should + (rnrs io simple)) be understood and weighed before choosing the course + (define (hello-world) described by the statement. + (display "Hello World") + (newline))) may This word, or the adjective “optional”, means that + an item is truly optional. + +1.13. Top-level programs In particular, this report occasionally uses “should” to des- + ignate circumstances that are outside the specification of +A Scheme program is invoked via a top-level program. Like this report, but cannot be practically detected by an im- +a library, a top-level program contains imports, definitions plementation; see section 5.4. In such circumstances, a +and expressions, and specifies an entry point for execution. particular implementation may allow the programmer to +Thus a top-level program defines, via the transitive closure ignore the recommendation of the report and even exhibit +of the libraries it imports, a Scheme program. reasonable behavior. However, as the report does not spec- + ify the behavior, these programs may be unportable, that +The following top-level program obtains the first ar- is, their execution might produce different results on dif- +gument from the command line via the command-line ferent implementations. + 10 Revised6 Scheme + +Moreover, this report occasionally uses the phrase “not re- may need to know the index exactly, as may some opera- +quired” to note the absence of an absolute requirement. tions on polynomial coefficients in a symbolic algebra sys- + tem. On the other hand, the results of measurements are +3. Numbers inherently inexact, and irrational numbers may be approx- + imated by rational and therefore inexact approximations. +This chapter describes Scheme’s model for numbers. It is In order to catch uses of numbers known only inexactly +important to distinguish between the mathematical num- where exact numbers are required, Scheme explicitly dis- +bers, the Scheme objects that attempt to model them, the tinguishes exact from inexact number objects. This dis- +machine representations used to implement the numbers, tinction is orthogonal to the dimension of type. +and notations used to write numbers. In this report, the +term number refers to a mathematical number, and the A number object is exact if it is the value of an exact nu- +term number object refers to a Scheme object representing merical literal or was derived from exact number objects +a number. This report uses the types complex, real, ra- using only exact operations. Exact number objects corre- +tional, and integer to refer to both mathematical numbers spond to mathematical numbers in the obvious way. +and number objects. The fixnum and flonum types refer +to special subsets of the number objects, as determined by Conversely, a number object is inexact if it is the value of +common machine representations, as explained below. an inexact numerical literal, or was derived from inexact + number objects, or was derived using inexact operations. +3.1. Numerical tower Thus inexactness is contagious. + +Numbers may be arranged into a tower of subsets in which Exact arithmetic is reliable in the following sense: If ex- +each level is a subset of the level above it: act number objects are passed to any of the arithmetic + procedures described in section 11.7.1, and an exact num- + number ber object is returned, then the result is mathematically + complex correct. This is generally not true of computations involv- + real ing inexact number objects because approximate methods + rational such as floating-point arithmetic may be used, but it is the + integer duty of each implementation to make the result as close as + practical to the mathematically ideal result. +For example, 5 is an integer. Therefore 5 is also a rational, +a real, and a complex. The same is true of the number 3.3. Fixnums and flonums +objects that model 5. + A fixnum is an exact integer object that lies within a cer- +Number objects are organized as a corresponding tower tain implementation-dependent subrange of the exact in- +of subtypes defined by the predicates number?, complex?, teger objects. (Library section 11.2 describes a library for +real?, rational?, and integer?; see section 11.7.4. Inte- computing with fixnums.) Likewise, every implementation +ger number objects are also called integer objects. must designate a subset of its inexact real number objects + as flonums, and to convert certain external representations +There is no simple relationship between the subset that into flonums. (Library section 11.3 describes a library for +contains a number and its representation inside a com- computing with flonums.) Note that this does not imply +puter. For example, the integer 5 may have several rep- that an implementation must use floating-point represen- +resentations. Scheme’s numerical operations treat number tations. +objects as abstract data, as independent of their represen- +tation as possible. Although an implementation of Scheme 3.4. Implementation requirements +may use many different representations for numbers, this +should not be apparent to a casual programmer writing Implementations of Scheme must support number objects +simple programs. for the entire tower of subtypes given in section 3.1. More- + over, implementations must support exact integer objects +3.2. Exactness and exact rational number objects of practically unlimited + size and precision, and to implement certain procedures +It is useful to distinguish between number objects that are (listed in 11.7.1) so they always return exact results when +known to correspond to a number exactly, and those num- given exact arguments. (“Practically unlimited” means +ber objects whose computation involved rounding or other that the size and precision of these numbers should only +errors. For example, index operations into data structures be limited by the size of the available memory.) + 4. Lexical syntax and datum syntax 11 + +Implementations may support only a limited range of inex- and might even be greater than positive infinity or less +act number objects of any type, subject to the requirements than negative infinity. +of this section. For example, an implementation may limit +the range of the inexact real number objects (and therefore 3.6. Distinguished -0.0 +the range of inexact integer and rational number objects) +to the dynamic range of the flonum format. Furthermore Some Scheme implementations, specifically those that fol- +the gaps between the inexact integer objects and rationals low the IEEE floating-point standards, distinguish between +are likely to be very large in such an implementation as the number objects for 0.0 and −0.0, i.e., positive and nega- +limits of this range are approached. tive inexact zero. This report will sometimes specify the + behavior of certain arithmetic operations on these number +An implementation may use floating point and other ap- objects. These specifications are marked with “if −0.0 is +proximate representation strategies for inexact numbers. distinguished” or “implementations that distinguish −0.0”. +This report recommends, but does not require, that the +IEEE floating-point standards be followed by implementa- 4. Lexical syntax and datum syntax +tions that use floating-point representations, and that im- +plementations using other representations should match or The syntax of Scheme code is organized in three levels: +exceed the precision achievable using these floating-point +standards [13]. 1. the lexical syntax that describes how a program text + is split into a sequence of lexemes, +In particular, implementations that use floating-point rep- +resentations must follow these rules: A floating-point result 2. the datum syntax, formulated in terms of the lexical +must be represented with at least as much precision as is syntax, that structures the lexeme sequence as a se- +used to express any of the inexact arguments to that oper- quence of syntactic data, where a syntactic datum is +ation. Potentially inexact operations such as sqrt, when a recursively structured entity, +applied to exact arguments, should produce exact answers +whenever possible (for example the square root of an exact 3. the program syntax formulated in terms of the read +4 ought to be an exact 2). However, this is not required. syntax, imposing further structure and assigning +If, on the other hand, an exact number object is operated meaning to syntactic data. +upon so as to produce an inexact result (as by sqrt), and +if the result is represented in floating point, then the most Syntactic data (also called external representations) double +precise floating-point format available must be used; but if as a notation for objects, and Scheme’s (rnrs io ports +the result is represented in some other way then the repre- (6)) library (library section 8.2) provides the get-datum +sentation must have at least as much precision as the most and put-datum procedures for reading and writing syntac- +precise floating-point format available. tic data, converting between their textual representation + and the corresponding objects. Each syntactic datum rep- +It is the programmer’s responsibility to avoid using inexact resents a corresponding datum value. A syntactic datum +number objects with magnitude or significand too large to can be used in a program to obtain the corresponding da- +be represented in the implementation. tum value using quote (see section 11.4.1). + +3.5. Infinities and NaNs Scheme source code consists of syntactic data and (non- + significant) comments. Syntactic data in Scheme source +Some Scheme implementations, specifically those that fol- code are called forms. (A form nested inside another form +low the IEEE floating-point standards, distinguish special is called a subform.) Consequently, Scheme’s syntax has +number objects called positive infinity, negative infinity, the property that any sequence of characters that is a form +and NaN. is also a syntactic datum representing some object. This + can lead to confusion, since it may not be obvious out of +Positive infinity is regarded as an inexact real (but not context whether a given sequence of characters is intended +rational) number object that represents an indeterminate to be a representation of objects or the text of a program. +number greater than the numbers represented by all ra- It is also a source of power, since it facilitates writing pro- +tional number objects. Negative infinity is regarded as an grams such as interpreters or compilers that treat programs +inexact real (but not rational) number object that rep- as objects (or vice versa). +resents an indeterminate number less than the numbers +represented by all rational numbers. A datum value may have several different external repre- + sentations. For example, both “#e28.000” and “#x1c” are +A NaN is regarded as an inexact real (but not rational) syntactic data representing the exact integer object 28, and +number object so indeterminate that it might represent the syntactic data “(8 13)”, “( 08 13 )”, “(8 . (13 . +any real number, including positive or negative infinity, + 12 Revised6 Scheme + +()))” all represent a list containing the exact integer ob- as part of the datum syntax. Being comments, however, +jects 8 and 13. Syntactic data that represent equal objects these datum s do not play a significant role in the syntax. +(in the sense of equal?; see section 11.5) are always equiv- +alent as forms of a program. Case is significant except in representations of booleans, + number objects, and in hexadecimal numbers specifying +Because of the close correspondence between syntactic data Unicode scalar values. For example, #x1A and #X1a are +and datum values, this report sometimes uses the term equivalent. The identifier Foo is, however, distinct from +datum for either a syntactic datum or a datum value when the identifier FOO. +the exact meaning is apparent from the context. + 4.2.1. Formal account +An implementation must not extend the lexical or datum +syntax in any way, with one exception: it need not treat the Interlexeme space may occur on either side of any lexeme, +syntax #! identifier , for any identifier (see section 4.2.4) but not within a lexeme. +that is not r6rs, as a syntax violation, and it may use +specific #!-prefixed identifiers as flags indicating that sub- Identifier s, ., number s, character s, and boolean s, +sequent input contains extensions to the standard lexical or must be terminated by a delimiter or by the end of the +datum syntax. The syntax #!r6rs may be used to signify input. +that the input afterward is written with the lexical syn- +tax and datum syntax described by this report. #!r6rs is The following two characters are reserved for future exten- +otherwise treated as a comment; see section 4.2.3. sions to the language: { } + +4.1. Notation lexeme −→ identifier | boolean | number + | character | string +The formal syntax for Scheme is written in an extended | ( | ) | [ | ] | #( | #vu8( | ’ | ` | , | ,@ | . +BNF. Non-terminals are written using angle brackets. Case | #’ | #` | #, | #,@ +is insignificant for non-terminal names. + delimiter −→ ( | ) | [ | ] | " | ; | # +All spaces in the grammar are for legibility. Empty | whitespace +stands for the empty string. + whitespace −→ character tabulation +The following extensions to BNF are used to make the de- | linefeed | line tabulation | form feed +scription more concise: thing * means zero or more occur- | carriage return | next line +rences of thing , and thing + means at least one thing . | any character whose category is Zs, Zl, or Zp + +Some non-terminal names refer to the Unicode scalar val- line ending −→ linefeed | carriage return +ues of the same name: character tabulation (U+0009), | carriage return linefeed | next line + linefeed (U+000A), carriage return (U+000D), | carriage return next line | line separator + line tabulation (U+000B), form feed (U+000C), + carriage return (U+000D), space (U+0020), comment −→ ; all subsequent characters up to a + next line (U+0085), line separator (U+2028), and line ending or paragraph separator + paragraph separator (U+2029). + | nested comment +4.2. Lexical syntax | #; interlexeme space datum + | #!r6rs +The lexical syntax determines how a character sequence is nested comment −→ #| comment text +split into a sequence of lexemes, omitting non-significant +portions such as comments and whitespace. The character comment cont * |# +sequence is assumed to be text according to the Unicode comment text −→ character sequence not containing +standard [27]. Some of the lexemes, such as identifiers, +representations of number objects, strings etc., of the lex- #| or |# +ical syntax are syntactic data in the datum syntax, and comment cont −→ nested comment comment text +thus represent objects. Besides the formal account of the atmosphere −→ whitespace | comment +syntax, this section also describes what datum values are interlexeme space −→ atmosphere * +represented by these syntactic data. + identifier −→ initial subsequent * +The lexical syntax, in the description of comments, con- | peculiar identifier +tains a forward reference to datum , which is described + initial −→ constituent | special initial + | inline hex escape + + letter −→ a | b | c | ... | z + | A | B | C | ... | Z + + constituent −→ letter + | any character whose Unicode scalar value is greater than + 127, and whose category is Lu, Ll, Lt, Lm, Lo, Mn, + Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co + 4. Lexical syntax and datum syntax 13 + + special initial −→ ! | $ | % | & | * | / | : | < | = | . digit 10 + suffix + |>|?|^|_|~ | digit 10 + . digit 10 * suffix + | digit 10 + . suffix + subsequent −→ initial | digit uinteger R −→ digit R + + | any character whose category is Nd, Mc, or Me prefix R −→ radix R exactness + | special subsequent | exactness radix R + + digit −→ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 suffix −→ empty + hex digit −→ digit | exponent marker sign digit 10 + + + |a|A|b|B|c|C|d|D|e|E|f|F exponent marker −→ e | E | s | S | f | F + special subsequent −→ + | - | . | @ |d|D|l|L + inline hex escape −→ \x hex scalar value ; + hex scalar value −→ hex digit + mantissa width −→ empty + peculiar identifier −→ + | - | ... | -> subsequent * | | digit 10 + + boolean −→ #t | #T | #f | #F + character −→ #\ any character sign −→ empty | + | - + exactness −→ empty + | #\ character name + | #\x hex scalar value | #i | #I | #e | #E + character name −→ nul | alarm | backspace | tab radix 2 −→ #b | #B + | linefeed | newline | vtab | page | return radix 8 −→ #o | #O + | esc | space | delete radix 10 −→ empty | #d | #D + string −→ " string element * " radix 16 −→ #x | #X + string element −→ any character other than " or \ digit 2 −→ 0 | 1 + | \a | \b | \t | \n | \v | \f | \r digit 8 −→ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 + | \" | \\ digit 10 −→ digit + | \ intraline whitespace line ending digit 16 −→ hex digit + + intraline whitespace 4.2.2. Line endings + | inline hex escape + intraline whitespace −→ character tabulation Line endings are significant in Scheme in single-line com- + | any character whose category is Zs ments (see section 4.2.3) and within string literals. In + Scheme source code, any of the line endings in line ending +A hex scalar value represents a Unicode scalar marks the end of a line. Moreover, the two-character line +value between 0 and #x10FFFF, excluding the range endings carriage return linefeed and carriage return +[#xD800, #xDFFF]. next line each count as a single line ending. + +The rules for num R , complex R , real R , ureal R , In a string literal, a line ending not preceded by a \ + uinteger R , and prefix R below should be replicated for stands for a linefeed character, which is the standard line- +R = 2, 8, 10, and 16. There are no rules for decimal 2 , ending character of Scheme. + decimal 8 , and decimal 16 , which means that num- +ber representations containing decimal points or exponents 4.2.3. Whitespace and comments +must be in decimal radix. + Whitespace characters are spaces, linefeeds, carriage re- + number −→ num 2 | num 8 turns, character tabulations, form feeds, line tabulations, + | num 10 | num 16 and any other character whose category is Zs, Zl, or Zp. + Whitespace is used for improved readability and as nec- + num R −→ prefix R complex R essary to separate lexemes from each other. Whitespace + complex R −→ real R | real R @ real R may occur between any two lexemes, but not within a lex- + eme. Whitespace may also occur inside a string, where it + | real R + ureal R i | real R - ureal R i is significant. + | real R + naninf i | real R - naninf i + | real R + i | real R - i The lexical syntax includes several comment forms. In all + | + ureal R i | - ureal R i cases, comments are invisible to Scheme, except that they + | + naninf i | - naninf i act as delimiters, so, for example, a comment cannot ap- + |+i|-i pear in the middle of an identifier or representation of a + real R −→ sign ureal R number object. + | + naninf | - naninf + naninf −→ nan.0 | inf.0 + ureal R −→ uinteger R + | uinteger R / uinteger R + | decimal R mantissa width + decimal 10 −→ uinteger 10 suffix + 14 Revised6 Scheme + +A semicolon (;) indicates the start of a line comment. The specified via an inline hex escape . For example, the iden- +comment continues to the end of the line on which the tifier H\x65;llo is the same as the identifier Hello, and +semicolon appears. the identifier \x3BB; is the same as the identifier λ. + +Another way to indicate a comment is to prefix a Any identifier may be used as a variable or as a syntactic + datum (cf. section 4.3.1) with #;, possibly with keyword (see sections 5.2 and 9.2) in a Scheme program. + interlexeme space before the datum . The comment Any identifier may also be used as a syntactic datum, in +consists of the comment prefix #; and the datum to- which case it represents a symbol (see section 11.10). +gether. This notation is useful for “commenting out” sec- +tions of code. 4.2.5. Booleans + +Block comments may be indicated with properly nested #| The standard boolean objects for true and false have ex- +and |# pairs. ternal representations #t and #f. + +#| + + The FACT procedure computes the factorial + + of a non-negative integer. 4.2.6. Characters + +|# + +(define fact Characters are represented using the nota- + tion #\ character or #\ character name or +(lambda (n) #\x hex scalar value . + + ;; base case For example: + + (if (= n 0) + + #;(= n 1) + + 1 ; identity of * + + (* n (fact (- n 1)))))) #\a lower case letter a + #\A upper case letter A +The lexeme #!r6rs, which signifies that the program text #\( left parenthesis +that follows is written with the lexical and datum syntax #\ space character +described in this report, is also otherwise treated as a com- #\nul U+0000 +ment. #\alarm U+0007 + #\backspace U+0008 +4.2.4. Identifiers #\tab U+0009 + #\linefeed U+000A +Most identifiers allowed by other programming languages #\newline U+000A +are also acceptable to Scheme. In general, a sequence of #\vtab U+000B +letters, digits, and “extended alphabetic characters” is an #\page U+000C +identifier when it begins with a character that cannot be- #\return U+000D +gin a representation of a number object. In addition, +, #\esc U+001B +-, and ... are identifiers, as is a sequence of letters, dig- #\space U+0020 +its, and extended alphabetic characters that begins with preferred way to write a space +the two-character sequence ->. Here are some examples of #\delete U+007F +identifiers: + #\xFF U+00FF +lambda q soup #\x03BB U+03BB + #\x00006587 U+6587 +list->vector + V17a #\λ U+03BB + +<= a34kTMNs ->- + +the-word-recursion-has-many-meanings #\x0001z &lexical exception + #\λx &lexical exception +Extended alphabetic characters may be used within iden- #\alarmx &lexical exception +tifiers as if they were letters. The following are extended #\alarm x U+0007 +alphabetic characters: followed by x + #\Alarm &lexical exception + !$%&*+-./:<=>?@^_~ #\alert &lexical exception + #\xA U+000A +Moreover, all characters whose Unicode scalar values are #\xFF U+00FF +greater than 127 and whose Unicode category is Lu, Ll, #\xff U+00FF +Lt, Lm, Lo, Mn, Mc, Me, Nd, Nl, No, Pd, Pc, Po, Sc, #\x ff U+0078 +Sm, Sk, So, or Co can be used within identifiers. In addi- followed by another datum, ff +tion, any character can be used within an identifier when + 4. Lexical syntax and datum syntax 15 + +#\x(ff) U+0078 These escape sequences are case-sensitive, except that the + alphabetic digits of a hex scalar value can be uppercase + followed by another datum, or lowercase. + + a parenthesized ff + +#\(x) &lexical exception Any other character in a string after a backslash is a syntax + violation. Except for a line ending, any character outside +#\(x &lexical exception of an escape sequence and not a doublequote stands for + itself in the string literal. For example the single-character +#\((x) U+0028 string literal "λ" (doublequote, a lower case lambda, dou- + blequote) represents the same string as "\x03bb;". A line + followed by another datum, ending that does not follow a backslash stands for a linefeed + character. + parenthesized x + +#\x00110000 &lexical exception + + out of range + +#\x000000001 U+0001 + +#\xD800 &lexical exception Examples: + + in excluded range + +(The notation &lexical exception means that the line in "abc" U+0061, U+0062, U+0063 +question is a lexical syntax violation.) "\x41;bc" "Abc" ; U+0041, U+0062, U+0063 + "\x41; bc" "A bc" +Case is significant in #\ character , and in #\ character U+0041, U+0020, U+0062, U+0063 +name , but not in #\x hex scalar value . A character "\x41bc;" U+41BC +must be followed by a delimiter or by the end of the in- "\x41" &lexical exception +put. This rule resolves various ambiguous cases involving "\x;" &lexical exception +named characters, requiring, for example, the sequence of "\x41bx;" &lexical exception +characters “#\space” to be interpreted as the space char- "\x00000041;" "A" ; U+0041 +acter rather than as the character “#\s” followed by the "\x0010FFFF;" U+10FFFF +identifier “pace”. "\x00110000;" &lexical exception + out of range +Note: The #\newline notation is retained for backward com- "\x000000001;" U+0001 +patibility. Its use is deprecated; #\linefeed should be used "\xD800;" &lexical exception +instead. in excluded range + "A +4.2.7. Strings bc" U+0041, U+000A, U+0062, U+0063 + if no space occurs after the A +String are represented by sequences of characters enclosed +within doublequotes ("). Within a string literal, various es- 4.2.8. Numbers +cape sequences represent characters other than themselves. +Escape sequences always start with a backslash (\): The syntax of external representations for number objects + is described formally by the number rule in the formal + • \a : alarm, U+0007 grammar. Case is not significant in external representa- + • \b : backspace, U+0008 tions of number objects. + • \t : character tabulation, U+0009 + • \n : linefeed, U+000A A representation of a number object may be written in bi- + • \v : line tabulation, U+000B nary, octal, decimal, or hexadecimal by the use of a radix + • \f : formfeed, U+000C prefix. The radix prefixes are #b (binary), #o (octal), #d + • \r : return, U+000D (decimal), and #x (hexadecimal). With no radix prefix, + • \" : doublequote, U+0022 a representation of a number object is assumed to be ex- + • \\ : backslash, U+005C pressed in decimal. + • \ intraline whitespace line ending + A representation of a number object may be specified to + intraline whitespace : nothing be either exact or inexact by a prefix. The prefixes are + • \x hex scalar value ; : specified character (note the #e for exact, and #i for inexact. An exactness prefix may + appear before or after any radix prefix that is used. If the + terminating semi-colon). representation of a number object has no exactness prefix, + the constant is inexact if it contains a decimal point, an + exponent, or a nonempty mantissa width; otherwise it is + exact. + + In systems with inexact number objects of varying preci- + sions, it may be useful to specify the precision of a constant. + 16 Revised6 Scheme + +For this purpose, representations of number objects may be If x is an external representation of an inexact real number +written with an exponent marker that indicates the desired object and contains no vertical bar and no exponent marker +precision of the inexact representation. The letters s, f, d, other than e, the inexact real number object it represents +and l specify the use of short, single, double, and long is a flonum (see library section 11.3). Some or all of the +precision, respectively. (When fewer than four internal in- other external representations of inexact real number ob- +exact representations exist, the four size specifications are jects may also represent flonums, but that is not required +mapped onto those available. For example, an implementa- by this report. +tion with two internal representations may map short and +single together and long and double together.) In addition, 4.3. Datum syntax +the exponent marker e specifies the default precision for +the implementation. The default precision has at least as The datum syntax describes the syntax of syntactic data in +much precision as double, but implementations may wish terms of a sequence of lexeme s, as defined in the lexical +to allow this default to be set by the user. syntax. + + 3.1415926535898F0 Syntactic data include the lexeme data described in the + Round to single, perhaps 3.141593 previous section as well as the following constructs for + forming compound data: + 0.6L0 + Extend to long, perhaps .600000000000000 • pairs and lists, enclosed by ( ) or [ ] (see sec- + tion 4.3.2) +A representation of a number object with nonempty man- +tissa width, x |p, represents the best binary floating-point • vectors (see section 4.3.3) +approximation of x using a p-bit significand. For example, +1.1|53 is a representation of the best approximation of • bytevectors (see section 4.3.4) +1.1 in IEEE double precision. If x is an external represen- +tation of an inexact real number object that contains no 4.3.1. Formal account +vertical bar, then its numerical value should be computed +as though it had a mantissa width of 53 or more. The following grammar describes the syntax of syntactic + data in terms of various kinds of lexemes defined in the +Implementations that use binary floating-point representa- grammar in section 4.2: +tions of real number objects should represent x |p using a +p-bit significand if practical, or by a greater precision if a datum −→ lexeme datum +p-bit significand is not practical, or by the largest available | compound datum +precision if p or more bits of significand are not practical +within the implementation. lexeme datum −→ boolean | number + | character | string | symbol +Note: The precision of a significand should not be confused +with the number of bits used to represent the significand. In the symbol −→ identifier +IEEE floating-point standards, for example, the significand’s compound datum −→ list | vector | bytevector +most significant bit is implicit in single and double precision list −→ ( datum *) | [ datum *] +but is explicit in extended precision. Whether that bit is im- +plicit or explicit does not affect the mathematical precision. In | ( datum + . datum ) | [ datum + . datum ] +implementations that use binary floating point, the default pre- | abbreviation +cision can be calculated by calling the following procedure: abbreviation −→ abbrev prefix datum + abbrev prefix −→ ’ | ` | , | ,@ + (define (precision) | #’ | #` | #, | #,@ + (do ((n 0 (+ n 1)) vector −→ #( datum *) + (x 1.0 (/ x 2.0))) bytevector −→ #vu8( u8 *) + ((= 1.0 (+ 1.0 x)) n))) u8 −→ any number representing an exact + +Note: When the underlying floating-point representation is integer in {0, . . . , 255} +IEEE double precision, the |p suffix should not always be omit- +ted: Denormalized floating-point numbers have diminished pre- 4.3.2. Pairs and lists +cision, and therefore their external representations should carry +a |p suffix with the actual width of the significand. List and pair data, representing pairs and lists of values (see + section 11.9) are represented using parentheses or brackets. +The literals +inf.0 and -inf.0 represent positive and neg- Matching pairs of brackets that occur in the rules of list +ative infinity, respectively. The +nan.0 literal represents are equivalent to matching pairs of parentheses. +the NaN that is the result of (/ 0.0 0.0), and may rep- +resent other NaNs as well. + 5. Semantic concepts 17 + +The most general notation for Scheme pairs as syntac- 4.3.5. Abbreviations +tic data is the “dotted” notation ( datum1 . datum2 ) +where datum1 is the representation of the value of the ’ datum +car field and datum2 is the representation of the value of ` datum +the cdr field. For example (4 . 5) is a pair whose car is , datum +4 and whose cdr is 5. ,@ datum + #’ datum +A more streamlined notation can be used for lists: the #` datum +elements of the list are simply enclosed in parentheses and #, datum +separated by spaces. The empty list is represented by () . #,@ datum +For example, + Each of these is an abbreviation: + (a b c d e) ’ datum for (quote datum ), + ` datum for (quasiquote datum ), +and , datum for (unquote datum ), + ,@ datum for (unquote-splicing datum ), + (a . (b . (c . (d . (e . ()))))) #’ datum for (syntax datum ), + #` datum for (quasisyntax datum ), +are equivalent notations for a list of symbols. #, datum for (unsyntax datum ), and + #,@ datum for (unsyntax-splicing datum ). +The general rule is that, if a dot is followed by an open +parenthesis, the dot, open parenthesis, and matching clos- 5. Semantic concepts +ing parenthesis can be omitted in the external representa- +tion. 5.1. Programs and libraries + +The sequence of characters “(4 . 5)” is the external rep- A Scheme program consists of a top-level program together +resentation of a pair, not an expression that evaluates to a with a set of libraries, each of which defines a part of the +pair. Similarly, the sequence of characters “(+ 2 6)” is not program connected to the others through explicitly spec- +an external representation of the integer 8, even though it ified exports and imports. A library consists of a set of +is an expression (in the language of the (rnrs base (6)) export and import specifications and a body, which con- +library) evaluating to the integer 8; rather, it is a syntac- sists of definitions, and expressions. A top-level program is +tic datum representing a three-element list, the elements similar to a library, but has no export specifications. Chap- +of which are the symbol + and the integers 2 and 6. ters 7 and 8 describe the syntax and semantics of libraries + and top-level programs, respectively. Chapter 11 describes +4.3.3. Vectors a base library that defines many of the constructs tradi- + tionally associated with Scheme. A separate report [24] de- +Vector data, representing vectors of objects (see sec- scribes the various standard libraries provided by a Scheme +tion 11.13), are represented using the notation #( datum system. +. . . ). For example, a vector of length 3 containing the +number object for zero in element 0, the list (2 2 2 2) The division between the base library and the other stan- +in element 1, and the string "Anna" in element 2 can be dard libraries is based on use, not on construction. In par- +represented as follows: ticular, some facilities that are typically implemented as + “primitives” by a compiler or the run-time system rather + #(0 (2 2 2 2) "Anna") than in terms of other standard procedures or syntactic + forms are not part of the base library, but are defined in +This is the external representation of a vector, not an ex- separate libraries. Examples include the fixnums and flon- +pression that evaluates to a vector. ums libraries, the exceptions and conditions libraries, and + the libraries for records. +4.3.4. Bytevectors + 5.2. Variables, keywords, and regions +Bytevector data, representing bytevectors (see library +chapter 2), are represented using the notation #vu8( u8 Within the body of a library or top-level program, an iden- +. . . ), where the u8 s represent the octets of the bytevec- tifier may name a kind of syntax, or it may name a location +tor. For example, a bytevector of length 3 containing the where a value can be stored. An identifier that names a +octets 2, 24, and 123 can be represented as follows: + + #vu8(2 24 123) + +This is the external representation of a bytevector, and also +an expression that evaluates to a bytevector. + 18 Revised6 Scheme + +kind of syntax is called a keyword, or syntactic keyword, 5.3. Exceptional situations +and is said to be bound to that kind of syntax (or, in the +case of a syntactic abstraction, a transformer that trans- A variety of exceptional situations are distinguished in this +lates the syntax into more primitive forms; see section 9.2). report, among them violations of syntax, violations of a +An identifier that names a location is called a variable and procedure’s specification, violations of implementation re- +is said to be bound to that location. At each point within strictions, and exceptional situations in the environment. +a top-level program or a library, a specific, fixed set of When an exceptional situation is detected by the imple- +identifiers is bound. The set of these identifiers, the set of mentation, an exception is raised , which means that a +visible bindings, is known as the environment in effect at special procedure called the current exception handler is +that point. called. A program can also raise an exception, and over- + ride the current exception handler; see library section 7.1. +Certain forms are used to create syntactic abstractions and +to bind keywords to transformers for those new syntactic When an exception is raised, an object is provided that de- +abstractions, while other forms create new locations and scribes the nature of the exceptional situation. The report +bind variables to those locations. Collectively, these forms uses the condition system described in library section 7.2 +are called binding constructs. Some binding constructs take to describe exceptional situations, classifying them by con- +the form of definitions, while others are expressions. With dition types. +the exception of exported library bindings, a binding cre- +ated by a definition is visible only within the body in which Some exceptional situations allow continuing the program +the definition appears, e.g., the body of a library, top-level if the exception handler takes appropriate action. The cor- +program, or lambda expression. Exported library bindings responding exceptions are called continuable. For most of +are also visible within the bodies of the libraries and top- the exceptional situations described in this report, portable +level programs that import them (see chapter 7). programs cannot rely upon the exception being continuable + at the place where the situation was detected. For those +Expressions that bind variables include the lambda, let, exceptions, the exception handler that is invoked by the +let*, letrec, letrec*, let-values, and let*-values exception should not return. In some cases, however, con- +forms from the base library (see sections 11.4.2, 11.4.6). tinuing is permissible, and the handler may return. See +Of these, lambda is the most fundamental. Variable def- library section 7.1. +initions appearing within the body of such an expression, +or within the bodies of a library or top-level program, are Implementations must raise an exception when they are +treated as a set of letrec* bindings. In addition, for li- unable to continue correct execution of a correct pro- +brary bodies, the variables exported from the library can be gram due to some implementation restriction. For ex- +referenced by importing libraries and top-level programs. ample, an implementation that does not support in- + finities must raise an exception with condition type +Expressions that bind keywords include the let-syntax &implementation-restriction when it evaluates an ex- +and letrec-syntax forms (see section 11.18). A define pression whose result would be an infinity. +form (see section 11.2.1) is a definition that creates a vari- +able binding (see section 11.2), and a define-syntax form Some possible implementation restrictions such as the +is a definition that creates a keyword binding (see sec- lack of representations for NaNs and infinities (see sec- +tion 11.2.2). tion 11.7.2) are anticipated by this report, and implemen- + tations typically must raise an exception of the appropriate +Scheme is a statically scoped language with block struc- condition type if they encounter such a situation. +ture. To each place in a top-level program or library body +where an identifier is bound there corresponds a region of This report uses the phrase “an exception is raised” syn- +code within which the binding is visible. The region is onymously with “an exception must be raised”. This re- +determined by the particular binding construct that estab- port uses the phrase “an exception with condition type t” +lishes the binding; if the binding is established by a lambda to indicate that the object provided with the exception is +expression, for example, then its region is the entire lambda a condition object of the specified type. The phrase “a +expression. Every mention of an identifier refers to the continuable exception is raised” indicates an exceptional +binding of the identifier that establishes the innermost of situation that permits the exception handler to return. +the regions containing the use. If a use of an identifier ap- +pears in a place where none of the surrounding expressions 5.4. Argument checking +contains a binding for the identifier, the use may refer to a +binding established by a definition or import at the top of Many procedures specified in this report or as part of a +the enclosing library or top-level program (see chapter 7). standard library restrict the arguments they accept. Typi- +If there is no binding for the identifier, it is said to be cally, a procedure accepts only specific numbers and types +unbound. of arguments. Many syntactic forms similarly restrict the + 5. Semantic concepts 19 + +values to which one or more of their subforms can evalu- If a top-level or library form in a program is not syntac- +ate. These restrictions imply responsibilities for both the tically correct, then the implementation must raise an ex- +programmer and the implementation. Specifically, the pro- ception with condition type &syntax, and execution of that +grammer is responsible for ensuring that the values indeed top-level program or library must not be allowed to begin. +adhere to the restrictions described in the specification. +The implementation must check that the restrictions in 5.6. Safety +the specification are indeed met, to the extent that it is +reasonable, possible, and necessary to allow the specified The standard libraries whose exports are described by this +operation to complete successfully. The implementation’s document are said to be safe libraries. Libraries and top- +responsibilities are specified in more detail in chapter 6 and level programs that import only from safe libraries are also +throughout the report. said to be safe. + +Note that it is not always possible for an implementation As defined by this document, the Scheme programming +to completely check the restrictions set forth in a speci- language is safe in the following sense: The execution of +fication. For example, if an operation is specified to ac- a safe top-level program cannot go so badly wrong as to +cept a procedure with specific properties, checking of these crash or to continue to execute while behaving in ways +properties is undecidable in general. Similarly, some oper- that are inconsistent with the semantics described in this +ations accept both lists and procedures that are called by document, unless an exception is raised. +these operations. Since lists can be mutated by the pro- +cedures through the (rnrs mutable-pairs (6)) library Violations of an implementation restriction must raise +(see library chapter 17), an argument that is a list when an exception with condition type &implementation- +the operation starts may become a non-list during the exe- restriction, as must all violations and errors that would +cution of the operation. Also, the procedure might escape otherwise threaten system integrity in ways that might re- +to a different continuation, preventing the operation from sult in execution that is inconsistent with the semantics +performing more checks. Requiring the operation to check described in this document. +that the argument is a list after each call to such a proce- +dure would be impractical. Furthermore, some operations The above safety properties are guaranteed only for top- +that accept lists only need to traverse these lists partially level programs and libraries that are said to be safe. In +to perform their function; requiring the implementation to particular, implementations may provide access to unsafe +traverse the remainder of the list to verify that all spec- libraries in ways that cannot guarantee safety. +ified restrictions have been met might violate reasonable +performance assumptions. For these reasons, the program- 5.7. Boolean values +mer’s obligations may exceed the checking obligations of +the implementation. Although there is a separate boolean type, any Scheme + value can be used as a boolean value for the purpose of +When an implementation detects a violation of a restriction a conditional test. In a conditional test, all values count +for an argument, it must raise an exception with condition as true in such a test except for #f. This report uses the +type &assertion in a way consistent with the safety of word “true” to refer to any Scheme value except #f, and +execution as described in section 5.6. the word “false” to refer to #f. + +5.5. Syntax violations 5.8. Multiple return values + +The subforms of a special form usually need to obey cer- A Scheme expression can evaluate to an arbitrary finite +tain syntactic restrictions. As forms may be subject to number of values. These values are passed to the expres- +macro expansion, which may not terminate, the question sion’s continuation. +of whether they obey the specified restrictions is undecid- +able in general. Not all continuations accept any number of values. For + example, a continuation that accepts the argument to a +When macro expansion terminates, however, implementa- procedure call is guaranteed to accept exactly one value. +tions must detect violations of the syntax. A syntax viola- The effect of passing some other number of values to such a +tion is an error with respect to the syntax of library bodies, continuation is unspecified. The call-with-values proce- +top-level bodies, or the “syntax” entries in the specifica- dure described in section 11.15 makes it possible to create +tion of the base library or the standard libraries. More- continuations that accept specified numbers of return val- +over, attempting to assign to an immutable variable (i.e., ues. If the number of return values passed to a continuation +the variables exported by a library; see section 7.1) is also created by a call to call-with-values is not accepted by +considered a syntax violation. + 20 Revised6 Scheme + +its consumer that was passed in that call, then an excep- to store a new value into a location referred to by an im- +tion is raised. A more complete description of the number mutable object should raise an exception with condition +of values accepted by different continuations and the conse- type &assertion. +quences of passing an unexpected number of values is given +in the description of the values procedure in section 11.15. 5.11. Proper tail recursion + +A number of forms in the base library have sequences of ex- Implementations of Scheme must be properly tail-recursive. +pressions as subforms that are evaluated sequentially, with Procedure calls that occur in certain syntactic contexts +the return values of all but the last expression being dis- called tail contexts are tail calls. A Scheme implementa- +carded. The continuations discarding these values accept tion is properly tail-recursive if it supports an unbounded +any number of values. number of active tail calls. A call is active if the called + procedure may still return. Note that this includes regu- +5.9. Unspecified behavior lar returns as well as returns through continuations cap- + tured earlier by call-with-current-continuation that +If an expression is said to “return unspecified values”, then are later invoked. In the absence of captured continuations, +the expression must evaluate without raising an exception, calls could return at most once and the active calls would +but the values returned depend on the implementation; be those that had not yet returned. A formal definition of +this report explicitly does not say how many or what val- proper tail recursion can be found in Clinger’s paper [5]. +ues should be returned. Programmers should not rely on The rules for identifying tail calls in constructs from the +a specific number of return values or the specific values (rnrs base (6)) library are described in section 11.20. +themselves. + +5.10. Storage model 5.12. Dynamic extent and the dynamic en- + vironment +Variables and objects such as pairs, vectors, bytevectors, +strings, hashtables, and records implicitly refer to locations For a procedure call, the time between when it is initiated +or sequences of locations. A string, for example, contains as and when it returns is called its dynamic extent. In Scheme, +many locations as there are characters in the string. (These call-with-current-continuation (section 11.15) allows +locations need not correspond to a full machine word.) A reentering a dynamic extent after its procedure call has +new value may be stored into one of these locations using returned. Thus, the dynamic extent of a call may not be a +the string-set! procedure, but the string contains the single, connected time period. +same locations as before. + Some operations described in the report acquire informa- +An object fetched from a location, by a variable reference or tion in addition to their explicit arguments from the dy- +by a procedure such as car, vector-ref, or string-ref, is namic environment. For example, call-with-current- +equivalent in the sense of eqv? (section 11.5) to the object continuation accesses an implicit context established by +last stored in the location before the fetch. dynamic-wind (section 11.15), and the raise procedure + (library section 7.1) accesses the current exception handler. +Every location is marked to show whether it is in use. No The operations that modify the dynamic environment do so +variable or object ever refers to a location that is not in use. dynamically, for the dynamic extent of a call to a procedure +Whenever this report speaks of storage being allocated for like dynamic-wind or with-exception-handler. When +a variable or object, what is meant is that an appropriate such a call returns, the previous dynamic environment is +number of locations are chosen from the set of locations restored. The dynamic environment can be thought of as +that are not in use, and the chosen locations are marked part of the dynamic extent of a call. Consequently, it is +to indicate that they are now in use before the variable or captured by call-with-current-continuation, and re- +object is made to refer to them. stored by invoking the escape procedure it creates. + +It is desirable for constants (i.e. the values of literal expres- 6. Entry format +sions) to reside in read-only memory. To express this, it is +convenient to imagine that every object that refers to loca- The chapters that describe bindings in the base library +tions is associated with a flag telling whether that object and the standard libraries are organized into entries. Each +is mutable or immutable. Literal constants, the strings re- entry describes one language feature or a group of related +turned by symbol->string, records with no mutable fields, features, where a feature is either a syntactic construct or +and other values explicitly designated as immutable are a built-in procedure. An entry begins with one or more +immutable objects, while all objects created by the other header lines of the form +procedures listed in this report are mutable. An attempt + 6. Entry format 21 + +template category 6.2. Procedure entries + +The category defines the kind of binding described by the If category is “procedure”, then the entry describes a pro- +entry, typically either “syntax” or “procedure”. An entry cedure, and the header line gives a template for a call to the +may specify various restrictions on subforms or arguments. procedure. Parameter names in the template are italicized . +For background on this, see section 5.4. Thus the header line + + (vector-ref vector k ) procedure + +6.1. Syntax entries indicates that the built-in procedure vector-ref takes two + arguments, a vector vector and an exact non-negative in- +If category is “syntax”, the entry describes a special syn- teger object k (see below). The header lines +tactic construct, and the template gives the syntax of the +forms of the construct. The template is written in a nota- (make-vector k ) procedure +tion similar to a right-hand side of the BNF rules in chap- (make-vector k fill ) procedure +ter 4, and describes the set of forms equivalent to the forms +matching the template as syntactic data. Some “syntax” indicate that the make-vector procedure takes either +entries carry a suffix (expand), specifying that the syn- one or two arguments. The parameter names are case- +tactic keyword of the construct is exported with level 1. insensitive: Vector is the same as vector . +Otherwise, the syntactic keyword is exported with level 0; +see section 7.2. As with syntax templates, an ellipsis . . . at the end of a + header line, as in +Components of the form described by a template are desig- +nated by syntactic variables, which are written using angle (= z1 z2 z3 . . . ) procedure +brackets, for example, expression , variable . Case is in- +significant in syntactic variables. Syntactic variables stand indicates that the procedure takes arbitrarily many argu- +for other forms, or sequences of them. A syntactic variable ments of the same type as specified for the last parameter +may refer to a non-terminal in the grammar for syntactic name. In this case, = accepts two or more arguments that +data (see section 4.3.1), in which case only forms match- must all be complex number objects. +ing that non-terminal are permissible in that position. For +example, identifier stands for a form which must be an A procedure that detects an argument that it is not speci- +identifier. Also, expression stands for any form which is fied to handle must raise an exception with condition type +a syntactically valid expression. Other non-terminals that &assertion. Also, the argument specifications are ex- +are used in templates are defined as part of the specifica- haustive: if the number of arguments provided in a pro- +tion. cedure call does not match any number of arguments ac- + cepted by the procedure, an exception with condition type +The notation &assertion must be raised. + + thing1 . . . For succinctness, the report follows the convention that if + a parameter name is also the name of a type, then the cor- +indicates zero or more occurrences of a thing , and responding argument must be of the named type. For ex- + ample, the header line for vector-ref given above dictates + thing1 thing2 . . . that the first argument to vector-ref must be a vector. + The following naming conventions imply type restrictions: +indicates one or more occurrences of a thing . + obj any object +It is the programmer’s responsibility to ensure that each z complex number object +component of a form has the shape specified by a template. x real number object +Descriptions of syntax may express other restrictions on y real number object +the components of a form. Typically, such a restriction is q rational number object +formulated as a phrase of the form “ x must be a . . . ”. n integer object +Again, these specify the programmer’s responsibility. It is k exact non-negative integer object +the implementation’s responsibility to check that these re- bool boolean (#f or #t) +strictions are satisfied, as long as the macro transformers octet exact integer object in {0, . . . , 255} +involved in expanding the form terminate. If the imple- byte exact integer object in {−128, . . . , 127} +mentation detects that a component does not meet the char character (see section 11.11) +restriction, an exception with condition type &syntax is pair pair (see section 11.9) +raised. vector vector (see section 11.13) + string string (see section 11.12) + condition condition (see library section 7.2) + bytevector bytevector (see library chapter 2) + proc procedure (see section 1.6) + 22 Revised6 Scheme + +Other type restrictions are expressed through parameter- unquote auxiliary syntax +naming conventions that are described in specific chapters. +For example, library chapter 11 uses a number of special indicates that unquote is a syntax binding that may +parameter variables for the various subsets of the numbers. occur only as part of specific surrounding expressions. + Any use as an independent syntactic construct or iden- +With the listed type restrictions, it is the programmer’s tifier is a syntax violation. As with “syntax” entries, +responsibility to ensure that the corresponding argument some “auxiliary syntax” entries carry a suffix (expand), +is of the specified type. It is the implementation’s respon- specifying that the syntactic keyword of the construct is +sibility to check for that type. exported with level 1. + +A parameter called list means that it is the programmer’s 6.5. Equivalent entries +responsibility to pass an argument that is a list (see sec- +tion 11.9). It is the implementation’s responsibility to The description of an entry occasionally states that it is +check that the argument is appropriately structured for the same as another entry. This means that both entries +the operation to perform its function, to the extent that are equivalent. Specifically, it means that if both entries +this is possible and reasonable. The implementation must have the same name and are thus exported from different +at least check that the argument is either an empty list or libraries, the entries from both libraries can be imported +a pair. under the same name without conflict. + +Descriptions of procedures may express other restrictions 6.6. Evaluation examples +on the arguments of a procedure. Typically, such a restric- +tion is formulated as a phrase of the form “x must be a +. . . ” (or otherwise using the word “must”). + +6.3. Implementation responsibilities The symbol “=⇒” used in program examples can be read + “evaluates to”. For example, +In addition to the restrictions implied by naming conven- +tions, an entry may list additional explicit restrictions. (* 5 8) =⇒ 40 +These explicit restrictions usually describe both the pro- +grammer’s responsibilities, who must ensure that the sub- means that the expression (* 5 8) evaluates to the ob- +forms of a form are appropriate, or that an appropriate ject 40. Or, more precisely: the expression given by the +argument is passed, and the implementation’s responsibil- sequence of characters “(* 5 8)” evaluates, in an environ- +ities, which must check that subform adheres to the speci- ment that imports the relevant library, to an object that +fied restrictions (if macro expansion terminates), or if the may be represented externally by the sequence of char- +argument is appropriate. A description may explicitly list acters “40”. See section 4.3 for a discussion of external +the implementation’s responsibilities for some arguments representations of objects. +or subforms in a paragraph labeled “Implementation re- +sponsibilities”. In this case, the responsibilities specified The “=⇒” symbol is also used when the evaluation of an +for these subforms or arguments in the rest of the descrip- expression causes a violation. For example, +tion are only for the programmer. A paragraph describing +implementation responsibility does not affect the imple- (integer->char #xD800) =⇒ &assertion exception +mentation’s responsibilities for checking subforms or argu- +ments not mentioned in the paragraph. means that the evaluation of the expression + (integer->char #xD800) must raise an exception + with condition type &assertion. + +6.4. Other kinds of entries Moreover, the “=⇒” symbol is also used to explicitly say + that the value of an expression in unspecified. For exam- + ple: + + (eqv? "" "") =⇒ unspecified + +If category is something other than “syntax” and “proce- Mostly, examples merely illustrate the behavior specified +dure”, then the entry describes a non-procedural value, and in the entry. In some cases, however, they disambiguate +the category describes the type of that value. The header otherwise ambiguous specifications and are thus norma- +line tive. Note that, in some cases, specifically in the case of + inexact number objects, the return value is only specified +&who condition type conditionally or approximately. For example: + +indicates that &who is a condition type. The header (atan -inf.0) +line =⇒ -1.5707963267948965 ; approximately + 7. Libraries 23 + +6.7. Naming conventions – the imported library’s name, and, optionally, + constraints on its version, +By convention, the names of procedures that store values +into previously allocated locations (see section 5.10) usu- – the relevant levels, e.g., expand or run time (see +ally end in “!”. section 7.2, and + +By convention, “->” appears within the names of proce- – the subset of the library’s exports to make avail- +dures that take an object of one type and return an anal- able within the importing library, and the local +ogous object of another type. For example, list->vector names to use within the importing library for +takes a list and returns a vector whose elements are the each of the library’s exports. +same as those of the list. + • The library body is the library body, consisting of a +By convention, the names of predicates—procedures that sequence of definitions followed by a sequence of ex- +always return a boolean value—end in “?” when the name pressions. The definitions may be both for local (un- +contains any letters; otherwise, the predicate’s name does exported) and exported bindings, and the expressions +not end with a question mark. are initialization expressions to be evaluated for their + effects. +By convention, the components of compound names are +separated by “-” In particular, prefixes that are actual An identifier can be imported with the same local name +words or can be pronounced as though they were actual from two or more libraries or for two levels from the same +words are followed by a hyphen, except when the first char- library only if the binding exported by each library is +acter following the hyphen would be something other than the same (i.e., the binding is defined in one library, and +a letter, in which case the hyphen is omitted. Short, un- it arrives through the imports only by exporting and re- +pronounceable prefixes (“fx” and “fl”) are not followed exporting). Otherwise, no identifier can be imported mul- +by a hyphen. tiple times, defined multiple times, or both defined and + imported. No identifiers are visible within a library except +By convention, the names of condition types start with “&”. for those explicitly imported into the library or defined + within the library. +7. Libraries + A library name uniquely identifies a library within an im- +Libraries are parts of a program that can be distributed plementation, and is globally visible in the import clauses +independently. The library system supports macro defini- (see below) of all other libraries within an implementation. +tions within libraries, macro exports, and distinguishes the A library name has the following form: +phases in which definitions and imports are needed. This +chapter defines the notation for libraries and a semantics ( identifier1 identifier2 ... version ) +for library expansion and execution. + where version is empty or has the following form: +7.1. Library form + ( sub-version ...) +A library definition must have the following form: + Each sub-version must represent an exact nonnegative + (library library name integer object. An empty version is equivalent to (). + (export export spec ...) + (import import spec ...) An export spec names a set of imported and locally de- + library body ) fined bindings to be exported, possibly with different exter- + nal names. An export spec must have one of the following +A library declaration contains the following elements: forms: + + • The library name specifies the name of the library identifier + (possibly with version). (rename ( identifier1 identifier2 ) ...) + + • The export subform specifies a list of exports, which In an export spec , an identifier names a single binding + name a subset of the bindings defined within or im- defined within or imported into the library, where the ex- + ported into the library. ternal name for the export is the same as the name of + the binding within the library. A rename spec exports + • The import subform specifies the imported bindings the binding named by identifier1 in each ( identifier1 + as a list of import dependencies, where each depen- identifier2 ) pairing, using identifier2 as the external + dency specifies: name. + + Each import spec specifies a set of bindings to be im- + ported into the library, the levels at which they are to + be available, and the local names by which they are to + be known. An import spec must be one of the follow- + ing: + 24 Revised6 Scheme + + import set sub-version + (for import set import level ...) (>= sub-version ) + (<= sub-version ) +An import level is one of the following: (and sub-version reference ...) + (or sub-version reference ...) + run (not sub-version reference ) + expand + (meta level ) A sub-version reference of the first form matches + +where level represents an exact integer object. a sub-version if it is equal to it. A >= + +As an import level , run is an abbreviation for (meta 0), sub-version reference of the first form matches a sub- +and expand is an abbreviation for (meta 1). Levels and +phases are discussed in section 7.2. version if it is greater or equal to the sub-version following + +An import set names a set of bindings from another li- it; analogously for <=. An and sub-version reference +brary and possibly specifies local names for the imported +bindings. It must be one of the following: matches a sub-version if all of the subsequent + + sub-version reference s match it. Correspondingly, + + an or sub-version reference matches a sub-version if one + + of the subsequent sub-version reference s matches it, and + + library reference a not sub-version reference matches a sub-version if the +(library library reference ) +(only import set identifier ...) subsequent sub-version reference does not match it. +(except import set identifier ...) +(prefix import set identifier ) Examples: +(rename import set ( identifier1 identifier2 ) ...) + version reference version match? +A library reference identifies a library by its name and () (1) yes +optionally by its version. It has one of the following forms: (1) (1) yes + (1) (2) no +( identifier1 identifier2 ...) (2 3) (2) no +( identifier1 identifier2 ... version reference ) (2 3) (2 3) yes + (2 3) (2 3 5) yes +A library reference whose first identifier is for, (or (1 (>= 1)) (2)) (2) yes +library, only, except, prefix, or rename is permitted (or (1 (>= 1)) (2)) (1 1) yes +only within a library import set . The import set (or (1 (>= 1)) (2)) (1 0) no +(library library reference ) is otherwise equivalent to ((or 1 2 3)) (1) yes + library reference . ((or 1 2 3)) (2) yes + ((or 1 2 3)) (3) yes +A library reference with no version reference (first ((or 1 2 3)) (4) no +form above) is equivalent to a library reference with a + version reference of (). When more than one library is identified by a library + reference, the choice of libraries is determined in some +A version reference specifies a set of version s that it implementation-dependent manner. +matches. The library reference identifies all libraries +of the same name and whose version is matched by the To avoid problems such as incompatible types and repli- + version reference . A version reference has the following cated state, implementations should prohibit the two li- +form: braries whose library names consist of the same sequence + of identifiers but whose versions do not match to co-exist +( sub-version reference1 ... sub-version referencen ) in the same program. +(and version reference ...) +(or version reference ...) By default, all of an imported library’s exported bind- +(not version reference ) ings are made visible within an importing library using + the names given to the bindings by the imported library. +A version reference of the first form matches a version The precise set of bindings to be imported and the names + of those bindings can be adjusted with the only, except, +with at least n elements, whose sub-version reference s prefix, and rename forms as described below. + +match the corresponding sub-version s. An + +and version reference matches a version if all + +version references following the and match it. Cor- + +respondingly, an or version reference matches a version + +if one of version references following the or matches it, • An only form produces a subset of the bindings + from another import set , including only the listed +and a not version reference matches a version if the identifier s. The included identifier s must be in the + original import set . +version reference following it does not match it. + +A sub-version reference has one of the following forms: + 7. Libraries 25 + + • An except form produces a subset of the bindings Bindings defined with a library are not visible in code out- + from another import set , including all but the listed side of the library, unless the bindings are explicitly ex- + identifier s. All of the excluded identifier s must be ported from the library. An exported macro may, however, + in the original import set . implicitly export an otherwise unexported identifier defined + within or imported into the library. That is, it may insert a + • A prefix form adds the identifier prefix to each reference to that identifier into the output code it produces. + name from another import set . + All explicitly exported variables are immutable in both the + • A rename form, (rename ( identifier1 identifier2 ) exporting and importing libraries. It is thus a syntax vi- + ...), removes the bindings for identifier1 ... to olation if an explicitly exported variable appears on the + form an intermediate import set , then adds the bind- left-hand side of a set! expression, either in the exporting + ings back for the corresponding identifier2 ... to or importing libraries. + form the final import set . Each identifier1 must + be in the original import set , each identifier2 must All implicitly exported variables are also immutable in both + not be in the intermediate import set , and the the exporting and importing libraries. It is thus a syn- + identifier2 s must be distinct. tax violation if a variable appears on the left-hand side of + a set! expression in any code produced by an exported +It is a syntax violation if a constraint given above is not macro outside of the library in which the variable is de- +met. fined. It is also a syntax violation if a reference to an + assigned variable appears in any code produced by an ex- +The library body of a library form consists of forms that ported macro outside of the library in which the variable +are classified as definitions or expressions. Which forms is defined, where an assigned variable is one that appears +belong to which class depends on the imported libraries on the left-hand side of a set! expression in the exporting +and the result of expansion—see chapter 10. Generally, library. +forms that are not definitions (see section 11.2 for defini- +tions available through the base library) are expressions. All other variables defined within a library are mutable. + +A library body is like a body (see section 11.3) except 7.2. Import and export levels +that a library body s need not include any expressions. It +must have the following form: Expanding a library may require run-time information + from another library. For example, if a macro transformer + definition ... expression ... calls a procedure from library A, then the library A must + be instantiated before expanding any use of the macro in +When begin, let-syntax, or letrec-syntax forms occur library B. Library A may not be needed when library B is +in a top-level body prior to the first expression, they are eventually run as part of a program, or it may be needed +spliced into the body; see section 11.4.7. Some or all of the for run time of library B, too. The library mechanism dis- +body, including portions wrapped in begin, let-syntax, tinguishes these times by phases, which are explained in +or letrec-syntax forms, may be specified by a syntactic this section. +abstraction (see section 9.2). + Every library can be characterized by expand-time infor- +The transformer expressions and bindings are evaluated mation (minimally, its imported libraries, a list of the ex- +and created from left to right, as described in chapter 10. ported keywords, a list of the exported variables, and code +The expressions of variable definitions are evaluated from to evaluate the transformer expressions) and run-time in- +left to right, as if in an implicit letrec*, and the body formation (minimally, code to evaluate the variable def- +expressions are also evaluated from left to right after the inition right-hand-side expressions, and code to evaluate +expressions of the variable definitions. A fresh location is the body expressions). The expand-time information must +created for each exported variable and initialized to the be available to expand references to any exported binding, +value of its local counterpart. The effect of returning twice and the run-time information must be available to evaluate +to the continuation of the last body expression is unspeci- references to any exported variable binding. +fied. + A phase is a time at which the expressions within a li- +Note: The names library, export, import, for, run, expand, brary are evaluated. Within a library body, top-level ex- +meta, import, export, only, except, prefix, rename, and, or, pressions and the right-hand sides of define forms are +not, >=, and <= appearing in the library syntax are part of evaluated at run time, i.e., phase 0, and the right-hand +the syntax and are not reserved, i.e., the same names can be sides of define-syntax forms are evaluated at expand +used for other purposes within the library or even exported time, i.e., phase 1. When define-syntax, let-syntax, +from or imported into a library with different meanings, without or letrec-syntax forms appear within code evaluated at +affecting their use in the library form. phase n, the right-hand sides are evaluated at phase n + 1. + 26 Revised6 Scheme + +These phases are relative to the phase in which the li- encloses the reference. For example, suppose that expand- +brary itself is used. An instance of a library corresponds ing a library invokes a macro transformer, and the evalua- +to an evaluation of its variable definitions and expressions tion of the macro transformer refers to an identifier that is +in a particular phase relative to another library—a process exported from another library (so the phase-1 instance of +called instantiation. For example, if a top-level expression the library is used); suppose further that the value of the +in a library B refers to a variable export from another li- binding is a syntax object representing an identifier with +brary A, then it refers to the export from an instance of only a level-n binding; then, the identifier must be used +A at phase 0 (relative to the phase of B). But if a phase only at phase n + 1 in the library being expanded. This +1 expression within B refers to the same binding from A, combination of levels and phases is why negative levels on +then it refers to the export from an instance of A at phase identifiers can be useful, even though libraries exist only at +1 (relative to the phase of B). non-negative phases. + +A visit of a library corresponds to the evaluation of its If any of a library’s definitions are referenced at phase 0 +syntax definitions in a particular phase relative to another in the expanded form of a program, then an instance of +library—a process called visiting. For example, if a top- the referenced library is created for phase 0 before the pro- +level expression in a library B refers to a macro export gram’s definitions and expressions are evaluated. This rule +from another library A, then it refers to the export from applies transitively: if the expanded form of one library ref- +a visit of A at phase 0 (relative to the phase of B), which erences at phase 0 an identifier from another library, then +corresponds to the evaluation of the macro’s transformer before the referencing library is instantiated at phase n, the +expression at phase 1. referenced library must be instantiated at phase n. When + an identifier is referenced at any phase n greater than 0, in +A level is a lexical property of an identifier that determines contrast, then the defining library is instantiated at phase +in which phases it can be referenced. The level for each n at some unspecified time before the reference is evalu- +identifier bound by a definition within a library is 0; that is, ated. Similarly, when a macro keyword is referenced at +the identifier can be referenced only at phase 0 within the phase n during the expansion of a library, then the defin- +library. The level for each imported binding is determined ing library is visited at phase n at some unspecified time +by the enclosing for form of the import in the importing before the reference is evaluated. +library, in addition to the levels of the identifier in the +exporting library. Import and export levels are combined An implementation may distinguish instances/visits of a +by pairwise addition of all level combinations. For example, library for different phases or to use an instance/visit at +references to an imported identifier exported for levels pa any phase as an instance/visit at any other phase. An im- +and pb and imported for levels qa, qb, and qc are valid at plementation may further expand each library form with +levels pa +qa, pa +qb, pa +qc, pb +qa, pb +qb, and pb +qc. An distinct visits of libraries in any phase and/or instances of + import set without an enclosing for is equivalent to (for libraries in phases above 0. An implementation may create + import set run), which is the same as (for import set instances/visits of more libraries at more phases than re- +(meta 0)). quired to satisfy references. When an identifier appears as + an expression in a phase that is inconsistent with the identi- +The export level of an exported binding is 0 for all bindings fier’s level, then an implementation may raise an exception +that are defined within the exporting library. The export either at expand time or run time, or it may allow the refer- +levels of a reexported binding, i.e., an export imported from ence. Thus, a library whose meaning depends on whether +another library, are the same as the effective import levels the instances of a library are distinguished or shared across +of that binding within the reexporting library. phases or library expansions may be unportable. + +For the libraries defined in the library report, the ex- 7.3. Examples +port level is 0 for nearly all bindings. The exceptions are +syntax-rules, identifier-syntax, ..., and from the Examples for various import spec s and export spec s: +(rnrs base (6)) library, which are exported with level 1, +set! from the (rnrs base (6)) library, which is exported (library (stack) +with levels 0 and 1, and all bindings from the composite (export make push! pop! empty!) +(rnrs (6)) library (see library chapter 15), which are ex- (import (rnrs)) +ported with levels 0 and 1. + (define (make) (list ’())) +Macro expansion within a library can introduce a reference (define (push! s v) (set-car! s (cons v (car s)))) +to an identifier that is not explicitly imported into the li- (define (pop! s) (let ([v (caar s)]) +brary. In that case, the phase of the reference must match +the identifier’s level as shifted by the difference between (set-car! s (cdar s)) +the phase of the source library (i.e., the library that sup- v)) +plied the identifier’s lexical context) and the library that (define (empty! s) (set-car! s ’()))) + 8. Top-level programs 27 + +(library (balloons) (import (rnrs) (for (my-helpers id-stuff) expand)) + (export make push pop) + (import (rnrs)) (define-syntax mvlet + (lambda (stx) + (define (make w h) (cons w h)) (syntax-case stx () + (define (push b amt) [( [(id ...) expr] body0 body ...) + (not (find-dup (syntax (id ...)))) + (cons (- (car b) amt) (+ (cdr b) amt))) (syntax + (define (pop b) (display "Boom! ") (call-with-values + (lambda () expr) + (display (* (car b) (cdr b))) (lambda (id ...) body0 body ...)))])))) + (newline))) + +(library (party) (library (let-div) + +;; Total exports: (export let-div) + +;; make, push, push!, make-party, pop! (import (rnrs) + +(export (rename (balloon:make make) (my-helpers values-stuff) + + (balloon:push push)) (rnrs r5rs)) + +push! + +make-party (define (quotient+remainder n d) + +(rename (party-pop! pop!))) (let ([q (quotient n d)]) + +(import (rnrs) (values q (- n (* q d))))) + +(only (stack) make push! pop!) ; not empty! (define-syntax let-div + +(prefix (balloons) balloon:)) (syntax-rules () + + [( n d (q r) body0 body ...) + +;; Creates a party as a stack of balloons, (mvlet [(q r) (quotient+remainder n d)] + +;; starting with two balloons body0 body ...)]))) + +(define (make-party) + +(let ([s (make)]) ; from stack 8. Top-level programs + (push! s (balloon:make 10 10)) + + (push! s (balloon:make 12 9)) A top-level program specifies an entry point for defining and + s)) running a Scheme program. A top-level program specifies +(define (party-pop! p) a set of libraries to import and code to run. Through the + (balloon:pop (pop! p)))) imported libraries, whether directly or through the tran- + + sitive closure of importing, a top-level program defines a + +(library (main) complete Scheme program. + +(export) + +(import (rnrs) (party)) + + 8.1. Top-level program syntax + +(define p (make-party)) + +(pop! p) ; displays "Boom! 108" A top-level program is a delimited piece of text, typically + a file, that has the following form: +(push! p (push (make 5 5) 1)) + import form top-level body +(pop! p)) ; displays "Boom! 24" + An import form has the following form: +Examples for macros and phases: + +(library (my-helpers id-stuff) (import import spec . . . ) + (export find-dup) A top-level body has the following form: + (import (rnrs)) + + (define (find-dup l) top-level body form . . . + (and (pair? l) + (let loop ((rest (cdr l))) A top-level body form is either a definition or an + (cond expression . + [(null? rest) (find-dup (cdr l))] + [(bound-identifier=? (car l) (car rest)) The import form is identical to the import clause in li- + (car rest)] braries (see section 7.1), and specifies a set of libraries + [else (loop (cdr rest))]))))) to import. A top-level body is like a library body + (see section 7.1), except that definitions and expressions +(library (my-helpers values-stuff) may occur in any order. Thus, the syntax specified by + (export mvlet) top-level body form refers to the result of macro expan- + sion. + 28 Revised6 Scheme + +When uses of begin, let-syntax, or letrec-syntax from string syntax +the (rnrs base (6)) library occur in a top-level body bytevector syntax +prior to the first expression, they are spliced into the body; +see section 11.4.7. Some or all of the body, including por- An expression consisting of a representation of a number +tions wrapped in begin, let-syntax, or letrec-syntax object, a boolean, a character, a string, or a bytevector, +forms, may be specified by a syntactic abstraction (see sec- evaluates “to itself”. +tion 9.2). + 145932 =⇒ 145932 +8.2. Top-level program semantics #t =⇒ #t + "abc" =⇒ "abc" +A top-level program is executed by treating the program #vu8(2 24 123) =⇒ #vu8(2 24 123) +similarly to a library, and evaluating its definitions and +expressions. The semantics of a top-level body may be As noted in section 5.10, the value of a literal expression is +roughly explained by a simple translation into a library immutable. +body: Each expression that appears before a definition in +the top-level body is converted into a dummy definition Variable references + + (define variable (begin expression unspecified )) variable syntax + +where variable is a fresh identifier and unspecified is a An expression consisting of a variable (section 5.2) is a +side-effect-free expression returning an unspecified value. variable reference if it is not a macro use (see below). The +(It is generally impossible to determine which forms are value of the variable reference is the value stored in the +definitions and expressions without concurrently expand- location to which the variable is bound. It is a syntax +ing the body, so the actual translation is somewhat more violation to reference an unbound variable. +complicated; see chapter 10.) + The following example examples assumes the base library +On platforms that support it, a top-level program may ac- has been imported: +cess its command line by calling the command-line proce- +dure (see library section 10). (define x 28) =⇒ 28 + x +9. Primitive syntax + Procedure calls +After the import form within a library form or a top- +level program, the forms that constitute the body of the ( operator operand1 . . . ) syntax +library or the top-level program depend on the libraries +that are imported. In particular, imported syntactic key- A procedure call consists of expressions for the procedure +words determine the available syntactic abstractions and to be called and the arguments to be passed to it, with +whether each form is a definition or expression. A few enclosing parentheses. A form in an expression context is +form types are always available independent of imported a procedure call if operator is not an identifier bound as +libraries, however, including constant literals, variable ref- a syntactic keyword (see section 9.2 below). +erences, procedure calls, and macro uses. + When a procedure call is evaluated, the operator and + operand expressions are evaluated (in an unspecified or- + der) and the resulting procedure is passed the resulting + arguments. + +9.1. Primitive expression types The following examples assume the (rnrs base (6)) li- + brary has been imported: +The entries in this section all describe expressions, which +may occur in the place of expression syntactic variables. (+ 3 4) =⇒ 7 +See also section 11.4. ((if #f + *) 3 4) =⇒ 12 + +Constant literals If the value of operator is not a procedure, an excep- + tion with condition type &assertion is raised. Also, if + number operator does not accept as many arguments as there are + boolean operand s, an exception with condition type &assertion + character is raised. + + syntax Note: In contrast to other dialects of Lisp, the order of evalua- + syntax tion is unspecified, and the operator expression and the operand + syntax expressions are always evaluated with the same evaluation rules. + 10. Expansion process 29 + +Although the order of evaluation is otherwise unspecified, the • If a macro transformer inserts a binding for an identi- +effect of any concurrent evaluation of the operator and operand fier (variable or keyword) not appearing in the macro +expressions is constrained to be consistent with some sequential use, the identifier is in effect renamed throughout its +order of evaluation. The order of evaluation may be chosen scope to avoid conflicts with other identifiers. +differently for each procedure call. + • If a macro transformer inserts a free reference to an +Note: In many dialects of Lisp, the form () is a legitimate identifier, the reference refers to the binding that was +expression. In Scheme, expressions written as list/pair forms visible where the transformer was specified, regardless +must have at least one subexpression, so () is not a syntactically of any local bindings that may surround the use of the +valid expression. macro. + +9.2. Macros Macros defined using the syntax-case facility are also hy- + gienic unless datum->syntax (see library section 12.6) is +Libraries and top-level programs can define and use new used. +kinds of derived expressions and definitions called syntactic +abstractions or macros. A syntactic abstraction is created 10. Expansion process +by binding a keyword to a macro transformer or, simply, +transformer. The transformer determines how a use of Macro uses (see section 9.2) are expanded into core forms +the macro (called a macro use) is transcribed into a more at the start of evaluation (before compilation or inter- +primitive form. pretation) by a syntax expander. The set of core forms + is implementation-dependent, as is the representation of +Most macro uses have the form: these forms in the expander’s output. If the expander en- + counters a syntactic abstraction, it invokes the associated + ( keyword datum . . . ) transformer to expand the syntactic abstraction, then re- + peats the expansion process for the form returned by the +where keyword is an identifier that uniquely determines transformer. If the expander encounters a core form, it re- +the kind of form. This identifier is called the syntactic cursively processes its subforms that are in expression or +keyword, or simply keyword, of the macro. The number of definition context, if any, and reconstructs the form from + datum s and the syntax of each depends on the syntactic the expanded subforms. Information about identifier bind- +abstraction. ings is maintained during expansion to enforce lexical scop- + ing for variables and keywords. +Macro uses can also take the form of improper lists, single- +ton identifiers, or set! forms, where the second subform To handle definitions, the expander processes the initial +of the set! is the keyword (see section 11.19) library sec- forms in a body (see section 11.3) or library body (see +tion 12.3): section 7.1) from left to right. How the expander processes + each form encountered depends upon the kind of form. + ( keyword datum . . . . datum ) + keyword macro use The expander invokes the associated trans- + (set! keyword datum ) former to transform the macro use, then recursively + performs whichever of these actions are appropriate +The define-syntax, let-syntax and letrec-syntax for the resulting form. +forms, described in sections 11.2.2 and 11.18, create bind- +ings for keywords, associate them with macro transformers, define-syntax form The expander expands and evalu- +and control the scope within which they are visible. ates the right-hand-side expression and binds the key- + word to the resulting transformer. +The syntax-rules and identifier-syntax forms, de- +scribed in section 11.19, create transformers via a pattern define form The expander records the fact that the de- +language. Moreover, the syntax-case form, described in fined identifier is a variable but defers expansion of the +library chapter 12, allows creating transformers via arbi- right-hand-side expression until after all of the defini- +trary Scheme code. tions have been processed. + +Keywords occupy the same name space as variables. That begin form The expander splices the subforms into the +is, within the same scope, an identifier can be bound as list of body forms it is processing. (See section 11.4.7.) +a variable or keyword, or neither, but not both, and local +bindings of either kind may shadow other bindings of either let-syntax or letrec-syntax form The expander +kind. splices the inner body forms into the list of (outer) + body forms it is processing, arranging for the key- +Macros defined using syntax-rules and identifier- words bound by the let-syntax and letrec-syntax +syntax are “hygienic” and “referentially transparent” and to be visible only in the inner body forms. +thus preserve Scheme’s lexical scoping [16, 15, 2, 6, 9]: + 30 Revised6 Scheme + +expression, i.e., nondefinition The expander com- Note that this algorithm does not directly reprocess any + pletes the expansion of the deferred right-hand-side form. It requires a single left-to-right pass over the defini- + expressions and the current and remaining expressions tions followed by a single pass (in any order) over the body + in the body, and then creates the equivalent of a expressions and deferred right-hand sides. + letrec* form from the defined variables, expanded + right-hand-side expressions, and expanded body Example: + expressions. + (lambda (x) +For the right-hand side of the definition of a variable, ex- (define-syntax defun +pansion is deferred until after all of the definitions have (syntax-rules () +been seen. Consequently, each keyword and variable refer- [( x a e) (define x (lambda a e))])) +ence within the right-hand side resolves to the local bind- (defun even? (n) (or (= n 0) (odd? (- n 1)))) +ing, if any. (define-syntax odd? + (syntax-rules () [( n) (not (even? n))])) +A definition in the sequence of forms must not define any (odd? (if (odd? x) (* x x) x))) +identifier whose binding is used to determine the meaning +of the undeferred portions of the definition or any definition In the example, the definition of defun is encountered first, +that precedes it in the sequence of forms. For example, the and the keyword defun is associated with the transformer +bodies of the following expressions violate this restriction. resulting from the expansion and evaluation of the corre- + sponding right-hand side. A use of defun is encountered + (let () next and expands into a define form. Expansion of the + (define define 17) right-hand side of this define form is deferred. The defini- + (list define)) tion of odd? is next and results in the association of the + keyword odd? with the transformer resulting from expand- +(let-syntax ([def0 (syntax-rules () ing and evaluating the corresponding right-hand side. A + [( x) (define x 0)])]) use of odd? appears next and is expanded; the resulting + call to not is recognized as an expression because not is + (let ([z 3]) bound as a variable. At this point, the expander completes + (def0 z) the expansion of the current expression (the call to not) + (define def0 list) and the deferred right-hand side of the even? definition; + (list z))) the uses of odd? appearing in these expressions are ex- + panded using the transformer associated with the keyword +(let () odd?. The final output is the equivalent of + (define-syntax foo + (lambda (e) (lambda (x) + (+ 1 2))) (letrec* ([even? + (define + 2) (lambda (n) + (foo)) (or (= n 0) + (not (even? (- n 1)))))]) +The following do not violate the restriction. (not (even? (if (not (even? x)) (* x x) x))))) + +(let ([x 5]) =⇒ (5 5) although the structure of the output is implementation- + (define lambda list) dependent. + (lambda x x)) + Because definitions and expressions can be interleaved in +(let-syntax ([def0 (syntax-rules () a top-level body (see chapter 8), the expander’s process- + ing of a top-level body is somewhat more complicated. It + [( x) (define x 0)])]) behaves as described above for a body or library body + with the following exceptions: When the expander finds a +(let ([z 3]) nondefinition, it defers its expansion and continues scan- + ning for definitions. Once it reaches the end of the set of +(define def0 list) forms, it processes the deferred right-hand-side and body + expressions, then generates the equivalent of a letrec* +(def0 z) form from the defined variables, expanded right-hand-side + expressions, and expanded body expressions. For each +(list z))) =⇒ (3) body expression expression that appears before a vari- + able definition in the body, a dummy binding is created +(let () at the corresponding place within the set of letrec* bind- + ings, with a fresh temporary variable on the left-hand side +(define-syntax foo + +(lambda (e) + +(let ([+ -]) (+ 1 2)))) + +(define + 2) + +(foo)) =⇒ -1 + +The implementation should treat a violation of the restric- +tion as a syntax violation. + 11. Base library 31 + +and the equivalent of (begin expression unspecified ), (define variable expression ) syntax +where unspecified is a side-effect-free expression return- (define variable ) syntax +ing an unspecified value, on the right-hand side, so that (define ( variable formals ) body ) syntax +left-to-right evaluation order is preserved. The begin (define ( variable . formal ) body ) syntax +wrapper allows expression to evaluate to an arbitrary +number of values. The first from of define binds variable to a new location + before assigning the value of expression to it. +11. Base library + (define add3 =⇒ 6 +This chapter describes Scheme’s (rnrs base (6)) library, (lambda (x) (+ x 3))) =⇒ 1 +which exports many of the procedure and syntax bindings +that are traditionally associated with Scheme. (add3 3) + (define first car) +Section 11.20 defines the rules that identify tail calls and (first ’(1 2)) +tail contexts in constructs from the (rnrs base (6)) li- +brary. The continuation of expression should not be invoked + more than once. + +11.1. Base types Implementation responsibilities: Implementations should + detect that the continuation of expression is invoked more + than once. If the implementation detects this, it must raise + an exception with condition type &assertion. + + The second form of define is equivalent to + +No object satisfies more than one of the following predi- (define variable unspecified ) +cates: + where unspecified is a side-effect-free expression return- +boolean? pair? ing an unspecified value. +symbol? number? +char? string? In the third form of define, formals must be either a +vector? procedure? sequence of zero or more variables, or a sequence of one +null? or more variables followed by a dot . and another variable + (as in a lambda expression, see section 11.4.2). This form +These predicates define the base types boolean, pair, sym- is equivalent to +bol, number, char (or character), string, vector, and pro- +cedure. Moreover, the empty list is a special object of its (define variable +own type. (lambda ( formals ) body )). + +Note that, although there is a separate boolean type, any In the fourth form of define, formal must be a single +Scheme value can be used as a boolean value for the pur- variable. This form is equivalent to +pose of a conditional test; see section 5.7. + (define variable + (lambda formal body )). + +11.2. Definitions 11.2.2. Syntax definitions + +Definitions may appear within a top-level body (sec- The define-syntax form described in this section is a +tion 8.1), at the top of a library body (section 7.1), or definition used to create keyword bindings and may ap- +at the top of a body (section 11.3). pear anywhere other definitions may appear. +A definition may be a variable definition (section 11.2.1) +or keyword definition (section 11.2.1). Macro uses that ex- (define-syntax keyword expression ) syntax +pand into definitions or groups of definitions (packaged in +a begin, let-syntax, or letrec-syntax form; see sec- Binds keyword to the value of expression , which +tion 11.4.7) may also appear wherever other definitions must evaluate, at macro-expansion time, to a trans- +may appear. former. Macro transformers can be created using the + syntax-rules and identifier-syntax forms described in +11.2.1. Variable definitions section 11.19. See library section 12.3 for a more complete + description of transformers. +The define form described in this section is a definition +used to create variable bindings and may appear anywhere Keyword bindings established by define-syntax are vis- +other definitions may appear. ible throughout the body in which they appear, except + where shadowed by other bindings, and nowhere else, just + like variable bindings established by define. All bind- + ings established by a set of definitions, whether keyword + 32 Revised6 Scheme + +or variable definitions, are visible within the definitions letrec* expression. For example, the let expression in +themselves. the above example is equivalent to + +Implementation responsibilities: The implementation (let ((x 5)) +should detect if the value of expression cannot possibly (letrec* ((foo (lambda (y) (bar x y))) +be a transformer. (bar (lambda (a b) (+ (* a b) a)))) + (foo (+ x 3)))) +Example: + +(let () + +(define even? 11.4. Expressions + +(lambda (x) The entries in this section describe the expressions of the + (rnrs base (6)) library, which may occur in the position + (or (= x 0) (odd? (- x 1))))) of the expression syntactic variable in addition to the + primitive expression types as described in section 9.1. +(define-syntax odd? + +(syntax-rules () + + ((odd? x) (not (even? x))))) + +(even? 10)) =⇒ #t + +An implication of the left-to-right processing order (sec- 11.4.1. Quotation +tion 10) is that one definition can affect whether a subse- +quent form is also a definition. (quote datum ) syntax + Syntax: Datum should be a syntactic datum. +Example: + +(let () + +(define-syntax bind-to-zero Semantics: (quote datum ) evaluates to the datum value + represented by datum (see section 4.3). This notation is +(syntax-rules () used to include constants. + + ((bind-to-zero id) (define id 0)))) + +(bind-to-zero x) + +x) =⇒ 0 (quote a) =⇒ a + (quote #(a b c)) =⇒ #(a b c) +The behavior is unaffected by any binding for (quote (+ 1 2)) =⇒ (+ 1 2) +bind-to-zero that might appear outside of the let +expression. As noted in section 4.3.5, (quote datum ) may be abbre- + viated as ’ datum : + +11.3. Bodies ’"abc" =⇒ "abc" + ’145932 =⇒ 145932 +The body of a lambda, let, let*, let-values, ’a =⇒ a +let*-values, letrec, or letrec* expression, or that of ’#(a b c) =⇒ #(a b c) +a definition with a body consists of zero or more defini- ’() =⇒ () +tions followed by one or more expressions. ’(+ 1 2) =⇒ (+ 1 2) + ’(quote a) =⇒ (quote a) + definition ... expression1 expression2 ... ’’a =⇒ (quote a) + +Each identifier defined by a definition is local to the body . As noted in section 5.10, constants are immutable. +That is, the identifier is bound, and the region of the bind- +ing is the entire body (see section 5.2). Note: Different constants that are the value of a quote expres- + sion may share the same locations. + +Example: + +(let ((x 5)) 11.4.2. Procedures + +(define foo (lambda (y) (bar x y))) + +(define bar (lambda (a b) (+ (* a b) a))) + +(foo (+ x 3))) =⇒ 45 (lambda formals body ) syntax + +When begin, let-syntax, or letrec-syntax forms occur Syntax: Formals must be a formal parameter list as de- +in a body prior to the first expression, they are spliced scribed below, and body must be as described in sec- +into the body; see section 11.4.7. Some or all of the tion 11.3. +body, including portions wrapped in begin, let-syntax, +or letrec-syntax forms, may be specified by a macro use Semantics: A lambda expression evaluates to a procedure. +(see section 9.2). The environment in effect when the lambda expression is + evaluated is remembered as part of the procedure. When +An expanded body (see chapter 10) containing variable the procedure is later called with some arguments, the en- +definitions can always be converted into an equivalent vironment in which the lambda expression was evaluated + 11. Base library 33 + +is extended by binding the variables in the parameter list 11.4.3. Conditionals +to fresh locations, and the resulting argument values are +stored in those locations. Then, the expressions in the (if test consequent alternate ) syntax +body of the lambda expression (which may contain defini- (if test consequent ) syntax +tions and thus represent a letrec* form, see section 11.3) +are evaluated sequentially in the extended environment. Syntax: Test , consequent , and alternate must be ex- +The results of the last expression in the body are returned pressions. +as the results of the procedure call. + Semantics: An if expression is evaluated as follows: first, +(lambda (x) (+ x x)) =⇒ a procedure test is evaluated. If it yields a true value (see section 5.7), +((lambda (x) (+ x x)) 4) =⇒ 8 then consequent is evaluated and its values are returned. + Otherwise alternate is evaluated and its values are re- +((lambda (x) turned. If test yields #f and no alternate is specified, + (define (p y) then the result of the expression is unspecified. + (+ y 1)) + (+ (p x) x)) =⇒ 11 (if (> 3 2) ’yes ’no) =⇒ yes + (if (> 2 3) ’yes ’no) =⇒ no + 5) (if (> 3 2) + =⇒ 1 +(define reverse-subtract (- 3 2) =⇒ unspecified + (lambda (x y) (- y x))) (+ 3 2)) + (if #f #f) +(reverse-subtract 7 10) + =⇒ 3 The consequent and alternate expressions are in tail + context if the if expression itself is; see section 11.20. +(define add4 + +(let ((x 4)) + +(lambda (y) (+ x y)))) 11.4.4. Assignments + +(add4 6) =⇒ 10 + + (set! variable expression ) syntax + +Formals must have one of the following forms: Expression is evaluated, and the resulting value is stored + in the location to which variable is bound. Variable +• ( variable1 . . . ): The procedure takes a fixed num- must be bound either in some region enclosing the set! + ber of arguments; when the procedure is called, the ar- expression or at the top level. The result of the set! ex- + guments are stored in the bindings of the correspond- pression is unspecified. + ing variables. + (let ((x 2)) +• variable : The procedure takes any number of argu- (+ x 1) =⇒ 5 + ments; when the procedure is called, the sequence of (set! x 4) + arguments is converted into a newly allocated list, and (+ x 1)) + the list is stored in the binding of the variable . + It is a syntax violation if variable refers to an immutable + binding. + +• ( variable1 . . . variablen . variablen+1 ): If a Note: The identifier set! is exported with level 1 as well. See + period . precedes the last variable, then the procedure section 11.19. + takes n or more arguments, where n is the number of + parameters before the period (there must be at least 11.4.5. Derived conditionals + one). The value stored in the binding of the last vari- + able is a newly allocated list of the arguments left over (cond cond clause1 cond clause2 . . . ) syntax + after all the other arguments have been matched up => + against the other parameters. else auxiliary syntax + + auxiliary syntax + + Syntax: Each cond clause must be of the form + +((lambda x x) 3 4 5 6) =⇒ (3 4 5 6) ( test expression1 . . . ) Alternatively, a +((lambda (x y . z) z) =⇒ (5 6) + where test is an expression. + 3 4 5 6) cond clause may be of the form + +Any variable must not appear more than once in ( test => expression ) + formals . + The last cond clause may be an “else clause”, which has + the form + 34 Revised6 Scheme + + (else expression1 expression2 . . . ). datum s of each case clause in turn, proceeding in or- + der from left to right through the set of clauses. If the +Semantics: A cond expression is evaluated by evaluating result of evaluating key is equivalent to a datum of a +the test expressions of successive cond clause s in order case clause , the corresponding expression s are evalu- +until one of them evaluates to a true value (see section 5.7). ated from left to right and the results of the last expres- +When a test evaluates to a true value, then the remaining sion in the case clause are returned as the results of the + expression s in its cond clause are evaluated in order, case expression. Otherwise, the comparison process con- +and the results of the last expression in the cond clause tinues. If the result of evaluating key is different from +are returned as the results of the entire cond expression. every datum in each set, then if there is an else clause its +If the selected cond clause contains only the test and expressions are evaluated and the results of the last are the +no expression s, then the value of the test is returned results of the case expression; otherwise the case expres- +as the result. If the selected cond clause uses the => sion returns unspecified values. +alternate form, then the expression is evaluated. Its value +must be a procedure. This procedure should accept one (case (* 2 3) +argument; it is called on the value of the test and the +values returned by this procedure are returned by the cond ((2 3 5 7) ’prime) +expression. If all test s evaluate to #f, and there is no else +clause, then the conditional expression returns unspecified ((1 4 6 8 9) ’composite)) =⇒ composite +values; if there is an else clause, then its expression s are unspecified +evaluated, and the values of the last one are returned. (case (car ’(c d)) consonant + + ((a) ’a) + + ((b) ’b)) =⇒ + + (case (car ’(c d)) + + ((a e i o u) ’vowel) + +(cond ((> 3 2) ’greater) ((w y) ’semivowel) + ((< 3 2) ’less)) + =⇒ greater (else ’consonant)) =⇒ +(cond ((> 3 3) ’greater) + ((< 3 3) ’less) =⇒ equal The last expression of a case clause is in tail context if + (else ’equal)) =⇒ 2 the case expression itself is; see section 11.20. + +(cond (’(1 2 3) => cadr) (and test1 . . . ) syntax + (else #f)) + +For a cond clause of one of the following forms Syntax: The test s must be expressions. + + ( test expression1 . . . ) Semantics: If there are no test s, #t is returned. Other- + (else expression1 expression2 . . . ) wise, the test expressions are evaluated from left to right + until a test returns #f or the last test is reached. In the +the last expression is in tail context if the cond form itself former case, the and expression returns #f without evalu- +is. For a cond clause of the form ating the remaining expressions. In the latter case, the last + expression is evaluated and its values are returned. + ( test => expression ) + (and (= 2 2) (> 2 1)) =⇒ #t +the (implied) call to the procedure that results from the (and (= 2 2) (< 2 1)) =⇒ #f +evaluation of expression is in a tail context if the cond (and 1 2 ’c ’(f g)) =⇒ (f g) +form itself is. See section 11.20. (and) =⇒ #t + +A sample definition of cond in terms of simpler forms is in +appendix B. + +(case key case clause1 case clause2 . . . ) syntax The and keyword could be defined in terms of if using + syntax-rules (see section 11.19) as follows: +Syntax: Key must be an expression. Each case clause +must have one of the following forms: (define-syntax and + (syntax-rules () + (( datum1 . . . ) expression1 expression2 . . . ) ((and) #t) + (else expression1 expression2 . . . ) ((and test) test) + ((and test1 test2 ...) +The second form, which specifies an “else clause”, may (if test1 (and test2 ...) #f)))) +only appear as the last case clause . Each datum is an +external representation of some object. The data repre- The last test expression is in tail context if the and ex- +sented by the datum s need not be distinct. pression itself is; see section 11.20. + +Semantics: A case expression is evaluated as follows. (or test1 . . . ) syntax + Key is evaluated and its result is compared using eqv? Syntax: The test s must be expressions. +(see section 11.5) against the data represented by the + 11. Base library 35 + +Semantics: If there are no test s, #f is returned. Other- (( variable1 init1 ) . . . ), +wise, the test expressions are evaluated from left to right +until a test returns a true value val (see section 5.7) or the where each init is an expression, and body is as de- +last test is reached. In the former case, the or expression scribed in section 11.3. Any variable must not appear more +returns val without evaluating the remaining expressions. than once in the variable s. +In the latter case, the last expression is evaluated and its +values are returned. Semantics: The init s are evaluated in the current envi- + ronment (in some unspecified order), the variable s are +(or (= 2 2) (> 2 1)) =⇒ #t bound to fresh locations holding the results, the body is +(or (= 2 2) (< 2 1)) =⇒ #t evaluated in the extended environment, and the values of +(or #f #f #f) =⇒ #f the last expression of body are returned. Each binding +(or ’(b c) (/ 3 0)) =⇒ (b c) of a variable has body as its region. + +The or keyword could be defined in terms of if using (let ((x 2) (y 3)) =⇒ 6 +syntax-rules (see section 11.19) as follows: (* x y)) + +(define-syntax or (let ((x 2) (y 3)) =⇒ 35 + (syntax-rules () (let ((x 7) + ((or) #f) (z (+ x y))) + ((or test) test) (* z x))) + ((or test1 test2 ...) + (let ((x test1)) See also named let, section 11.16. + (if x x (or test2 ...)))))) + (let* bindings body ) syntax + +The last test expression is in tail context if the or expres- Syntax: Bindings must have the form +sion itself is; see section 11.20. + (( variable1 init1 ) . . . ), + +11.4.6. Binding constructs where each init is an expression, and body is as de- + scribed in section 11.3. +The binding constructs described in this section create lo- +cal bindings for variables that are visible only in a delimited Semantics: The let* form is similar to let, but the init s +region. The syntax of the constructs let, let*, letrec, are evaluated and bindings created sequentially from left to +and letrec* is identical, but they differ in the regions (see right, with the region of each binding including the bind- +section 5.2) they establish for their variable bindings and ings to its right as well as body . Thus the second init +in the order in which the values for the bindings are com- is evaluated in an environment in which the first binding +puted. In a let expression, the initial values are computed is visible and initialized, and so on. +before any of the variables become bound; in a let* expres- +sion, the bindings and evaluations are performed sequen- (let ((x 2) (y 3)) =⇒ 70 +tially. In a letrec or letrec* expression, all the bindings (let* ((x 7) +are in effect while their initial values are being computed, (z (+ x y))) +thus allowing mutually recursive definitions. In a letrec (* z x))) +expression, the initial values are computed before being as- +signed to the variables; in a letrec*, the evaluations and Note: While the variables bound by a let expression must be +assignments are performed sequentially. distinct, the variables bound by a let* expression need not be + distinct. +In addition, the binding constructs let-values and +let*-values generalize let and let* to allow multiple (letrec bindings body ) syntax +variables to be bound to the results of expressions that +evaluate to multiple values. They are analogous to let and Syntax: Bindings must have the form +let* in the way they establish regions: in a let-values +expression, the initial values are computed before any of (( variable1 init1 ) . . . ), +the variables become bound; in a let*-values expression, +the bindings are performed sequentially. where each init is an expression, and body is as de- + scribed in section 11.3. Any variable must not appear more +Sample definitions of all the binding forms of this section than once in the variable s. +in terms of simpler forms are in appendix B. + Semantics: The variable s are bound to fresh locations, +(let bindings body ) syntax the init s are evaluated in the resulting environment (in +Syntax: Bindings must have the form some unspecified order), each variable is assigned to the + result of the corresponding init , the body is evaluated in + the resulting environment, and the values of the last expres- + sion in body are returned. Each binding of a variable + has the entire letrec expression as its region, making it + possible to define mutually recursive procedures. + 36 Revised6 Scheme + + (letrec ((even? It must be possible to evaluate each init without assigning + (lambda (n) or referring to the value of the corresponding variable + (if (zero? n) or the variable of any of the bindings that follow it in + #t bindings . Another restriction is that the continuation of + (odd? (- n 1))))) each init should not be invoked more than once. + + (odd? Implementation responsibilities: Implementations must, + [diff truncated]