Revised7 Report on the Algorithmic Language Scheme

ALEX SHINN,JOHN COWAN, AND ARTHUR A. GLECKLER (Editors)

STEVEN GANZ ALEXEY RADUL OLIN SHIVERS AARON W. HSU JEFFREY . READ ALARIC SNELL-PYM BRADLEY LUCIER DAVID RUSH GERALD J. SUSSMAN EMMANUEL MEDERNACH BENJAMIN L. RUSSEL

RICHARD KELSEY,WILLIAM CLINGER, AND JONATHAN REES (Editors, Revised5 Report on the Algorithmic Language Scheme)

MICHAEL SPERBER, R. KENT DYBVIG,MATTHEW FLATT, AND ANTON VAN STRAATEN (Editors, Revised6 Report on the Algorithmic Language Scheme)

Dedicated to the memory of John McCarthy

13 February 2012 2 Revised7 Scheme

SUMMARY CONTENTS The report gives a defining description of the programming Introduction ...... 3 language Scheme. Scheme is a statically scoped and prop- 1 Overview of Scheme ...... 5 erly tail recursive dialect of the Lisp 1.1 Semantics ...... 5 invented by Guy Lewis Steele Jr. and . 1.2 Syntax ...... 5 1.3 Notation and terminology ...... 5 It was designed to have an exceptionally clear and simple 2 Lexical conventions ...... 7 semantics and few different ways to form expressions. A 2.1 Identifiers ...... 7 wide variety of programming paradigms, including impera- 2.2 Whitespace and comments ...... 8 tive, functional, and object-oriented styles, find convenient 2.3 Other notations ...... 8 expression in Scheme. 2.4 Datum labels ...... 9 The introduction offers a brief history of the language and 3 Basic concepts ...... 9 3.1 Variables, syntactic keywords, and regions ...... 9 of the report. 3.2 Disjointness of types ...... 9 The first three chapters present the fundamental ideas of 3.3 External representations ...... 10 the language and describe the notational conventions used 3.4 Storage model ...... 10 for describing the language and for writing programs in the 3.5 Proper tail recursion ...... 10 language. 4 Expressions ...... 12 4.1 Primitive expression types ...... 12 Chapters 4 and 5 describe the syntax and semantics of 4.2 Derived expression types ...... 13 expressions, definitions, programs, and libraries. 4.3 Macros ...... 20 5 Program structure ...... 23 Chapter 6 describes Scheme’s built-in procedures, which 5.1 Programs ...... 23 include all of the language’s data manipulation and in- 5.2 Definitions ...... 23 put/output primitives. 5.3 Syntax definitions ...... 25 Chapter 7 provides a formal syntax for Scheme written in 5.4 Record type definitions ...... 25 extended BNF, along with a formal denotational semantics. 5.5 Libraries ...... 26 An example of the use of the language follows the formal 6 Standard procedures ...... 28 6.1 Equivalence predicates ...... 28 syntax and semantics. 6.2 Numbers ...... 30 Appendix A provides a list of the standard libraries and 6.3 Booleans ...... 37 the identifiers that they export. 6.4 Pairs and lists ...... 38 6.5 Symbols ...... 40 Appendix B provides a list of optional but standardized 6.6 Characters ...... 41 implementation feature names. 6.7 Strings ...... 42 The report concludes with a list of references and an al- 6.8 Vectors ...... 45 phabetic index. 6.9 Bytevectors ...... 46 6.10 Control features ...... 47 6.11 Exceptions ...... 50 6.12 Eval ...... 51 6.13 Input and output ...... 51 7 Formal syntax and semantics ...... 57 7.1 Formal syntax ...... 57 7.2 Formal semantics ...... 60 7.3 Derived expression types ...... 63 A Standard Libraries ...... 68 B Standard Feature Identifiers ...... 70 Notes ...... 71 *** DRAFT*** Additional material ...... 73 February 14, 2012 Example ...... 74 References ...... 75 Alphabetic index of definitions of concepts, keywords, and procedures ...... 77 Introduction 3 INTRODUCTION

Programming languages should be designed not by piling Programming Language in 1991 [20]. In 1998, several ad- feature on top of feature, but by removing the weaknesses ditions to the IEEE standard, including high-level hygienic and restrictions that make additional features appear nec- macros, multiple return values and eval, were finalized as essary. Scheme demonstrates that a very small number of the R5RS [2]. rules for forming expressions, with no restrictions on how In the fall of 2006, work began on a more ambitious stan- they are composed, suffice to form a practical and efficient dard, including many new improvements and stricter re- programming language that is flexible enough to support quirements made in the interest of improved portability. most of the major programming paradigms in use today. The resulting standard, the R6RS, was completed in Au- Scheme was one of the first programming languages to in- gust 2007 [1], and was organized as a core language and corporate first class procedures as in the lambda calculus, set of mandatory standard libraries. The size and goals of thereby proving the usefulness of static scope rules and the R6RS, however, were controversial, and adoption of the block structure in a dynamically typed language. Scheme new standard was not as widespread as had been hoped. was the first major dialect of Lisp to distinguish procedures In consequence, the Scheme Steering Committee decided in from lambda expressions and symbols, to use a single lex- August 2009 to divide the standard into two separate but ical environment for all variables, and to evaluate the op- compatible languages — a “small” language, suitable for erator position of a procedure call in the same way as an educators, researchers and embedded languages, focused operand position. By relying entirely on procedure calls on R5RS compatibility, and a “large” language focused on to express iteration, Scheme emphasized the fact that tail- the practical needs of mainstream software development recursive procedure calls are essentially GOTO’s that pass which would evolve to become a replacement for R6RS. arguments, thus allowing a programming style that is both The present report describes the “small” language of that coherent and efficient. Scheme was the first widely used effort. programming language to embrace first class escape proce- dures, from which all previously known sequential control We intend this report to belong to the entire Scheme com- structures can be synthesized. A subsequent version of munity, and so we grant permission to copy it in whole or in Scheme introduced the concept of exact and inexact num- part without fee. In particular, we encourage implementors bers, an extension of ’s generic arithmetic. of Scheme to use this report as a starting point for manuals More recently, Scheme became the first programming lan- and other documentation, modifying it as necessary. guage to support hygienic macros, which permit the syntax of a block-structured language to be extended in a consis- tent and reliable manner. Acknowledgements

We would like to thank the members of the Steering Background Committee, William Clinger, Marc Feeley, Chris Hanson, Jonathan Rees, and Olin Shivers, for their support and The first description of Scheme was written in 1975 [36]. A guidance. We’d like to thank the following people for revised report [33] appeared in 1978, which described the their help: Per Bothner, Taylor Campbell, Ray Dillinger, evolution of the language as its MIT implementation was Brian Harvey, Shiro Kawai, Jonathan Kraut, Thomas upgraded to support an innovative [34]. Three Lord, Vincent Manis, Jeronimo Pellegrini, Jussi Piitu- distinct projects began in 1981 and 1982 to use variants lainen, Alex Queiroz, Jim Rees, Jay Reynolds Freeman, of Scheme for courses at MIT, Yale, and Indiana Univer- Malcolm Tredinnick, Denis Washington, Andy Wingo, and sity [29, 25, 16]. An introductory text- Andre van Tonder. book using Scheme was published in 1984 [3]. In addition we would like to thank all the past editors, and As Scheme became more widespread, local dialects be- the people who helped them in turn: , Nor- gan to diverge until students and researchers occasion- man Adams, David Bartley, Alan Bawden, Michael Blair, ally found it difficult to understand code written at other Gary Brooks, George Carrette, Andy Cromarty, Pavel Cur- sites. Fifteen representatives of the major implementations tis, Jeff Dalton, Olivier Danvy, Ken Dickey, Bruce Duba, of Scheme therefore met in October 1984 to work toward Robert Findler, Andy Freeman, Richard Gabriel, Yekta a better and more widely accepted standard for Scheme. G¨ursel,Ken Haase, Robert Halstead, Robert Hieb, Paul Their report, the RRRS [8], was published at MIT and In- Hudak, Morry Katz, Eugene Kohlbecker, Chris Lindblad, diana University in the summer of 1985. Further revision Jacob Matthews, Mark Meyer, Jim Miller, Don Oxley, Jim took place in the spring of 1986, resulting in the R3RS [31]. Philbin, , John Ramsdell, Guillermo Rozas, Work in the spring of 1988 resulted in R4RS [10], which Mike Shaff, Jonathan Shapiro, Guy Steele, Julie Sussman, became the basis for the IEEE Standard for the Scheme Perry Wagle, Mitchel Wand, Daniel Weise, Henry Wu, and 4 Revised7 Scheme

Ozan Yigit. We thank Carol Fessenden, Daniel Friedman, and Christopher Haynes for permission to use text from the Scheme 311 version 4 reference manual. We thank Texas Instruments, Inc. for permission to use text from the TI Scheme Language Reference Manual [38]. We gladly ac- knowledge the influence of manuals for MIT Scheme [25], T [30], Scheme 84 [17], Common Lisp [35], and Algol 60 [26]. 1. Overview of Scheme 5 DESCRIPTION OF THE LANGUAGE

1. Overview of Scheme its place is a distinction between exact arithmetic, which corresponds to the mathematical ideal, and inexact arith- 1.1. Semantics metic on approximations. Exact arithmetic is not limited to integers. This section gives an overview of Scheme’s semantics. A detailed informal semantics is the subject of chapters 3 through 6. For reference purposes, section 7.2 provides a 1.2. Syntax formal semantics of Scheme. Scheme is a statically scoped programming language. Each Scheme, like most dialects of Lisp, employs a fully paren- use of a variable is associated with a lexically apparent thesized prefix notation for programs and other data; the binding of that variable. grammar of Scheme generates a sublanguage of the lan- guage used for data. An important consequence of this Scheme is a dynamically typed language. Types are asso- simple, uniform representation is that Scheme programs ciated with values (also called objects) rather than with and data can easily be treated uniformly by other Scheme variables. Statically typed languages, by contrast, asso- programs. For example, the eval procedure evaluates a ciate types with variables and expressions as well as with Scheme program expressed as data. values. The procedure performs syntactic as well as lexical All objects created in the course of a Scheme computation, read decomposition of the data it reads. The procedure including procedures and continuations, have unlimited ex- read parses its input as data (section 7.1.2), not as program. tent. No Scheme object is ever destroyed. The reason that implementations of Scheme do not (usually!) run out of The formal syntax of Scheme is described in section 7.1. storage is that they are permitted to reclaim the storage occupied by an object if they can prove that the object cannot possibly matter to any future computation. 1.3. Notation and terminology Implementations of Scheme are required to be properly 1.3.1. Base and optional features tail-recursive. This allows the execution of an iterative computation in constant space, even if the iterative compu- Every identifier defined in this report appears in one of tation is described by a syntactically recursive procedure. several libraries. Identifiers defined in the base library are Thus with a properly tail-recursive implementation, iter- not marked specially in the body of the report. A summary ation can be expressed using the ordinary procedure-call of all the standard libraries and the features they provide mechanics, so that special iteration constructs are useful is given in Appendix A. only as syntactic sugar. See section 3.5. Implementations must provide the base library and all the Scheme procedures are objects in their own right. Proce- identifiers exported from it. Implementations are free to dures can be created dynamically, stored in data structures, provide or omit the other libraries given in this report, but returned as results of procedures, and so on. each library must either be provided in its entirety, export- One distinguishing feature of Scheme is that continuations, ing no additional identifiers, or else omitted altogether. which in most other languages only operate behind the Implementations may provide other libraries not described scenes, also have “first-class” status. Continuations are in this report. Implementations may also extend the func- useful for implementing a wide variety of advanced control tion of any identifier in this report, provided the extensions constructs, including non-local exits, backtracking, and are not in conflict with the language reported here. In par- coroutines. See section 6.10. ticular, implementations must support portable code by Arguments to Scheme procedures are always passed by providing a mode of operation in which the lexical syntax value, which means that the actual argument expressions does not conflict with the lexical syntax described in this are evaluated before the procedure gains control, regardless report. of whether the procedure needs the result of the evaluation. Scheme’s model of arithmetic is designed to remain as in- 1.3.2. Error situations and unspecified behavior dependent as possible of the particular ways in which num- bers are represented within a computer. In Scheme, every When speaking of an error situation, this report uses the integer is a rational number, every rational is a real, and phrase “an error is signalled” to indicate that implementa- every real is a complex number. Thus the distinction be- tions must detect and report the error. An error is signalled tween integer and real arithmetic, so important to many by raising a non-continuable exception, as if by the proce- programming languages, does not appear in Scheme. In dure raise as described in section 6.11. The object raised 6 Revised7 Scheme is implementation-dependent and need not be a newly al- If category is “syntax,” the entry describes an expression located object every time. In addition to errors signalled type, and the template gives the syntax of the expression by situations described in this report, programmers may type. Components of expressions are designated by syn- signal their own errors and handle signalled errors. tactic variables, which are written using angle brackets, for If such wording does not appear in the discussion of an example, hexpressioni, hvariablei. Syntactic variables are error, then implementations are not required to detect or intended to denote segments of program text; for example, report the error, though they are encouraged to do so. Such hexpressioni stands for any string of characters which is a a situation is sometimes, but not always, referred to with syntactically valid expression. The notation the phrase “an error.” For example, it is an error for a pro- cedure to be passed an argument of a type that the proce- dure is not explicitly specified to handle, even though such hthing1i ... domain errors are seldom mentioned in this report. Imple- mentations may extend a procedure’s domain of definition to include such arguments. indicates zero or more occurrences of a hthingi, and This report uses the phrase “may report a violation of an implementation restriction” to indicate circumstances un- der which an implementation is permitted to report that it is unable to continue execution of a correct program hthing1i hthing2i ... because of some restriction imposed by the implementa- tion. Implementation restrictions are discouraged, but im- plementations are encouraged to report violations of im- indicates one or more occurrences of a hthingi. plementation restrictions. For example, an implementation may report a violation of If category is “auxiliary syntax,” then the entry describes an implementation restriction if it does not have enough a syntax binding that occurs only as part of specific sur- storage to run a program, or if an arithmetic operation rounding expressions. Any use as an independent syntactic would produce an exact number that is too large for the construct or identifier is an error. implementation to represent. If the value of an expression is said to be “unspecified,” then the expression must evaluate to some object without If category is “procedure,” then the entry describes a pro- signalling an error, but the value depends on the imple- cedure, and the header line gives a template for a call to the mentation; this report explicitly does not say what value procedure. Argument names in the template are italicized. is returned. Thus the header line Finally, the words and phrases “must,” “must not,” “shall,” “shall not,” “should,” “should not,” “may,” “re- (vector-ref vector k) procedure quired,” “recommended,” and “optional,” although not capitalized in this report, are to be interpreted as described indicates that the procedure bound to the vector-ref in RFC 2119 [6]. In particular, “must” and “must not” are variable takes two arguments, a vector vector and an exact used only when absolute restrictions are placed on imple- non-negative integer k (see below). The header lines mentations.

(make-vector k) procedure 1.3.3. Entry format (make-vector k fill) procedure Chapters 4 and 6 are organized into entries. Each entry describes one language feature or a group of related fea- indicate that the make-vector procedure must be defined tures, where a feature is either a syntactic construct or a to take either one or two arguments. procedure. An entry begins with one or more header lines of the form It is an error for an operation to be presented with an ar- template category gument that it is not specified to handle. For succinctness, for identifiers in the base library, or we follow the convention that if an argument name is also the name of a type listed in section 3.2, then it is an error if template library category that argument is not of the named type. For example, the where library is the short name of a library as defined in header line for vector-ref given above dictates that the Appendix A. first argument to vector-ref is a vector. The following 2. Lexical conventions 7 naming conventions also imply type restrictions: 2. Lexical conventions

obj any object This section gives an informal account of some of the lexical list, list , . . . list , ... list (see section 6.4) conventions used in writing Scheme programs. For a formal 1 j syntax of Scheme, see section 7.1. z, z1, . . . zj, ... complex number x, x1, . . . xj, ... real number y, y1, . . . yj, ... real number q, q1, . . . qj, ... rational number 2.1. Identifiers n, n1, . . . nj, ... integer k, k1, . . . kj, ... exact non-negative integer An identifier is any sequence of letters, digits, and “ex- string string tended identifier characters” provided that it does not have pair pair a prefix which is a valid number. However, the . token (a list list single period) used in the list syntax is not an identifier. alist association list (list of pairs) symbol symbol All implementations of Scheme must support the following char character extended identifier characters: letter alphabetic character !$%&*+-./:<=>?@^_~ byte exact non-negative integer < 256 bytevector bytevector In addition, any character supported by an implementation proc procedure can be used within an identifier when specified using an thunk zero-argument procedure hinline hex escapei. For example, the identifier H\x65;llo port port is the same as the identifier Hello, and in an implementa- tion that supports the appropriate Unicode character the identifier \x3BB; is the same as the identifier λ. 1.3.4. Evaluation examples As a convenience, identifiers may also be written as a se- The symbol “=⇒” used in program examples is read “eval- quence of zero or more characters enclosed within vertical uates to.” For example, bars (|), analogous to string literals. Any character, includ- ing whitespace characters, but excluding the backslash and (* 5 8) =⇒ 40 vertical bar characters, may appear verbatim in such an identifier. It is also possible to include the backslash and means that the expression (* 5 8) evaluates to the ob- vertical bar characters, as well as any other character, in ject 40. Or, more precisely: the expression given by the the identifier with an hinline hex escapei. Thus the identi- sequence of characters “(* 5 8)” evaluates, in the initial fier |foo bar| is the same as the identifier foo\x20;bar. environment, to an object that can be represented exter- Note that || is a valid identifier that is not equal to any nally by the sequence of characters “40.” See section 3.3 other identifier. for a discussion of external representations of objects. Here are some examples of identifiers:

lambda q 1.3.5. Naming conventions list->vector +soup+ + V17a By convention, ? is the final character of the names of <=? a34kTMNs procedures that always return a boolean value. Such pro- ->string ... cedures are called predicates. |two words| two\x20;words the-word-recursion-has-many-meanings Similarly, ! is the final character of the names of proce- dures that store values into previously allocated locations See section 7.1.1 for the formal syntax of identifiers. (see section 3.4). Such procedures are called mutation pro- Identifiers have two uses within Scheme programs: cedures. The value returned by a mutation procedure is unspecified. • Any identifier may be used as a variable or as a syn- By convention, “->” appears within the names of proce- tactic keyword (see sections 3.1 and 4.3). dures that take an object of one type and return an anal- ogous object of another type. For example, list->vector • When an identifier appears as a literal or within a takes a list and returns a vector whose elements are the literal (see section 4.1.2), it is being used to denote a same as those of the list. symbol (see section 6.5). 8 Revised7 Scheme

In contrast with earlier revisions of the report [2], the syn- #| tax distinguishes between upper and lower case in identi- The FACT procedure computes the factorial fiers and in characters specified using their names. How- of a non-negative integer. ever, it does not distinguish between upper and lower case |# in numbers, nor in hinline hex escapesi used in the syntax (define fact of identifiers, characters, or strings. None of the identifiers (lambda (n) (if (= n 0) defined in this report contain upper-case characters, even #;(= n 1) when they may appear to do so as a result of the English- 1 ;Base case: return 1 language convention of capitalizing the word at the begin- (* n (fact (- n 1)))))) ning of a sentence. The following directives give explicit control over case fold- ing. 2.3. Other notations

For a description of the notations used for numbers, see #!fold-case section 6.2. #!no-fold-case These directives may appear anywhere comments are per- . + - These are used in numbers, and may also occur any- mitted (see section 2.2) and are treated as comments, where in an identifier. A delimited plus or minus sign except that they affect the reading of subsequent data. by itself is also an identifier. A delimited period (not The #!fold-case directive causes the read procedure to occurring within a number or identifier) is used in the case-fold (as if by string-foldcase; see section 6.7) each notation for pairs (section 6.4), and to indicate a rest- identifier and character name subsequently read from the parameter in a formal parameter list (section 4.1.4). same port. (It has no effect on character literals.) The Note that a sequence of two or more periods is an #!no-fold-case directive causes the read procedure to identifier. return to the default, non-folding behavior. () Parentheses are used for grouping and to notate lists (section 6.4). 2.2. Whitespace and comments ’ The single quote character is used to indicate literal data Whitespace characters include the space and newline char- (section 4.1.2). acters. (Implementations may provide additional whites- ` The backquote character is used to indicate partly con- pace characters such as tab or page break.) Whitespace is stant data (section 4.2.8). used for improved readability and as necessary to separate tokens from each other, a token being an indivisible lexi- , ,@ The character comma and the sequence comma at- cal unit such as an identifier or number, but is otherwise sign are used in conjunction with backquote (sec- insignificant. Whitespace can occur between any two to- tion 4.2.8). kens, but not within a token. Whitespace occurring inside a string or inside a symbol delimited by vertical bars is " The double quote character is used to delimit strings significant. (section 6.7). The lexical syntax includes several comment forms. Com- \ Backslash is used in the syntax for character constants ments are treated exactly like whitespace. (section 6.6) and as an escape character within string constants (section 6.7) and identifiers (section 7.1.1). A semicolon (;) indicates the start of a line comment. The comment continues to the end of the line on which the []{} Left and right square brackets and curly braces semicolon appears. Comments are invisible to Scheme, but are reserved for possible future extensions to the lan- the end of the line is visible as whitespace. This prevents a guage. comment from appearing in the middle of an identifier or number. # Sharp sign is used for a variety of purposes depending on the character that immediately follows it: Another way to indicate a comment is to prefix a hdatumi (cf. section 7.1.2) with #; and optional hwhitespacei. The #t #f These are the boolean constants (section 6.3), along comment consists of the comment prefix #;, the space, and with the alternatives #true and #false. the hdatumi together. This notation is useful for “com- menting out” sections of code. #\ This introduces a character constant (section 6.6). Block comments are indicated with properly nested #| and #( This introduces a vector constant (section 6.8). Vector |# pairs. constants are terminated by ) . 3. Basic concepts 9

#u8( This introduces a bytevector constant (section 6.9). is bound is called the variable’s value. By abuse of termi- Bytevector constants are terminated by ) . nology, the variable is sometimes said to name the value or to be bound to the value. This is not quite accurate, but #e #i #b #o #d #x These are used in the notation for confusion rarely results from this practice. numbers (section 6.2.5). Certain expression types are used to create new kinds of #hni= #hni# These are used for labeling and referencing syntax and to bind syntactic keywords to those new syn- other literal data (section 2.4). taxes, while other expression types create new locations and bind variables to those locations. These expression types are called binding constructs. Those that bind syn- 2.4. Datum labels tactic keywords are listed in section 4.3. The most fun- damental of the variable binding constructs is the lambda #hni=hdatumi lexical syntax expression, because all other variable binding constructs #hni# lexical syntax can be explained in terms of lambda expressions. The other variable binding constructs are let, let*, letrec, The lexical syntax #hni=hdatumi reads the same as letrec*, let-values, let*-values, and do expressions hdatumi, but also results in hdatumi being labelled by hni. (see sections 4.1.4, 4.2.2, and 4.2.4). It is an error if hni is not a sequence of digits. The lexical syntax #hni# serves as a reference to some ob- Scheme is a language with block structure. To each place ject labelled by #hni=; the result is the same object as the where an identifier is bound in a program there corresponds #hni= as compared with eqv? (see section 6.1). a region of the program text within which the binding is visible. The region is determined by the particular bind- Together, these syntaxes permit the notation of structures ing construct that establishes the binding; if the binding is with shared or circular substructure. established by a lambda expression, for example, then its (let ((x (list ’a ’b ’c))) region is the entire lambda expression. Every mention of (set-cdr! (cddr x) x) an identifier refers to the binding of the identifier that es- x) =⇒ #0=(a b c . #0#) tablished the innermost of the regions containing the use. If there is no binding of the identifier whose region con- tains the use, then the use refers to the binding for the The scope of a datum label is the portion of the outermost variable in the top level environment, if any (chapters 4 datum in which it appears that is to the right of the label. and 6); if there is no binding for the identifier, it is said to Consequently, a reference #hni# may occur only after a la- be unbound. bel #hni=; it is an error to attempt a forward reference. In addition, it is an error if the reference appears as the la- belled object itself (as in #hni= #hni#), because the object labelled by #hni= is not well defined in this case. 3.2. Disjointness of types It is an error for a hprogrami or hlibraryi to include circular references except in literals. In particular, it is an error for No object satisfies more than one of the following predi- quasiquote (section 4.2.8) to contain them. cates:

#1=(begin (display #\x) . #1#) boolean? pair? =⇒ error symbol? number? char? string? vector? bytevector? 3. Basic concepts port? procedure? 3.1. Variables, syntactic keywords, and re- null? gions These predicates define the types boolean, pair, symbol, number, char (or character), string, vector, bytevector, port, An identifier names either a type of syntax or a location procedure, and the empty list object. where a value can be stored. An identifier that names a type of syntax is called a syntactic keyword and is said to be Although there is a separate boolean type, any Scheme bound to that syntax. An identifier that names a location value can be used as a boolean value for the purpose of is called a variable and is said to be bound to that location. a conditional test. As explained in section 6.3, all values The set of all visible bindings in effect at some point in count as true in such a test except for #f. This report uses a program is known as the environment in effect at that the word “true” to refer to any Scheme value except #f, point. The value stored in the location to which a variable and the word “false” to refer to #f. 10 Revised7 Scheme

3.3. External representations An object fetched from a location, by a variable reference or by a procedure such as car, vector-ref, or string-ref, An important concept in Scheme (and Lisp) is that of the is equivalent in the sense of eqv? (section 6.1) to the object external representation of an object as a sequence of char- last stored in the location before the fetch. acters. For example, an external representation of the inte- Every location is marked to show whether it is in use. No ger 28 is the sequence of characters “28,” and an external variable or object ever refers to a location that is not in use. representation of a list consisting of the integers 8 and 13 Whenever this report speaks of storage being allocated for is the sequence of characters “(8 13).” a variable or object, what is meant is that an appropriate The external representation of an object is not neces- number of locations are chosen from the set of locations sarily unique. The integer 28 also has representations that are not in use, and the chosen locations are marked “#e28.000” and “#x1c,” and the list in the previous para- to indicate that they are now in use before the variable or graph also has the representations “( 08 13 )” and “(8 object is made to denote them. . (13 . ()))” (see section 6.4). Every object that denotes locations is either mutable or Many objects have standard external representations, but immutable. Literal constants, the strings returned by some, such as procedures, do not have standard represen- symbol->string, and possibly the environment returned tations (although particular implementations may define by scheme-report-environment are immutable objects. representations for them). All objects created by the other procedures listed in this report are mutable. It is an error to attempt to store a An external representation can be written in a program to new value into a location that is denoted by an immutable obtain the corresponding object (see quote, section 4.1.2). object. External representations can also be used for input and These locations should be understood as conceptual, not output. The procedure read (section 6.13.2) parses ex- physical. Hence, they do not necessarily correspond to ternal representations, and the procedure write (sec- memory addresses, and even if they do, the memory ad- tion 6.13.3) generates them. Together, they provide an dress may not be constant. elegant and powerful input/output facility. Rationale: In many systems it is desirable for constants (i.e. Note that the sequence of characters “(+ 2 6)” is not an the values of literal expressions) to reside in read-only memory. external representation of the integer 8, even though it is an Making it an error to alter constants permits this implementa- expression evaluating to the integer 8; rather, it is an exter- tion strategy, while not requiring other systems to distinguish nal representation of a three-element list, the elements of between mutable and immutable objects. which are the symbol + and the integers 2 and 6. Scheme’s syntax has the property that any sequence of characters that is an expression is also the external representation of 3.5. Proper tail recursion some object. This can lead to confusion, since it is not always obvious out of context whether a given sequence of Implementations of Scheme are required to be properly tail- characters is intended to denote data or program, but it is recursive. Procedure calls that occur in certain syntactic also a source of power, since it facilitates writing programs contexts defined below are tail calls. A Scheme imple- such as interpreters and that treat programs as mentation is properly tail-recursive if it supports an un- data (or vice versa). bounded number of active tail calls. A call is active if The syntax of external representations of various kinds of the called procedure might still return. Note that this in- objects accompanies the description of the primitives for cludes calls that might be returned from either by the cur- manipulating the objects in the appropriate sections of rent continuation or by continuations captured earlier by chapter 6. call-with-current-continuation that are later invoked. In the absence of captured continuations, calls could return at most once and the active calls would be those that had 3.4. Storage model not yet returned. A formal definition of proper tail recur- sion can be found in [12]. Variables and objects such as pairs, vectors, and strings Rationale: implicitly denote locations or sequences of locations. A Intuitively, no space is needed for an active tail call because the string, for example, denotes as many locations as there are continuation that is used in the tail call has the same semantics characters in the string. A new value can be stored into as the continuation passed to the procedure containing the call. one of these locations using the string-set! procedure, Although an improper implementation might use a new con- but the string continues to denote the same locations as tinuation in the call, a return to this new continuation would before. be followed immediately by a return to the continuation passed 3. Basic concepts 11 to the procedure. A properly tail-recursive implementation re- (let* (hbinding speci*) htail bodyi) turns to that continuation directly. (letrec (hbinding speci*) htail bodyi) Proper tail recursion was one of the central ideas in Steele and (letrec* (hbinding speci*) htail bodyi) Sussman’s original version of Scheme. Their first Scheme in- (let-values (hformalsi*) htail bodyi) terpreter implemented both functions and actors. Control flow (let*-values (hformalsi*) htail bodyi) was expressed using actors, which differed from functions in that they passed their results on to another actor instead of (let-syntax (hsyntax speci*) htail bodyi) returning to a caller. In the terminology of this section, each (letrec-syntax (hsyntax speci*) htail bodyi) actor finished with a tail call to another actor. Steele and Sussman later observed that in their the (begin htail sequencei) code for dealing with actors was identical to that for functions and thus there was no need to include both in the language. (do (hiteration speci*) A tail call is a procedure call that occurs in a tail con- (htesti htail sequencei) text. Tail contexts are defined inductively. Note that a tail hexpressioni*) context is always determined with respect to a particular lambda expression. where

hcond clausei −→ htesti htail sequencei • The last expression within the body of a lambda ex- ( ) hcase clausei −→ hdatumi* htail sequencei pression, shown as htail expressioni below, occurs in (( ) ) a tail context. The same is true of all the bodies of htail bodyi −→ hdefinitioni* htail sequencei case-lambda expressions. htail sequencei −→ hexpressioni* htail expressioni (lambda hformalsi hdefinitioni* hexpressioni* htail expressioni) • If a cond or case expression is in a tail con- text, and has a clause of the form (hexpression1i => • If one of the following expressions is in a tail context, hexpression2i) then the (implied) call to the proce- then the subexpressions shown as htail expressioni are dure that results from the evaluation of hexpression2i in a tail context. These were derived from rules in the is in a tail context. hexpression2i itself is not in a tail grammar given in chapter 7 by replacing some occur- context. rences of hbodyi with htail bodyi, some occurrences of • Note that hcond clauseis appear in guard expressions hexpressioni with htail expressioni, and some occur- as well as cond expressions. rences of hsequencei with htail sequencei. Only those rules that contain tail contexts are shown here. Certain procedures defined in this report are also re- (if hexpressioni htail expressioni htail expressioni) quired to perform tail calls. The first argument passed (if hexpressioni htail expressioni) to apply and to call-with-current-continuation, and the second argument passed to call-with-values, must (cond hcond clausei+) be called via a tail call. Similarly, eval must evaluate its (cond hcond clausei* (else htail sequencei)) first argument as if it were in tail position within the eval procedure. (case hexpressioni In the following example the only tail call is the call to f. hcase clausei+) None of the calls to g or h are tail calls. The reference to (case hexpressioni x is in a tail context, but it is not a call and thus is not a hcase clausei* tail call. (else htail sequencei)) (lambda () (if (g) (and hexpressioni* htail expressioni) (let ((x (h))) (or hexpressioni* htail expressioni) x) (and (g) (f)))) (when htesti htail sequencei) (unless htesti htail sequencei) Note: Implementations are allowed, but not required, to recog- nize that some non-tail calls, such as the call to h above, can be (let (hbinding speci*) htail bodyi) evaluated as though they were tail calls. In the example above, (let hvariablei (hbinding speci*) htail bodyi) the let expression could be compiled as a tail call to h. (The 12 Revised7 Scheme possibility of h returning an unexpected number of values can Numerical constants, string constants, character constants, be ignored, because in that case the effect of the let is explicitly bytevector constants, and boolean constants evaluate to unspecified and implementation-dependent.) themselves; they need not be quoted. ’"abc" =⇒ "abc" 4. Expressions "abc" =⇒ "abc" ’145932 =⇒ 145932 Expression types are categorized as primitive or derived. 145932 =⇒ 145932 Primitive expression types include variables and procedure ’#t =⇒ #t calls. Derived expression types are not semantically prim- #t =⇒ #t itive, but can instead be defined as macros. Suitable defi- As noted in section 3.4, it is an error to alter a constant nitions of some of the derived expressions are given in sec- (i.e. the value of a literal expression) using a mutation pro- tion 7.3. cedure like set-car! or string-set!. The procedures force, eager, and make-parameter are also described in this chapter because they are intimately 4.1.3. Procedure calls associated with the delay, lazy, and parameterize ex- pression types. (hoperatori hoperand1i ... ) syntax A procedure call is written by simply enclosing in paren- theses expressions for the procedure to be called and the 4.1. Primitive expression types arguments to be passed to it. The operator and operand expressions are evaluated (in an unspecified order) and the 4.1.1. Variable references resulting procedure is passed the resulting arguments. (+ 3 4) =⇒ 7 hvariablei syntax ((if #f + *) 3 4) =⇒ 12 An expression consisting of a variable (section 3.1) is a A number of procedures are available as the values of vari- variable reference. The value of the variable reference is ables in the initial environment; for example, the addition the value stored in the location to which the variable is and multiplication procedures in the above examples are bound. It is an error to reference an unbound variable. the values of the variables + and *. New procedures are cre- ated by evaluating lambda expressions (see section 4.1.4). (define x 28) Procedure calls may return any number of values (see =⇒ x 28 values in section 6.10). Most of the procedures defined in this report return one value or, for procedures such as apply, pass on the values returned by a call to one of their 4.1.2. Literal expressions arguments. Exceptions are noted in the individual descrip- tions. hdatumi syntax (quote ) Note: In contrast to other dialects of Lisp, the order of hdatumi syntax ’ evaluation is unspecified, and the operator expression and the hconstanti syntax operand expressions are always evaluated with the same evalu- (quote hdatumi) evaluates to hdatumi. hDatumi may be ation rules. any external representation of a Scheme object (see sec- Note: Although the order of evaluation is otherwise unspeci- tion 3.3). This notation is used to include literal constants fied, the effect of any concurrent evaluation of the operator and in Scheme code. operand expressions is constrained to be consistent with some (quote a) =⇒ a sequential order of evaluation. The order of evaluation may be (quote #(a b c)) =⇒ #(a b c) chosen differently for each procedure call. (quote (+ 1 2)) =⇒ (+ 1 2) Note: In many dialects of Lisp, the empty list, (), is a legiti- mate expression evaluating to itself. In Scheme, it is an error. (quote hdatumi) may be abbreviated as ’hdatumi. The two notations are equivalent in all respects. 4.1.4. Procedures ’a =⇒ a ’#(a b c) =⇒ #(a b c) (lambda hformalsi hbodyi) syntax ’() =⇒ () ’(+ 1 2) =⇒ (+ 1 2) Syntax: hFormalsi should be a formal arguments list as ’(quote a) =⇒ (quote a) described below, and hbodyi should be a sequence of one ’’a =⇒ (quote a) or more expressions. 4. Expressions 13

Semantics: A lambda expression evaluates to a procedure. 4.1.5. Conditionals The environment in effect when the lambda expression was evaluated is remembered as part of the procedure. When (if htesti hconsequenti halternatei) syntax the procedure is later called with some actual arguments, (if htesti hconsequenti) syntax the environment in which the lambda expression was evalu- Syntax: hTesti, hconsequenti, and halternatei should be ated will be extended by binding the variables in the formal expressions. argument list to fresh locations, the corresponding actual argument values will be stored in those locations, and the Semantics: An if expression is evaluated as follows: first, body of the lambda expression will be evaluated in the ex- htesti is evaluated. If it yields a true value (see section 6.3), tended environment. The results of the last expression in then hconsequenti is evaluated and its values are returned. the body will be returned as the results of the procedure Otherwise halternatei is evaluated and its values are re- call. turned. If htesti yields a false value and no halternatei is specified, then the result of the expression is unspecified. (lambda (x) (+ x x)) =⇒ a procedure (if (> 3 2) ’yes ’no) =⇒ yes ((lambda (x) (+ x x)) 4) =⇒ 8 (if (> 2 3) ’yes ’no) =⇒ no (if (> 3 2) (define reverse-subtract (- 3 2) (lambda (x y) (- y x))) (+ 3 2)) =⇒ 1 (reverse-subtract 7 10) =⇒ 3

(define add4 4.1.6. Assignments (let ((x 4)) (lambda (y) (+ x y)))) (add4 6) =⇒ 10 (set! hvariablei hexpressioni) syntax hExpressioni is evaluated, and the resulting value is stored hFormalsi should have one of the following forms: in the location to which hvariablei is bound. It is an error if hvariablei is not bound either in some region enclosing the set! expression or at top level. The result of the set! • (hvariable1i ... ): The procedure takes a fixed num- expression is unspecified. ber of arguments; when the procedure is called, the arguments will be stored in newly allocated locations (define x 2) that are bound to the corresponding variables. (+ x 1) =⇒ 3 (set! x 4) =⇒ unspecified (+ x 1) =⇒ 5 •h variablei: The procedure takes any number of argu- ments; when the procedure is called, the sequence of actual arguments is converted into a newly allocated 4.2. Derived expression types list, and the list is stored in a newly allocated location that is bound to hvariablei. The constructs in this section are hygienic, as discussed in section 4.3. For reference purposes, section 7.3 gives • (hvariable i ... hvariable i . hvariable i): If a 1 n n+1 macro definitions that will convert most of the constructs space-delimited period precedes the last variable, then described in this section into the primitive constructs de- the procedure takes n or more arguments, where n is scribed in the previous section. the number of formal arguments before the period (it is an error if there is not at least one). The value stored in the binding of the last variable will be a newly allo- 4.2.1. Conditionals cated list of the actual arguments left over after all the

other actual arguments have been matched up against (cond hclause1i hclause2i ... ) syntax the other formal arguments. else auxiliary syntax => auxiliary syntax It is an error for a hvariablei to appear more than once in Syntax: hClausesi take one of two forms, either hformalsi. (htesti hexpression1i ... ) where htesti is any expression, or ((lambda x x) 3 4 5 6) =⇒ (3 4 5 6) ((lambda (x y . z) z) (htesti => hexpressioni) 3 4 5 6) =⇒ (5 6) The last hclausei may be an “else clause,” which has the form 14 Revised7 Scheme

(else hexpression1i hexpression2i ... ). If the result of evaluating hkeyi is different from every hdatumi, then if there is an else clause its expressions are Semantics: A cond expression is evaluated by evaluating evaluated and the results of the last are the results of the the htesti expressions of successive hclauseis in order until case expression; otherwise the result of the case expres- one of them evaluates to a true value (see section 6.3). sion is unspecified. When a htesti evaluates to a true value, then the remaining hexpressionis in its hclausei are evaluated in order, and the If the selected hclausei or else clause uses the => alternate results of the last hexpressioni in the hclausei are returned form, then the hexpressioni is evaluated. It is an error if as the results of the entire cond expression. its value is not a procedure accepting one argument. This procedure is then called on the value of the hkeyi and the If the selected hclausei contains only the htesti and no values returned by this procedure are returned by the case hexpressionis, then the value of the htesti is returned as expression. the result. If the selected hclausei uses the => alternate form, then the hexpressioni is evaluated. It is an error if (case (* 2 3) its value is not a procedure that accepts one argument. ((2 3 5 7) ’prime) This procedure is then called on the value of the htesti and ((1 4 6 8 9) ’composite)) =⇒ composite the values returned by this procedure are returned by the (case (car ’(c d)) cond expression. ((a) ’a) ((b) ’b)) =⇒ unspecified If all htestis evaluate to #f, and there is no else clause, (case (car ’(c d)) then the result of the conditional expression is unspecified; ((a e i o u) ’vowel) if there is an else clause, then its hexpressionis are evaluated ((w y) ’semivowel) in order, and the values of the last one are returned. (else => (lambda (x) x))) =⇒ c

(cond ((> 3 2) ’greater) ((< 3 2) ’less)) =⇒ greater (and htest1i ... ) syntax (cond ((> 3 3) ’greater) ((< 3 3) ’less) The htesti expressions are evaluated from left to right, and (else ’equal)) =⇒ equal if any expression evaluates to #f (see section 6.3), then #f (cond ((assv ’b ’((a 1) (b 2))) => cadr) is returned. Any remaining expressions are not evaluated. (else #f)) =⇒ 2 If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then #t is returned. (case hkeyi hclause1i hclause2i ... ) syntax (and (= 2 2) (> 2 1)) =⇒ #t Syntax: hKeyi may be any expression. Each hclausei (and (= 2 2) (< 2 1)) =⇒ #f should have the form (and 1 2 ’c ’(f g)) =⇒ (f g) (and) =⇒ #t ((hdatum1i ... ) hexpression1i hexpression2i ... ), where each hdatumi is an external representation of some object. It is an error if any of the hdatumis are the same (or htest1i ... ) syntax anywhere in the expression. Alternatively, a hclausei may be of the form The htesti expressions are evaluated from left to right, and the value of the first expression that evaluates to a true ((hdatum1i ... ) => hexpressioni) value (see section 6.3) is returned. Any remaining expres- The last hclausei may be an “else clause,” which has one sions are not evaluated. If all expressions evaluate to #f or of the forms if there are no expressions, #f is returned.

(else hexpression1i hexpression2i ... ) (or (= 2 2) (> 2 1)) =⇒ #t (or (= 2 2) (< 2 1)) =⇒ #t =⇒ or (or #f #f #f) #f (or (memq ’b ’(a b c)) (else => hexpressioni). (/ 3 0)) =⇒ (b c) Semantics: A case expression is evaluated as follows. hKeyi is evaluated and its result is compared against each (when htesti hexpression1i hexpression2i ... ) syntax hdatumi. If the result of evaluating hkeyi is equivalent (in the sense of eqv?; see section 6.1) to a hdatumi, then the The htesti expression is evaluated, and if it evaluates to expressions in the corresponding hclausei are evaluated in a true value, the expressions are evaluated in order. The order and the results of the last expression in the hclausei result of the when expression is unspecified. are returned as the results of the case expression. The following example outputs 12: 4. Expressions 15

(when (= 1 1.0) See also “named let,” section 4.2.4. (display "1") (display "2") =⇒ unspecified (let* hbindingsi hbodyi) syntax Syntax: hBindingsi should have the form (unless htesti hexpression1i hexpression2i ... ) syntax The htesti expression is evaluated, and if it evaluates to #f, ((hvariable1i hinit1i) ... ), the expressions are evaluated in order. The result of the and hbodyi should be a sequence of zero or more defini- unless expression is unspecified. tions followed by one or more expressions as described in The following example outputs nothing: section 4.1.4. (unless (= 1 1.0) Semantics: The let* binding construct is similar to let, (display "1") but the bindings are performed sequentially from left to (display "2") =⇒ unspecified right, and the region of a binding indicated by (hvariablei hiniti) is that part of the let* expression to the right of the binding. Thus the second binding is done in an en- 4.2.2. Binding constructs vironment in which the first binding is visible, and so on. The hvariableis need not be distinct. The binding constructs let, let*, letrec, letrec*, let-values, and let*-values give Scheme a block struc- (let ((x 2) (y 3)) ture, like Algol 60. The syntax of the first four constructs (let* ((x 7) is identical, but they differ in the regions they establish (z (+ x y))) for their variable bindings. In a let expression, the initial (* z x))) =⇒ 70 values are computed before any of the variables become bound; in a let* expression, the bindings and evaluations are performed sequentially; while in letrec and letrec* (letrec hbindingsi hbodyi) syntax expressions, all the bindings are in effect while their initial values are being computed, thus allowing mutually recur- Syntax: hBindingsi should have the form sive definitions. The let-values and let*-values con- ((hvariable i hinit i) ... ), structs are analogous to let and let* respectively, but 1 1 are designed to handle multiple-valued expressions, bind- and hbodyi should be a sequence of zero or more defini- ing different identifiers to each returned value. tions followed by one or more expressions as described in section 4.1.4. It is an error for a hvariablei to appear more (let hbindingsi hbodyi) syntax than once in the list of variables being bound. Syntax: hBindingsi should have the form Semantics: The hvariableis are bound to fresh locations holding unspecified values, the hinitis are evaluated in the ((hvariable1i hinit1i) ... ), resulting environment (in some unspecified order), each where each hiniti is an expression, and hbodyi should be a hvariablei is assigned to the result of the corresponding sequence of zero or more definitions followed by a sequence hiniti, the hbodyi is evaluated in the resulting environment, of one or more expressions as described in section 4.1.4. It and the values of the last expression in hbodyi are returned. is an error for a hvariablei to appear more than once in the Each binding of a hvariablei has the entire letrec expres- list of variables being bound. sion as its region, making it possible to define mutually Semantics: The hinitis are evaluated in the current envi- recursive procedures. ronment (in some unspecified order), the hvariableis are bound to fresh locations holding the results, the hbodyi is (letrec ((even? evaluated in the extended environment, and the values of (lambda (n) the last expression of hbodyi are returned. Each binding (if (zero? n) of a hvariablei has hbodyi as its region. #t (odd? (- n 1))))) (let ((x 2) (y 3)) (odd? (* x y)) =⇒ 6 (lambda (n) (if (zero? n) (let ((x 2) (y 3)) #f (let ((x 7) (even? (- n 1)))))) (z (+ x y))) (even? 88)) (* z x))) =⇒ 35 =⇒ #t 16 Revised7 Scheme

One restriction on letrec is very important: if it is not Semantics: The hinitis are evaluated in the current en- possible to evaluate each hiniti without assigning or refer- vironment (in some unspecified order) as if by invoking ring to the value of any hvariablei, it is an error. The call-with-values, and the variables occurring in the restriction is necessary because letrec is defined in terms hformalsi are bound to fresh locations holding the values of a procedure call where a lambda expression binds the returned by the hinitis, where the hformalsi are matched hvariableis to the values of the hinitis. In the most com- to the return values in the same way that the hformalsi mon uses of letrec, all the hinitis are lambda expressions in a lambda expression are matched to the arguments in and the restriction is satisfied automatically. Another re- a procedure call. Then, the hbodyi is evaluated in the ex- striction is that the continuation of a hiniti should not be tended environment, and the values of the last expression invoked more than once. of hbodyi are returned. Each binding of a hvariablei has hbodyi as its region.

(letrec* hbindingsi hbodyi) syntax It is an error if the hformalsi do not match the number of values returned by the corresponding hiniti. Syntax: hBindingsi should have the form (let-values (((root rem) (exact-integer-sqrt 32))) ((hvariable1i hinit1i) ... ), (* root rem) =⇒ 35 and hbodyi should be a sequence of zero or more defini- tions followed by one or more expressions as described in section 4.1.4. It is an error for a hvariablei to appear more (let*-values hmvbindingsi hbodyi) syntax than once in the list of variables being bound. Syntax: hMvbindingsi should have the form Semantics: The hvariableis are bound to fresh locations, each hvariablei is assigned in left-to-right order to the re- ((hformalsi hiniti) ... ), sult of evaluating the corresponding hiniti, the hbodyi is and hbodyi should be a sequence of zero or more defini- evaluated in the resulting environment, and the values of tions followed by one or more expressions as described in the last expression in hbodyi are returned. Despite the left- section 4.1.4. In each hformalsi, it is an error if any variable to-right evaluation and assignment order, each binding of a appears more than once. hvariablei has the entire letrec* expression as its region, making it possible to define mutually recursive procedures. Semantics: The let-values* construct is similar to let-values, but the hinitis are evaluated and bindings cre- If it is not possible to evaluate each hiniti without assigning ated sequentially from left to right, with the region of the or referring to the value of the corresponding hvariablei bindings of each hformalsi including the hinitis to its right or the hvariablei of any of the bindings that follow it in as well as hbodyi. Thus the second hiniti is evaluated in hbindingsi, it is an error. an environment in which the first set of bindings is visible (letrec* ((p and initialized, and so on. (lambda (x) (let ((a ’a) (b ’b) (x ’x) (y ’y)) (+ 1 (q (- x 1))))) (let*-values (((a b) (values x y)) (q ((x y) (values a b))) (lambda (y) (list a b x y))) =⇒ (x y x y) (if (zero? y) 0 (+ 1 (p (- y 1)))))) (x (p 5)) 4.2.3. Sequencing (y x)) Both of Scheme’s sequencing constructs are named begin, y) but the two have slightly different forms and uses: =⇒ 5

(begin hexpression or definitioni ... ) syntax (let-values hmvbindingsi hbodyi) syntax This form of begin may appear as part of a hbodyi, or Syntax: hMvbindingsi should have the form at the htop-leveli, or directly nested in a begin that is

((hformals1i hinit1i) ... ), itself of this form. It causes the contained expressions and definitions to be evaluated exactly as if the enclosing begin where each hiniti should be an expression, and hbodyi construct were not present. should be zero or more definitions followed by a sequence of one or more expressions as described in section 4.1.4. It Rationale: This form is commonly used in the output of macros is an error for a variable to appear more than once in the (see section 4.3) which need to generate multiple definitions and set of hformalsi. splice them into the context in which they are expanded. 4. Expressions 17

(begin hexpression1i hexpression2i ... ) syntax (vector-set! vec i i)) =⇒ #(0 1 2 3 4) This form of begin can be used as an ordinary expression. (let ((x ’(1 3 5 7 9))) The hexpressionis are evaluated sequentially from left to (do ((x x (cdr x)) right, and the values of the last hexpressioni are returned. (sum 0 (+ sum (car x)))) This expression type is used to sequence side effects such ((null? x) sum))) =⇒ 25 as assignments or input and output.

(define x 0) (let hvariablei hbindingsi hbodyi) syntax

(and (= x 0) “Named let” is a variant on the syntax of let which pro- (begin (set! x 5) vides a more general looping construct than do and can (+ x 1) =⇒ 6 also be used to express recursions. It has the same syn- tax and semantics as ordinary let except that hvariablei (begin (display "4 plus 1 equals ") is bound within hbodyi to a procedure whose formal argu- (display (+ 4 1))) =⇒ unspecified ments are the bound variables and whose body is hbodyi. and prints 4 plus 1 equals 5 Thus the execution of hbodyi can be repeated by invoking the procedure named by hvariablei. 4.2.4. Iteration (let loop ((numbers ’(3 -2 1 6 -5)) (nonneg ’()) (do ((hvariable1i hinit1i hstep1i) syntax (neg ’())) ... ) (cond ((null? numbers) (list nonneg neg)) (htesti hexpressioni ... ) ((>= (car numbers) 0) hcommandi ... ) (loop (cdr numbers) (cons (car numbers) nonneg) A do expression is an iteration construct. It specifies a set neg)) of variables to be bound, how they are to be initialized at ((< (car numbers) 0) the start, and how they are to be updated on each iteration. (loop (cdr numbers) When a termination condition is met, the loop exits after nonneg evaluating the hexpressionis. (cons (car numbers) neg))))) =⇒ ((6 1 3) (-5 -2)) A do expression is evaluated as follows: The hiniti ex- pressions are evaluated (in some unspecified order), the hvariableis are bound to fresh locations, the results of 4.2.5. Delayed evaluation the hiniti expressions are stored in the bindings of the hvariableis, and then the iteration phase begins. (delay hexpressioni) lazy library syntax The delay construct is used together with the proce- Each iteration begins by evaluating htesti; if the result is dure force to implement lazy evaluation or call by need. false (see section 6.3), then the hcommandi expressions are (delay hexpressioni) returns an object called a promise evaluated in order for effect, the hstepi expressions are eval- which at some point in the future may be asked (by the uated in some unspecified order, the hvariableis are bound force procedure) to evaluate hexpressioni, and deliver the to fresh locations, the results of the hstepis are stored in the resulting value. The effect of hexpressioni returning mul- bindings of the hvariableis, and the next iteration begins. tiple values is unspecified. If htesti evaluates to a true value, then the hexpressionis are evaluated from left to right and the values of the last (lazy hexpressioni) lazy library syntax hexpressioni are returned. If no hexpressionis are present, then the value of the do expression is unspecified. The lazy construct is similar to delay, but it is an error for its argument not to evaluate to a promise. The returned The region of the binding of a hvariablei consists of the promise, when forced, will evaluate to whatever the original entire do expression except for the hinitis. It is an error promise would have evaluated to if it had been forced. for a hvariablei to appear more than once in the list of do variables. (force promise) lazy library procedure A hstepi may be omitted, in which case the effect is the The force procedure forces the value of a promise cre- same as if (hvariablei hiniti hvariablei) had been written ated by delay or lazy. If no value has been computed for instead of (hvariablei hiniti). the promise, then a value is computed and returned. The (do ((vec (make-vector 5)) value of the promise is cached (or “memoized”) so that if (i 0 (+ i 1))) it is forced a second time, the previously computed value ((= i 5) vec) is returned. 18 Revised7 Scheme

(force (delay (+ 1 2))) =⇒ 3 • Calling force on an object that is not a promise may (let ((p (delay (+ 1 2)))) simply return the object. (list (force p) (force p))) =⇒ (3 3) • It may be the case that there is no means by which a promise can be operationally distinguished from its (define integers forced value. That is, expressions like the following (letrec ((next may evaluate to either #t or to #f, depending on the (lambda (n) implementation: (delay (cons n (next (+ n 1))))))) (next 0))) (define head (eqv? (delay 1) 1) =⇒ unspecified (lambda (stream) (car (force stream)))) (pair? (delay (cons 1 2))) =⇒ unspecified (define tail (lambda (stream) (cdr (force stream)))) • Some implementations may implement “implicit forc- ing,” where the value of a promise is forced by primi- (head (tail (tail integers))) tive procedures like cdr and +: =⇒ 2

The following example is a mechanical transformation of (+ (delay (* 3 7)) 13) =⇒ 34 a lazy stream-filtering algorithm into Scheme. Each call to a constructor is wrapped in delay, and each argument passed to a deconstructor is wrapped in force. The use of (lazy ...) instead of (delay (force ...)) around (eager obj ) lazy library procedure the body of the procedure ensures that an ever-growing The eager procedure returns a promise which, when sequence of pending promises does not exhaust the heap. forced, will return obj . It is similar to delay, but does (define (stream-filter p? s) not delay its argument: it is a procedure rather than syn- (lazy tax. (if (null? (force s)) (delay ’()) (let ((h (car (force s))) 4.2.6. Dynamic bindings (t (cdr (force s)))) (if (p? h) init procedure (delay (cons h (stream-filter p? t))) (make-parameter ) (stream-filter p? t)))))) (make-parameter init converter) procedure Returns a newly allocated parameter object, which is a pro- (head (tail (tail (stream-filter odd? integers)))) cedure that accepts zero arguments and returns the value =⇒ 5 associated with the parameter object. Initially, this value is the value of (converter init), or of init if the conversion The following examples are not intended to illustrate good procedure converter is not specified. The associated value programming style, as delay, lazy, and force are mainly can be temporarily changed using parameterize, which is intended for programs written in the functional style. How- described below. ever, they do illustrate the property that only one value is computed for a promise, no matter how many times it is The effect of passing arguments to a parameter object is forced. implementation-dependent. (define count 0) (define p (parameterize ((hparam1i hvalue1i) ... ) syntax (delay (begin (set! count (+ count 1)) hbodyi) (if (> count x) count A parameterize expression is used to change the values (force p))))) returned by specified parameter objects during the evalua- (define x 5) tion of the body. It is an error if the value of any hparami p =⇒ a promise expression is not a parameter object. The hparami and (force p) =⇒ 6 hvaluei expressions are evaluated in an unspecified order. p =⇒ a promise, still The hbodyi is evaluated in a dynamic environment in which (begin (set! x 10) calls to the parameters return the results of passing the (force p)) =⇒ 6 corresponding values to the conversion procedure specified Various extensions to this semantics of delay, force and when the parameters were created. Then the previous val- lazy are supported in some implementations: ues of the parameters are restored without passing them to 4. Expressions 19 the conversion procedure. The results of the last expres- 4.2.8. Quasiquotation sion in the hbodyi are returned as the results of the entire parameterize expression. (quasiquote hqq templatei) syntax Note: If the conversion procedure is not idempotent, the results `hqq templatei syntax of (parameterize ((x (x))) ...), which appears to bind the unquote auxiliary syntax parameter x to its current value, may not be what the user unquote-splicing auxiliary syntax expects. “Backquote” or “quasiquote” expressions are useful for If an implementation supports multiple threads of execu- constructing a list or vector structure when some but not tion, then parameterize must not change the associated all of the desired structure is known in advance. If no values of any parameters in any thread other than the cur- commas appear within the hqq templatei, the result of rent thread and threads created inside hbodyi. evaluating `hqq templatei is equivalent to the result of Parameter objects can be used to specify configurable set- evaluating ’hqq templatei. If a comma appears within tings for a computation without the need to pass the value the hqq templatei, however, the expression following the to every procedure in the call chain explicitly. comma is evaluated (“unquoted”) and its result is inserted into the structure instead of the comma and the expression. (define radix If a comma appears followed immediately by an at-sign (@), (make-parameter then it is an error if the following expression does not eval- 10 (lambda (x) uate to a list; the opening and closing parentheses of the (if (and (integer? x) (<= 2 x 16)) list are then “stripped away” and the elements of the list x are inserted in place of the comma at-sign expression se- (error "invalid radix"))))) quence. A comma at-sign should only appear within a list or vector hqq templatei. (define (f n) (number->string n (radix))) `(list ,(+ 1 2) 4) =⇒ (list 3 4) (f 12) =⇒ "12" (let ((name ’a)) `(list ,name ’,name)) (parameterize ((radix 2)) =⇒ (list a (quote a)) (f 12)) =⇒ "1100" `(a ,(+ 1 2) ,@(map abs ’(4 -5 6)) b) (f 12) =⇒ "12" =⇒ (a 3 4 5 6 b) `(( foo ,(- 10 3)) ,@(cdr ’(c)) . ,(car ’(cons))) (radix 16) =⇒ unspecified =⇒ ((foo 7) . cons) `#(10 5 ,(sqrt 4) ,@(map sqrt ’(16 9)) 8) (parameterize ((radix 0)) =⇒ #(10 5 2 4 3 8) =⇒ error (f 12)) Quasiquote expressions may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost backquote. The nesting level 4.2.7. Exception Handling increases by one inside each successive quasiquotation, and decreases by one inside each unquotation. (guard (hvariablei syntax hcond clause1i hcond clause2i ... ) `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) hbodyi) =⇒ (a `(b ,(+ 1 2) ,(foo 4 d) e) f) (let ((name1 ’x) Syntax: Each hcond clausei is as in the specification of (name2 ’y)) cond. `(a `(b ,,name1 ,’,name2 d) e)) Semantics: The hbodyi is evaluated with an exception =⇒ (a `(b ,x ,’y d) e) handler that binds the raised object to hvariablei and, A quasiquote expression may return either fresh, mutable within the scope of that binding, evaluates the clauses as objects or literal structure for any structure that is con- if they were the clauses of a cond expression. That im- structed at run time during the evaluation of the expres- plicit cond expression is evaluated with the continuation sion. Portions that do not need to be rebuilt are always and dynamic environment of the guard expression. If ev- literal. Thus, ery hcond clausei’s htesti evaluates to #f and there is no else clause, then raise-continuable is re-invoked on the (let ((a 3)) `((1 2) ,a ,4 ,’five 6)) raised object within the dynamic environment of the origi- nal call to raise except that the current exception handler may be equivalent to either of the following expressions: is that of the guard expression. See section 6.11 for a more complete discussion of excep- `((1 2) 3 4 five 6) tions. 20 Revised7 Scheme

(let ((a 3)) 4.3. Macros (cons ’(1 2) (cons a (cons 4 (cons ’five ’(6)))))) Scheme programs can define and use new derived expres- sion types, called macros. Program-defined expression However, it is not equivalent to this expression: types have the syntax (hkeywordi hdatumi ...) (let ((a 3)) (list (list 1 2) a 4 ’five 6)) where hkeywordi is an identifier that uniquely determines the expression type. This identifier is called the syntactic The two notations hqq templatei and ` (quasiquote keyword, or simply keyword, of the macro. The number of hqq templatei are identical in all respects. hexpressioni ) , the hdatumis, and their syntax, depends on the expression is identical to hexpressioni , and hexpressioni (unquote ) ,@ type. is identical to (unquote-splicing hexpressioni). The ex- ternal syntax generated by write for two-element lists Each instance of a macro is called a use of the macro. The whose car is one of these symbols may vary between im- set of rules that specifies how a use of a macro is transcribed plementations. into a more primitive expression is called the transformer of the macro. (quasiquote (list (unquote (+ 1 2)) 4)) =⇒ (list 3 4) The macro definition facility consists of two parts: ’(quasiquote (list (unquote (+ 1 2)) 4)) =⇒ `(list ,(+ 1 2) 4) • A set of expressions used to establish that certain iden- i.e., (quasiquote (list (unquote (+ 1 2)) 4)) tifiers are macro keywords, associate them with macro transformers, and control the scope within which a It is an error if any of the identifiers quasiquote, macro is defined, and unquote, or unquote-splicing appear in positions within a hqq templatei otherwise than as described above. • a pattern language for specifying macro transformers.

4.2.9. Case-lambda The syntactic keyword of a macro may shadow variable bindings, and local variable bindings may shadow keyword bindings: (case-lambda hclause1i hclause2i ... ) case-lambda library syntax • If a macro transformer inserts a binding for an identi- Syntax: Each hclausei should be of the form (hformalsi fier (variable or keyword), the identifier will in effect be hbodyi), where hformalsi and hbodyi have the same syntax renamed throughout its scope to avoid conflicts with as in a lambda expression. other identifiers. Note that a define at top level may Semantics: A case-lambda expression evaluates to a pro- or may not introduce a binding; see section 5.2. cedure that accepts a variable number of arguments and • If a macro transformer inserts a free reference to an is lexically scoped in the same manner as a procedure re- identifier, the reference refers to the binding that was sulting from a lambda expression. When the procedure visible where the transformer was specified, regard- is called, the first hclausei for which the arguments agree less of any local bindings that surround the use of the with hformalsi is selected, where agreement is specified as macro. for the hformalsi of a lambda expression. The variables of hformalsi are bound to fresh locations, the values of In consequence, all macros defined using the pattern lan- the arguments are stored in those locations, the hbodyi guage are “hygienic” and “referentially transparent” and is evaluated in the extended environment, and the results thus preserve Scheme’s lexical scoping. [21, 22, 4, 11, 15] of hbodyi are returned as the results of the procedure call. It is an error for the arguments not to agree with the 4.3.1. Binding constructs for syntactic keywords hformalsi of any hclausei. (define range The let-syntax and letrec-syntax binding constructs (case-lambda are analogous to let and letrec, but they bind syn- ((e) (range 0 e)) tactic keywords to macro transformers instead of binding ((b e) (do ((r ’() (cons e r)) variables to locations that contain values. Syntactic key- (e (- e 1) (- e 1))) words may also be bound at top level or elsewhere with ((< e b) r))))) define-syntax; see section 5.3.

(range 3) =⇒ (0 1 2) (range 3 5) =⇒ (3 4) (let-syntax hbindingsi hbodyi) syntax Syntax: hBindingsi should have the form 4. Expressions 21

((hkeywordi htransformer speci) ... ) 4.3.2. Pattern language

Each hkeywordi is an identifier, each htransformer speci A htransformer speci has one of the following forms: is an instance of syntax-rules, and hbodyi should be a sequence of one or more definitions followed by one or more expressions. It is an error for a hkeywordi to appear more (syntax-rules (hliterali ... ) syntax than once in the list of keywords being bound. hsyntax rulei ... ) (syntax-rules hellipsisi (hliterali ... ) syntax Semantics: The hbodyi is expanded in the syntactic envi- hsyntax rulei ... ) ronment obtained by extending the syntactic environment auxiliary syntax of the let-syntax expression with macros whose keywords ... auxiliary syntax are the hkeywordis, bound to the specified transformers. Syntax: It is an error if any of the hliteralis, or the hellipsisi Each binding of a hkeywordi has hbodyi as its region. in the second form, is not an identifier. It is also an error (let-syntax ((when (syntax-rules () if hsyntax rulei is not of the form ((when test stmt1 stmt2 ...) (hpatterni htemplatei) (if test (begin stmt1 The hpatterni in a hsyntax rulei is a list hpatterni whose stmt2 ...)))))) first element is an identifier. (let ((if #t)) A hpatterni is either an identifier, a constant, or one of the (when if (set! if ’now)) following if)) =⇒ now (hpatterni ...) (let ((x ’outer)) (hpatterni hpatterni ... . hpatterni) (let-syntax ((m (syntax-rules () ((m) x)))) (hpatterni ... hpatterni hellipsisi hpatterni ...) (let ((x ’inner)) (hpatterni ... hpatterni hellipsisi hpatterni ... (m)))) =⇒ outer . hpatterni) #(hpatterni ...) #(hpatterni ... hpatterni hellipsisi hpatterni ...) (letrec-syntax hbindingsi hbodyi) syntax and a template is either an identifier, a constant, or one of the following Syntax: Same as for let-syntax. (helementi ...) Semantics: The hbodyi is expanded in the syntactic (helementi helementi ... . htemplatei) environment obtained by extending the syntactic envi- (hellipsisi htemplatei) ronment of the letrec-syntax expression with macros #(helementi ...) whose keywords are the hkeywordis, bound to the speci- where an helementi is a htemplatei optionally followed by fied transformers. Each binding of a hkeywordi has the an hellipsisi. An hellipsisi is the identifier specified in the htransformer specis as well as the hbodyi within its region, second form of syntax-rules, or the default identifier ... so the transformers can transcribe expressions into uses of (three consecutive periods) otherwise. the macros introduced by the letrec-syntax expression. Semantics: An instance of syntax-rules produces a new (letrec-syntax macro transformer by specifying a sequence of hygienic ((my-or (syntax-rules () rewrite rules. A use of a macro whose keyword is associated ((my-or) #f) with a transformer specified by syntax-rules is matched ((my-or e) e) against the patterns contained in the hsyntax ruleis, be- ((my-or e1 e2 ...) ginning with the leftmost hsyntax rulei. When a match is (let ((temp e1)) found, the macro use is transcribed hygienically according (if temp to the template. temp (my-or e2 ...))))))) An identifier appearing within a hpatterni may be an un- (let ((x #f) derscore ( ), a literal identifier listed in the list of hliteralis, (y 7) or the hellipsisi. All other identifiers appearing within a (temp 8) hpatterni are pattern variables. (let odd?) (if even?)) The keyword at the beginning of the pattern in a (my-or x hsyntax rulei is not involved in the matching and is con- (let temp) sidered neither a pattern variable nor a literal identifier. (if y) y))) =⇒ 7 Pattern variables match arbitrary input elements and are used to refer to elements of the input in the template. It 22 Revised7 Scheme is an error for the same pattern variable to appear more • P is a constant and E is equal to P in the sense of the than once in a hpatterni. equal? procedure. Underscores also match arbitrary input elements but are not pattern variables and so cannot be used to refer to It is an error to use a macro keyword, within the scope of those elements. If an underscore appears in the hliteralis its binding, in an expression that does not match any of list, then that takes precedence and underscores in the the patterns. hpatterni match as literals. Multiple underscores may ap- When a macro use is transcribed according to the template pear in a hpatterni. of the matching hsyntax rulei, pattern variables that occur Identifiers that appear in (hliterali ... ) are interpreted as in the template are replaced by the elements they match in literal identifiers to be matched against corresponding el- the input. Pattern variables that occur in subpatterns fol- ements of the input. An element in the input matches lowed by one or more instances of the identifier hellipsisi are a literal identifier if and only if it is an identifier and ei- allowed only in subtemplates that are followed by as many ther both its occurrence in the macro expression and its instances of hellipsisi. They are replaced in the output by occurrence in the macro definition have the same lexical all of the elements they match in the input, distributed as binding, or the two identifiers are equal and both have no indicated. It is an error if the output cannot be built up lexical binding. as specified. A subpattern followed by hellipsisi can match zero or Identifiers that appear in the template but are not pattern more elements of the input, unless hellipsisi appears in the variables or the identifier hellipsisi are inserted into the out- hliteralis, in which case it is matched as a literal. put as literal identifiers. If a literal identifier is inserted as a More formally, an input expression E matches a pattern P free identifier then it refers to the binding of that identifier if and only if: within whose scope the instance of syntax-rules appears. If a literal identifier is inserted as a bound identifier then • P is an underscore ( ). it is in effect renamed to prevent inadvertent captures of free identifiers. • P is a non-literal identifier; or A template of the form (hellipsisi htemplatei) is identical • P is a literal identifier and E is an identifier with the to htemplatei, except that ellipses within the template have same binding; or no special meaning. That is, any ellipses contained within

• P is a list (P1 ...Pn) and E is a list of n elements htemplatei are treated as ordinary identifiers. In partic- that match P1 through Pn, respectively; or ular, the template (hellipsisi hellipsisi) produces a single hellipsisi. This allows syntactic abstractions to expand into • P is an improper list (P1 P2 ...Pn . Pn+1) and code containing ellipses. E is a list or improper list of n or more elements that match P1 through Pn, respectively, and whose nth tail (define-syntax be-like-begin (syntax-rules () matches Pn+1; or ((be-like-begin name) • P is of the form (P1 ...Pe−1 Pe hellipsisi Pm+1 (define-syntax name ...Pn) where E is a proper list of n elements, the first (syntax-rules () e − 1 of which match P1 through Pe−1, respectively, ((name expr (...... )) whose next m − k elements each match Pe, whose re- (begin expr (...... )))))))) maining n − m elements match Pm+1 through Pn; or (be-like-begin sequence) • P is of the form (P1 ...Pe−1 Pe hellipsisi Pm+1 (sequence 1 2 3 4) =⇒ 4 ...Pn . Px) where E is an list or improper list of As an example, if let and cond are defined as in section 7.3 n elements, the first e − 1 of which match P1 through P , whose next m−k elements each match P , whose then they are hygienic (as required) and the following is not e−1 e an error. remaining n − m elements match Pm+1 through Pn, and whose nth and final cdr matches Px; or (let ((=> #f)) (cond (#t => ’ok))) =⇒ ok • P is a vector of the form #(P1 ...Pn) and E is a vector of n elements that match P1 through Pn; or The macro transformer for cond recognizes => as a local variable, and hence an expression, and not as the top-level • P is of the form #(P ...P P hellipsisi P 1 e−1 e m+1 identifier =>, which the macro transformer treats as a syn- ...P ) where E is a vector of n elements the first n tactic keyword. Thus the example expands into e − 1 of which match P1 through Pe−1, whose next m − k elements each match Pe, and whose remaining (let ((=> #f)) n − m elements match Pm+1 through Pn; or (if #t (begin => ’ok))) 5. Program structure 23 instead of 5. Program structure (let ((=> #f)) 5.1. Programs (let ((temp #t)) (if temp (’ok temp)))) A Scheme program consists of a sequence of program parts: which would result in an invalid procedure call. expressions, definitions, syntax definitions, record type def- initions, imports, cond-expands, and includes. A collec- tion of program parts may be encapsulated in a library to 4.3.3. Signalling errors in macro transformers be reused by multiple programs. Expressions are described in chapter 4; the other program parts, as well as libraries, (syntax-error hmessagei hargsi ... ) syntax are the subject of the present chapter. syntax-error behaves similarly to error (6.11) except Programs and libraries are typically stored in files, al- that implementations with an expansion pass separate from though programs can be entered interactively to a running evaluation should signal an error as soon as syntax-error Scheme system, and other paradigms are possible. Imple- is expanded. This can be used as a syntax-rules mentations which store libraries in files should document htemplatei for a hpatterni that is an invalid use of the the mapping from the name of a library to its location in macro, which can provide more descriptive error messages. the file system. hmessagei should be a string literal, and hargsi arbitrary Program parts other than expressions that are present at expressions providing additional information. Applications the top level of a program can be interpreted declaratively. cannot count on being able to catch syntax errors with ex- They cause bindings to be created in the top level envi- ception handlers or guards. ronment or modify the value of existing top-level bindings. (define-syntax simple-let The initial (or “top level”) Scheme environment is empty (syntax-rules () except for import, so further bindings can only be intro- (( (head ... ((x . y) val) . tail) duced with import. body1 body2 ...) (syntax-error Expressions occurring at the top level of a program are "expected an identifier but got" interpreted imperatively; they are executed in order when (x . y))) the program is invoked or loaded, and typically perform (( ((name val) ...) body1 body2 ...) some kind of initialization. ((lambda (name ...) body1 body2 ...) val ...)))) At the top level of a program (begin hform1i ... ) is equivalent to the sequence of expressions, definitions, and syntax definitions in the begin. Macros can expand into such begins. Implementations may provide an interactive session called a REPL (Read-Eval-Print Loop), where Scheme program parts can be entered and evaluated one at a time. For con- venience and ease of use, the “top-level” Scheme environ- ment in a REPL must not be not empty, but must start out with variables bound to locations containing at least the bindings provided by the base library. This library includes the core syntax of Scheme and generally useful procedures that manipulate data. For example, the variable abs is bound to a procedure of one argument that computes the absolute value of a number, and the variable + is bound to a procedure that computes sums. The full list of (scheme base) bindings can be found in Appendix A.

5.2. Definitions

Definitions are valid in some, but not all, contexts where expressions are allowed. They are valid only at the top level of a hprogrami and at the beginning of a hbodyi. 24 Revised7 Scheme

In a hbodyi (begin hdefinition1i ... ) is equivalent to the 5.2.2. Internal definitions sequence of definitions hdefinition1i ... . Macros can ex- pand into such begins. Definitions may occur at the beginning of a hbodyi (that is, the body of a lambda, let, let*, letrec, letrec*, A definition takes one of the following forms: let-values, let-values*, let-syntax, letrec-syntax, parameterize, guard, or case-lambda expression or that of a definition of an appropriate form). Such definitions are • (define hvariablei hexpressioni) known as internal definitions as opposed to the top-level definitions described above. The variable defined by an • (define (hvariablei hformalsi) hbodyi) internal definition is local to the hbodyi. That is, hvariablei hFormalsi should be either a sequence of zero or more is bound rather than assigned, and the region of the binding variables, or a sequence of one or more variables fol- is the entire hbodyi. For example, lowed by a space-delimited period and another vari- (let ((x 5)) able (as in a lambda expression). This form is equiv- (define foo (lambda (y) (bar x y))) alent to (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3))) =⇒ 45 (define hvariablei An expanded hbodyi containing internal definitions can al- (lambda (hformalsi) hbodyi)). ways be converted into a completely equivalent letrec* expression. For example, the let expression in the above • (define (hvariablei . hformali) hbodyi) example is equivalent to hFormali should be a single variable. This form is (let ((x 5)) equivalent to (letrec* ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (define hvariablei (foo (+ x 3)))) (lambda hformali hbodyi)). Just as for the equivalent letrec* expression, it is an er- ror if it is not possible to evaluate each hexpressioni of every internal definition in a hbodyi without assigning or 5.2.1. Top level definitions referring to the value of the corresponding hvariablei or the hvariablei of any of the definitions that follow it in hbodyi. At the top level of a program, a definition It is an error to define the same identifier more than once (define hvariablei hexpressioni) in the same hbodyi. Wherever an internal definition may occur, (begin has essentially the same effect as the assignment expres- hdefinition i ... ) is equivalent to the sequence of defini- sion 1 tions that form the body of the begin. (set! hvariablei hexpressioni) 5.2.3. Multiple-value definitions if hvariablei is bound to a non-syntax value. However, if hvariablei is not bound, or is bound to a syntax definition The construct define-values introduces new definitions (see below), then the definition will bind hvariablei to a like define, but can create multiple definitions from a sin- new location before performing the assignment, whereas gle expression returning multiple values. It is allowed wher- it would be an error to perform a set! on an unbound ever define is allowed. variable. (define-values hformalsi hexpressioni) syntax (define add3 (lambda (x) (+ x 3))) It is an error if a variable appears more than once in the (add3 3) =⇒ 6 set of hformalsi. (define first car) Semantics: hExpressioni is evaluated, and the hformalsi (first ’(1 2)) =⇒ 1 are bound to the return values in the same way that the hformalsi in a lambda expression are matched to the argu- Implementations are permitted to provide an initial envi- ments in a procedure call. ronment in which all possible variables are bound to loca- tions, most of which contain unspecified values. Top level (let () definitions in such an implementation are truly equivalent (define-values (x y) (values 1 2)) to assignments. (+ x y)) =⇒ 3 5. Program structure 25

5.3. Syntax definitions each record type. Record type definitions are valid wher- ever definitions are. Syntax definitions are valid wherever definitions are. They have the following form: (define-record-type hnamei syntax (define-syntax hkeywordi htransformer speci) hconstructori hpredi hfieldi ... ) hKeywordi is an identifier, and the htransformer speci Syntax: hnamei and hpredi should be identifiers. The should be an instance of syntax-rules. If the hconstructori should be of the form define-syntax occurs at the top level, then the top- (hconstructor namei hfield namei ... ) level syntactic environment is extended by binding the and each hfieldi should be either of the form hkeywordi to the specified transformer, but existing ref- erences to any top-level binding for hkeywordi remain un- (hfield namei haccessor namei) changed. Otherwise, it is an internal syntax definition, and or of the form is local to the hbodyi in which it is defined. (hfield namei haccessor namei hmodifier namei) (let ((x 1) (y 2)) It is an error for the same identifier to occur more than (define-syntax swap! once as a field name. (syntax-rules () ((swap! a b) define-record-type is generative: each use creates a new (let ((tmp a)) record type that is distinct from all existing types, includ- (set! a b) ing Scheme’s predefined types and other record types — (set! b tmp))))) even record types of the same name or structure. (swap! x y) (list x y)) =⇒ (2 1) An instance of define-record-type is equivalent to the following definitions: Macros can expand into definitions in any context that permits them. However, it is an error for a definition to •h namei is bound to a representation of the record type define an identifier whose binding has to be known in or- itself. This may be a run-time object or a purely syn- der to determine the meaning of the definition itself, or of tactic representation. any preceding definition that belongs to the same group of internal definitions. Similarly, it is an error for an in- •h constructor namei is bound to a procedure that takes ternal definition to define an identifier whose binding has as many arguments as there are hfield nameis in the to be known in order to determine the boundary between (hconstructor namei ... ) subexpression and returns the internal definitions and the expressions of the body it a new record of type hnamei. Fields whose names are belongs to. For example, the following are errors: listed with hconstructor namei have the corresponding (define define 3) argument as their initial value. The initial values of all other fields are unspecified. It is an error for a (begin (define begin list)) field name to appear in hconstructori but not as a hfield namei. (let-syntax ((foo (syntax-rules () •h predi is bound to a predicate that returns #t when ((foo (proc args ...) body ...) given a value returned by the procedure bound to (define proc hconstructor namei and #f for everything else. (lambda (args ...) body ...)))))) • Each haccessor namei is bound to a procedure that (let ((x 3)) takes a record of type hnamei and returns the cur- (foo (plus x y) (+ x y)) rent value of the corresponding field. It is an error to (define foo x) pass an accessor a value which is not a record of the (plus foo x))) appropriate type. • Each hmodifier namei is bound to a procedure that 5.4. Record type definitions takes a record of type hnamei and a value which be- comes the new value of the corresponding field; an Record type definitions are used to introduce new data unspecified value is returned. It is an error to pass a types, called record types. The values of a record type are modifier a first argument which is not a record of the called records and are aggregations of zero or more fields, appropriate type. each of which holds a single location. A predicate, a con- structor, and field accessors and mutators are defined for For instance, the following definition 26 Revised7 Scheme

(define-record-type •h identifieri (kons x y) pare? • (rename hidentifier1i hidentifier2i) (x kar set-kar!) (y kdr)) In an hexport speci, an hidentifieri names a single bind- ing defined within or imported into the library, where the defines kons to be a constructor, kar and kdr to be ac- external name for the export is the same as the name cessors, set-kar! to be a modifier, and pare? to be a of the binding within the library. A rename spec ex- predicate for instances of . ports the binding defined within or imported into the li- brary and named by hidentifier1i in each (hidentifier1i (pare? (kons 1 2)) =⇒ #t hidentifier2i) pairing, using hidentifier2i as the external (pare? (cons 1 2)) =⇒ #f name. (kar (kons 1 2)) =⇒ 1 (kdr (kons 1 2)) =⇒ 2 An import declaration provides a way to import the iden- (let ((k (kons 1 2))) tifiers exported by a library. Each himport seti names a (set-kar! k 3) set of bindings from another library and possibly specifies (kar k)) =⇒ 3 local names for the imported bindings. It takes one of the following forms:

5.5. Libraries •h library namei

• (rename himport set1i (hidentifier2i hidentifieri) Libraries provide a way to organize Scheme programs into ... ) reusable parts with explicitly defined interfaces to the rest of the program. This section defines the notation and se- • (prefix himport seti hidentifieri) mantics for libraries. • (only himport seti hidentifieri ... )

5.5.1. Library Syntax • (except himport seti hidentifieri ... )

A library definition takes the following form: In the first form, all of the identifiers in the named library’s (define-library hlibrary namei export clauses are imported with the same names (or the hlibrary declarationi ... ) exported names if exported with rename). The additional himport seti forms modify this set as follows: hlibrary namei is a list whose members are identifiers and • rename modifies the given himport seti, replacing each unsigned exact integers. It is used to identify the library instance of hidentifier i with hidentifier i. It is an uniquely when importing from other programs or libraries. 1 2 error if any of the listed identifiers are not found in Libraries whose first identifier is scheme are reserved for use the original set. by this report and future versions of this report. Libraries whose first identifier is srfi are reserved for libraries im- • prefix automatically renames all identifiers in the plementing Scheme Requests for Implementation. given himport seti, prefixing each with the specified A hlibrary declarationi may be any of: hidentifieri. • only produces a subset of the given himport seti, in- • (export hexport speci ... ) cluding only the listed identifiers (after any renaming). • (import himport seti ... ) It is an error if any of the listed identifiers are not found in the original set. • (begin hcommand or definitioni ... ) • except produces a subset of the given himport seti, • (include hfilename1i hfilename2i ... ) excluding the listed identifiers (after any renaming). It is an error if any of the listed identifiers are not • (include-ci hfilename i hfilename i ... ) 1 2 found in the original set. • (cond-expand hcond-expand clausei ... ) The top level of a program may also include import dec- An export declaration specifies a list of identifiers which larations. In a library declaration, it is an error to import can be made visible to other libraries or programs. An the same identifier more than once with different bindings, hexport speci takes one of the following forms: or to redefine or mutate an imported binding with define, 5. Program structure 27 define-syntax or set!. However, a REPL should permit is found, the corresponding hlibrary declarationis are these actions. spliced into the current library definition and the remaining The begin, include, and include-ci declarations are clauses are ignored. If none of the hfeature requirementis used to specify the commands and definitions that make evaluate to #t, then if there is an else clause, its up the body of the library. The begin declaration takes hlibrary declarationis are included. Otherwise, the a list of expressions and definitions to be spliced literally, cond-expand has no effect. analogous to the top-level begin. Both the include and The exact features provided are implementation-defined, include-ci declarations take one or more filenames ex- but for portability a core set of features is given in ap- pressed as string literals, apply an implementation-specific pendix B. algorithm to find corresponding files, read the whole con- After all cond-expand library declarations are expanded, tents of each file, and include the results into the library a new environment is constructed for the library consisting body or program as though wrapped in a top-level begin. of all imported bindings. The expressions and declarations The difference between the two is that include-ci reads from all begin, include and include-ci declarations are each file as if it began with the #!fold-case directive, expanded in that environment in the order in which they while include does not. All three may appear at the top occur in the library declaration. level of a program. The top-level expressions in a library are executed in the Note: Implementations are encouraged to search for files in order in which they occur when the library is loaded. A the directory which contains the including file, and to provide library is loaded zero or more times when it is imported a way for users to specify other directories to search. by a program or by another library which is about to be Note: For portability, include and include-ci must operate loaded, but must be loaded at least once in every program on source files. Their operation on other kinds of files necessarily in which it is so imported. varies among implementations. The cond-expand library declaration provides a way to 5.5.2. Library example statically expand different library declarations depending on the implementation under which the library is being The following example shows how a program may be loaded. A hcond-expand clausei takes the following form: divided into libraries plus a relatively small main pro- (hfeature requirementi hlibrary declarationi ... ) gram [18]. If the main program is entered into a REPL, it The last clause may be an “else clause,” which has the form is not necessary to import the base library. (else hlibrary declarationi ... ) (define-library (example grid) (export make rows cols ref each A hfeature requirementi takes one of the following forms: (rename put! set!)) (import (scheme base)) •h feature identifieri (begin ;; Create an NxM grid. • (library hlibrary namei) (define (make n m) (let ((grid (make-vector n))) • (and hfeature requirementi ... ) (do ((i 0 (+ i 1))) • (or hfeature requirementi ... ) ((= i n) grid) (let ((v (make-vector m #f))) • (not hfeature requirementi) (vector-set! grid i v))))) (define (rows grid) (vector-length grid)) Each implementation maintains a list of feature identifiers (define (cols grid) which are present, as well as a list of libraries which can be (vector-length (vector-ref grid 0))) imported. The value of a hfeature requirementi is deter- ;; Return #false if out of range. mined by replacing each hfeature identifieri and (library (define (ref grid n m) hlibrary namei) on the implementation’s lists with #t, and (and (< -1 n (rows grid)) all other feature identifiers and library names with #f, then (< -1 m (cols grid)) evaluating the resulting expression as a Scheme boolean ex- (vector-ref (vector-ref grid n) m))) pression under the normal interpretation of and, or, and (define (put! grid n m v) not. (vector-set! (vector-ref grid n) m v)) (define (each grid proc) A cond-expand is then expanded by evaluating the (do ((j 0 (+ j 1))) hfeature requirementis of successive hcond-expand clauseis ((= j (rows grid))) in order, until one of them returns #t. When a true clause (do ((k 0 (+ k 1))) 28 Revised7 Scheme

((= k (cols grid))) (proc j k (ref grid j k)))))))

(define-library (example life) (export life) 6. Standard procedures (import (except (scheme base) set!) (scheme write) This chapter describes Scheme’s built-in procedures. (example grid)) The procedures force and eager are intimately associ- (begin ated with the expression types and , and are (define (life-count grid i j) delay lazy (define (count i j) described with them in section 4.2.5. In the same way, the (if (ref grid i j) 1 0)) procedure make-parameter is intimately associated with (+ (count (- i 1) (- j 1)) the expression type parameterize, and is described with (count (- i 1) j) it in section 4.2.6. (count (- i 1) (+ j 1)) A program may use a top-level definition to bind any vari- (count i (- j 1)) (count i (+ j 1)) able. It may subsequently alter any such binding by an (count (+ i 1) (- j 1)) assignment (see section 4.1.6). These operations do not (count (+ i 1) j) modify the behavior of any procedure defined in this re- (count (+ i 1) (+ j 1)))) port or imported from a library. (see section 5.5). Altering (define (life-alive? grid i j) any top-level binding that has not been introduced by a (case (life-count grid i j) definition has an unspecified effect on the behavior of the ((3) #true) procedures defined in this chapter. ((2) (ref grid i j)) (else #false))) (define (life-print grid) 6.1. Equivalence predicates (display "\x1B;[1H\x1B;[J") ; clear vt100 (each grid (lambda (i j v) A predicate is a procedure that always returns a boolean (display (if v "*" " ")) value (#t or #f). An equivalence predicate is the compu- (when (= j (- (cols grid) 1)) tational analogue of a mathematical equivalence relation; (newline))))) it is symmetric, reflexive, and transitive. Of the equiva- (define (life grid iterations) lence predicates described in this section, eq? is the finest (do ((i 0 (+ i 1)) or most discriminating, equal? is the coarsest, and eqv? (grid0 grid grid1) is slightly less discriminating than eq?. (grid1 (make (rows grid) (cols grid)) grid0))

((= i iterations)) (eqv? obj1 obj2) procedure (each grid0 (lambda (j k v) The eqv? procedure defines a useful equivalence relation on (let ((a (life-alive? grid0 j k))) objects. Briefly, it returns #t if obj1 and obj2 are normally (set! grid1 j k a)))) regarded as the same object. This relation is left slightly (life-print grid1))))) open to interpretation, but the following partial specifica- tion of eqv? holds for all implementations of Scheme. ;; Main program. (import (scheme base) The eqv? procedure returns #t if: (only (example life) life) (rename (prefix (example grid) grid-) • obj1 and obj2 are both #t or both #f. (grid-make make-grid)))

• obj1 and obj2 are both symbols and ;; Initialize a grid with a glider. (define grid (make-grid 24 24)) (grid-set! grid 1 1 #true) (string=? (symbol->string obj1) (grid-set! grid 2 2 #true) (symbol->string obj2)) =⇒ (grid-set! grid 3 0 #true) #t (grid-set! grid 3 1 #true)

(grid-set! grid 3 2 #true) Note: This assumes that neither obj1 nor obj2 is an “un- interned symbol” as alluded to in section 6.5. This report ;; Run for 80 iterations. does not specify the behavior of eqv? on implementation- (life grid 80) dependent extensions. 6. Standard procedures 29

• obj1 and obj2 are both numbers, are numerically equal (eqv? "" "") =⇒ unspecified (see =, section 6.2), and are either both exact or both (eqv? ’#() ’#()) =⇒ unspecified inexact. (eqv? (lambda (x) x) (lambda (x) x)) =⇒ unspecified • obj1 and obj2 are both characters and are the same (let ((p (lambda (x) x))) character according to the char=? procedure (sec- (eqv? p p)) =⇒ unspecified tion 6.6). (eqv? (lambda (x) x) (lambda (y) y)) =⇒ unspecified • obj1 and obj2 are both the empty list. (eqv? +nan.0 +nan.0) =⇒ unspecified

• obj1 and obj2 are pairs, vectors, bytevectors, records, The next set of examples shows the use of eqv? with pro- or strings that denote the same location in the store cedures that have local state. The gen-counter procedure (section 3.4). must return a distinct procedure every time, since each pro- cedure has its own internal counter. The gen-loser pro- The eqv? procedure returns #f if: cedure, however, returns equivalent procedures each time, since the local state does not affect the value or side effects of the procedures. However, eqv? may or may not detect • obj and obj are of different types (section 3.2). 1 2 this equivalence. • one of obj1 and obj2 is #t but the other is #f. (define gen-counter • obj and obj are symbols but (lambda () 1 2 (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (string=? (symbol->string obj1) (let ((g (gen-counter))) (symbol->string obj2)) (eqv? g g)) =⇒ #t =⇒ #f (eqv? (gen-counter) (gen-counter)) =⇒ #f • one of obj1 and obj2 is an exact number but the other (define gen-loser is an inexact number. (lambda () (let ((n 0)) • obj1 and obj2 are numbers for which the = procedure (lambda () (set! n (+ n 1)) 27)))) returns #f, and nan? returns #f for both. (let ((g (gen-loser))) (eqv? g g)) =⇒ #t • obj1 and obj2 are characters for which the char=? pro- (eqv? (gen-loser) (gen-loser)) cedure returns #f. =⇒ unspecified

• one of obj1 and obj2 is the empty list but the other is (letrec ((f (lambda () (if (eqv? f g) ’both ’f))) not. (g (lambda () (if (eqv? f g) ’both ’g)))) (eqv? f g)) • obj and obj are pairs, vectors, bytevectors, records, 1 2 =⇒ unspecified or strings that denote distinct locations. • obj and obj are procedures that would behave dif- (letrec ((f (lambda () (if (eqv? f g) ’f ’both))) 1 2 (g (lambda () (if (eqv? f g) ’g ’both)))) ferently (return different values or have different side (eqv? f g)) effects) for some arguments. =⇒ #f (eqv? ’a ’a) =⇒ #t Since it is an error to modify constant objects (those re- (eqv? ’a ’b) =⇒ #f turned by literal expressions), implementations are per- (eqv? 2 2) =⇒ #t mitted, though not required, to share structure between (eqv? ’() ’()) =⇒ #t constants where appropriate. Thus the value of eqv? on (eqv? 100000000 100000000) =⇒ #t constants is sometimes implementation-dependent. (eqv? (cons 1 2) (cons 1 2))=⇒ #f (eqv? (lambda () 1) (eqv? ’(a) ’(a)) =⇒ unspecified (lambda () 2)) =⇒ #f (eqv? "a" "a") =⇒ unspecified (eqv? #f ’nil) =⇒ #f (eqv? ’(b) (cdr ’(a b))) =⇒ unspecified (let ((x ’(a))) (eqv? x x)) =⇒ #t The following examples illustrate cases in which the above rules do not fully specify the behavior of eqv?. All that Rationale: The above definition of eqv? allows implementa- can be said about such cases is that the value returned by tions latitude in their treatment of procedures and literals: im- eqv? must be a boolean. plementations are free either to detect or to fail to detect that 30 Revised7 Scheme two procedures or two literals are equivalent to each other, and (equal? ’(a (b) c) can decide whether or not to merge representations of equivalent ’(a (b) c)) =⇒ #t objects by using the same pointer or bit pattern to represent (equal? "abc" "abc") =⇒ #t both. (equal? 2 2) =⇒ #t (equal? (make-vector 5 ’a) (make-vector 5 ’a)) =⇒ #t (eq? obj1 obj2) procedure (equal? (lambda (x) x) (lambda (y) y)) =⇒ unspecified The eq? procedure is similar to eqv? except that in some cases it is capable of discerning distinctions finer than those Note: A rule of thumb is that objects are generally equal? if detectable by eqv?. they print the same. On symbols, booleans, the empty list, pairs, procedures, non-empty strings, vectors, bytevectors, and records, eq? and eqv? are guaranteed to have the same behavior. On 6.2. Numbers numbers and characters, eq?’s behavior is implementation- dependent, but it will always return either true or false, and It is important to distinguish between mathematical num- will return true only when eqv? would also return true. On bers, the Scheme numbers that attempt to model them, empty strings, vectors, bytevectors, and records, eq? may the machine representations used to implement the Scheme also behave differently from eqv?. numbers, and notations used to write numbers. This report uses the types number, complex, real, rational, and integer (eq? ’a ’a) =⇒ #t (eq? ’(a) ’(a)) =⇒ unspecified to refer to both mathematical numbers and Scheme num- (eq? (list ’a) (list ’a)) =⇒ #f bers. (eq? "a" "a") =⇒ unspecified (eq? "" "") =⇒ unspecified (eq? ’() ’()) =⇒ #t 6.2.1. Numerical types (eq? 2 2) =⇒ unspecified (eq? #\A #\A) =⇒ unspecified Mathematically, numbers are arranged into a tower of sub- (eq? car car) =⇒ unspecified types in which each level is a subset of the level above it: (let ((n (+ 2 3))) number (eq? n n)) =⇒ unspecified complex number (let ((x ’(a))) (eq? x x)) =⇒ #t real number (let ((x ’#())) rational number (eq? x x)) =⇒ #t integer (let ((p (lambda (x) x))) For example, 3 is an integer. Therefore 3 is also a rational, (eq? p p)) =⇒ #t a real, and a complex number. The same is true of the Rationale: It will usually be possible to implement eq? much Scheme numbers that model 3. For Scheme numbers, these more efficiently than eqv?, for example, as a simple pointer types are defined by the predicates number?, complex?, comparison instead of as some more complicated operation. real?, rational?, and integer?. One reason is that it is not always possible to compute eqv? There is no simple relationship between a number’s type of two numbers in constant time, whereas eq? implemented as and its representation inside a computer. Although most pointer comparison will always finish in constant time. In appli- implementations of Scheme will offer at least two different cations using procedures to implement objects with state, eq? representations of 3, these different representations denote may be used instead of eqv? since it obeys the same constraints the same integer. as eqv?. Scheme’s numerical operations treat numbers as abstract data, as independent of their representation as possible. (equal? obj1 obj2) procedure Although an implementation of Scheme may use multiple The equal? procedure recursively compares the contents of internal representations of numbers, this should not be ap- pairs, vectors, strings, bytevectors, and records, applying parent to a casual programmer writing simple programs. eqv? on other objects such as numbers and symbols. If It is necessary, however, to distinguish between numbers two objects are eqv?, they must be equal? as well. Even that are represented exactly and those that might not be. if its arguments are circular data structures, equal? must For example, indexes into data structures must be known always terminate. exactly, as must some polynomial coefficients in a symbolic (equal? ’a ’a) =⇒ #t algebra system. On the other hand, the results of measure- (equal? ’(a) ’(a)) =⇒ #t ments are inherently inexact, and irrational numbers may 6. Standard procedures 31 be approximated by rational and therefore inexact approx- numbers of that type. For example, an implementation imations. In order to catch uses of inexact numbers where that uses IEEE double-precision floating-point numbers to exact numbers are required, Scheme explicitly distinguishes represent all its inexact real numbers may also support a exact from inexact numbers. This distinction is orthogonal practically unbounded range of exact integers and rationals to the dimension of type. while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the IEEE double format. Furthermore, the gaps 6.2.2. Exactness between the representable inexact integers and rationals Scheme numbers are either exact or inexact. A number is are likely to be very large in such an implementation as exact if it was written as an exact constant or was derived the limits of this range are approached. from exact numbers using only exact operations. A number An implementation of Scheme must support exact in- is inexact if it was written as an inexact constant, if it tegers throughout the range of numbers permitted as was derived using inexact ingredients, or if it was derived indexes of lists, vectors, bytevectors, and strings or using inexact operations. Thus inexactness is a contagious that result from computing the length of one of these. property of a number. The length, vector-length, bytevector-length, and If two implementations produce exact results for a com- string-length procedures must return an exact integer, putation that did not involve inexact intermediate results, and it is an error to use anything but an exact integer as the two ultimate results will be mathematically equivalent. an index. Furthermore, any integer constant within the This is generally not true of computations involving inexact index range, if expressed by an exact integer syntax, must numbers since approximate methods such as floating-point be read as an exact integer, regardless of any implemen- arithmetic may be used, but it is the duty of each imple- tation restrictions that apply outside this range. Finally, mentation to make the result as close as practical to the the procedures listed below will always return exact inte- mathematically ideal result. ger results provided all their arguments are exact integers and the mathematically expected results are representable Rational operations such as + should always produce exact as exact integers within the implementation: results when given exact arguments. If the operation is unable to produce an exact result, then it may either report + - * the violation of an implementation restriction or it may quotient remainder modulo silently coerce its result to an inexact value. However, (/ max min abs 3 4) must not return the mathematically incorrect value numerator denominator gcd 0. See section 6.2.3. lcm floor ceiling truncate round rationalize Except for inexact->exact, the operations described in expt exact-integer-sqrt this section must generally return inexact results when floor/ ceiling/ centered/ given any inexact arguments. An operation may, however, truncate/ round/ euclidean/ return an exact result if it can prove that the value of the floor-quotient floor-remainder result is unaffected by the inexactness of its arguments. ceiling-quotient ceiling-remainder For example, multiplication of any number by an exact centered-quotient centered-remainder zero may produce an exact zero result, even if the other truncate-quotient truncate-remainder argument is inexact. round-quotient round-remainder euclidean-quotient euclidean-remainder

6.2.3. Implementation restrictions It is recommended, but not required, that implementations Implementations of Scheme are not required to implement support exact integers and exact rationals of practically the whole tower of subtypes given in section 6.2.1, but they unlimited size and precision, and to implement the above must implement a coherent subset consistent with both procedures and the / procedure in such a way that they the purposes of the implementation and the spirit of the always return exact results when given exact arguments. If Scheme language. For example, implementations in which one of these procedures is unable to deliver an exact result all numbers are real, or in which non-real numbers are al- when given exact arguments, then it may either report a ways inexact, or in which exact numbers are always integer, violation of an implementation restriction or it may silently are still quite useful. coerce its result to an inexact number; such a coercion can Implementations may also support only a limited range of cause an error later. Nevertheless, implementations that do numbers of any type, subject to the requirements of this not provide exact rational numbers should return inexact section. The supported range for exact numbers of any rational numbers rather than reporting an implementation type may be different from the supported range for inexact restriction. 32 Revised7 Scheme

An implementation may use floating-point and other ap- Negative zero is an inexact real value written -0.0 which is proximate representation strategies for inexact numbers. distinct (in the sense of eqv?) from 0.0. A Scheme imple- This report recommends, but does not require, that imple- mentation is not required to distinguish negative zero. If it mentations that use floating-point representations follow does, however, the behavior of the transcendental functions the IEEE 754 standard, and that implementations using is sensitive to the distinction in accordance with IEEE 754. other representations should match or exceed the preci- Furthermore, the negation of negative zero is ordinary zero sion achievable using these floating-point standards [19]. and vice versa. This implies that the sum of two negative In particular, the description of transcendental functions zeros is negative, and the result of subtracting (positive) in IEEE 754-2008 should be followed by such implementa- zero from a negative zero is likewise negative. However, tions, particularly with respect to infinities and NaNs. numerical comparisons treat negative zero as equal to zero. Although Scheme allows a variety of written notations for numbers, any particular implementation may support only 6.2.5. Syntax of numerical constants some of them. For example, an implementation in which all numbers are real need not support the rectangular and The syntax of the written representations for numbers is polar notations for complex numbers. If an implementa- described formally in section 7.1.1. Note that case is not tion encounters an exact numerical constant that it cannot significant in numerical constants. represent as an exact number, then it may either report a A number can be written in binary, octal, decimal, or hexa- violation of an implementation restriction or it may silently decimal by the use of a radix prefix. The radix prefixes represent the constant by an inexact number. are #b (binary), #o (octal), #d (decimal), and #x (hexa- decimal). With no radix prefix, a number is assumed to be expressed in decimal. 6.2.4. Implementation extensions A numerical constant can be specified to be either exact or Implementations may provide more than one representa- inexact by a prefix. The prefixes are #e for exact, and #i tion of floating-point numbers with differing precisions. In for inexact. An exactness prefix may appear before or after an implementation which does so, an inexact result must any radix prefix that is used. If the written representation be represented with at least as much precision as is used of a number has no exactness prefix, the constant is inexact to express any of the inexact arguments to that operation. if it contains a decimal point or an exponent. Otherwise, Although it is desirable for potentially inexact operations it is exact. such as sqrt to produce exact answers when applied to In systems with inexact numbers of varying precisions it exact arguments, if an exact number is operated upon so can be useful to specify the precision of a constant. For as to produce an inexact result, then the most precise rep- this purpose, implementations may accept numerical con- resentation available must be used. For example, the value stants written with an exponent marker that indicates the of (sqrt 4) should be 2, but in an implementation that desired precision of the inexact representation. The let- provides both single and double precision floating point ters s, f, d, and l, meaning short, single, double, and long numbers it may be the latter but must not be the former. precision respectively, are acceptable in place of e. The In addition, implementations may distinguish special num- default precision has at least as much precision as double, bers called positive infinity, negative infinity, NaN, and but implementations may allow this default to be set by negative zero. the user. Positive infinity is regarded as an inexact real (but not 3.14159265358979F0 rational) number that represents an indeterminate value Round to single — 3.141593 greater than the numbers represented by all rational num- 0.6L0 Extend to long — .600000000000000 bers. Negative infinity is regarded as an inexact real (but not rational) number that represents an indetermi- The numbers positive infinity, negative infinity and NaN nate value less than the numbers represented by all rational are written +inf.0, -inf.0 and +nan.0 respectively. Im- numbers. plementations are not required to support them, but if they do, they must be in conformance with IEEE 754. How- A NaN is regarded as an inexact real (but not rational) ever, implementations are not required to support signal- number so indeterminate that it might represent any real ing NaNs, or provide a way to distinguish between different value, including positive or negative infinity, and might NaNs. even be greater than positive infinity or less than negative infinity. It might even represent no number at all, as in the case of (asin 2.0). 6.2.6. Numerical operations Note that the real and the imaginary parts of a complex The reader is referred to section 1.3.3 for a summary of number can be infinities or NaNs. the naming conventions used to specify restrictions on the 6. Standard procedures 33 types of arguments to numerical routines. The examples of a quantity. For any Scheme number, precisely one of used in this section assume that any numerical constant these predicates is true. written using an exact notation is indeed represented as (exact? 3.0) =⇒ #f an exact number. Some examples also assume that cer- (exact? #e3.0) =⇒ #t tain numerical constants written using an inexact notation (inexact? 3.) =⇒ #t can be represented without loss of accuracy; the inexact constants were chosen so that this is likely to be true in implementations that use IEEE doubles to represent inex- act numbers. (exact-integer? z) procedure Returns #t if z is both exact and an integer; otherwise (number? obj ) procedure returns #f. (complex? obj ) procedure (exact-integer? 32) =⇒ #t (real? obj ) procedure (exact-integer? 32.0) =⇒ #f (rational? obj ) procedure (exact-integer? 32/5) =⇒ #f (integer? obj ) procedure These numerical type predicates can be applied to any kind of argument, including non-numbers. They return #t if the (finite? z) inexact library procedure object is of the named type, and otherwise they return . #f The finite? procedure returns #t on all real numbers ex- In general, if a type predicate is true of a number then cept +inf.0, -inf.0, and +nan.0, and on complex num- all higher type predicates are also true of that number. bers if their real and imaginary parts are both finite. Oth- Consequently, if a type predicate is false of a number, then erwise it returns #f. all lower type predicates are also false of that number. (finite? 3) =⇒ #t If z is a complex number, then (real? z) is true (finite? +inf.0) =⇒ #f if and only if (zero? (imag-part z)) and (exact? (finite? 3.0+inf.0i) =⇒ #f (imag-part z)) are both true. If x is an inexact real num- ber, then (integer? x) is true if and only if (= x (round x)). (nan? z) inexact library procedure The numbers +inf.0, -inf.0, and +nan.0 are real but not rational. The nan? procedure returns #t on +nan.0, and on any complex number if its real part or its imaginary part or (complex? 3+4i) =⇒ #t both are +nan.0. Otherwise it returns #f. (complex? 3) =⇒ #t (real? 3) =⇒ #t (nan? +nan.0) =⇒ #t (real? -2.5+0i) =⇒ #t (nan? 32) =⇒ #f (real? -2.5+0.0i) =⇒ #f (nan? +nan.0+5.0i) =⇒ #t (real? #e1e10) =⇒ #t (nan? 1+2i) =⇒ #f (real? +inf.0) =⇒ #t (rational? -inf.0) =⇒ #f (rational? 6/10) =⇒ #t (rational? 6/3) =⇒ #t (= z1 z2 z3 ... ) procedure (integer? 3+0i) =⇒ #t (< x1 x2 x3 ... ) procedure (integer? 3.0) =⇒ #t (> x1 x2 x3 ... ) procedure (integer? 8/4) =⇒ #t (<= x1 x2 x3 ... ) procedure (>= x x x ... ) procedure Note: The behavior of these type predicates on inexact num- 1 2 3 bers is unreliable, since any inaccuracy might affect the result. These procedures return #t if their arguments are (respec- tively): equal, monotonically increasing, monotonically de- Note: In many implementations the complex? procedure will creasing, monotonically nondecreasing, or monotonically be the same as number?, but unusual implementations may be nonincreasing, and #f otherwise. If any of the arguments able to represent some irrational numbers exactly or may ex- are +nan.0, all the predicates return #f. tend the number system to support some kind of non-complex numbers. These predicates are required to be transitive. Note: The traditional implementations of these predicates in (exact? z) procedure Lisp-like languages are not transitive. (inexact? z) procedure Note: While it is not an error to compare inexact numbers These numerical predicates provide tests for the exactness using these predicates, the results are unreliable because a small 34 Revised7 Scheme inaccuracy can affect the result; this is especially true of = and (abs x) procedure zero?. When in doubt, consult a numerical analyst. The abs procedure returns the absolute value of its argu- ment. (zero? z) procedure (abs -7) =⇒ 7 (positive? x) procedure (negative? x) procedure (odd? n) procedure (floor/ n n ) procedure (even? n) procedure 1 2 (floor-quotient n1 n2) procedure These numerical predicates test a number for a particular (floor-remainder n1 n2) procedure property, returning or . See note above. #t #f (ceiling/ n1 n2) procedure (ceiling-quotient n1 n2) procedure (max x1 x2 ... ) procedure (ceiling-remainder n1 n2) procedure (min x1 x2 ... ) procedure (truncate/ n1 n2) procedure These procedures return the maximum or minimum of their (truncate-quotient n1 n2) procedure arguments. (truncate-remainder n1 n2) procedure (round/ n1 n2) procedure (max 3 4) =⇒ 4 ; exact (round-quotient n1 n2) procedure (max 3.9 4) =⇒ 4.0 ; inexact (round-remainder n1 n2) procedure Note: If any argument is inexact, then the result will also be (euclidean/ n1 n2) procedure inexact (unless the procedure can prove that the inaccuracy is (euclidean-quotient n1 n2) procedure not large enough to affect the result, which is possible only in (euclidean-remainder n1 n2) procedure unusual implementations). If min or max is used to compare (centered/ n1 n2) procedure numbers of mixed exactness, and the numerical value of the (centered-quotient n1 n2) procedure result cannot be represented as an inexact number without loss (centered-remainder n1 n2) procedure of accuracy, then the procedure may report a violation of an These procedures, all in the division library, implement implementation restriction. number-theoretic (integer) division. It is an error if n2 is zero. The procedures ending in / return two integers; (+ z1 ... ) procedure the other procedures return an integer. All the procedures (* z1 ... ) procedure compute a quotient nq and remainder nr such that n1 = These procedures return the sum or product of their argu- n2nq + nr. For each of the six division operators, there are ments. three procedures defined as follows: (+ 3 4) =⇒ 7 (hoperatori/ n1 n2) =⇒ nq nr (+ 3) =⇒ 3 (hoperatori-quotient n1 n2) =⇒ nq (+) =⇒ 0 (hoperatori-remainder n1 n2) =⇒ nr (* 4) =⇒ 4 (*) =⇒ 1 The remainder nr is determined by the choice of integer nq: nr = n1 − n2nq. Each set of operators uses a different (- z1 z2) procedure choice of nq: (- z) procedure ceiling nq = dn1/n2e (- z1 z2 ... ) procedure floor nq = bn1/n2c (/ z1 z2) procedure truncate nq = truncate(n1/n2) (/ z) procedure round nq = [n1/n2] (/ z1 z2 ... ) procedure euclidean if n2 > 0, nq = bn1/n2c; if n2 < 0, nq = dn1/n2e With two or more arguments, these procedures return the centered choose nq such that −|n2/2| <= nr < |n2/2| difference or quotient of their arguments, associating to the For any of the operators, and for integers n1 and n2 with left. With one argument, however, they return the additive n2 not equal to 0, or multiplicative inverse of their argument. It is an error (= n (+ (* n (hoperatori-quotient n n )) if any argument of / other than the first is an exact zero. 1 2 1 2 (hoperatori-remainder n1 n2))) (- 3 4) =⇒ -1 =⇒ #t (- 3 4 5) =⇒ -6 provided all numbers involved in that computation are ex- =⇒ (- 3) -3 act. (/ 3 4 5) =⇒ 3/20 (/ 3) =⇒ 1/3 See [5] for discussion. 6. Standard procedures 35

(quotient n1 n2) procedure procedure returns the smallest integer not smaller than x, (remainder n1 n2) procedure truncate returns the integer closest to x whose absolute (modulo n1 n2) procedure value is not larger than the absolute value of x, and round returns the closest integer to x, rounding to even when x The quotient and remainder procedures are equivalent is halfway between two integers. to truncate-quotient and truncate-remainder, respec- tively, and modulo is equivalent to floor-remainder. Rationale: The round procedure rounds to even for consistency with the default rounding mode specified by the IEEE 754 IEEE (modulo 13 4) =⇒ 1 floating-point standard. (remainder 13 4) =⇒ 1 Note: If the argument to one of these procedures is inexact, (modulo -13 4) =⇒ 3 then the result will also be inexact. If an exact value is needed, (remainder -13 4) =⇒ -1 the result can be passed to the inexact->exact procedure.

(modulo 13 -4) =⇒ -3 (floor -4.3) =⇒ -5.0 (remainder 13 -4) =⇒ 1 (ceiling -4.3) =⇒ -4.0 (truncate -4.3) =⇒ -4.0 (modulo -13 -4) =⇒ -1 (round -4.3) =⇒ -4.0 (remainder -13 -4) =⇒ -1 (floor 3.5) =⇒ 3.0 (remainder -13 -4.0) =⇒ -1.0 ; inexact (ceiling 3.5) =⇒ 4.0 (truncate 3.5) =⇒ 3.0 Note: These procedures are provided for backward compati- (round 3.5) =⇒ 4.0 ; inexact bility with earlier versions of this report. (round 7/2) =⇒ 4 ; exact (round 7) =⇒ 7 (gcd n1 ... ) procedure (lcm n1 ... ) procedure These procedures return the greatest common divisor or (rationalize x y) procedure least common multiple of their arguments. The result is always non-negative. The rationalize procedure returns the simplest rational (gcd 32 -36) =⇒ 4 number differing from x by no more than y. A rational (gcd) =⇒ 0 number r1 is simpler than another rational number r2 if (lcm 32 -36) =⇒ 288 r1 = p1/q1 and r2 = p2/q2 (in lowest terms) and |p1| ≤ |p2| (lcm 32.0 -36) =⇒ 288.0 ; inexact and |q1| ≤ |q2|. Thus 3/5 is simpler than 4/7. Although not (lcm) =⇒ 1 all rationals are comparable in this ordering (consider 2/7 and 3/5) any interval contains a rational number that is simpler than every other rational number in that interval (numerator q) procedure (the simpler 2/5 lies between 2/7 and 3/5). Note that (denominator q) procedure 0 = 0/1 is the simplest rational of all. These procedures return the numerator or denominator of their argument; the result is computed as if the argument (rationalize was represented as a fraction in lowest terms. The denom- (inexact->exact .3) 1/10) =⇒ 1/3 ; exact inator is always positive. The denominator of 0 is defined (rationalize .3 1/10) =⇒ #i1/3 ; inexact to be 1. (numerator (/ 6 4)) =⇒ 3 (exp z) inexact library procedure (denominator (/ 6 4)) =⇒ 2 (log z) inexact library procedure (denominator (sin z) inexact library procedure (exact->inexact (/ 6 4))) =⇒ 2.0 (cos z) inexact library procedure (tan z) inexact library procedure (floor x) procedure (asin z) inexact library procedure (ceiling x) procedure (acos z) inexact library procedure (truncate x) procedure (atan z) inexact library procedure (round x) procedure (atan y x) inexact library procedure These procedures compute the usual transcendental func- These procedures return integers. The floor procedure tions. The log procedure computes the natural loga- returns the largest integer not larger than x. The ceiling rithm of z (not the base ten logarithm). The asin, 36 Revised7 Scheme acos, and atan procedures compute arcsine (sin−1), ar- (magnitude z) complex library procedure ccosine (cos−1), and arctangent (tan−1), respectively. (angle z) complex library procedure The two-argument variant of atan computes (angle Let x , x , x , and x be real numbers and z be a complex (make-rectangular x y)) (see below), even in imple- 1 2 3 4 number such that mentations that don’t support the complex library.

ix4 In general, the mathematical functions log, arcsine, arc- z = x1 + x2i = x3 · e cosine, and arctangent are multiply defined. The value of log z is defined to be the one whose imaginary part lies in Then all of the range from −π (exclusive) to π (inclusive). The value (make-rectangular x1 x2) =⇒ z of log 0 is undefined. With log defined this way, the val- (make-polar x3 x4) =⇒ z −1 −1 −1 ues of sin z, cos z, and tan z are according to the (real-part z) =⇒ x1 following formulæ: (imag-part z) =⇒ x2 (magnitude z) =⇒ |x3| −1 p 2 sin z = −i log(iz + 1 − z ) (angle z) =⇒ xangle

cos−1 z = π/2 − sin−1 z are true, where −π < xangle ≤ π with xangle = x4 + 2πn tan−1 z = (log(1 + iz) − log(1 − iz))/(2i) for some integer n. The make-polar procedure may return an inexact complex The above specification follows [35], which in turn number even if its arguments are exact. cites [27]; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation Rationale: The magnitude procedure is the same as abs for a of these functions. When it is possible, these procedures real argument, but abs is in the base library, whereas magnitude produce a real result from a real argument. is in the optional complex library.

(sqrt z) inexact library procedure (exact->inexact z) procedure Returns the principal square root of z. The result will (inexact->exact z) procedure have either a positive real part, or a zero real part and a The procedure exact->inexact returns an inexact repre- non-negative imaginary part. sentation of z. The value returned is the inexact number that is numerically closest to the argument. For inexact ar- (exact-integer-sqrt k) procedure guments, the result is the same as the argument. For exact complex numbers, the result is a complex number whose Returns two non-negative exact integers s and r where k = real and imaginary parts are the result of applying exact-> 2 2 s + r and k < (s + 1) . inexact to the real and imaginary parts of the argument, respectively. If an exact argument has no reasonably close (exact-integer-sqrt 4) =⇒ 2 0 (exact-integer-sqrt 5) =⇒ 2 1 inexact equivalent, then a violation of an implementation restriction may be reported. The procedure inexact->exact returns an exact represen- tation of z. The value returned is the exact number that is (expt z1 z2) procedure numerically closest to the argument. For exact arguments, Returns z1 raised to the power z2. For nonzero z1, this is the result is the same as the argument. For inexact non- integral real arguments, the implementation may return a z2 z2 log z1 z1 = e rational approximation, or may report an implementation violation. For inexact complex arguments, the result is a z 0.0 is 1.0 if z = 0.0, and 0.0 if (real-part z) is positive. complex number whose real and imaginary parts are the re- For other cases in which the first argument is zero, either sult of applying inexact->exact to the real and imaginary an error is signalled or an unspecified number is returned. parts of the argument, respectively. If an inexact argument has no reasonably close exact equivalent, then a violation of an implementation restriction may be reported.

(make-rectangular x1 x2) complex library procedure These procedures implement the natural one-to-one corre- (make-polar x3 x4) complex library procedure spondence between exact and inexact integers throughout (real-part z) complex library procedure an implementation-dependent range. See section 6.2.3. (imag-part z) complex library procedure 6. Standard procedures 37

6.2.7. Numerical input and output real, then string->number is permitted to return #f whenever string uses the polar or rectangular notations for complex num- bers. If all numbers are integers, then string->number may (number->string z) procedure return #f whenever the fractional notation is used. If all num- (number->string z radix) procedure bers are exact, then string->number may return #f whenever It is an error if radix is not one of 2, 8, 10, or 16. If an exponent marker or explicit exactness prefix is used. If all omitted, radix defaults to 10. The procedure number-> inexact numbers are integers, then string->number may return string takes a number and a radix and returns as a string #f whenever a decimal point is used. an external representation of the given number in the given radix such that (let ((number number) 6.3. Booleans (radix radix)) (eqv? number The standard boolean objects for true and false are writ- (string->number (number->string number ten as #t and #f. Alternatively, they may be written radix) #true and #false, respectively. What really matters, radix))) though, are the objects that the Scheme conditional expres- sions (if, cond, and, or, when, unless, do) treat as true or is true. It is an error if no possible result makes this ex- false. The phrase “a true value” (or sometimes just “true”) pression true. means any object treated as true by the conditional expres- If z is inexact, the radix is 10, and the above expression sions, and the phrase “a false value” (or “false”) means any can be satisfied by a result that contains a decimal point, object treated as false by the conditional expressions. then the result contains a decimal point and is expressed Of all the Scheme values, only #f counts as false in condi- using the minimum number of digits (exclusive of exponent tional expressions. All other Scheme values, including #t, and trailing zeroes) needed to make the above expression count as true. true [7, 9]; otherwise the format of the result is unspecified. Note: Unlike some other dialects of Lisp, Scheme distinguishes The result returned by number->string never contains an #f and the empty list from each other and from the symbol explicit radix prefix. nil. Note: The error case can occur only when z is not a complex Boolean constants evaluate to themselves, so they do not number or is a complex number with a non-rational real or need to be quoted in programs. imaginary part. #t =⇒ #t Rationale: If z is an inexact number and the radix is 10, then #f =⇒ #f the above expression is normally satisfied by a result containing ’#f =⇒ #f a decimal point. The unspecified case allows for infinities, NaNs, and unusual representations. (not obj ) procedure (string->number string) procedure The not procedure returns #t if obj is false, and returns (string->number string radix) procedure #f otherwise. Returns a number of the maximally precise representation (not #t) =⇒ #f expressed by the given string. It is an error if radix is not (not 3) =⇒ #f 2, 8, 10, or 16. If supplied, radix is a default radix that (not (list 3)) =⇒ #f will be overridden if an explicit radix prefix is present in (not #f) =⇒ #t string (e.g. "#o177"). If radix is not supplied, then the (not ’()) =⇒ #f default radix is 10. If string is not a syntactically valid (not (list)) =⇒ #f =⇒ notation for a number, then string->number returns #f. (not ’nil) #f (string->number "100") =⇒ 100 (string->number "100" 16) =⇒ 256 (boolean? obj ) procedure (string->number "1e2") =⇒ 100.0 The boolean? predicate returns #t if obj is either #t or #f and returns #f otherwise. Note: The domain of string->number may be restricted by implementations in the following ways. Whenever string con- (boolean? #f) =⇒ #t (boolean? 0) =⇒ #f tains an explicit radix prefix, string->number is permitted to (boolean? ’()) =⇒ #f return #f. If all numbers supported by an implementation are 38 Revised7 Scheme

6.4. Pairs and lists (a . (b . (c . d)))

A pair (sometimes called a dotted pair) is a record structure Whether a given pair is a list depends upon what is stored with two fields called the car and cdr fields (for historical in the cdr field. When the set-cdr! procedure is used, an object can be a list one moment and not the next: reasons). Pairs are created by the procedure cons. The car and cdr fields are accessed by the procedures car and (define x (list ’a ’b ’c)) cdr. The car and cdr fields are assigned by the procedures (define y x) set-car! and set-cdr!. y =⇒ (a b c) Pairs are used primarily to represent lists. A list can be (list? y) =⇒ #t (set-cdr! x 4) =⇒ unspecified defined recursively as either the empty list or a pair whose x =⇒ (a . 4) cdr is a list. More precisely, the set of lists is defined as (eqv? x y) =⇒ #t the smallest set X such that y =⇒ (a . 4) (list? y) =⇒ #f • The empty list is in X . (set-cdr! x x) =⇒ unspecified (list? x) =⇒ #f • If list is in X , then any pair whose cdr field contains list is also in X . Within literal expressions and representations of ob- jects read by the read procedure, the forms ’hdatumi, `hdatumi, ,hdatumi, and ,@hdatumi denote two-ele- The objects in the car fields of successive pairs of a list are ment lists whose first elements are the symbols quote, the elements of the list. For example, a two-element list quasiquote, unquote, and unquote-splicing, respec- is a pair whose car is the first element and whose cdr is a tively. The second element in each case is hdatumi. This pair whose car is the second element and whose cdr is the convention is supported so that arbitrary Scheme programs empty list. The length of a list is the number of elements, can be represented as lists. That is, according to Scheme’s which is the same as the number of pairs. grammar, every hexpressioni is also a hdatumi (see sec- The empty list is a special object of its own type It is not tion 7.1.2). Among other things, this permits the use of a pair, it has no elements, and its length is zero. the read procedure to parse Scheme programs. See sec- Note: The above definitions imply that all lists have finite tion 3.3. length and are terminated by the empty list. The most general notation (external representation) for (pair? obj ) procedure Scheme pairs is the “dotted” notation (c1 . c2) where c1 The pair? predicate returns #t if obj is a pair, and other- is the value of the car field and c2 is the value of the cdr wise returns #f. field. For example (4 . 5) is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the external repre- (pair? ’(a . b)) =⇒ #t sentation of a pair, not an expression that evaluates to a (pair? ’(a b c)) =⇒ #t pair. (pair? ’()) =⇒ #f (pair? ’#(a b)) =⇒ #f A more streamlined notation can be used for lists: the elements of the list are simply enclosed in parentheses and separated by spaces. The empty list is written () . For (cons obj obj ) procedure example, 1 2 Returns a newly allocated pair whose car is obj1 and whose (a b c d e) cdr is obj2. The pair is guaranteed to be different (in the and sense of eqv?) from every existing object.

(a . (b . (c . (d . (e . ()))))) (cons ’a ’()) =⇒ (a) (cons ’(a) ’(b c d)) =⇒ ((a) b c d) are equivalent notations for a list of symbols. (cons "a" ’(b c)) =⇒ ("a" b c) A chain of pairs not ending in the empty list is called an (cons ’a 3) =⇒ (a . 3) improper list. Note that an improper list is not a list. (cons ’(a b) ’c) =⇒ ((a b) . c) The list and dotted notations can be combined to represent improper lists: (car pair) procedure (a b c . d) Returns the contents of the car field of pair. Note that it is equivalent to is an error to take the car of the empty list. 6. Standard procedures 39

(car ’(a b c)) =⇒ a (make-list k) procedure (car ’((a) b c d)) =⇒ (a) (make-list k fill) procedure (car ’(1 . 2)) =⇒ 1 (car ’()) =⇒ error Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspeci- (cdr pair) procedure fied.

Returns the contents of the cdr field of pair. Note that it (make-list 2 3) =⇒ (3 3) is an error to take the cdr of the empty list. (cdr ’((a) b c d)) =⇒ (b c d) (cdr ’(1 . 2)) =⇒ 2 (cdr ’()) =⇒ error (list obj ... ) procedure Returns a newly allocated list of its arguments. (set-car! pair obj ) procedure (list ’a (+ 3 4) ’c) =⇒ (a 7 c) Stores obj in the car field of pair. The value returned by (list) =⇒ () set-car! is unspecified. (define (f) (list ’not-a-constant-list)) (length list) procedure (define (g) ’(constant-list)) (set-car! (f) 3) =⇒ unspecified Returns the length of list. (set-car! (g) 3) =⇒ error (length ’(a b c)) =⇒ 3 (length ’(a (b) (c d e))) =⇒ 3 (set-cdr! pair obj ) procedure (length ’()) =⇒ 0 Stores obj in the cdr field of pair. The value returned by set-cdr! is unspecified. (append list ... ) procedure

(caar pair) procedure Returns a list consisting of the elements of the first list (cadr pair) procedure followed by the elements of the other lists. . . . . (append ’(x) ’(y)) =⇒ (x y) (cdddar pair) procedure (append ’(a) ’(b c d)) =⇒ (a b c d) =⇒ (cddddr pair) procedure (append ’(a (b)) ’((c))) (a (b) (c)) These procedures are compositions of car and cdr, where The resulting list is always newly allocated, except that for example caddr could be defined by it shares structure with the last list argument. The last argument may actually be any object; an improper list (define caddr (lambda (x) (car (cdr (cdr x))))). results if the last argument is not a proper list. Arbitrary compositions, up to four deep, are provided. (append ’(a b) ’(c . d)) =⇒ (a b c . d) There are twenty-eight of these procedures in all. (append ’() ’a) =⇒ a

(null? obj ) procedure (reverse list) procedure Returns #t if obj is the empty list, otherwise returns #f. Returns a newly allocated list consisting of the elements of list in reverse order. (list? obj ) procedure Returns #t if obj is a list. Otherwise, it returns #f. By (reverse ’(a b c)) =⇒ (c b a) definition, all lists have finite length and are terminated by (reverse ’(a (b c) d (e (f)))) the empty list. =⇒ ((e (f)) d (b c) a) (list? ’(a b c)) =⇒ #t (list? ’()) =⇒ #t (list-tail list k) procedure (list? ’(a . b)) =⇒ #f (let ((x (list ’a))) Returns the sublist of list obtained by omitting the first k (set-cdr! x x) elements. It is an error if list has fewer than k elements. (list? x)) =⇒ #f The list-tail procedure could be defined by 40 Revised7 Scheme

(define list-tail (assq obj alist) procedure (lambda (x k) (assv obj alist) procedure (if (zero? k) (assoc obj alist) procedure x (assoc obj alist compare) procedure (list-tail (cdr x) (- k 1))))) It is an error if alist (for “association list”) is not a list of pairs. These procedures find the first pair in alist whose car field is obj , and returns that pair. If no pair in alist (list-ref list k) procedure has obj as its car, then #f (not the empty list) is returned. Returns the kth element of list. (This is the same as the The assq procedure uses eq? to compare obj with the car car of (list-tail list k).) It is an error if list has fewer fields of the pairs in alist, while assv uses eqv? and assoc than k elements. uses compare if given and equal? otherwise. (define e ’((a 1) (b 2) (c 3))) (list-ref ’(a b c d) 2) =⇒ c (assq ’a e) =⇒ (a 1) (list-ref ’(a b c d) (assq ’b e) =⇒ (b 2) (inexact->exact (round 1.8))) (assq ’d e) =⇒ #f =⇒ c (assq (list ’a) ’(((a)) ((b)) ((c)))) =⇒ #f (assoc (list ’a) ’(((a)) ((b)) ((c)))) (list-set! list k obj ) procedure =⇒ ((a)) (assoc 2.0 ’((1 1) (2 4) (3 9)) =) The list-set! procedure stores obj in element k of list. =⇒ (2 4) It is an error if k is not a valid index of list. The value (assq 5 ’((2 3) (5 7) (11 13))) returned by list-set! is unspecified. =⇒ unspecified (assv 5 ’((2 3) (5 7) (11 13))) (let ((ls (list ’one ’two ’five!))) =⇒ (5 7) (list-set! ls 2 ’three) ls) Rationale: Although they are often used as predicates, memq, =⇒ (one two three) memv, member, assq, assv, and assoc do not have question marks in their names because they return potentially useful (list-set! ’(0 1 2) 1 "oops") values rather than just #t or #f. =⇒ error ; constant list (list-copy list) procedure

(memq obj list) procedure Returns a newly allocated copy of the given list. Only the (memv obj list) procedure pairs themselves are copied; the cars of the result are the (member obj list) procedure same (in the sense of eqv? as the cars of list. If the last (member obj list compare) procedure pair of list has a cdr which is not the empty list, the last pair of the result does, too. An argument which is not a These procedures return the first sublist of list whose car list is returned unchanged. is obj , where the sublists of list are the non-empty lists returned by (list-tail list k) for k less than the length of list. If obj does not occur in list, then #f (not the empty 6.5. Symbols list) is returned. The memq procedure uses eq? to compare obj with the elements of list, while memv uses eqv? and Symbols are objects whose usefulness rests on the fact that member uses compare, if given, and equal? otherwise. two symbols are identical (in the sense of eqv?) if and only if their names are spelled the same way. For instance, they (memq ’a ’(a b c)) =⇒ (a b c) can be used the way enumerated values are used in other (memq ’b ’(a b c)) =⇒ (b c) languages. (memq ’a ’(b c d)) =⇒ #f (memq (list ’a) ’(b (a) c)) =⇒ #f The rules for writing a symbol are exactly the same as the (member (list ’a) rules for writing an identifier; see sections 2.1 and 7.1.1. ’(b (a) c)) =⇒ ((a) c) (member "B" It is guaranteed that any symbol that has been returned ’("a" "b" "c") as part of a literal expression, or read using the read pro- string-ci=?) =⇒ ("b" "c") cedure, and subsequently written out using the write pro- (memq 101 ’(100 101 102)) =⇒ unspecified cedure, will read back in as the identical symbol (in the (memv 101 ’(100 101 102)) =⇒ (101 102) sense of eqv?). 6. Standard procedures 41

Note: Some implementations have values known as “unin- any of the following procedures to a non-Unicode character terned symbols,” which defeat write/read invariance, and also is implementation-dependent. violate the rule that two symbols are the same if and only if Characters are written using the notation #\hcharacteri or their names are spelled the same. #\hcharacter namei or #\xhhex scalar valuei. Here are some examples: (symbol? obj ) procedure

Returns #t if obj is a symbol, otherwise returns #f. #\a ; lower case letter (symbol? ’foo) =⇒ #t #\A ; upper case letter (symbol? (car ’(a b))) =⇒ #t #\( ; left parenthesis (symbol? "bar") =⇒ #f #\ ; the space character (symbol? ’nil) =⇒ #t #\iota ; ι (if supported) (symbol? ’()) =⇒ #f #\x03BB ; λ (if supported) (symbol? #f) =⇒ #f The following character names must be supported by all implementations: (symbol->string symbol) procedure Returns the name of symbol as a string. It is an error to apply mutation procedures like string-set! to strings #\alarm ; U+0007 returned by this procedure. #\backspace ; U+0008 #\delete ; U+007F (symbol->string ’flying-fish) ; U+001B =⇒ "flying-fish" #\escape (symbol->string ’Martin) =⇒ "Martin" #\newline ; the linefeed character, U+000A (symbol->string #\null ; the null character, U+0000 (string->symbol "Malvina")) #\return ; the return character, U+000D =⇒ "Malvina" #\space ; the preferred way to write a space #\tab ; the tab character, U+0009

(string->symbol string) procedure Case is significant in #\hcharacteri, and in #\hcharacter Returns the symbol whose name is string. This procedure namei, but not in #\xhhex scalar valuei. If hcharacteri in can create symbols with names containing special charac- #\hcharacteri is alphabetic, then any character immedi- ters that would require escaping when written. ately following hcharacteri must be a delimiter character such as a space or parenthesis. This rule resolves the am- (string->symbol "mISSISSIppi") =⇒ mISSISSIppi biguous case where, for example, the sequence of characters (eq? ’bitBlt (string->symbol "bitBlt")) “#\space” could be taken to be either a representation of =⇒ #t the space character or a representation of the character (eq? ’JollyWog “#\s” followed by a representation of the symbol “pace.” (string->symbol Characters written in the #\ notation are self-evaluating. (symbol->string ’JollyWog))) =⇒ #t That is, they do not have to be quoted in programs. (string=? "K. Harper, M.D." Some of the procedures that operate on characters ignore (symbol->string the difference between upper case and lower case. The pro- (string->symbol "K. Harper, M.D."))) cedures that ignore case have “-ci” (for “case insensitive”) =⇒ #t embedded in their names.

6.6. Characters (char? obj ) procedure Returns #t if obj is a character, otherwise returns #f. Characters are objects that represent printed characters such as letters and digits. All Scheme implementations must support at least the ASCII character repertoire: that (char=? char1 char2 char3 ... ) procedure is, Unicode characters U+0000 through U+007F. Imple- (char? char1 char2 char3 ... ) procedure see fit, and may also support non-Unicode characters as (char<=? char1 char2 char3 ... ) procedure well. Except as otherwise specified, the result of applying (char>=? char1 char2 char3 ... ) procedure 42 Revised7 Scheme

These procedures return #t if the Unicode codepoints cor- (char->integer char) procedure responding to their arguments are (respectively): equal, (integer->char n) procedure monotonically increasing, monotonically decreasing, mono- Given a Unicode character, char->integer returns an ex- tonically nondecreasing, or monotonically nonincreasing. act integer between 0 and #xD7FF or between #xE000 and These predicates are required to be transitive. #x10FFFF which is equal to the Unicode code point of that character. Given a non-Unicode character, it returns an These procedures impose a total ordering on the set of exact integer greater than #x10FFFF. This is true indepen- characters which is the same as the Unicode code point dent of whether the implementation uses the Unicode rep- ordering. This is true whether or not the implementation resentation internally. uses the Unicode representation internally. Given an exact integer that is the value returned by a char- acter when char->integer is applied to it, integer->char (char-ci=? char1 char2 char3 ... ) returns that character. char library procedure (char-ci? char1 char2 char3 ... ) char library procedure (char-foldcase char) char library procedure (char-ci<=? char1 char2 char3 ... ) The char-upcase procedure, given an argument that is char library procedure the lowercase part of a Unicode casing pair, returns the (char-ci>=? char1 char2 char3 ... ) uppercase member of the pair, provided that both charac- char library procedure ters are supported by the Scheme implementation. Note that language-sensitive casing pairs are not used. If the These procedures are similar to char=? et cetera, but they treat upper case and lower case letters as the same. For argument is not the lowercase member of such a pair, it is returned. example, (char-ci=? #\A #\a) returns #t. The char-downcase procedure, given an argument that is Specifically, these procedures behave as if char-foldcase the uppercase part of a Unicode casing pair, returns the were applied to their arguments before they were com- lowercase member of the pair, provided that both charac- pared. ters are supported by the Scheme implementation. Note that language-sensitive casing pairs are not used. If the (char-alphabetic? char) char library procedure argument is not the uppercase member of such a pair, it is (char-numeric? char) char library procedure returned. (char-whitespace? char) char library procedure The char-foldcase procedure applies the Unicode simple (char-upper-case? letter) char library procedure case-folding algorithm to its argument and returns the re- (char-lower-case? letter) char library procedure sult. Note that language-sensitive folding is not used. If These procedures return #t if their arguments are alpha- the argument is an uppercase letter, the result will be ei- betic, numeric, whitespace, upper case, or lower case char- ther a lowercase letter or the same as the argument if the acters, respectively, otherwise they return #f. lowercase letter does not exist or is not supported by the implementation. See UAX #29 [14] (part of the Unicode Specifically, they must return #t when applied to char- Standard) for details. acters with the Unicode properties Alphabetic, Nu- meric Digit, White Space, Uppercase, and Lowercase re- Note that many Unicode lowercase characters do not have spectively, and #f when applied to any other Unicode char- uppercase equivalents. acters. Note that many Unicode characters are alphabetic but neither upper nor lower case. 6.7. Strings

(digit-value char) char library procedure Strings are sequences of characters. Strings are written as sequences of characters enclosed within double quotes ("). This procedure returns the numeric value (0 to 9) of its Within a string literal, various escape sequences represent argument if it is a numeric digit (that is, if char-numeric? characters other than themselves. Escape sequences always returns #t), or #f on any other character. start with a backslash (\): (digit-value #\3) =⇒ 3 (digit-value #\x0664) =⇒ 4 • \a : alarm, U+0007 (digit-value #\x0EA6) =⇒ 0 • \b : backspace, U+0008 6. Standard procedures 43

• \t : character tabulation, U+0009 (string? obj ) procedure

• \n : linefeed, U+000A Returns #t if obj is a string, otherwise returns #f.

• \r : return, U+000D (make-string k) procedure • \" : doublequote, U+0022 (make-string k char) procedure

• \\ : backslash, U+005C The make-string procedure returns a newly allocated string of length k. If char is given, then all the characters • \hintraline whitespaceihline endingi of the string are initialized to char, otherwise the contents hintraline whitespacei : nothing of the string are unspecified.

• \xhhex scalar valuei; : specified character (note the terminating semi-colon). (string char ... ) procedure Returns a newly allocated string composed of the argu- The result is unspecified if any other character in a string ments. It is analogous to list. occurs after a backslash. Except for a line ending, any character outside of an escape (string-length string) procedure sequence stands for itself in the string literal. A line end- Returns the number of characters in the given string. ing which is preceded by \hintraline whitespacei expands to nothing (along with any trailing intraline whitespace), and can be used to indent strings for improved legibility. (string-ref string k) procedure Any other line ending has the same effect as inserting a \n It is an error if k is not a valid index of string. The character into the string. string-ref procedure returns character k of string us- Examples: ing zero-origin indexing. There is no requirement for this procedure to execute in constant time. "The word \"recursion\" has many meanings." "Another example:\ntwo lines of text" "Here’s a text \ (string-set! string k char) procedure containing just one line" "\x03B1; is named GREEK SMALL LETTER ALPHA." It is an error if k is not a valid index of string. The string-set! procedure stores char in element k of string The length of a string is the number of characters that it and returns an unspecified value. There is no requirement contains. This number is an exact, non-negative integer for this procedure to execute in constant time. that is fixed when the string is created. The valid indexes of a string are the exact non-negative integers less than (define (f) (make-string 3 #\*)) the length of the string. The first character of a string has (define (g) "***") (string-set! (f) 0 #\?) =⇒ unspecified index 0, the second has index 1, and so on. (string-set! (g) 0 #\?) =⇒ error In phrases such as “the characters of string beginning with (string-set! (symbol->string ’immutable) index start and ending with index end,” it is understood 0 that the index start is inclusive and the index end is ex- #\?) =⇒ error clusive. Thus if start and end are the same index, a null substring is referred to, and if start is zero and end is the (string=? string string string ... ) procedure length of string, then the entire string is referred to. It is 1 2 3 an error if start is less than end. Returns #t if all the strings are the same length and contain exactly the same characters in the same positions, other- Some of the procedures that operate on strings ignore the wise returns #f. difference between upper and lower case. The versions that ignore case have “-ci” (for “case insensitive”) embedded in their names. (string-ci=? string1 string2 string3 ... ) string library procedure Implementations may forbid certain characters from ap- pearing in strings. For example, an implementation might Returns #t if, after case-folding, all the strings are the support the entire Unicode repertoire, but only allow char- same length and contain the same characters in the same acters U+0000 to U+00FF (the Latin-1 repertoire) in positions, otherwise returns #f. Specifically, these proce- strings. It is an error to pass such a forbidden character to dures behave as if string-foldcase were applied to their make-string, string, string-set!, or string-fill!. arguments before comparing them. 44 Revised7 Scheme

(string-ni=? string1 string2 string3 ... ) procedure In all cases, a pair of strings must satisfy exactly one of , , and , and must satisfy Returns #t if, after an implementation-defined normaliza- string? tion, all the strings are the same length and contain the string<=? if and only if they do not satisfy string>? and same characters in the same positions, otherwise returns string>=? if and only if they do not satisfy string

(string? string1 string2 string3 ... ) procedure The result may differ in length from the argument. What (string-ci>? string1 string2 string3 ... ) is more, a few characters have case-mappings that depend char library procedure on the surrounding context. For example, Greek capital (string-ni>? string1 string2 string3 ... ) sigma normally lowercases to Greek small sigma, but at char library procedure the end of a word it downcases to Greek small final sigma (string<=? string1 string2 string3 ... ) procedure instead. See UAX #29 [14] (part of the Unicode Standard) (string-ci<=? string1 string2 string3 ... ) for details. char library procedure (string-ni<=? string1 string2 string3 ... ) char library procedure (substring string start end) procedure (string>=? string1 string2 string3 ... ) procedure It is an error if start and end are not exact integers satis- (string-ci>=? string1 string2 string3 ... ) fying the inequality char library procedure (string-ni>=? string1 string2 string3 ... ) 0 ≤ start ≤ end ≤ (string-length string). char library procedure The substring procedure returns a newly allocated string These procedures return if their arguments are (respec- #t formed from the characters of string beginning with index tively): equal, monotonically increasing, monotonically de- start (inclusive) and ending with index end (exclusive). creasing, monotonically nondecreasing, or monotonically nonincreasing. These predicates are required to be transitive. (string-append string ... ) procedure These procedures compare strings in an implementation- Returns a newly allocated string whose characters are the defined way. One approach is to make them the lexico- concatenation of the characters in the given strings. graphic extensions to strings of the corresponding order- ings on characters. In that case, stringlist string) procedure lexicographic ordering on strings induced by the ordering (list->string list) procedure charlist returns a newly allocated list of the charac- shorter string would be considered to be lexicographically ters that make up the given string. list->string returns less than the longer string. However, it is also permit- a newly allocated string formed from the elements in the ted to use the natural ordering imposed by the internal list list. It is an error if any element is not a character. representation of strings, or a more complex locale-specific In both procedures, order is preserved. string->list and ordering. list->string are inverses so far as equal? is concerned. 6. Standard procedures 45

(string-copy string) procedure (vector ’a ’b ’c) =⇒ #(a b c) Returns a newly allocated copy of the given string. (vector-length vector) procedure (string-fill! string char) procedure Returns the number of elements in vector as an exact in- (string-fill! string char start end) procedure teger. If start and end are given, string-fill! stores fill in all the elements of string between start (inclusive) and end (exclusive). It is an error if fill is not a character or is (vector-ref vector k) procedure forbidden in strings, or if start is less than end. If start It is an error if k is not a valid index of vector. The and endy are omitted, fill is stored in all the elements of vector-ref procedure returns the contents of element k string. In any case, an unspecified value is returned. of vector. (vector-ref ’#(1 1 2 3 5 8 13 21) 6.8. Vectors 5) =⇒ 8 Vectors are heterogeneous structures whose elements are (vector-ref ’#(1 1 2 3 5 8 13 21) indexed by integers. A vector typically occupies less space (inexact->exact (round (* 2 (acos -1))))) than a list of the same length, and the average time needed =⇒ 13 to access a randomly chosen element is typically less for the vector than for the list. The length of a vector is the number of elements that it (vector-set! vector k obj ) procedure contains. This number is a non-negative integer that is It is an error if k is not a valid index of vector. The fixed when the vector is created. The valid indexes of a vector-set! procedure stores obj in element k of vector. vector are the exact non-negative integers less than the The value returned by vector-set! is unspecified. length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than (let ((vec (vector 0 ’(2 2 2 2) "Anna"))) the length of the vector. (vector-set! vec 1 ’("Sue" "Sue")) vec) Vectors are written using the notation #(obj ... ). For =⇒ #(0 ("Sue" "Sue") "Anna") example, a vector of length 3 containing the number zero in element 0, the list (2 2 2 2) in element 1, and the (vector-set! ’#(0 1 2) 1 "doe") string "Anna" in element 2 can be written as following: =⇒ error ; constant vector #(0 (2 2 2 2) "Anna") Note that this is the external representation of a vector, (vector->list vector) procedure not an expression evaluating to a vector. It is an error not (list->vector list) procedure to quote a vector constant: The vector->list procedure returns a newly allocated list ’#(0 (2 2 2 2) "Anna") of the objects contained in the elements of vector. The =⇒ #(0 (2 2 2 2) "Anna") list->vector procedure returns a newly created vector initialized to the elements of the list list. In both proce- dures, order is preserved. (vector? obj ) procedure (vector->list ’#(dah dah didah)) Returns #t if obj is a vector; otherwise returns #f. =⇒ (dah dah didah) (list->vector ’(dididit dah)) (make-vector k) procedure =⇒ #(dididit dah) (make-vector k fill) procedure Returns a newly allocated vector of k elements. If a second (vector->string string) procedure argument is given, then each element is initialized to fill. (string->vector vector) procedure Otherwise the initial contents of each element is unspeci- The procedure returns a newly allocated fied. vector->string string of the objects contained in the elements of vector. It is an error if any element is not a character allowed in (vector obj ... ) procedure strings. The string->vector procedure returns a newly Returns a newly allocated vector whose elements contain created vector initialized to the elements of the string the given arguments. It is analogous to list. string. In both procedures, order is preserved. 46 Revised7 Scheme

(string->vector "ABC") =⇒ #(#\A #\B #\C) (make-bytevector k) procedure (vector->string (make-bytevector k byte) procedure #(#\1 #\2 #\3) =⇒ "123" The make-bytevector procedure returns a newly allocated bytevector of length k. If byte is given, then all elements of the bytevector are initialized to byte, otherwise the con- (vector-copy vector) procedure tents of each element are unspecified. (vector-copy vector start) procedure (vector-copy vector start end) procedure (vector-copy vector start end fill) procedure (bytevector-length bytevector) procedure Returns a newly allocated copy of the given vector. The Returns the length of bytevector in bytes as an exact inte- elements of the new vector are the same (in the sense of ger. eqv?) as the elements of the old. The arguments start, end, and fill default to 0, the length (bytevector-u8-ref bytevector k) procedure of vector, and an implementation-specified value respec- Returns the kth byte of bytevector. tively. If end is greater than the length of vector, the fill argument is used to fill the additional elements of the re- sult. (bytevector-u8-set! bytevector k byte) procedure Stores byte as the kth byte of bytevector. The value re- (vector-fill! vector fill) procedure turned by bytevector-u8-set! is unspecified. (vector-fill! vector fill start end) procedure If start and end are given, vector-fill! stores fill (which (bytevector-copy bytevector) procedure can be any object) in all the elements of vector between Returns a newly allocated bytevector containing the same start (inclusive) and end (exclusive). It is an error if start bytes as bytevector. is less than end. If they are omitted, fill is stored in all the elements of vector. In either case, an unspecified value is returned. (bytevector-copy! from to) procedure Copies the bytes of bytevector from to bytevector to. It is 6.9. Bytevectors an error if to is shorter than from. The value returned by bytevector-copy! is unspecified. Bytevectors represent blocks of binary data. They are fixed-length sequences of bytes, where a byte is an exact (bytevector-copy-partial bytevector start end) integer in the range [0, 255]. A bytevector is typically more procedure space-efficient than a vector containing the same values. Returns a newly allocated bytevector containing the bytes The length of a bytevector is the number of elements that in bytevector between start (inclusive) and end (exclusive). it contains. This number is a non-negative integer that is It is an error if start is less than end, or start is less than fixed when the bytevector is created. The valid indexes of zero, or end is greater than the length of bytevector. a bytevector are the exact non-negative integers less than the length of the bytevector, starting at index zero as with (bytevector-copy-partial! from start end to at) vectors. procedure Bytevectors are written using the notation #u8(byte ... ). Copies the bytes of bytevector from between start and end For example, a bytevector of length 3 containing the byte to bytevector to, starting at at. The order in which bytes 0 in element 0, the byte 10 in element 1, and the byte 5 in are copied is unspecified, except that if the source and des- element 2 can be written as following: tination overlap, copying takes place as if the source is first #u8(0 10 5) copied into a temporary bytevector and then into the des- tination. This can be achieved without allocating storage Note that this is both the external representation of a by making sure to copy in the correct direction in such bytevector and an expression evaluating to a bytevector. circumstances. It is an error if start is less than end, or start is less than (bytevector? obj ) procedure zero, or end is greater than the length of from, or to is Returns #t if obj is a bytevector. Otherwise, #f is returned. less than zero or greater than the length of to. It is also an error if the inequality (>= (- (bytevector-length 6. Standard procedures 47 to) at) (- end start)) is false. The value returned by returns a list of the results, in order. If more than one list is bytevector-copy-partial! is unspecified. given and not all lists have the same length, map terminates when the shortest list runs out. It is an error for proc to mutate any of the lists. The dynamic order in which proc (utf8->string bytevector) procedure is applied to the elements of the lists is unspecified. If (string->utf8 string) procedure multiple returns occur from map, the values returned by These procedures translate between strings and bytevec- earlier returns are not mutated. tors that encode those strings using the UTF-8 encod- (map cadr ’((a b) (d e) (g h))) ing. The utf8->string procedure decodes a bytevector =⇒ (b e h) and returns the corresponding string; the string->utf8 procedure encodes a string and returns the corresponding (map (lambda (n) (expt n n)) bytevector. It is an error to pass invalid byte sequences or ’(1 2 3 4 5)) byte sequences representing characters which are forbidden =⇒ (1 4 27 256 3125) in strings to utf8->string. (map + ’(1 2 3) ’(4 5 6 7)) =⇒ (5 7 9) (utf8->string #u8(#x41)) =⇒ "A" (string->utf8 "λ") =⇒ #u8(#xCE #xBB) (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) 6.10. Control features ’(a b))) =⇒ (1 2) or (2 1)

This section describes various primitive procedures which (string-map proc string string ... ) procedure control the flow of program execution in special ways. The 1 2 procedure? predicate is also described here. It is an error if proc does not accept as many arguments as there are strings and return a single character. The string-map procedure applies proc element-wise to the el- (procedure? obj ) procedure ements of the strings and returns a string of the results, Returns #t if obj is a procedure, otherwise returns #f. in order. If more than one string is given and not all strings have the same length, string-map terminates when (procedure? car) =⇒ #t the shortest string runs out. The dynamic order in which (procedure? ’car) =⇒ #f proc is applied to the elements of the strings is unspecified. (procedure? (lambda (x) (* x x))) =⇒ #t If multiple returns occur from string-map, the values re- (procedure? ’(lambda (x) (* x x))) turned by earlier returns are not mutated. =⇒ #f (string-map char-foldcase "AbdEgH") (call-with-current-continuation procedure?) =⇒ "abdegh" =⇒ #t (string-map (lambda (c) (apply proc arg1 ... args) procedure (integer->char (+ 1 (char->integer c)))) The apply procedure calls proc with the elements of the list "HAL") =⇒ "IBM" (append (list arg1 ... ) args) as the actual arguments.

(apply + (list 3 4)) =⇒ 7 (string-map (lambda (c k) (define compose ((if (eqv? k #\u) char-upcase char-downcase) (lambda (f g) c)) (lambda args "studlycaps xxx" (f (apply g args))))) "ululululul") =⇒ "StUdLyCaPs" ((compose sqrt *) 12 75) =⇒ 30

(vector-map proc vector1 vector2 ... ) procedure (map proc list1 list2 ... ) procedure It is an error if proc does not accept as many argu- It is an error if proc does not accept as many arguments as ments as there are vectors and return a single value. The there are lists and return a single value. The map procedure vector-map procedure applies proc element-wise to the el- applies proc element-wise to the elements of the lists and ements of the vectors and returns a vector of the results, 48 Revised7 Scheme in order. If more than one vector is given and not all vec- (vector-for-each proc vector1 vector2 ... ) procedure tors have the same length, vector-map terminates when The arguments to vector-for-each are like the arguments the shortest vector runs out. The dynamic order in which to vector-map, but vector-for-each calls proc for its proc is applied to the elements of the vectors is unspeci- side effects rather than for its values. Unlike vector-map, fied. If multiple returns occur from vector-map, the values vector-for-each is guaranteed to call proc on the ele- returned by earlier returns are not mutated. ments of the vectors in order from the first element(s) to (vector-map cadr ’#((a b) (d e) (g h))) the last, and the value returned by vector-for-each is un- =⇒ #(b e h) specified. If more than one vector is given and not all vec- tors have the same length, vector-for-each terminates (vector-map (lambda (n) (expt n n)) when the shortest vector runs out. It is an error for proc ’#(1 2 3 4 5)) to mutate any of the vectors. =⇒ #(1 4 27 256 3125) (let ((v (make-list 5))) (vector-map + ’#(1 2 3) ’#(4 5 6 7)) (vector-for-each =⇒ #(5 7 9) (lambda (i) (list-set! v i (* i i))) ’#(0 1 2 3 4)) (let ((count 0)) v) =⇒ (0 1 4 9 16) (vector-map (lambda (ignored) (set! count (+ count 1)) (call-with-current-continuation proc) procedure count) (call/cc proc) procedure ’#(a b))) =⇒ #(1 2) or #(2 1) It is an error if proc does not accept one argument. The procedure call-with-current-continuation (or its (for-each proc list1 list2 ... ) procedure equivalent abbreviation call/cc) packages the current The arguments to for-each are like the arguments to map, continuation (see the rationale below) as an “escape pro- but for-each calls proc for its side effects rather than for cedure” and passes it as an argument to proc. The escape its values. Unlike map, for-each is guaranteed to call proc procedure is a Scheme procedure that, if it is later called, on the elements of the lists in order from the first ele- will abandon whatever continuation is in effect at that later ment(s) to the last, and the value returned by for-each time and will instead use the continuation that was in ef- is unspecified. If more than one list is given and not all fect when the escape procedure was created. Calling the lists have the same length, for-each terminates when the escape procedure may cause the invocation of before and shortest list runs out. It is an error for proc to mutate any after thunks installed using dynamic-wind. of the lists. The escape procedure accepts the same number of ar- (let ((v (make-vector 5))) guments as the continuation to the original call to (for-each (lambda (i) call-with-current-continuation. Except for continu- (vector-set! v i (* i i))) ations created by the call-with-values procedure (in- ’(0 1 2 3 4)) cluding the initialization expressions of let-values and v) =⇒ #(0 1 4 9 16) let*-values expressions), all continuations take exactly one value. The effect of passing no value or more (string-for-each proc string1 string2 ... ) procedure than one value to continuations that were not created by The arguments to string-for-each are like the arguments call-with-values is unspecified. to string-map, but string-for-each calls proc for its However, the continuations of all non-final expressions side effects rather than for its values. Unlike string-map, within a sequence of expressions, such as in lambda, string-for-each is guaranteed to call proc on the ele- case-lambda, begin, let, let*, letrec, letrec*, ments of the lists in order from the first element(s) to let-values, let*-values, let-syntax, letrec-syntax, the last, and the value returned by string-for-each is parameterize, guard, case, cond, when, and unless ex- unspecified. If more than one string is given and not all pressions, take an arbitrary number of values, because they strings have the same length, string-for-each terminates discard the values passed to them in any event. when the shortest string runs out. It is an error for proc to mutate any of the strings. The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It can be (let ((v ’())) stored in variables or data structures and can be called as (string-for-each many times as desired. (lambda (c) (set! v (cons (char->integer c) v)) "abcde") The following examples show only the simplest ways v) =⇒ (101 100 99 98 97) in which call-with-current-continuation is used. If 6. Standard procedures 49 all real uses were as simple as these examples, there that the full power of catch could be provided by a proce- would be no need for a procedure with the power of dure instead of by a special syntactic construct, and the name call-with-current-continuation. call-with-current-continuation was coined in 1982. This name is descriptive, but opinions differ on the merits of such a (call-with-current-continuation long name, and some people prefer the name call/cc instead. (lambda (exit) (for-each (lambda (x) (if (negative? x) (values obj ...) procedure (exit x))) Delivers all of its arguments to its continuation. The ’(54 0 37 -3 245 19)) values procedure might be defined as follows: #t)) =⇒ -3 (define (values . things) (define list-length (call-with-current-continuation (lambda (obj) (lambda (cont) (apply cont things)))) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (obj) (call-with-values producer consumer) procedure (cond ((null? obj) 0) Calls its producer argument with no values and a contin- ((pair? obj) uation that, when passed some values, calls the consumer (+ (r (cdr obj)) 1)) procedure with those values as arguments. The continua- (else (return #f)))))) tion for the call to consumer is the continuation of the call (r obj)))))) to call-with-values. (list-length ’(1 2 3 4)) =⇒ 4 (call-with-values (lambda () (values 4 5)) (lambda (a b) b)) (list-length ’(a b . c)) =⇒ #f =⇒ 5 Rationale: (call-with-values * -) =⇒ -1 A common use of call-with-current-continuation is for structured, non-local exits from loops or procedure bodies, but in fact call-with-current-continuation is useful for imple- menting a wide variety of advanced control structures. (dynamic-wind before thunk after) procedure Whenever a Scheme expression is evaluated there is a contin- Calls thunk without arguments, returning the result(s) of uation wanting the result of the expression. The continuation this call. Before and after are called, also without ar- represents an entire (default) future for the computation. If the guments, as required by the following rules. Note that, expression is evaluated at top level, for example, then the con- in the absence of calls to continuations captured using tinuation might take the result, print it on the screen, prompt call-with-current-continuation, the three arguments for the next input, evaluate it, and so on forever. Most of the are called once each, in order. Before is called when- time the continuation includes actions specified by user code, ever execution enters the dynamic extent of the call to as in a continuation that will take the result, multiply it by the thunk and after is called whenever it exits that dynamic value stored in a local variable, add seven, and give the answer extent. The dynamic extent of a procedure call is the pe- to the top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and pro- riod between when the call is initiated and when it returns. grammers do not think much about them. On rare occasions, Before and after are excluded from the dynamic extent. In however, a programmer needs to deal with continuations explic- Scheme, because of call-with-current-continuation, itly. The call-with-current-continuation procedure allows the dynamic extent of a call is not always a single, con- Scheme programmers to do that by creating a procedure that nected time period. It is defined as follows: acts just like the current continuation.

Most programming languages incorporate one or more special- • The dynamic extent is entered when execution of the purpose escape constructs with names like exit, return, or body of the called procedure begins. even goto. In 1965, however, Peter Landin [23] invented a • The dynamic extent is also entered when exe- general purpose escape operator called the J-operator. John cution is not within the dynamic extent and a Reynolds [32] described a simpler but equally powerful con- continuation is invoked that was captured (using struct in 1972. The catch syntax described by Sussman and call-with-current-continuation) during the dy- Steele in the 1975 report on Scheme is exactly the same as namic extent. Reynolds’s construct, though its name came from a less general construct in . Several Scheme implementors noticed • It is exited when the called procedure returns. 50 Revised7 Scheme

• It is also exited when execution is within the dynamic one argument may serve as an exception handler and any extent and a continuation is invoked that was captured object may be used to represent an exception. while not within the dynamic extent.

If a second call to dynamic-wind occurs within the dynamic (with-exception-handler handler thunk) procedure extent of the call to thunk and then a continuation is in- It is an error if handler does not accept one argument. It voked in such a way that the afters from these two invoca- is also an error if thunk does not accept zero arguments. tions of dynamic-wind are both to be called, then the after The with-exception-handler procedure returns the re- associated with the second (inner) call to dynamic-wind is sults of invoking thunk. Handler is installed as the current called first. exception handler for the dynamic extent (as determined If a second call to dynamic-wind occurs within the dy- by dynamic-wind) of the invocation of thunk. namic extent of the call to thunk and then a continua- tion is invoked in such a way that the befores from these (raise obj ) procedure two invocations of dynamic-wind are both to be called, then the before associated with the first (outer) call to Raises an exception by invoking the current exception han- dynamic-wind is called first. dler on obj . The handler is called with a continuation whose dynamic extent is that of the call to raise, except If invoking a continuation requires calling the before from that the current exception handler is the one that was in one call to dynamic-wind and the after from another, then place when the handler being called was installed. If the the after is called first. handler returns, an exception is raised in the same dynamic The effect of using a captured continuation to enter or exit extent as the handler. the dynamic extent of a call to before or after is unspecified. (let ((path ’()) (raise-continuable obj ) procedure (c #f)) (let ((add (lambda (s) Raises an exception by invoking the current exception (set! path (cons s path))))) handler on obj . The handler is called with a continu- (dynamic-wind ation that is equivalent to the continuation of the call (lambda () (add ’connect)) to raise-continuable, except that: (1) the current ex- (lambda () ception handler is the one that was in place when the (add (call-with-current-continuation handler being called was installed, and (2) if the handler (lambda (c0) being called returns, then it will again become the cur- (set! c c0) rent exception handler. If the handler returns, the val- ’talk1)))) ues it returns become the values returned by the call to (lambda () (add ’disconnect))) raise-continuable. (if (< (length path) 4) (c ’talk2) (with-exception-handler (reverse path)))) (lambda (con) (cond =⇒ (connect talk1 disconnect ((string? con) connect talk2 disconnect) (display con)) (else (display "a warning has been issued"))) 42) 6.11. Exceptions (lambda () (+ (raise-continuable "should be a number") This section describes Scheme’s exception-handling and 23))) exception-raising procedures. For the concept of Scheme prints: should be a number exceptions, see section 1.3.2. See also 4.2.7 for the guard =⇒ 65 syntax. Exception handlers are one-argument procedures that de- termine the action the program takes when an exceptional (error message obj ...) procedure situation is signalled. The system implicitly maintains a Message should be a string. Raises an exception as if by current exception handler. calling raise on a newly allocated implementation-defined The program raises an exception by invoking the current object which encapsulates the information provided by exception handler, passing it an object encapsulating in- message, as well as any obj s, known as the irritants. The formation about the exception. Any procedure accepting procedure error-object? must return #t on such objects. 6. Standard procedures 51

(define (null-list? l) Implementations may also support other values of version, (cond ((pair? l) #f) in which case they should return an environment contain- ((null? l) #t) ing bindings corresponding to the corresponding version of (else the report. If version is neither 7 nor another value sup- (error ported by the implementation, an error is signalled. "null-list?: argument out of domain" l)))) The effect of assigning (through the use of eval) a vari- able bound in a scheme-report-environment (for exam- ple car) is unspecified. Thus the environments specified by scheme-report-environment may be immutable. (error-object? obj ) procedure Returns #t if obj is an object created by error or one of an implementation-defined set of objects. Otherwise, it (null-environment version) eval library procedure returns #f. If version is equal to 7, corresponding to this revision of the Scheme report (the Revised7 Report on Scheme), the (error-object-message error-object) procedure null-environment procedure returns a specifier for an en- vironment that contains only the bindings for all syntactic Returns the message encapsulated by error-object. keywords defined either in the base library or in the other libraries of this report, provided that the implementation (error-object-irritants error-object) procedure supports them. Implementations must support this value of version. Returns a list of the irritants encapsulated by error-object. Implementations may also support other values of version, in which case they should return an environment contain- 6.12. Eval ing bindings corresponding to the corresponding version of the report. If version is neither 7 nor another value sup- ported by the implementation, an error is signalled. (eval expression environment-specifier) eval library procedure (environment list1 ... ) eval library procedure Evaluates expression in the specified environment and re- turns its value. It is an error if expression is not a valid This procedure returns a specifier for the environment that Scheme expression represented as a datum. Implementa- results by starting with an empty environment and then tions may extend eval to allow non-expression programs importing each list, considered as an import set, into it. such as definitions as the first argument, with the re- (See section 5.5 for a description of import sets.) The striction that eval is not allowed to create new bindings bindings of the environment represented by the specifier in the environments returned by null-environment or are immutable. scheme-report-environment. (eval ’(* 7 3) (scheme-report-environment 7)) (interaction-environment) repl library procedure =⇒ 21 This procedure returns a specifier for an environment that contains an implementation-defined set of bindings, typi- (let ((f (eval ’(lambda (f x) (f x x)) (null-environment 7)))) cally a superset of those exported by (scheme base). The (f + 10)) intent is that this procedure will return the environment =⇒ 20 in which the implementation would evaluate expressions entered by the user into a REPL.

(scheme-report-environment version) 6.13. Input and output eval library procedure If version is equal to 7, corresponding to this revision 6.13.1. Ports of the Scheme report (the Revised7 Report on Scheme), scheme-report-environment returns a specifier for an en- Ports represent input and output devices. To Scheme, an vironment that contains only the bindings defined either in input port is a Scheme object that can deliver data upon the base library or in the other libraries of this report that command, while an output port is a Scheme object that can the implementation supports. Implementations must sup- accept data. Whether the input and output port types are port this value of version. disjoint is implementation-dependent. 52 Revised7 Scheme

Different port types operate on different data. Scheme (binary-port? obj ) procedure implementations are required to support textual ports and (port? obj ) procedure binary ports, but may also provide other port types. These procedures return #t if obj is an input port, out- A textual port supports reading or writing of individual put port, textual port, binary port, or any kind of port, characters from or to a backing store containing charac- respectively. Otherwise they return #f. ters using read-char and write-char below, as well as operations defined in terms of characters such as read and (port-open? port) procedure write. Returns #t if port is still open and capable of performing A binary port supports reading or writing of individual input or output, and #f otherwise. bytes from or to a backing store containing bytes using read-u8 and write-u8 below, as well as operations defined in terms of bytes. Whether the textual and binary port (current-input-port) procedure types are disjoint is implementation-dependent. (current-output-port) procedure Ports can be used to access files, devices, and similar things (current-error-port) procedure on the host system on which the Scheme program is run- Returns the current default input port, output port, or ning. error port (an output port), respectively. These proce- dures are parameter objects, which can be overridden with parameterize (see section 4.2.6). The initial bindings for (call-with-input-file string proc) these are system-defined textual ports. file library procedure (call-with-output-file string proc) file library procedure (with-input-from-file string thunk) It is an error if proc does not accept one argument. For file library procedure call-with-input-file, the file named by string should (with-output-to-file string thunk) already exist; for call-with-output-file, the effect is file library procedure unspecified if the file already exists. These procedures For with-input-from-file, it is an error if the call proc with one argument: the textual port obtained file named by string does not already exist; for by opening the named file for input or output as if by with-output-to-file, the effect is unspecified if the file open-input-file or open-output-file. If the file can- already exists. The file is opened for input or out- not be opened, an error is signalled. If proc returns, then put as if by open-input-file or open-output-file, the port is closed automatically and the values yielded by and the new port is made the default value returned the proc are returned. If proc does not return, then the by current-input-port or current-output-port (and is port must not be closed automatically unless it is possible used by (read), (write obj ), and so forth). The thunk is to prove that the port will never again be used for a read then called with no arguments. When the thunk returns, or write operation. the port is closed and the previous default is restored. It Rationale: Because Scheme’s escape procedures have un- is an error if thunk does not accept zero arguments. Both limited extent, it is possible to escape from the current con- procedures return the values yielded by thunk. If an escape tinuation but later to escape back in. If implementations procedure is used to escape from the continuation of these were permitted to close the port on any escape from the procedures, their behavior is implementation-dependent. current continuation, then it would be impossible to write portable code using both call-with-current-continuation (open-input-file string) file library procedure and call-with-input-file or call-with-output-file. (open-binary-input-file string) file library procedure Takes a string for an existing file and returns a textual (call-with-port port proc) procedure input port or binary input port capable of delivering data It is an error if proc does not accept one argument. The from the file. If the file cannot be opened, an error is call-with-port procedure calls proc with port as an ar- signalled. gument. If proc returns, port is closed automatically and the values returned by proc are returned. (open-output-file string) file library procedure (open-binary-output-file string) file library procedure (input-port? obj ) procedure (output-port? obj ) procedure Takes a string naming an output file to be created and (textual-port? obj ) procedure returns a textual output port or binary output port capable 6. Standard procedures 53 of writing data to a new file by that name. If the file cannot 6.13.2. Input be opened, an error is signalled. If a file with the given name already exists, the effect is unspecified. (read) read library procedure (read port) read library procedure (close-port port) procedure The read procedure converts external representations of (close-input-port port) procedure Scheme objects into the objects themselves. That is, it is (close-output-port port) procedure a parser for the nonterminal hdatumi (see sections 7.1.2 Closes the resource associated with port, rendering the port and 6.4). It returns the next object parsable from the incapable of delivering or accepting data. It is an error to given textual input port, updating port to point to the apply the last two procedures to a port which is not an first character past the end of the external representation input or output port, respectively. Scheme implementa- of the object. tions may provide ports which are simultaneously input If an end of file is encountered in the input before any char- and output ports, such as sockets; the close-input-port acters are found that can begin an object, then an end-of- and close-output-port procedures can then be used to file object is returned. The port remains open, and further close the input and output sides of the port independently. attempts to read will also return an end-of-file object. If an end of file is encountered after the beginning of an object’s These routines have no effect if the file has already been external representation, but the external representation is closed. The value returned is unspecified. incomplete and therefore not parsable, an error is signalled. Port may be omitted, in which case it defaults to the value (open-input-string string) procedure returned by current-input-port. It is an error to read Takes a string and returns a textual input port that delivers from a closed port. characters from the string. (read-char) procedure (read-char port) procedure (open-output-string) procedure Returns the next character available from the textual input Returns a textual output port that will accumulate char- port, updating the port to point to the following character. acters for retrieval by get-output-string. If no more characters are available, an end-of-file object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port. (get-output-string port) procedure It is an error if port was not created with (peek-char) procedure open-output-string. Returns a string consisting of (peek-char port) procedure the characters that have been output to the port so far in the order they were output. Returns the next character available from the textual input port, without updating the port to point to the following character. If no more characters are available, an end-of- (open-input-bytevector bytevector) procedure file object is returned. Port may be omitted, in which case Takes a bytevector and returns a binary input port that it defaults to the value returned by current-input-port. delivers bytes from the bytevector. Note: The value returned by a call to peek-char is the same as the value that would have been returned by a call to read-char with the same port. The only difference is that the very next call (open-output-bytevector) procedure to read-char or peek-char on that port will return the value Returns a binary output port that will accumulate bytes returned by the preceding call to peek-char. In particular, a for retrieval by get-output-bytevector. call to peek-char on an interactive port will hang waiting for input whenever a call to read-char would have hung.

port procedure (get-output-bytevector ) (read-line) procedure It is an error if port was not created with (read-line port) procedure open-output-bytevector. Returns a bytevector consist- Returns the next line of text available from the textual ing of the bytes that have been output to the port so far input port, updating the port to point to the following in the order they were output. character. If an end of line is read, a string containing all 54 Revised7 Scheme of the text up to (but not including) the end of line is re- If no more bytes are available, an end-of-file object is re- turned, and the port is updated to point just past the end turned. Port may be omitted, in which case it defaults to of line. If an end of file is encountered before any end of the value returned by current-input-port. line is read, but some characters have been read, a string containing those characters is returned. If an end of file is encountered before any characters are read, an end-of-file (u8-ready?) procedure object is returned. For the purpose of this procedure, an (u8-ready? port) procedure end of line consists of either a linefeed character, a carriage Returns #t if a byte is ready on the binary input port and return character, or a sequence of a carriage return charac- returns #f otherwise. If u8-ready? returns #t then the ter followed by a linefeed character. Implementations may next read-u8 operation on the given port is guaranteed also recognize other end of line characters or sequences. not to hang. If the port is at end of file then u8-ready? Port may be omitted, in which case it defaults to the value returns #t. Port may be omitted, in which case it defaults returned by current-input-port. to the value returned by current-input-port.

(eof-object? obj ) procedure (read-bytevector length) procedure Returns #t if obj is an end-of-file object, otherwise returns (read-bytevector length port) procedure #f. The precise set of end-of-file objects will vary among Reads the next length bytes, or as many as are available implementations, but in any case no end-of-file object will before the end of file, from the binary input port into a ever be an object that can be read in using read. newly allocated bytevector in left-to-right order and re- turns the bytevector. If no bytes are available before the (char-ready?) procedure end of file, an end-of-file object is returned. Port may be (char-ready? port) procedure omitted, in which case it defaults to the value returned by current-input-port. Returns #t if a character is ready on the textual in- put port and returns #f otherwise. If char-ready re- turns #t then the next read-char operation on the given (read-bytevector! bytevector start end) procedure port is guaranteed not to hang. If the port is at end of (read-bytevector! bytevector start end port) file then char-ready? returns #t. Port may be omit- procedure ted, in which case it defaults to the value returned by current-input-port. Reads the next end − start bytes, or as many as are avail- able before the end of file, from the binary input port into Rationale: The char-ready? procedure exists to make it pos- bytevector in left-to-right order beginning at the start po- sible for a program to accept characters from interactive ports sition. Returns the number of bytes read. If no bytes are without getting stuck waiting for input. Any input editors as- available, an end-of-file object is returned. Port may be sociated with such ports must ensure that characters whose omitted, in which case it defaults to the value returned by existence has been asserted by char-ready? cannot be removed current-input-port. from the input. If char-ready? were to return #f at end of file, a port at end-of-file would be indistinguishable from an interactive port that has no ready characters. 6.13.3. Output

(read-u8) procedure (write obj ) write library procedure (read-u8 port) procedure (write obj port) write library procedure Returns the next byte available from the binary input port, Writes a representation of obj to the given textual output updating the port to point to the following byte. If no port. Strings that appear in the written representation are more bytes are available, an end-of-file object is returned. enclosed in double quotes, and within those strings back- Port may be omitted, in which case it defaults to the value slash and double quote characters are escaped by back- returned by current-input-port. slashes. Symbols that contain non-ASCII characters are escaped either with inline hex escapes or with vertical bars. Character objects are written using the #\ nota- (peek-u8) procedure tion. Shared list structure is represented using datum la- (peek-u8 port) procedure bels. The write procedure returns an unspecified value. Returns the next byte available from the binary input port, Port may be omitted, in which case it defaults to the value without updating the port to point to the following byte. returned by current-output-port. 6. Standard procedures 55

(write-simple obj ) write library procedure (write-partial-bytevector bytevector start end) (write-simple obj port) write library procedure procedure (write-partial-bytevector bytevector start end port) The write-simple procedure is the same as write, ex- procedure cept that shared structure is not represented using datum labels. This may cause write-simple not to terminate if Writes the bytes of bytevector from start (inclusive) to end obj contains circular structure. (exclusive) in left-to-right order to the binary output port. Port may be omitted, in which case it defaults to the value returned by current-output-port. (display obj ) write library procedure (display obj port) write library procedure (flush-output-port) procedure Writes a representation of obj to the given textual output (flush-output-port port) procedure port. Strings that appear in the written representation are not enclosed in double quotes, and no characters are Flushes any buffered output from the buffer of output-port escaped within those strings. Symbols are not escaped. to the underlying file or device and returns an unspecified Character objects appear in the representation as if writ- value. Port may be omitted, in which case it defaults to ten by write-char instead of by write. The display pro- the value returned by current-output-port. cedure returns an unspecified value. Port may be omit- ted, in which case it defaults to the value returned by 6.13.4. System interface current-output-port. Rationale: The write procedure is intended for producing Questions of system interface generally fall outside of the machine-readable output and display for producing human- domain of this report. However, the following operations readable output. are important enough to deserve description here.

(newline) procedure (load filename) load library procedure (newline port) procedure (load filename environment-specifier) load library procedure Writes an end of line to textual output port. Exactly An implementation-dependent operation is used to trans- how this is done differs from one to an- form filename into the name of an existing file con- other. Returns an unspecified value. Port may be omit- taining Scheme source code. The procedure reads ted, in which case it defaults to the value returned by load expressions and definitions from the file and evalu- current-output-port. ates them sequentially in the environment specified by environment-specifier. If environment-specifier is omitted, (write-char char) procedure (interaction-environment) is assumed. (write-char char port) procedure It is unspecified whether the results of the expres- Writes the character char (not an external representa- sions are printed. The load procedure does not af- tion of the character) to the given textual output port fect the values returned by current-input-port and and returns an unspecified value. Port may be omit- current-output-port. It returns an unspecified value. ted, in which case it defaults to the value returned by Rationale: For portability, load must operate on source files. current-output-port. Its operation on other kinds of files necessarily varies among implementations. (write-u8 byte) procedure (write-u8 byte port) procedure (file-exists? filename) file library procedure Writes the byte to the given binary output port and returns It is an error if filename is not a string. The file-exists? an unspecified value. Port may be omitted, in which case procedure returns #t if the named file exists at the time it defaults to the value returned by current-output-port. the procedure is called, and #f otherwise.

(write-bytevector bytevector) procedure (delete-file filename) file library procedure (write-bytevector bytevector port) procedure It is an error if filename is not a string. The delete-file Writes the bytes of bytevector in left-to-right order to the procedure deletes the named file if it exists and can be binary output port. Port may be omitted, in which case it deleted, and returns an unspecified value. If the file does defaults to the value returned by current-output-port. not exist or cannot be deleted, an error is signalled. 56 Revised7 Scheme

(command-line) process-context library procedure 1970 TAI (equivalent to midnight Universal Time) and the value 1.0 represents one TAI second later. Neither high Returns the command line passed to the process as a list accuracy nor high precision are required; in particular, re- of strings. The first string corresponds to the command turning Coordinated Universal Time plus a suitable con- name, and is implementation-dependent. It is an error to stant may be the best an implementation can do. mutate any of these strings.

(current-jiffy) time library procedure (exit) process-context library procedure (exit obj ) process-context library procedure Returns the number of jiffies as an exact integer that have elapsed since an arbitrary, implementation-defined Exits the running program and communicates an exit value epoch. A jiffy is an implementation-defined fraction of to the operating system. If no argument is supplied, the a second which is defined by the return value of the exit procedure should communicate to the operating sys- jiffies-per-second procedure. The starting epoch is tem that the program exited normally. If an argument is guaranteed to be constant during a run of the program, supplied, the exit procedure should translate the argument but may vary between different runs. into an appropriate exit value for the operating system. If obj is #f, the exit is assumed to be abnormal. (jiffies-per-second) time library procedure (get-environment-variable name) Returns an exact integer representing the number of jiffies process-context library procedure per SI second. This value is an implementation-specified constant. Most operating systems provide each running process with an environment consisting of environment vari- (define (time-length) ables. (This environment is not to be confused with (let ((list (make-list 100000)) the Scheme environments that can be passed to eval: (start (current-jiffy))) see section 6.12.) Both the name and value of (length list) an environment variable are strings. The procedure (/ (- (current-jiffy) start) get-environment-variable returns the value of the en- (jiffies-per-second)))) vironment variable name, or #f if the named environment variable is not found. get-environment-variable may use locale-setting information to encode the name and de- code the value of the environment variable. It is an error if get-environment-variable can’t decode the value. It is also an error to mutate the resulting string.

(get-environment-variable "PATH") =⇒ "/usr/local/bin:/usr/bin:/bin"

(get-environment-variables) process-context library procedure Returns the names and values of all the environment vari- ables as an alist, where the car of each entry is the name of an environment variable and the cdr is its value, both as strings. The order of the list is unspecified. It is an error to mutate any of these strings.

(get-environment-variables) =⇒ (("USER" . "root") ("HOME" . "/"))

(current-second) time library procedure Returns an inexact number representing the current time on the International Atomic Time (TAI) scale. The value 0.0 represents ten seconds after midnight on January 1, 7. Formal syntax and semantics 57

7. Formal syntax and semantics | ( | ) | #( | #u8( | ’ | ` | , | ,@ | . hdelimiteri −→ hwhitespacei | | | | | This chapter provides formal descriptions of what has al- ( ) " ; | hintraline whitespacei −→ hspace or tabi ready been described informally in previous chapters of this hwhitespacei −→ hintraline whitespacei | hnewlinei report. | hreturni hcommenti −→ ; hall subsequent characters up to a 7.1. Formal syntax line breaki | hnested commenti | hatmospherei hdatumi This section provides a formal syntax for Scheme written #; hnested commenti −→ hcomment texti in an extended BNF. #| hcomment conti* |# All spaces in the grammar are for legibility. Case is insignif- hcomment texti −→ hcharacter sequence not containing icant; for example, #x1A and #X1a are equivalent. hemptyi #| or |#i stands for the empty string. hcomment conti −→ hnested commenti hcomment texti The following extensions to BNF are used to make the de- hatmospherei −→ hwhitespacei | hcommenti scription more concise: hthingi* means zero or more occur- hintertoken spacei −→ hatmospherei* rences of hthingi; and hthingi+ means at least one hthingi. Note that +i, -i and hinfinityi below are exceptions to the hpeculiar identifieri rule; they are parsed as numbers, not 7.1.1. Lexical structure identifiers.

This section describes how individual tokens (identifiers, hidentifieri −→ hinitiali hsubsequenti* numbers, etc.) are formed from sequences of characters. | hvertical bari hsymbol elementi* hvertical bari The following sections describe how expressions and pro- | hpeculiar identifieri grams are formed from sequences of tokens. hinitiali −→ hletteri | hspecial initiali | hinline hex escapei hIntertoken spacei may occur on either side of any token, hletteri −→ a | b | c | ... | z but not within a token. | A | B | C | ... | Z Identifiers that do not begin with a vertical bar are termi- hspecial initiali −→ ! | $ | % | & | * | / | : | < | = nated by a hdelimiteri or by the end of the input. So are | > | ? | ^ | _ | ~ dot, numbers, characters, and booleans. Identifiers that hsubsequenti −→ hinitiali | hdigiti begin with a vertical bar are terminated by another verti- | hspecial subsequenti cal bar. hdigiti −→ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 hhex digiti −→ hdigiti The following four characters from the ASCII repertoire | a | A | b | B | c | C | d | D | e | E | f | F are reserved for future extensions to the language: []{ hexplicit signi −→ + | - } hspecial subsequenti −→ hexplicit signi | . | @ In addition to the identifier characters of the ASCII reper- hinline hex escapei −→ \xhhex scalar valuei; toire specified below, Scheme implementations may permit hhex scalar valuei −→ hhex digiti+ any additional repertoire of Unicode characters to be em- hpeculiar identifieri −→ hexplicit signi ployed in identifiers, provided that each such character has | hexplicit signi hsign subsequenti hsubsequenti* a Unicode general category of Lu, Ll, Lt, Lm, Lo, Mn, Mc, | hexplicit signi . hdot subsequenti hsubsequenti* Me, Nd, Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co, or is | . hnon-digiti hsubsequenti* U+200C or U+200D (the zero-width non-joiner and joiner, hnon-digiti −→ hdot subsequenti | hexplicit signi respectively, which are needed for correct spelling in Per- hdot subsequenti −→ hsign subsequenti | . sian, Hindi, and other languages). It is an error to use a hsign subsequenti −→ hinitiali | hexplicit signi | @ non-Unicode character in symbols or identifiers. hsymbol elementi −→ All Scheme implementations must permit the escape se- hany character other than hvertical bari or \i | hhex inline escapei quence \x; to appear in Scheme identifiers. If the character with the given Unicode scalar value is sup- ported by the implementation, identifiers containing such hbooleani −→ #t | #f | #true | #false a sequence are equivalent to identifiers containing the cor- responding character. hcharacteri −→ #\ hany characteri | #\ hcharacter namei htokeni −→ hidentifieri | hbooleani | hnumberi | #\xhhex scalar valuei | hcharacteri | hstringi hcharacter namei −→ alarm | backspace | delete 58 Revised7 Scheme

| escape | newline | null | return | space | tab 7.1.2. External representations hstringi −→ " hstring elementi* " hDatumi is what the read procedure (section 6.13.2) suc- hstring elementi −→ hany character other than " or \i cessfully parses. Note that any string that parses as an | \a | \b | \t | \n | \r | \" | \\ hexpressioni will also parse as a hdatumi. | \hintraline whitespaceihline endingi hdatumi −→ hsimple datumi | hcompound datumi hintraline whitespacei | hlabeli = hdatumi | hlabeli # | hinline hex escapei hsimple datumi −→ hbooleani | hnumberi hbytevectori −→ #u8(hbytei*) | hcharacteri | hstringi | hsymboli | hbytevectori hbytei −→ hany exact integer between 0 and 255i hsymboli −→ hidentifieri hnumberi −→ hnum 2i | hnum 8i hcompound datumi −→ hlisti | hvectori + | hnum 10i | hnum 16i hlisti −→ (hdatumi*) | (hdatumi . hdatumi) | habbreviationi habbreviationi −→ habbrev prefixi hdatumi The following rules for hnum Ri, hcomplex Ri, hreal Ri, habbrev prefixi −→ ’ | ` | , | ,@ hureal Ri, huinteger Ri, and hprefix Ri are implicitly repli- hvectori −→ #(hdatumi*) cated for R = 2, 8, 10, and 16. There are no rules for hlabeli −→ # hdigit 10i+ hdecimal 2i, hdecimal 8i, and hdecimal 16i, which means that numbers containing decimal points or exponents are always in decimal radix. Although not shown below, all al- 7.1.3. Expressions phabetic characters used in the grammar of numbers may appear in either upper or lower case. The definitions in this and the following subsections assume that all the syntax keywords defined in this report have hnum Ri −→ hprefix Ri hcomplex Ri been properly imported from their libraries, and that none hcomplex Ri −→ hreal Ri | hreal Ri @ hreal Ri of them have been redefined or shadowed. | hreal Ri + hureal Ri i | hreal Ri - hureal Ri i | hreal Ri + i | hreal Ri - i | hreal Ri hinfinityi i hexpressioni −→ hidentifieri | + hureal Ri i | - hureal Ri i | hliterali | hinfinityi i | + i | - i | hprocedure calli hreal Ri −→ hsigni hureal Ri | hlambda expressioni | hinfinityi | hconditionali hureal Ri −→ huinteger Ri | hassignmenti | huinteger Ri / huinteger Ri | hderived expressioni | hdecimal Ri | hmacro usei hdecimal 10i −→ huinteger 10i hsuffixi | hmacro blocki | . hdigit 10i+ hsuffixi | hdigit 10i+ . hdigit 10i* hsuffixi hliterali −→ hquotationi | hself-evaluatingi huinteger Ri −→ hdigit Ri+ hself-evaluatingi −→ hbooleani | hnumberi hprefix Ri −→ hradix Ri hexactnessi | hcharacteri | hstringi | hbytevectori | hexactnessi hradix Ri hquotationi −→ ’hdatumi | (quote hdatumi) hinfinityi −→ +inf.0 | -inf.0 | +nan.0 hprocedure calli −→ (hoperatori hoperandi*) hoperatori −→ hexpressioni hoperandi −→ hexpressioni hsuffixi −→ hemptyi + | hexponent markeri hsigni hdigit 10i hlambda expressioni −→ (lambda hformalsi hbodyi) hexponent markeri −→ e | s | f | d | l hformalsi −→ (hidentifieri*) | hidentifieri hsigni −→ hemptyi | + | - | (hidentifieri+ . hidentifieri) hexactnessi −→ hemptyi | #i | #e hbodyi −→ hdefinitioni* hsequencei hradix 2i −→ #b hsequencei −→ hcommandi* hexpressioni hradix 8i −→ #o hcommandi −→ hexpressioni hradix 10i −→ hemptyi | #d hradix 16i −→ #x hconditionali −→ (if htesti hconsequenti halternatei) hdigit 2i −→ 0 | 1 htesti −→ hexpressioni hdigit 8i −→ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 hconsequenti −→ hexpressioni hdigit 10i −→ hdigiti halternatei −→ hexpressioni | hemptyi hdigit 16i −→ hdigit 10i | a | b | c | d | e | f 7. Formal syntax and semantics 59 hassignmenti −→ (set! hidentifieri hexpressioni) (let-syntax (hsyntax speci*) hbodyi) | (letrec-syntax (hsyntax speci*) hbodyi) hderived expressioni −→ hsyntax speci −→ (hkeywordi htransformer speci) (cond hcond clausei+) | (cond hcond clausei* (else hsequencei)) | (case hexpressioni hcase clausei+) | (case hexpressioni 7.1.4. Quasiquotations hcase clausei* The following grammar for quasiquote expressions is not (else hsequencei)) context-free. It is presented as a recipe for generating an | (case hexpressioni infinite number of production rules. Imagine a copy of the hcase clausei* following rules for D = 1, 2, 3,.... D keeps track of the (else => hrecipienti)) nesting depth. | (and htesti*) | (or htesti*) hquasiquotationi −→ hquasiquotation 1i | (when hexpressioni htesti hsequencei) hqq template 0i −→ hexpressioni | (unless hexpressioni htesti hsequencei) hquasiquotation Di −→ `hqq template Di | (let (hbinding speci*) hbodyi) | (quasiquote hqq template Di) | (let hidentifieri (hbinding speci*) hbodyi) hqq template Di −→ hsimple datumi | (let* (hbinding speci*) hbodyi) | hlist qq template Di | (letrec (hbinding speci*) hbodyi) | hvector qq template Di | (letrec* (hbinding speci*) hbodyi) | hunquotation Di | (let-values (hmv binding speci*) hbodyi) hlist qq template Di −→ (hqq template or splice Di*) | (let*-values (hmv binding speci*) hbodyi) | (hqq template or splice Di+ . hqq template Di) | (begin hsequencei) | ’hqq template Di | (do (hiteration speci*) | hquasiquotation D + 1i (htesti hdo resulti) hvector qq template Di −→ #(hqq template or splice Di*) hcommandi*) hunquotation Di −→ ,hqq template D − 1i | (delay hexpressioni) | (unquote hqq template D − 1i) | (lazy hexpressioni) hqq template or splice Di −→ hqq template Di | (parameterize (hexpressioni hexpressioni)* | hsplicing unquotation Di hbodyi) hsplicing unquotation Di −→ ,@hqq template D − 1i | (guard (hidentifieri hcond clausei*) hbodyi) | (unquote-splicing hqq template D − 1i) | hquasiquotationi | (case-lambda hcase-lambda clausei*) In hquasiquotationis, a hlist qq template Di can some- times be confused with either an hunquotation Di or hcond clausei −→ (htesti hsequencei) a hsplicing unquotation Di. The interpretation as an | (htesti) hunquotationi or hsplicing unquotation Di takes prece- | (htesti => hrecipienti) dence. hrecipienti −→ hexpressioni hcase clausei −→ ((hdatumi*) hsequencei) 7.1.5. Transformers | ((hdatumi*) => hrecipienti) hbinding speci −→ hidentifieri hexpressioni ( ) htransformer speci −→ hmv binding speci −→ (hformalsi hexpressioni) (syntax-rules (hidentifieri*) hsyntax rulei*) hiteration speci −→ (hidentifieri hiniti hstepi) | (syntax-rules hidentifieri (hidentifieri*) | hidentifieri hiniti ( ) hsyntax rulei*) hcase-lambda clausei −→ hformalsi hbodyi ( ) hsyntax rulei −→ (hpatterni htemplatei) hiniti −→ hexpressioni hpatterni −→ hpattern identifieri hstepi −→ hexpressioni | hunderscorei hdo resulti −→ hsequencei | hemptyi | (hpatterni*) | (hpatterni+ . hpatterni) hmacro usei −→ hkeywordi hdatumi* ( ) | (hpatterni* hpatterni hellipsisi hpatterni*) hkeywordi −→ hidentifieri | (hpatterni* hpatterni hellipsisi hpatterni* . hpatterni) hmacro blocki −→ | #(hpatterni*) 60 Revised7 Scheme

| #(hpatterni* hpatterni hellipsisi hpatterni*) | (include hstringi+) | hpattern datumi | (include-ci hstringi+) hpattern datumi −→ hstringi | (cond-expand hcond-expand clausei*) | hcharacteri | (cond-expand hcond-expand clausei* | hbooleani (else hlibrary declarationi*)) | hnumberi hexport speci −→ hidentifieri htemplatei −→ hpattern identifieri | (rename hidentifieri hidentifieri) | (htemplate elementi*) himport seti −→ hlibrary namei | (htemplate elementi+ . htemplatei) | (only himport seti hidentifieri+) | #(htemplate elementi*) | (except himport seti hidentifieri+) | htemplate datumi | (prefix himport seti hidentifieri) htemplate elementi −→ htemplatei | (rename himport seti hexport speci+) | htemplatei hellipsisi hcond-expand clausei −→ htemplate datumi −→ hpattern datumi (hfeature requirementi hlibrary declarationi*) hpattern identifieri −→ hany identifier except ...i hfeature requirementi −→ hidentifieri hellipsisi −→ han identifier defaulting to ...i | hlibrary namei hunderscorei −→ hthe identifier i | (and hfeature requirementi*) | (or hfeature requirementi*) | (not hfeature requirementi) 7.1.6. Programs and definitions hprogrami −→ hcommand or definitioni* hcommand or definitioni −→ hcommandi 7.2. Formal semantics | hdefinitioni | (import himport seti+) This section provides a formal denotational semantics for | (begin hcommand or definitioni+) the primitive expressions of Scheme and selected built-in hdefinitioni −→ (define hidentifieri hexpressioni) procedures. The concepts and notation used here are de- | (define (hidentifieri hdef formalsi) hbodyi) scribed in [37]; the notation is summarized below: | hsyntax definitioni h ... i sequence formation | (define-values hdef formalsi hbodyi) s ↓ k kth member of the sequence s (1-based) | (define-record-type hidentifieri #s length of sequence s hconstructori hidentifieri hfield speci*) s § t concatenation of sequences s and t | (begin hdefinitioni*) s † k drop the first k members of sequence s hdef formalsi −→ hidentifieri* t → a, b McCarthy conditional “if t then a else b” | hidentifieri* . hidentifieri ρ[x/i] substitution “ρ with x for i” hconstructori −→ hidentifieri hfield namei* ( ) x in D injection of x into domain D hfield speci −→ hfield namei haccessori ( ) x | D projection of x to domain D | (hfield namei haccessori hmutatori) hfield namei −→ hidentifieri The reason that expression continuations take sequences haccessori −→ hidentifieri of values instead of single values is to simplify the formal hmutatori −→ hidentifieri treatment of procedure calls and multiple return values. hsyntax definitioni −→ The boolean flag associated with pairs, vectors, and strings (define-syntax hkeywordi htransformer speci) will be true for mutable objects and false for immutable objects. The order of evaluation within a call is unspecified. We 7.1.7. Libraries mimic that here by applying arbitrary permutations per- mute and unpermute, which must be inverses, to the argu- hlibraryi −→ ments in a call before and after they are evaluated. This is (define-library hlibrary namei not quite right since it suggests, incorrectly, that the order hlibrary declarationi*) of evaluation is constant throughout a program (for any hlibrary namei −→ (hlibrary name parti+) given number of arguments), but it is a closer approxima- hlibrary name parti −→ hidentifieri | huinteger 10i tion to the intended semantics than a left-to-right evalua- hlibrary declarationi −→ (export hexport speci*) tion would be. | (import himport seti*) | (begin hcommand or definitioni*) The storage allocator new is implementation-dependent, 7. Formal syntax and semantics 61 but it must obey the following axiom: if new σ ∈ L, then 7.2.3. Semantic functions σ (new σ | L) ↓ 2 = false. K : Con → E The definition of K is omitted because an accurate defini- E : Exp → U → K → C tion of K would complicate the semantics without being E* : Exp* → U → K → C very interesting. C : Com* → U → C → C

If P is a program in which all variables are defined before Definition of K deliberately omitted. being referenced or assigned, then the meaning of P is E[[K]] = λρκ . send (K[[K]]) κ E[[((lambda (I*) P’) hundefinedi ... )]] E[[I]] = λρκ . hold (lookup ρ I) where I* is the sequence of variables defined in P, P0 is the (single(λ .  = undefined → sequence of expressions obtained by replacing every defini- wrong “undefined variable”, send  κ)) tion in P by an assignment, hundefinedi is an expression that evaluates to undefined, and E is the semantic function E[[(E0 E*)]] = that assigns meaning to expressions. λρκ . E*(permute(hE0i § E*)) ρ (λ* . ((λ* . applicate (* ↓ 1) (* † 1) κ) 7.2.1. Abstract syntax (unpermute *)))

K ∈ Con constants, including quotations E[[(lambda (I*) Γ* E0)]] = λρκ . λσ . I ∈ Ide identifiers (variables) new σ ∈ L → E ∈ Exp expressions send (hnew σ | L, Γ ∈ Com = Exp commands λ*κ0 . #* = #I* → 0 0 0 0 tievals(λα* . (λρ . C[[Γ*]]ρ (E[[E0]]ρ κ )) (extends ρ I* α*)) Exp −→ K | I | (E E*) 0 *, | (lambda (I*) Γ* E0) wrong “wrong number of arguments”i | (lambda (I* . I) Γ* E0) in E) | (lambda I Γ* E0) κ | (if E0 E1 E2) | (if E0 E1) (update (new σ | L) unspecified σ), | (set! IE) wrong “out of memory” σ

E[[(lambda (I* . I) Γ* E0)]] = λρκ . λσ . 7.2.2. Domain equations new σ ∈ L → send (hnew σ | L, 0 α ∈ L locations λ*κ . #* ≥ #I* → tievalsrest ν ∈ N natural numbers (λα* . (λρ0 . C[[Γ*]]ρ0(E[[E ]]ρ0κ0)) T = {false, true} booleans 0 (extends ρ (I* § hIi) α*)) symbols Q * H characters (#I*), R numbers wrong “too few arguments”i in E) Ep = L × L × T pairs κ Ev = L* × T vectors (update (new σ | L) unspecified σ), Es = L* × T strings wrong “out of memory” σ M = {false, true, null, undefined, unspecified} miscellaneous E[[(lambda I Γ* E0)]] = E[[(lambda (. I) Γ* E0)]] ∈ φ F = L × (E* → K → C) procedure values E[[(if E0 E1 E2)]] =  ∈ E = Q + H + R + Ep + Ev + Es + M + F λρκ . E[[E0]] ρ (single (λ . truish  → E[[E1]]ρκ, expressed values E[[E2]]ρκ)) σ ∈ S = L → (E × T) stores E[[(if E E )]] = ρ ∈ U = Ide → L environments 0 1 λρκ . E[[E0]] ρ (single (λ . truish  → E[[E1]]ρκ, ∈ θ C = S → A command continuations send unspecified κ)) κ ∈ K = E* → C expression continuations A answers Here and elsewhere, any expressed value other than undefined X errors may be used in place of unspecified. 62 Revised7 Scheme

E[[(set! IE)]] = unpermute : E* → E* [inverse of permute] λρκ . E[[E]] ρ (single(λ . assign (lookup ρ I)  applicate : E → E* → K → C (send unspecified κ))) applicate = λ*κ .  ∈ F → ( | F ↓ 2)*κ, wrong “bad procedure” E*[[]] = λρκ . κh i onearg :(E → K → C) → (E* → K → C) E*[[E E*]] = 0 onearg = λρκ . E[[E ]] ρ (single(λ . E*[[E*]] ρ (λ* . κ (h i § *)))) 0 0 0 λζ*κ . #* = 1 → ζ(* ↓ 1)κ, C[[]] = λρθ . θ wrong “wrong number of arguments”

C[[Γ0 Γ*]] = λρθ . E[[Γ0]] ρ (λ* . C[[Γ*]]ρθ) twoarg :(E → E → K → C) → (E* → K → C) twoarg = λζ*κ . #* = 2 → ζ(* ↓ 1)(* ↓ 2)κ, 7.2.4. Auxiliary functions wrong “wrong number of arguments” lookup : U → Ide → L list : E* → K → C lookup = λρI . ρI list = λ*κ . #* = 0 → send null κ, extends : U → Ide* → L* → U list (* † 1)(single(λ . consh* ↓ 1, iκ)) extends = λρI*α* . #I* = 0 → ρ, cons : E* → K → C extends (ρ[(α* ↓ 1)/(I* ↓ 1)]) (I* † 1) (α* † 1) cons = wrong : X → C [implementation-dependent] twoarg (λ12κσ . new σ ∈ L → 0 0 (λσ . new σ ∈ L → send : E → K → C send (hnew σ | L, new σ0 | L, truei send = λκ . κhi in E) κ single :(E → C) → K (update(new σ0 | L) σ0), single = 2 wrong “out of memory”σ0) λψ* . #* = 1 → ψ(* ↓ 1), (update(new σ | L) σ), wrong “wrong number of return values” 1 wrong “out of memory”σ) new : S → (L + {error}) [implementation-dependent] less : E* → K → C hold : → → L K C less = hold = λακσ . send (σα ↓ 1)κσ twoarg (λ12κ . (1 ∈ R ∧ 2 ∈ R) → assign : L → E → C → C send (1 | R < 2 | R → true, false)κ, assign = λαθσ . θ(update ασ) wrong “non-numeric argument to <”) update : L → E → S → S add : E* → K → C update = λασ . σ[h, truei/α] add = tievals :(L* → C) → E* → C twoarg (λ12κ . (1 ∈ R ∧ 2 ∈ R) → tievals = send ((1 | R + 2 | R) in E)κ, λψ*σ . #* = 0 → ψh iσ, wrong “non-numeric argument to +”) new σ ∈ L → tievals (λα* . ψ(hnew σ | Li § α*)) (* † 1) car : E* → K → C (update(new σ | L)(* ↓ 1)σ), car = wrong “out of memory”σ onearg (λκ .  ∈ Ep → hold ( | Ep ↓ 1)κ, wrong “non-pair argument to car”) tievalsrest :(L* → C) → E* → N → C tievalsrest = cdr : E* → K → C [similar to car] λψ*ν . list (dropfirst *ν) (single(λ . tievals ψ ((takefirst *ν) § hi))) setcar : E* → K → C setcar = dropfirst = λln . n = 0 → l, dropfirst (l † 1)(n − 1) twoarg (λ12κ . 1 ∈ Ep → takefirst = λln . n = 0 → h i, hl ↓ 1i § (takefirst (l † 1)(n − 1)) (1 | Ep ↓ 3) → assign (1 | Ep ↓ 1) 2 truish : E → T (send unspecified κ), truish = λ .  = false → false, true wrong “immutable argument to set-car!”, permute : Exp* → Exp* [implementation-dependent] wrong “non-pair argument to set-car!”) 7. Formal syntax and semantics 63 eqv : E* → K → C 7.3. Derived expression types eqv = twoarg (λ12κ . (1 ∈ M ∧ 2 ∈ M) → This section gives macro definitions for the derived ex- send ( | M =  | M → true, false)κ, 1 2 pression types in terms of the primitive expression types ( ∈ Q ∧  ∈ Q) → 1 2 (literal, variable, call, lambda, if, and set!), except for send (1 | Q = 2 | Q → true, false)κ, quasiquote. (1 ∈ H ∧ 2 ∈ H) → send ( | H =  | H → true, false)κ, 1 2 (define-syntax cond ( ∈ R ∧  ∈ R) → 1 2 (syntax-rules (else =>) send ( | R =  | R → true, false)κ, 1 2 ((cond (else result1 result2 ...)) ( ∈ E ∧  ∈ E ) → 1 p 2 p (begin result1 result2 ...)) send ((λp p . ((p ↓ 1) = (p ↓ 1)∧ 1 2 1 2 ((cond (test => result)) (p ↓ 2) = (p ↓ 2)) → true, 1 2 (let ((temp test)) false) (if temp (result temp)))) ( | E ) 1 p ((cond (test => result) clause1 clause2 ...) ( | E )) 2 p (let ((temp test)) κ, (if temp ( ∈ E ∧  ∈ E ) → ..., 1 v 2 v (result temp) ( ∈ E ∧  ∈ E ) → ..., 1 s 2 s (cond clause1 clause2 ...)))) ( ∈ F ∧  ∈ F) → 1 2 ((cond (test)) test) send (( | F ↓ 1) = ( | F ↓ 1) → true, false) 1 2 ((cond (test) clause1 clause2 ...) κ, (let ((temp test)) send false κ) (if temp temp apply : E* → K → C (cond clause1 clause2 ...)))) apply = ((cond (test result1 result2 ...)) (if test (begin result1 result2 ...))) twoarg (λ12κ . 1 ∈ F → valueslist h2i(λ* . applicate 1*κ), wrong “bad procedure argument to apply”) ((cond (test result1 result2 ...) clause1 clause2 ...) (if test valueslist : E* → K → C (begin result1 result2 ...) valueslist = (cond clause1 clause2 ...))))) onearg (λκ .  ∈ Ep → cdrhi (λ* . valueslist (define-syntax case * (syntax-rules (else =>) (λ* . carhi(single(λ . κ(hi § *))))), ((case (key ...)  = null → κh i, clauses ...) wrong “non-list argument to values-list”) (let ((atom-key (key ...))) (case atom-key clauses ...))) cwcc : E* → K → C [call-with-current-continuation] ((case key cwcc = (else => result)) onearg (λκ .  ∈ F → (result key)) (λσ . new σ ∈ L → ((case key applicate  (else result1 result2 ...)) hhnew σ | L, λ*κ0 . κ*i in Ei (begin result1 result2 ...)) κ ((case key (update (new σ | L) ((atoms ...) result1 result2 ...)) unspecified (if (memv key ’(atoms ...)) σ), (begin result1 result2 ...))) wrong “out of memory” σ), ((case key wrong “bad procedure argument”) ((atoms ...) => result)) (if (memv key ’(atoms ...)) values : E* → K → C (result key))) values = λ*κ . κ* ((case key ((atoms ...) => result) clause clauses ...) cwv : E* → K → C [call-with-values] (if (memv key ’(atoms ...)) cwv = (result key) twoarg (λ12κ . applicate 1h i(λ* . applicate 2 *)) (case key clause clauses ...))) 64 Revised7 Scheme

((case key The following letrec macro uses the symbol ((atoms ...) result1 result2 ...) in place of an expression which returns something that clause clauses ...) when stored in a location makes it an error to try to ob- (if (memv key ’(atoms ...)) tain the value stored in the location (no such expression is (begin result1 result2 ...) defined in Scheme). A trick is used to generate the tempo- (case key clause clauses ...))))) rary names needed to avoid specifying the order in which the values are evaluated. This could also be accomplished (define-syntax and by using an auxiliary macro. (syntax-rules () (define-syntax letrec ((and) #t) (syntax-rules () ((and test) test) ((letrec ((var1 init1) ...) body ...) ((and test1 test2 ...) (letrec "generate temp names" (if test1 (and test2 ...) #f)))) (var1 ...) () ((var1 init1) ...) (define-syntax or body ...)) (syntax-rules () ((letrec "generate temp names" ((or) #f) () ((or test) test) (temp1 ...) ((or test1 test2 ...) ((var1 init1) ...) (let ((x test1)) body ...) (if x x (or test2 ...)))))) (let ((var1 ) ...) (let ((temp1 init1) ...) (set! var1 temp1) (define-syntax when ... (syntax-rules () body ...))) ((when test result1 result2 ...) ((letrec "generate temp names" (if test (x y ...) (begin result1 result2 ...))))) (temp ...) ((var1 init1) ...) (define-syntax unless body ...) (syntax-rules () (letrec "generate temp names" ((unless test result1 result2 ...) (y ...) (if (not test) (newtemp temp ...) (begin result1 result2 ...))))) ((var1 init1) ...) body ...))))

(define-syntax let (define-syntax letrec* (syntax-rules () (syntax-rules () ((let ((name val) ...) body1 body2 ...) ((letrec* ((var1 init1) ...) body1 body2 ...) ((lambda (name ...) body1 body2 ...) (let ((var1 ) ...) val ...)) (set! var1 init1) ((let tag ((name val) ...) body1 body2 ...) ... ((letrec ((tag (lambda (name ...) (let () body1 body2 ...))))) body1 body2 ...))) tag) (define-syntax let-values val ...)))) (syntax-rules () ((let-values (binding ...) body0 body1 ...) (let-values "bind" (define-syntax let* (binding ...) () (begin body0 body1 ...))) (syntax-rules () ((let* () body1 body2 ...) ((let-values "bind" () tmps body) (let () body1 body2 ...)) (let tmps body)) ((let* ((name1 val1) (name2 val2) ...) body1 body2 ...) ((let-values "bind" ((b0 e0) (let ((name1 val1)) binding ...) tmps body) (let* ((name2 val2) ...) (let-values "mktmp" b0 e0 () body1 body2 ...))))) (binding ...) tmps body)) 7. Formal syntax and semantics 65

((let-values "mktmp" () e0 args (let ((v (cadr var0))) bindings tmps body) (set-cdr! var0 (cddr var0)) (call-with-values v)) ... (lambda () e0) (define varn (lambda args (let ((v (cdr var0))) (let-values "bind" (set! var0 (car var0)) bindings tmps body)))) v)))) ((define-values var expr) ((let-values "mktmp" (a . b) e0 (arg ...) (define var bindings (tmp ...) body) (call-with-values (lambda () expr) (let-values "mktmp" b e0 (arg ... x) list))))) bindings (tmp ... (a x)) body))

((let-values "mktmp" a e0 (arg ...) (define-syntax begin bindings (tmp ...) body) (syntax-rules () (call-with-values ((begin exp ...) (lambda () e0) ((lambda () exp ...))))) (lambda (arg ... . x) (let-values "bind" The following alternative expansion for begin does not bindings (tmp ... (a x)) body)))))) make use of the ability to write more than one expression in the body of a lambda expression. In any case, note that (define-syntax let*-values these rules apply only if the body of the begin contains no (syntax-rules () definitions. ((let*-values () body0 body1 ...) (begin body0 body1 ...)) (define-syntax begin (syntax-rules () ((let*-values (binding0 binding1 ...) ((begin exp) body0 body1 ...) exp) (let-values (binding0) ((begin exp1 exp2 ...) (let*-values (binding1 ...) (call-with-values body0 body1 ...))))) (lambda () exp1) (lambda args (begin exp2 ...)))))) (define-syntax define-values (syntax-rules () ((define-values () expr) The following definition of do uses a trick to expand the (define dummy variable clauses. As with letrec above, an auxiliary macro (call-with-values (lambda () expr) would also work. The expression (if #f #f) is used to (lambda args #f)))) obtain an unspecific value. ((define-values (var) expr) (define var expr)) (define-syntax do ((define-values (var0 var1 ... varn) expr) (syntax-rules () (begin ((do ((var init step ...) ...) (define var0 (test expr ...) (call-with-values (lambda () expr) command ...) list)) (letrec (define var1 ((loop (let ((v (cadr var0))) (lambda (var ...) (set-cdr! var0 (cddr var0)) (if test v)) ... (begin (define varn (if #f #f) (let ((v (cadr var0))) expr ...) (set! var0 (car var0)) (begin v)))) command ((define-values (var0 var1 ... . varn) expr) ... (begin (loop (do "step" var step ...) (define var0 ...)))))) (call-with-values (lambda () expr) (loop init ...))) list)) ((do "step" x) (define var1 x) 66 Revised7 Scheme

((do "step" x y) The following implementation of make-parameter and y))) parameterize is suitable for an implementation with no threads. Parameter objects are implemented here as pro- cedures, using two arbitrary unique objects Here is a possible implementation of delay, force and and : lazy. We define the expression (define (make-parameter init . o) (lazy hexpressioni) (let* ((converter to have the same meaning as the procedure call (if (pair? o) (car o) (lambda (x) x))) (value (converter init))) (make-promise #f (lambda () hexpressioni)) (lambda args (cond as follows ((null? args) (define-syntax lazy value) (syntax-rules () ((eq? (car args) ) ((lazy expression) (set! value (cadr args))) (make-promise #f (lambda () expression))))) ((eq? (car args) ) converter) and we define the expression (else (error "bad parameter syntax")))))) (delay hexpressioni) Then parameterize uses dynamic-wind to dynamically re- to have the same meaning as: bind the associated value: (lazy (make-promise #t hexpressioni)) (define-syntax parameterize as follows (syntax-rules () ((parameterize ("step") (define-syntax delay ((param value p old new) ...) (syntax-rules () () ((delay expression) body) (lazy (make-promise #t expression))))) (let ((p param) ...) (let ((old (p)) ... where make-promise is defined as follows: (new ((p ) value)) ...) (dynamic-wind (define make-promise (lambda () (p new) ...) (lambda (done? proc) (lambda () . body) (list (cons done? proc)))) (lambda () (p old) ...))))) Finally, we define force to call the procedure expressions ((parameterize ("step") in promises iteratively using a trampoline technique fol- args lowing [39] until a non-lazy result (i.e. a value created by ((param value) . rest) body) delay instead of lazy) is returned, as follows: (parameterize ("step") (define (force promise) ((param value p old new) . args) (if (promise-done? promise) rest (promise-value promise) body)) (let ((promise* ((promise-value promise)))) ((parameterize ((param value) ...) . body) (unless (promise-done? promise) (parameterize ("step") (promise-update! promise* promise)) () (force promise)))) ((param value) ...) body)))) with the following promise accessors:

(define promise-done? The following implementation of guard depends on an aux- (lambda (x) (car (car x)))) iliary macro, here called guard-aux. (define promise-value (lambda (x) (cdr (car x)))) (define-syntax guard (define promise-update! (syntax-rules () (lambda (new old) ((guard (var clause ...) e1 e2 ...) (set-car! (car old) (promise-done? new)) ((call/cc (set-cdr! (car old) (promise-value new)) (lambda (guard-k) (set-car! new (car old)))) (with-exception-handler 7. Formal syntax and semantics 67

(lambda (condition) (error "no matching clause")) ((call/cc ((cl ((p :::) . body) . rest) (lambda (handler-k) (if (= len (length ’(p :::))) (guard-k (apply (lambda (p :::) (lambda () . body) (let ((var condition)) args) (guard-aux (cl . rest))) (handler-k ((cl ((p ::: . tail) . body) (lambda () . rest) (raise condition))) (if (>= len (length ’(p :::))) clause ...)))))))) (apply (lambda () (lambda (p ::: . tail) (call-with-values . body) (lambda () e1 e2 ...) args) (lambda args (cl . rest)))))) (guard-k (cl (params body0 body1 ...) ...))))))) (lambda () (apply values args)))))))))))))

(define-syntax guard-aux (syntax-rules (else =>) ((guard-aux reraise (else result1 result2 ...)) (begin result1 result2 ...)) ((guard-aux reraise (test => result)) (let ((temp test)) (if temp (result temp) reraise))) ((guard-aux reraise (test => result) clause1 clause2 ...) (let ((temp test)) (if temp (result temp) (guard-aux reraise clause1 clause2 ...)))) ((guard-aux reraise (test)) test) ((guard-aux reraise (test) clause1 clause2 ...) (let ((temp test)) (if temp temp (guard-aux reraise clause1 clause2 ...)))) ((guard-aux reraise (test result1 result2 ...)) (if test (begin result1 result2 ...) reraise)) ((guard-aux reraise (test result1 result2 ...) clause1 clause2 ...) (if test (begin result1 result2 ...) (guard-aux reraise clause1 clause2 ...)))))

(define-syntax case-lambda (syntax-rules () ((case-lambda (params body0 body1 ...) ...) (lambda args (let ((len (length args))) (let-syntax ((cl (syntax-rules ::: () ((cl) 68 Revised7 Scheme

Appendix A. Standard Libraries gcd get-output-bytevector get-output-string guard This section lists the exports provided by the standard li- if import inexact->exact braries. The libraries are factored so as to separate features inexact? input-port? integer->char which might not be supported by all implementations, or integer? lambda lcm which might be expensive to load. length let let* The scheme library prefix is used for all standard libraries, let*-values let-syntax let-values and is reserved for use by future standards. letrec letrec* letrec-syntax list list->string list->vector Base Library list-copy list-ref list-set! list-tail list? make-bytevector The (scheme base) library exports many of the proce- make-list make-parameter make-string dures and syntax bindings that are traditionally associated make-vector map max with Scheme. member memq memv * + - min modulo negative? ... / < newline not null? <= = => number->string number? numerator > >= odd? open-input-bytevector abs and append open-input-string apply assoc assq open-output-bytevector assv begin binary-port? open-output-string or boolean? bytevector-copy output-port? pair? parameterize bytevector-copy! peek-char peek-u8 port-open? bytevector-copy-partial port? positive? procedure? bytevector-copy-partial! quasiquote quote quotient bytevector-length raise raise-continuable bytevector-u8-ref rational? rationalize read-bytevector bytevector-u8-set! bytevector? read-bytevector! read-char caaaar caaadr caaar read-line read-u8 real? caadar caaddr caadr remainder reverse round caar caar cadaar set! set-car! set-cdr! cadadr cadar caddar string string->list string->number cadddr caddr cadr string->symbol string->utf8 string->vector cadr call-with-current-continuation string-append string-copy string-fill! call-with-port call-with-values string-for-each string-length string-map call/cc car case string-ref string-set! string<=? cdaaar cdaadr cdaar string=? cdadar cdaddr cdadr string>? string? substring cdar cddaar cddadr symbol->string symbol? syntax-error cddar cdddar cddddr syntax-rules textual-port? truncate cdddr cddr cdr u8-ready? unless unquote ceiling char->integer char-ready? unquote-splicing utf8->string char<=? charlist char>=? char>? char? vector->string vector-copy vector-fill! close-input-port vector-for-each vector-length vector-map close-output-port close-port vector-ref vector-set! vector? complex? cond cond-expand when with-exception-handler cons current-error-port write-bytevector write-char current-input-port write-partial-bytevector write-u8 current-output-port define zero? define-record-type define-syntax define-values denominator do Inexact Library dynamic-wind else eof-object? eq? equal? eqv? The (scheme inexact) library exports procedures which error error-object-irritants are typically only useful with inexact values. error-object-message error-object? even? exact->inexact acos asin atan exact-integer-sqrt exact-integer? cos exp finite? exact? expt floor log nan? sin flush-output-port for-each sqrt tan Appendix A. Standard Libraries 69

command-line exit get-environment-variable Complex Library get-environment-variables The (scheme complex) library exports procedures which are typically only useful with non-real numbers. Load Library angle imag-part magnitude The (scheme load) library exports procedures for loading make-polar make-rectangular Scheme expressions from files. real-part load Division Library File Library The (scheme division) library exports procedures for in- teger division. The (scheme file) library provides procedures for access- ing files. ceiling-quotient ceiling-remainder ceiling/ call-with-input-file centered-quotient call-with-output-file delete-file centered-remainder centered/ file-exists? open-binary-input-file euclidean-quotient open-binary-output-file open-input-file euclidean-remainder euclidean/ open-output-file floor-quotient floor-remainder floor/ with-input-from-file round-quotient round-remainder round/ with-output-to-file truncate-quotient truncate-remainder truncate/ Read Library

Lazy Library The (scheme read) library provides procedures for read- ing Scheme objects. The (scheme lazy) library exports procedures and syntax keywords for lazy evaluation. read delay eager force lazy Write Library The (scheme write) library provides procedures for writ- Case-Lambda Library ing Scheme objects. The (scheme case-lambda) library exports the display write write-simple case-lambda syntax. case-lambda Char Library The (scheme char) library provides procedures for deal- Eval Library ing with Unicode character operations. The (scheme eval) library exports procedures for evalu- char-alphabetic? char-ci<=? ating Scheme data as programs. char-ci=? char-ci>? char-downcase char-foldcase environment eval char-lower-case? char-numeric? null-environment char-upcase char-upper-case? scheme-report-environment char-whitespace? digit-value string-ci<=? string-ci=? string-ci>? string-downcase string-foldcase string-upcase The (scheme repl) library exports the interaction-environment procedure. Char Normalization Library interaction-environment The (scheme char normalization) library provides pro- cedures for dealing with Unicode normalization operations. Process Context Library string-ni<=? string-ni=? string-ni>? dures for accessing with the program’s calling context. 70 Revised7 Scheme

Time Library Appendix B. Standard Feature Identi- The (scheme time) library provides access to time-related fiers values. An implementation may provide any or all of the feature identifiers listed below, as well as any others that it chooses, current-jiffy current-second but must not provide a feature identifier if it does not pro- jiffies-per-second vide the corresponding feature. These features are used by cond-expand.

r7rs All R7RS Scheme implementations have this feature.

exact-closed All algebraic operations except / produce exact values given exact inputs.

ratios / with exact arguments produces an exact result when the divisor is nonzero.

exact-complex Exact complex numbers are provided.

ieee-float Inexact numbers are IEEE 754 floating point values.

full-unicode All Unicode codepoints are supported as characters (except the surrogates).

windows This Scheme implementation is running on Windows.

posix This Scheme implementation is running on a POSIX system.

unix, darwin, linux, bsd, freebsd, solaris, ... Operating system flags (more than one may apply).

i386, x86-64, ppc, sparc, jvm, clr, llvm, ... CPU architecture flags.

ilp32, lp64, ilp64, ... C memory model flags.

big-endian, little-endian Byte order flags.

hnamei The name of this implementation.

hname-versioni The name and version of this implementation. Notes 71

NOTES • The procedures current-input-port and current-output-port are now parameter objects, as is the newly introduced current-error-port. Language changes since R5RS • The syntax-rules construct now recognizes (under- This section enumerates the differences between this report score) as a wildcard, allows the ellipsis symbol to be and the “Revised5 report” [2]. specified explicitly instead of the default ..., allows template escapes with an ellipsis-prefixed list, and al- The list is incomplete and subject to change while this lows tail patterns to follow an ellipsis pattern. report is in draft status. • The syntax-error syntax has been added as a way to • Various minor ambiguities and unclarities in R5RS signal immediate and more informative errors when a have been cleaned up. macro is expanded.

• Libraries have been added as a new program structure • Internal define-syntax definitions are now allowed to improve encapsulation and sharing of code. Some wherever internal defines are. existing and new identifiers have been factored out into separate libraries. Libraries can be imported into • The letrec* binding construct has been added, and other libraries or main programs, with controlled ex- internal define is specified in terms of it. posure and renaming of identifiers. The contents of a library can be made conditional on the features of the • Support for capturing multiple values has been implementation on which it is to be used. enhanced with define-values, let-values, and let*-values. Programs are now explicitly permitted • Exceptions can now be signalled explicitly with raise, to pass zero values or more than one value to contin- raise-continuable or error, and can be handled uations which discard them. with with-exception-handler and the guard syn- tax. Any object can specify an error condition; the • The case conditional now supports a => syntax anal- implementation-defined conditions signalled by error ogous to cond. have accessor functions to retrieve the arguments • To support dispatching on the number of arguments passed to error. passed to a procedure, case-lambda has been added • New disjoint types supporting access to multiple fields in its own library. can be generated with SRFI 9’s define-record-type. • The convenience conditionals when and unless have • Parameter objects can be created with been added. make-parameter, and dynamically rebound with parameterize. • Positive infinity, negative infinity, NaN, and nega- tive inexact zero have been added to the numeric • Bytevectors, homogeneous vectors of integers in the tower as inexact values with the written representa- range [0, 255], have been added as a new disjoint type. tions +inf.0, -inf.0, +nan.0, and -0.0 respectively. A subset of the procedures available for vectors is provided. Bytevectors can be converted to and from • The procedures map and for-each are now required strings in accordance with the UTF-8 character en- to terminate on the shortest list when inputs have dif- coding. Bytevectors have a datum representation and ferent length. evaluate to themselves. • The procedures member and assoc now take an op- • The procedure read-line is provided to make line- tional third argument specifying the equality predicate oriented textual input simpler. to be used.

• Ports can now be designated as textual or binary ports, • The procedures exact-integer? and with new procedures for reading and writing binary exact-integer-sqrt have been added. data. The new predicate port-open? returns whether a port is open or closed. • The procedures make-list, list-copy, list-set!, string-map, string-for-each, string->vector, • String ports have been added as a way to read and vector-copy, vector-map, vector-for-each, and write characters to and from strings, and bytevector vector->string have been added to round out the ports to read and write bytes to and from bytevectors. sequence operations. 72 Revised7 Scheme

• Implementations may provide any subset of the full • The syntax of the library system was deliberately cho- Unicode repertoire that includes ASCII, but imple- sen to be syntactically different from R6RS, using mentations must support any such subset in a way define-library instead of library in order to al- consistent with Unicode. Various character and string low easy disambiguation between R6RS and R7RS li- procedures have been extended accordingly. String braries. comparison remains implementation-dependent, and is no longer required to be consistent with character • The library system does not support phase distinc- comparison, which is based on Unicode code points. tions, which are unnecessary in the absence of low- The new digit-value procedure is added to obtain level macros (see below), nor does it support version- the numerical value of a numeric character. ing, which is an important feature but deserves more experimentation before being standardized. • The procedures string-ni=? and related procedures have been added to compare strings as though they • Putting an extra level of indirection around the li- 6 had gone through an implementation-defined normal- brary body allows room for extensibility. The R RS ization, without exposing the normalization. syntax provides two positional forms which must be present and must have the correct keywords, export • Case insensitivity is now the default. and import, which does not allow for unambiguous ex- tensions. The Working Group considers extensibility • There are now two additional comment syntaxes: #; to be important, and so chose a syntax which provides to skip the next datum, and #| ... |# for nestable a clear separation between the library declarations and block comments. the Scheme code which makes up the body. • Data prefixed with datum labels #= can be refer- • The include library declaration makes it easier to in- enced with ##, allowing for reading and writing of clude separate files, and the variant allows data with shared structure. include-ci legacy case-insensitive code to be incorporated. • Strings and symbols now allow mnemonic and numeric • The cond-expand library declaration based on SRFI escape sequences, and the list of named characters has 6 been extended. 0 allows for a more flexible alternative to the R RS .impl.sls file naming convention. • The procedures file-exists? and delete-file are 7 available in the (scheme file) library. • Since the R RS library system is straightforward, we expect that R6RS implementations will be able to sup- • An interface to the system environment and command port the define-library syntax in addition to their line is available in the (scheme process-context) li- library syntax. brary. • The grouping of standardized identifiers into libraries • Procedures for accessing time-related values are avail- is different from the R6RS approach. In particular, able in the (scheme time) library. procedures which are optional either expressly or by implication in R5RS have been removed from the base • A complete set of integer division operators is available library. Only the base library is an absolute require- in the (scheme division) library. ment. • The load procedure now accepts a second argument • Identifier syntax is not provided. This is a useful specifying the environment to load into. feature in some situations, but the existence of such • The procedures transcript-on and transcript-off macros means that neither programmers nor other have been removed. macros can look at an identifier in an evaluated po- sition and know it is a reference — this in a sense • The semantics of read-eval-print loops are now partly makes all macros slightly weaker. Individual imple- prescribed, allowing the redefinition of procedures mentations are encouraged to continue experimenting (but not syntax keywords) to be retroactive. with this and other extensions before further standard- ization is done. Incompatibilities with the main R6RS document • Internal syntax definitions are allowed, but all ref- This section enumerates the incompatibilities between erences to syntax must follow the definition; the 6 R7RS and the “Revised6 report” [1]. even/odd example given in R RS is not allowed. The list is incomplete and subject to change while this • The R6RS exception system was incorporated as-is, report is in draft status. but the condition types have been left unspecified. Additional material 73

Specific errors that must be signalled in R6RS remain • The low-level macro system and syntax-case were errors in R7RS, allowing implementations to provide not adopted. There are two general families of macro their own extensions. There is no discussion of safety. systems in widespread use — the syntax-case family and the syntactic-closures family — and they have • Full Unicode support is not required. Instead neither been shown to be equivalent nor capable of of explicit normalization forms this report provides implementing each other. Given this situation, low- normalization-insensitive string comparisons that use level macros have been left to the large language. an implementation-defined normalization form (which 6 may be the identity transformation). Character com- • The new I/O system from R RS was not adopted. parisons are defined by Unicode, but string compar- Historically, standardization reflects technologies that isons are implementation-dependent, and therefore have undergone a period of adoption, experimenta- need not be the lexicographic mapping of the corre- tion, and usage before incorporation into a stan- sponding character comparisons (an incompatibility dard. The Working Group was unhappy with the re- with R5RS). Non-Unicode characters are permitted. dundant provision of both the new system and the R5RS-compatible “simple I/O” system, which rele- • The full numeric tower is optional as in R5RS, gated R5RS code to being a second-class citizen. How- but optional support for IEEE infinities, NaN, and ever, binary I/O was added using binary ports that are -0.0 was adopted from R6RS. Most clarifications on at least potentially disjoint from textual ports and use numeric results were also adopted, but the R6RS their own parallel set of procedures. procedures real-valued?, rational-valued?, and • String ports are compatible with SRFI 6 rather than integer-valued? were not. The R5RS names R6RS; analogous bytevector ports are also provided. inexact->exact for exact and exact->inexact for inexact were retained, with a note indicating that • The Working Group felt that the R6RS records sys- their names are historical. The R6RS division op- tem was overly complex, and the two layers poorly erators div, mod, div-and-mod, div0, mod0 and integrated. The Working Group spent a lot of time div0-and-mod0 have been replaced with a full set of debating this, but in the end decided to simply use a 18 operators describing 6 different rounding semantics. generative version of SRFI 9, which has near-universal support among implementations. The Working Group • When a result is unspecified, it is still required to be hopes to provide a more powerful records system in the 5 a single value, in the interests of R RS compatibility. large language. However, non-final expressions in a body may return any number of values. • Enumerations are not included in the small language.

6 • Because of widespread SRFI 1 support and extensive • R RS-style bytevectors are included, but provide only code that uses it, the semantics of map and for-each the “u8” procedures in the small language. The lexical have been changed to use the SRFI 1 early termination syntax uses #u8 for compatibility with SRFI 4, rather 6 behavior. Likewise assoc and member take an optional than the R RS #vu8 style. With a library system, it’s equal? argument as in SRFI 1, instead of the separate easier to change names than reader syntax. 6 assp and memp procedures of R RS. • The utility macros when and unless are provided, but since it would be meaningless to try to use their result, • The R6RS quasiquote clarifications have been it is left unspecified. adopted, but the Working Group has not seen convinc- ing enough examples of multiple-argument unquote • The Working Group could not agree on a single design and unquote-splicing, so they are not provided. for hash tables and left them for the large language.

• The R6RS method of specifying mantissa widths was • Sorting, bitwise arithmetic, and enumerations were not adopted. not considered to be sufficiently useful to include in the small language. They will probably be included in the large language. Incompatibilities with the R6RS Standard Li- braries document • Pair and string mutation are too well-established to be relegated to separate libraries. This section enumerates the incompatibilities between R7RS and the R6RS [1] Standard Libraries. ADDITIONAL MATERIAL The list is incomplete and subject to change while this report is in draft status. The Internet Scheme Repository at 74 Revised7 Scheme

http://www.cs.indiana.edu/scheme-repository/ EXAMPLE contains an extensive Scheme bibliography, as well as pa- The procedure integrate-system integrates the sys- pers, programs, implementations, and other material re- tem lated to Scheme. 0 yk = fk(y1, y2, . . . , yn), k = 1, . . . , n The Scheme community website at of differential equations with the method of Runge-Kutta. http://schemers.org/ The parameter system-derivative is a function that contains additional resources for learning and program- takes a system state (a vector of values for the state vari- ming, job and event postings, and Scheme user group in- ables y1, . . . , yn) and produces a system derivative (the val- 0 0 formation. ues y1, . . . , yn). The parameter initial-state provides an initial system state, and h is an initial guess for the A bibliography of Scheme-related research at length of the integration step. http://library.readscheme.org/ The value returned by integrate-system is an infi- links to technical papers and theses related to the Scheme nite stream of system states. language, including both classic papers and recent re- (define integrate-system search. (lambda (system-derivative initial-state h) (let ((next (runge-kutta-4 system-derivative h))) (letrec ((states (cons initial-state (delay (map-streams next states))))) states)))) The procedure runge-kutta-4 takes a function, f, that produces a system derivative from a system state. It produces a function that takes a system state and produces a new system state. (define runge-kutta-4 (lambda (f h) (let ((*h (scale-vector h)) (*2 (scale-vector 2)) (*1/2 (scale-vector (/ 1 2))) (*1/6 (scale-vector (/ 1 6)))) (lambda (y) ;; y is a system state (let* ((k0 (*h (f y))) (k1 (*h (f (add-vectors y (*1/2 k0))))) (k2 (*h (f (add-vectors y (*1/2 k1))))) (k3 (*h (f (add-vectors y k2))))) (add-vectors y (*1/6 (add-vectors k0 (*2 k1) (*2 k2) k3))))))))

(define elementwise (lambda (f) (lambda vectors (generate-vector (vector-length (car vectors)) (lambda (i) (apply f (map (lambda (v) (vector-ref v i)) vectors)))))))

(define generate-vector (lambda (size proc) References 75

(let ((ans (make-vector size))) REFERENCES (letrec ((loop (lambda (i) [1] Michael Sperber, R. Kent Dybvig, Mathew Flatt, (cond ((= i size) ans) and Anton van Straaten, editors. The revised6 report (else on the algorithmic language Scheme. (vector-set! ans i (proc i)) (loop (+ i 1))))))) [2] Richard Kelsey, William Clinger, and Jonathan Rees, (loop 0))))) editors. The revised5 report on the algorithmic lan- guage Scheme. (define add-vectors (elementwise +)) [3] Harold Abelson and Gerald Jay Sussman with Julie (define scale-vector Sussman. Structure and Interpretation of Computer (lambda (s) Programs, second edition. MIT Press, Cambridge, (elementwise (lambda (x) (* x s))))) 1996. The map-streams procedure is analogous to map: it applies its first argument (a procedure) to all the elements [4] Alan Bawden and Jonathan Rees. Syntactic closures. of its second argument (a stream). In Proceedings of the 1988 ACM Symposium and Functional Programming, pages 86–95. (define map-streams (lambda (f s) [5] Raymond T. Boute. The Euclidean definition of the (cons (f (head s)) functions div and mod. In ACM Transactions on Pro- (delay (map-streams f (tail s)))))) gramming Languages and Systems 14(2), pages 127– 144, April 1992. Infinite streams are implemented as pairs whose car holds the first element of the stream and whose cdr holds [6] S. Bradner. Key words for use in RFCs to In- a promise to deliver the rest of the stream. dicate Requirement Levels. http://www.ietf.org/ (define head car) rfc/rfc2119.txt, 1997. (define tail [7] Robert G. Burger and R. Kent Dybvig. Printing (lambda (stream) (force (cdr stream)))) floating-point numbers quickly and accurately. In Proceedings of the ACM SIGPLAN ’96 Conference The following illustrates the use of integrate-system on Programming Language Design and Implementa- in integrating the system tion, pages 108–116. dv v [8] William Clinger, editor. The revised revised report C C = −i − C dt L R on Scheme, or an uncommon Lisp. MIT Artificial Intelligence Memo 848, August 1985. Also published di as Computer Science Department Technical Report L L = v dt C 174, Indiana University, June 1985. which models a damped oscillator. [9] William Clinger. How to read floating point numbers (define damped-oscillator accurately. In Proceedings of the ACM SIGPLAN (lambda (R L C) ’90 Conference on Programming Language Design (lambda (state) and Implementation, pages 92–101. Proceedings pub- (let ((Vc (vector-ref state 0)) lished as SIGPLAN Notices 25(6), June 1990. (Il (vector-ref state 1))) (vector (- 0 (+ (/ Vc (* R C)) (/ Il C))) [10] William Clinger and Jonathan Rees, editors. The 4 (/ Vc L)))))) revised report on the algorithmic language Scheme. In ACM Lisp Pointers 4(3), pages 1–55, 1991. (define the-states (integrate-system [11] William Clinger and Jonathan Rees. Macros that (damped-oscillator 10000 1000 .001) work. In Proceedings of the 1991 ACM Conference ’#(1 0) on Principles of Programming Languages, pages 155– .01)) 162. [12] William Clinger. Proper Tail Recursion and Space Efficiency. In Proceedings of the 1998 ACM Confer- ence on Programming Language Design and Imple- mentation, June 1998. 76 Revised7 Scheme

[13] Mark Davis, Ken Whistler. Unicode Standard An- [27] Paul Penfield, Jr. Principal values and branch cuts nex #15, Unicode Normalization Forms. http:// in complex APL. In APL ’81 Conference Proceed- unicode.org/reports/tr15/, 2010. ings, pages 248–256. ACM SIGAPL, San Fran- cisco, September 1981. Proceedings published as [14] Mark Davis. Unicode Standard Annex #29, Unicode APL Quote Quad 12(1), ACM, September 1981. Text Segmentation. http://unicode.org/reports/ tr29/, 2010. [28] Kent M. Pitman. The revised MacLisp manual (Sat- urday evening edition). MIT Laboratory for Com- [15] R. Kent Dybvig, Robert Hieb, and Carl Bruggeman. puter Science Technical Report 295, May 1983. Syntactic abstraction in Scheme. Lisp and Symbolic Computation 5(4):295–326, 1993. [29] Jonathan A. Rees and Norman I. Adams IV. T: A [16] Carol Fessenden, William Clinger, Daniel P. Fried- dialect of Lisp or, lambda: The ultimate software man, and Christopher Haynes. Scheme 311 version 4 tool. In Conference Record of the 1982 ACM Sym- reference manual. Indiana University Computer Sci- posium on Lisp and Functional Programming, pages ence Technical Report 137, February 1983. Super- 114–122. seded by [17]. [30] Jonathan A. Rees, Norman I. Adams IV, and James [17] D. Friedman, C. Haynes, E. Kohlbecker, and R. Meehan. The T manual, fourth edition. Yale M. Wand. Scheme 84 interim reference manual. Indi- University Computer Science Department, January ana University Computer Science Technical Report 1984. 153, January 1985. [31] Jonathan Rees and William Clinger, editors. The [18] Martin Gardner. Mathematical Games: The fan- revised3 report on the algorithmic language Scheme. tastic combinations of John Conway’s new solitaire In ACM SIGPLAN Notices 21(12), pages 37–79, De- game “Life.” In Scientific American, 223:120–123, cember 1986. October 1970. [32] John Reynolds. Definitional interpreters for higher [19] IEEE Standard 754-1985. IEEE Standard for Binary order programming languages. In ACM Conference Floating-Point Arithmetic. IEEE, New York, 1985. Proceedings, pages 717–740. ACM, 1972. [20] IEEE Standard 1178-1990. IEEE Standard for the [33] Guy Lewis Steele Jr. and Gerald Jay Sussman. The Scheme Programming Language. IEEE, New York, revised report on Scheme, a dialect of Lisp. MIT Ar- 1991. tificial Intelligence Memo 452, January 1978. [21] Eugene E. Kohlbecker Jr. Syntactic Extensions in [34] Guy Lewis Steele Jr. Rabbit: a compiler for Scheme. the Programming Language Lisp. PhD thesis, Indi- MIT Artificial Intelligence Laboratory Technical Re- ana University, August 1986. port 474, May 1978. [22] Eugene E. Kohlbecker Jr., Daniel P. Friedman, [35] Guy Lewis Steele Jr. Common Lisp: The Language, , and Bruce Duba. Hygienic macro second edition. Digital Press, Burlington MA, 1990. expansion. In Proceedings of the 1986 ACM Con- ference on Lisp and Functional Programming, pages [36] Gerald Jay Sussman and Guy Lewis Steele Jr. 151–161. Scheme: an interpreter for extended lambda calcu- lus. MIT Artificial Intelligence Memo 349, December [23] Peter Landin. A correspondence between Algol 60 1975. and Church’s lambda notation: Part I. Communica- tions of the ACM 8(2):89–101, February 1965. [37] Joseph E. Stoy. Denotational Semantics: The Scott- Strachey Approach to Programming Language The- [24] John McCarthy. Recursive Functions of Symbolic Ex- ory. MIT Press, Cambridge, 1977. pressions and Their Computation by Machine, Part I. Communications of the ACM 3(4):184–195, April [38] Texas Instruments, Inc. TI Scheme Language Ref- 1960. erence Manual. Preliminary version 1.0, November 1985. [25] MIT Department of Electrical Engineering and Com- puter Science. Scheme manual, seventh edition. [39] Andre van Tonder. SRFI-45: Primitives for Ex- September 1984. pressing Iterative Lazy Algorithms. http://srfi. [26] Peter Naur et al. Revised report on the algorith- schemers.org/srfi-45/, 2002. mic language Algol 60. Communications of the ACM 6(1):1–17, January 1963. Index 77 ALPHABETIC INDEX OF DEFINITIONS OF CONCEPTS, KEYWORDS, AND PROCEDURES

The principal entry for each term, procedure, or keyword is bytevector-u8-set! 45 listed first, separated from the other entries by a semicolon. bytevector? 45; 9 bytevectors 45 ! 7 ’ 12; 38 caaaar 38 * 33 caaadr 38 + 33; 61 caaar 38 , 19; 38 caadar 38 ,@ 19 caaddr 38 - 34 caadr 38 -> 7 caar 38 . 7 cadaar 38 ... 21 cadadr 38 / 34 cadar 38 ; 8 caddar 38 < 33; 61 cadddr 38 <= 33 caddr 38 = 33 cadr 38 => 14 call 12 > 33 call by need 17 >= 33 call-with-current-continuation 47; 11, 49, 62 ? 7 call-with-input-file 51 21 call-with-output-file 51 ‘ 20 call-with-port 51 call-with-values 48; 11, 62 abs 34; 36 call/cc 47; 48 acos 35 car 38; 61 and 14; 62 case 14; 62 angle 36 case-lambda 20; 24, 66 append 39 catch 48 apply 46; 11, 62 cdaaar 38 asin 35 cdaadr 38 assoc 40 cdaar 38 assq 40 cdadar 38 assv 40 cdaddr 38 atan 35 cdadr 38 cdar 38 #b 32; 57 cddaar 38 backquote 19 cddadr 38 begin 16; 23, 24, 27, 64 cddar 38 binary-port? 51 cdddar 38 binding 9 cddddr 38 binding construct 9 cdddr 38 boolean? 37; 9 cddr 38 bound 9 cdr 38 byte 45 ceiling 35 bytevector-copy 46 ceiling-quotient 34 bytevector-copy! 46 ceiling-remainder 34 bytevector-copy-partial 46 ceiling/ 34 bytevector-copy-partial! 46 centered-quotient 34 bytevector-length 45; 31 centered-remainder 34 bytevector-u8-ref 45 centered/ 34 78 Revised7 Scheme char->integer 42 eager 18 char-alphabetic? 41 else 14; 27 char-ci<=? 41 empty list 37; 9, 38 char-ci=? 41 eof-object? 53 char-ci>? 41 eq? 29 char-downcase 42 equal? 30 char-foldcase 42 equivalence predicate 28 char-lower-case? 41 eqv? 28; 10, 61 char-numeric? 41 error 5; 50 char-ready? 53 error-object-irritants 50 char-upcase 42 error-object-message 50 char-upper-case? 41 error-object? 50 char-whitespace? 41 escape procedure 47 char<=? 41 escape sequence 42 char=? 41 euclidean/ 34 char>? 41 eval 50; 11 char? 41; 9 even? 33 close-input-port 52 exact 28 close-output-port 52 exact->inexact 36 close-port 52 exact-integer-sqrt 35 comma 19 exact-integer? 33 command-line 55 exact? 33 comment 8; 56 exactness 30 complex? 32; 30, 33 except 26 cond 13; 22, 62 exception handler 49 cond-expand 27 exit 55 cons 38 exp 35 constant 10 export 26 continuation 48 expt 36 cos 35 current exception handler 49 #f 37 current-error-port 51 false 9; 37 current-input-port 51 fields 25 current-jiffy 55 file-exists? 55 current-output-port 51 finite? 33 current-second 55 floor 35 floor-quotient 34 #d 32 floor-remainder 34 define 24; 20 floor/ 34 define-syntax 25 flush-output-port 54 define-values 24; 64 fold-case@#!fold-case 8 definition 23 for-each 47 delay 17 force 17 delete-file 55 denominator 35 gcd 34 digit-value 41 get-environment-variable 55 display 54 get-environment-variables 55 do 17; 64 get-output-bytevector 52 dotted pair 37 get-output-string 52 dynamic-wind 49; 48 guard 19; 24

#e 32; 57 hygienic 20 Index 79

#i 32; 57 macro transformer 20 identifier 7; 9, 56 macro use 20 if 13; 60 magnitude 36 imag-part 36 make-bytevector 45 immutable 10 make-list 39 implementation extension 31 make-parameter 18 implementation restriction 6; 31 make-polar 36 import 26 make-rectangular 36 improper list 38 make-string 43 include 27 make-vector 44 include-ci 27 map 46 inexact 28 max 33 inexact->exact 36; 30 member 39 inexact? 33 memq 39 initial environment 28 memv 39 input-port? 51 min 33 integer->char 42 modulo 34 integer? 32; 30 mutable 10 interaction-environment 51 internal definition 24 nan? 33 irritants 50 negative? 33 newline 54 jiffies 55 nil 37 jiffies-per-second 55 no-fold-case@#!no-fold-case 8 not 37 keyword 20 null-environment 50 null? 38 lambda 12; 24, 60 number 30 lazy 17 number->string 36 lazy evaluation 17 number? 32; 9, 30, 33 lcm 34 numerator 35 length 39; 31 numerical types 30 let 15; 17, 22, 24, 63 let* 15; 24, 63 #o 32; 57 let*-values 16; 63 object 5 let-syntax 20; 24 odd? 33 let-values 16; 24, 63 only 26 let-values* 24 open-binary-input-file 52 letrec 15; 24, 63 open-binary-output-file 52 letrec* 16; 24, 63 open-input-bytevector 52 letrec-syntax 21; 24 open-input-file 52 libraries 5 open-input-string 52 list 37; 39 open-output-bytevector 52 list->string 44 open-output-file 52 list->vector 45 open-output-string 52 list-copy 40 or 14; 62 list-ref 39 output-port? 51 list-set! 39 list-tail 39 pair 37 list? 38 pair? 38; 9 load 54 parameter object 18 location 10 parameterize 18; 24 log 35 peek-char 53 peek-u8 53 macro 20 port 51 macro keyword 20 port-open? 51 80 Revised7 Scheme port? 51; 9 string-ci<=? 43 positive? 33 string-ci=? 43 procedure 28 string-ci>? 43 procedure call 12 string-copy 44 procedure? 46; 9 string-downcase 44 program parts 23 string-fill! 44 promise 17 string-foldcase 44 proper tail recursion 10 string-for-each 47 string-length 43; 31 quasiquote 19; 38 string-map 46 quote 12; 38 string-ni<=? 43 quotient 34 string-ni=? 43 raise-continuable 49 string-ni>? 43 rational? 32; 30 string-ref 43 rationalize 35 string-set! 43; 40 read 52; 38, 57 string-upcase 44 read-bytevector 53 string<=? 43 read-bytevector! 53 string=? 43 read-u8 53 string>? 43 real-part 36 string? 42; 9 real? 32; 30 substring 44 record type definitions 25 symbol->string 40; 10 record types 25 symbol? 40; 9 records 25 syntactic keyword 9; 7, 20 referentially transparent 20 syntax definition 25 region 9; 13, 15, 16, 17 syntax-error 23 remainder 34 syntax-rules 25 rename 26 repl 23 #t 37 reverse 39 tail call 11 round 35 tan 35 round-quotient 34 textual-port? 51 round-remainder 34 token 56 round/ 34 top level environment 28; 9 true 9; 13, 14, 37 scheme-report-environment 50 truncate 35 set! 13; 24, 60 truncate-quotient 34 set-car! 38 truncate-remainder 34 set-cdr! 38 truncate/ 34 setcar 61 type 9 simplest rational 35 sin 35 u8-ready? 53 sqrt 35 unbound 9; 12, 24 string 43 unless 15 string->list 44 unquote 38 string->number 37 unquote-splicing 38 string->symbol 40 unspecified 6 string->utf8 46 utf8->string 46 string->vector 45 string-append 44 valid indexes 42; 44, 45 Index 81 values 48; 12 variable 9; 7, 12 vector 44 vector->list 45 vector->string 45 vector-copy 45 vector-fill! 45 vector-for-each 47 vector-length 45; 31 vector-map 47 vector-ref 45 vector-set! 45 vector? 44; 9 when 14 whitespace 8 with-exception-handler 49 with-input-from-file 51 with-output-to-file 51 write 54; 20 write-bytevector 54 write-char 54 write-partial-bytevector 54 write-simple 54 write-u8 54

#x 32; 57 zero? 33