Revised Rep ort on the Algorithmic Language

Scheme

JONATHAN REES AND WILLIAM CLINGER Editors

H ABELSON R K DYBVIG C HAYNES G J ROZAS

N I ADAMS IV D P FRIEDMAN E KOHLBECKER G J SUSSMAN

D H BARTLEY R HALSTEAD D OXLEY M WAND

G BROOKS C HANSON K M PITMAN

Dedicated to the Memory of ALGOL

CONTENTS SUMMARY

Introduction

The rep ort gives a dening description of the program

Overview of Scheme

ming language Scheme Scheme is a statically scop ed and

Semantics

prop erly tailrecursive dialect of the Lisp programming

Syntax

language invented by Guy Lewis Steele Jr and Gerald

Notation and terminology

Jay Sussman It was designed to have an exceptionally

Lexical conventions

clear and simple semantics and few dierent ways to form

Identiers

expressions A wide variety of programming paradigms in

Whitespace and comments

cluding imp erative functional and message passing styles

Other notations

nd convenient expression in Scheme

Basic concepts

The introduction oers a brief history of the language and

Variables and regions

of the rep ort

True and false

External representations

The rst three chapters present the fundamental ideas of

Expressions

the language and describ e the notational conventions used

Primitive expression types

for describing the language and for writing programs in the

Derived expression types

language

Program structure

Chapters and describ e the syntax and semantics of

Programs

expressions programs and denitions

Denitions

Standard pro cedures

Chapter describ es Schemes builtin pro cedures which

Bo oleans

include all of the languages data manipulation and in

Equivalence predicates

putoutput primitives

Pairs and lists

Chapter provides a formal syntax for Scheme written in

Symbols

extended BNF along with a formal denotational semantics

Numbers

The rep ort concludes with an example of the use of the

Characters

language and an alphab etic index

Strings

Vectors

Control features

Input and output

Formal syntax and semantics

Formal syntax

Formal semantics

Derived expression types

Notes

Example

Bibliography and references

Alphab etic index of denitions of concepts

keywords and pro cedures

Revised Scheme

INTRODUCTION

Programming languages should b e designed not by piling agenda for the workshop but was unable to attend the ses

feature on top of feature but by removing the weaknesses sions

and restrictions that make additional features app ear nec

Subsequent electronic mail discussions and committee work

essary Scheme demonstrates that a very small number of

completed the denition of the language Gerry Sussman

rules for forming expressions with no restrictions on how

drafted the section on numbers Chris Hanson drafted the

they are comp osed suce to form a practical and ecient

sections on characters and strings and Gary Bro oks and

that is exible enough to supp ort

William Clinger drafted the sections on input and output

most of the ma jor programming paradigms in use to day

William Clinger recorded the decisions of the workshop and

compiled the pieces into a coherent do cument The Re

Scheme has inuenced the evolution of Lisp Scheme was

vised revised rep ort on Scheme was published at MIT

one of the rst programming languages to incorp orate rst

and Indiana University in the summer of Another

class pro cedures as in the lambda calculus thereby proving

round of revision in the spring of again accomplished

the usefulness of static scop e rules and blo ck structure in

almost entirely by electronic mail resulted in the present

a dynamically typed language Scheme was the rst ma jor

rep ort

dialect of Lisp to distinguish pro cedures from lambda ex

pressions and symbols to use a single lexical environment

We intend this rep ort to b elong to the entire Scheme com

for all variables and to evaluate the op erator p osition of

munity and so we grant p ermission to copy it in whole or in

a pro cedure call in the same way as an op erand p osition

part without fee In particular we encourage implementors

By relying entirely on pro cedure calls to express iteration

of Scheme to use this rep ort as a starting p oint for manuals

Scheme emphasized the fact that tailrecursive pro cedure

and other do cumentation mo difying it as necessary

calls are essentially gotos that pass arguments Scheme

was the rst widely used programming language to em

Acknowledgements

brace rst class escap e pro cedures from which all known

sequential control structures can b e synthesized A few

We would like to thank the following p eople for their

of these innovations have recently b een incorp orated into

comments and criticisms Alan Bawden George Carrette

Common Lisp while others remain to b e adopted

Andy Cromarty Andy Freeman Richard Gabriel Yekta

Gursel Ken Haase Paul Hudak Richard Kelsey Chris

Lindblad Mark Meyer Jim Miller Jim Philbin John

Background

Ramsdell Guy Lewis Steele Jr Julie Sussman Perry Wa

The rst description of Scheme was written in A

gle Daniel Weise and Henry Wu We thank Carol Fes

revised rep ort app eared in which describ ed the

senden Daniel Friedman and Christopher Haynes for p er

evolution of the language as its MIT implementation was

mission to use text from the Scheme version reference

upgraded to supp ort an innovative Three

manual We thank Texas Instruments Inc for p ermission

distinct pro jects b egan in and to use variants

to use text from the TI Scheme Language Reference Man

of Scheme for courses at MIT Yale and Indiana Univer

ual We gladly acknowledge the inuence of manuals for

sity An introductory text

MIT Scheme T Scheme and Algol

b o ok using Scheme was published in

We also thank Betty Dexter for the extreme eort she put

As might b e exp ected of a language used primarily for ed

into setting this rep ort in T X and Donald Knuth for de

E

ucation and research Scheme has always evolved rapidly

signing the program that caused her troubles

This was no problem when Scheme was used only within

The Articial Intelligence Lab oratory of the Massachusetts

MIT but as Scheme b ecame more widespread lo cal di

Institute of Technology and the Computer Science Depart

alects b egan to diverge until students and researchers o c

ment of Indiana University supp orted the preparation of

casionally found it dicult to understand co de written at

this rep ort Supp ort for the MIT work was provided in

other sites

part by the Advanced Research Pro jects Agency of the

Fifteen representatives of the ma jor implementations of

Department of Defense under Oce of Naval Research con

Scheme therefore met in Octob er to work toward

tract NC Supp ort for the Indiana Univer

a b etter and more widely accepted standard for Scheme

sity work was provided by NSF grants NCS and

Participating in this workshop were Hal Ab elson Nor

NCS

man Adams David Bartley Gary Bro oks William Clinger

Daniel Friedman Rob ert Halstead Chris Hanson Christo

pher Haynes Eugene Kohlb ecker Don Oxley Jonathan

Rees Guillermo Rozas and Mitchell

Wand Kent Pitman made valuable contributions to the

Overview of Scheme

DESCRIPTION OF THE LANGUAGE

Overview of Scheme ML C and APL are three other languages that always

pass arguments by value This is distinct from the lazy

evaluation semantics of SASL or the callbyname seman

Semantics

tics of Algol where an argument expression is not eval

This section gives an overview of Schemes semantics A

uated unless its value is needed by the pro cedure

detailed informal semantics is the sub ject of chapters

through For reference purp oses section provides a

Syntax

formal semantics of Scheme

Scheme employs a parenthesizedlist Polish notation to de

Following Algol Scheme is a statically scop ed program

scrib e programs and other data The syntax of Scheme

ming language Each use of a variable is asso ciated with a

like that of most Lisp dialects provides for great expressive

lexically apparent binding of that variable

p ower largely due to its simplicity An imp ortant conse

Scheme has latent as opp osed to manifest types Types

quence of this simplicity is the susceptibility of Scheme

are asso ciated with values also called ob jects rather than

programs and data to uniform treatment by other Scheme

with variables Some authors refer to languages with

programs As with other Lisp dialects the read primitive

latent types as weakly typed or dynamically typed lan

parses its input that is it p erforms syntactic as well as

guages Other languages with latent types are APL

lexical decomp osition of what it reads

Snob ol and other dialects of Lisp Languages with mani

fest types sometimes referred to as strongly typed or stat

ically typed languages include Algol Pascal and C

Notation and terminology

All ob jects created in the course of a Scheme computation

Essential and nonessential features

including pro cedures and continuations have unlimited ex

It is required that every implementation of Scheme supp ort

tent No Scheme ob ject is ever destroyed The reason that

features that are marked as b eing essential Features not

implementations of Scheme do not usually run out of

explicitly marked as essential are not essential Implemen

storage is that they are p ermitted to reclaim the storage

tations are free to omit nonessential features of Scheme

o ccupied by an ob ject if they can prove that the ob ject

or to add extensions provided the extensions are not in

cannot p ossibly matter to any future computation Other

conict with the language rep orted here

languages in which most ob jects have unlimited extent in

clude APL and other Lisp dialects

Error situations and unsp ecied b ehavior

Implementations of Scheme are required to b e prop erly

When sp eaking of an error situation this rep ort uses the

tailrecursive This allows the execution of an iterative

phrase an error is signalled to indicate that implemen

computation in constant space even if the iterative compu

tations must detect and rep ort the error If such wording

tation is describ ed by a syntactically recursive pro cedure

do es not app ear in the discussion of an error then imple

Thus with a tailrecursive implementation iteration can b e

mentations are not required to detect or rep ort the error

expressed using the ordinary pro cedurecall mechanics so

though they are encouraged to do so An error situation

that sp ecial iteration constructs are useful only as syntactic

that implementations are not required to detect is usually

sugar

referred to simply as an error

Scheme pro cedures are ob jects in their own right Pro

For example it is an error for a pro cedure to b e passed an

cedures can b e created dynamically stored in data struc

argument that the pro cedure is not explicitly sp ecied to

tures returned as results of pro cedures and so on Other

handle even though such domain errors are seldom men

languages with these prop erties include Common Lisp and

tioned in this rep ort Implementations may extend a pro

ML

cedures domain of denition to include other arguments

One distinguishing feature of Scheme is that continuations

If the value of an expression is said to b e unsp ecied

which in most other languages only op erate b ehind the

then the expression must evaluate to some ob ject without

scenes also have rstclass status Continuations are

signalling an error but the value dep ends on the imple

useful for implementing a wide variety of advanced control

mentation this rep ort explicitly do es not say what value

constructs including nonlo cal exits backtracking and

should b e returned

coroutines See section

Arguments to Scheme pro cedures are always passed by

Entry format

value which means that the actual argument expressions

are evaluated b efore the pro cedure gains control whether Chapters and are organized into entries Each entry de

the pro cedure needs the result of the evaluation or not scrib es one language feature or a group of related features

Revised Scheme

where a feature is either a syntactic construct or a builtin Evaluation examples

pro cedure An entry b egins with one or more header lines

The symbol used in program examples should b e

of the form

read evaluates to For example

template essential category

if the feature is an essential feature or simply

means that the expression evaluates to the ob

template category

ject Or more precisely the expression given by the

sequence of characters evaluates in the initial

if the feature is not an essential feature

environment to an ob ject that may b e represented exter

If category is syntax the entry describ es an expression

nally by the sequence of characters See section

type and the header line gives the syntax of the expression

for a discussion of external representations of ob jects

type Comp onents of expressions are designated by syn

tactic variables which are written using angle brackets

Lexical conventions

for example hexpressioni hvariablei Syntactic variables

should b e understo o d to denote segments of program text

This section gives an informal account of some of the lexical

for example hexpressioni stands for any string of charac

conventions used in writing Scheme programs For a formal

ters which is a syntactically valid expression The notation

syntax of Scheme see section

hthing i

Upp er and lower case forms of a letter are never distin

guished except within character and string constants For

indicates zero or more o ccurrences of a hthingi and

example Foo is the same identier as FOO and xAB is

hthing i hthing i

the same number as Xab

indicates one or more o ccurrences of a hthingi

Identiers

If category is pro cedure then the entry describ es a pro

cedure and the header line gives a template for a call to the

Most identiers allowed by other programming languages

pro cedure Argument names in the template are italicized

are also acceptable to Scheme The precise rules for form

Thus the header line

ing identiers vary among implementations of Scheme but

in all implementations a sequence of letters digits and ex

vectorref vector k essential pro cedure

tended alphab etic characters that b egins with a character

indicates that the essential builtin pro cedure vectorref

that cannot b egin a number is an identier In addition

takes two arguments a vector vector and an exact non

and which can b egin numbers are identiers Here are

negative integer k see b elow The header lines

some examples of identiers

append list list essential pro cedure

lambda q

append list pro cedure

listvector soup

Va

indicate that in all implementations the append pro cedure

akTMNs

must b e dened to take two arguments and some imple

thewordrecursionhasmany meani ngs

mentations will extend it to take zero or more arguments

Extended alphab etic characters may b e used in identiers

It is an error for an op eration to b e presented with an ar

exactly as if they were letters The following are extended

gument that it is not sp ecied to handle For succinctness

alphab etic characters

we follow the convention that if an argument name is also

the name of a type then this implies a restriction on the

type of that argument to the pro cedure For example the

See section for a formal syntax of identiers

header line for vectorref given ab ove dictates that rst

Identiers have several uses within Scheme programs

argument to vectorref must b e a vector The following

naming conventions also imply type restrictions

Certain identiers are reserved for use as syntactic

keywords see b elow

obj any ob ject

z z z complex real rational integer

j

Any identier that is not a syntactic keyword may b e

x x x real rational integer

j

used as a variable see section

y y y real rational integer

j

q q q rational integer

j

When an identier app ears as a literal or within a

n n n integer

j

literal see section it is b eing used to denote a

k k k exact nonnegative integer

j

symbol see section

Basic concepts

The following identiers are syntactic keywords and delimited plus or minus sign by itself is also an identi

should not b e used as variables er A delimited p erio d not o ccurring within a num

b er or identier is used in the notation for pairs sec

do or

tion and to indicate a restparameter in a formal

and else quasiquote

parameter list section

begin if quote

case lambda set

Parentheses are used for grouping and to notate lists

cond let unquote

section

define let unquotesplicing

delay letrec

The single quote character is used to indicate literal data

section

Some implementations allow all identiers including syn

tactic keywords to b e used as variables This is a com

The backquote character is used to indicate almost

patible extension to the language but ambiguities in the

constant data section

language result when the restriction is relaxed and the

ways in which these ambiguities are resolved vary b etween

The character comma and the sequence comma at

implementations

sign are used in conjunction with backquote sec

tion

The characters and have no sp ecial prop ertiesthey

are extended alphab etic characters By convention how

The double quote character is used to delimit strings

ever most predicate pro cedures those that return b o olean

section

values are named by identiers that end in and most

data mutation pro cedures are named by identiers that end

Backslash is used in the syntax for character constants

in

and as an escap e character within string constants

section

Whitespace and comments

Left and right square brackets and curly braces

are reserved for p ossible future extensions to the lan

Whitespace characters are spaces and newlines Imple

guage

mentations typically provide additional whitespace char

acters such as tab or page break Whitespace is used for

Sharp sign is used for a variety of purp oses dep ending

improved readability and as necessary to separate tokens

on the character that immediately follows it

from each other a token b eing an indivisible lexical unit

such as an identier or number but is otherwise insigni

t f These are the b o olean constants section

cant Whitespace may o ccur b etween any two tokens but

not within a token Whitespace may also o ccur inside a

This introduces a character constant section

string where it is signicant

This introduces a vector constant section Vector

A semicolon indicates the start of a comment The

constants are terminated by

comment continues to the end of the line on which the

semicolon app ears Comments are invisible to Scheme but

e i l s b o d x These are used in the nota

the end of the line is visible as whitespace This prevents a

tion for numbers section

comment from app earing in the middle of an identier or

number

Basic concepts

The FACT procedure computes the factorial

of a nonnegative integer

Variables and regions

define fact

lambda n

Any identier that is not a syntactic keyword see sec

if n

tion may b e used as a variable A variable may name

Base case return

a lo cation where a value can b e stored A variable that

n fact n

do es so is said to b e bound to the lo cation The set of all

such bindings in eect at some p oint in a program is known

Other notations

as the environment in eect at that p oint The value stored

in the lo cation to which a variable is b ound is called the

For a description of the notations used for numbers see

variables value By abuse of terminology the variable is

section

sometimes said to name the value or to b e b ound to the

These are used in numbers and may also o ccur any value This is not quite accurate but confusion rarely re

where in an identier except as the rst character A sults from this practice

Revised Scheme

Certain expression types are used to create new lo cations External representations can also b e used for input and

and to bind variables to those lo cations The most funda output The pro cedure read section parses ex

mental of these binding constructs is the lambda expres ternal representations and the pro cedure write sec

sion b ecause all other binding constructs can b e explained tion generates them Together they provide an

in terms of lambda expressions The other binding con elegant and p owerful inputoutput facility

structs are let let letrec and do expressions see sec

Note that the sequence of characters is not an

tions and

external representation of the integer even though it is an

Like Algol and Pascal and unlike most other dialects of

expression evaluating to the integer rather it is an exter

Lisp except for Common Lisp Scheme is a statically scop ed

nal representation of a threeelement list the elements of

language with blo ck structure To each place where a vari

which are the symbol and the integers and Schemes

able is b ound in a program there corresp onds a region of the

syntax has the prop erty that any sequence of characters

program text within which the binding is eective The re

which is an expression is also the external representation

gion is determined by the particular binding construct that

of some ob ject This can lead to confusion since it may

establishes the binding if the binding is established by a

not b e obvious out of context whether a given sequence of

lambda expression for example then its region is the en

characters is intended to denote data or program but it is

tire lambda expression Every reference to or assignment

also a source of p ower since it facilitates writing programs

of a variable refers to the binding of the variable that es

such as interpreters and which treat programs as

tablished the innermost of the regions containing the use

data or vice versa

If there is no binding of the variable whose region contains

The syntax of external representations of various kinds of

the use then the use refers to the binding for the variable

ob jects accompanies the description of the primitives for

in the top level environment if any section if there is

manipulating the ob jects in the appropriate sections of

no binding for the identier it is said to b e unbound

chapter

True and false

Expressions

Any Scheme value can b e used as a b o olean value for the

purp ose of a conditional test As explained in section

A Scheme expression is a construct that returns a value

all values count as true in such a test except for f and

such as a variable reference literal pro cedure call or con

the empty list which count as false This rep ort uses the

ditional

word true to refer to any Scheme value that counts as

true and the word false to refer to any Scheme value

Expression types are categorized as primitive or derived

that counts as false

Primitive expression types include variables and pro cedure

calls Derived expression types are not semantically primi

tive but can instead b e explained in terms of the primitive

External representations

constructs as in section They are redundant in the

strict sense of the word but they capture common pat

An imp ortant concept in Scheme and Lisp is that of the

terns of usage and are therefore provided as convenient

external representation of an ob ject as a sequence of char

abbreviations

acters For example an external representation of the inte

ger is the sequence of characters and an external

representation of a list consisting of the integers and

Primitive expression types

is the sequence of characters

Variable references

The external representation of an ob ject is not necessarily

unique The integer also has representations

and xc and the list in the previous paragraph also has

hvariablei essential syntax

the representations and

An expression consisting of a variable section is a

see section

variable reference The value of the variable reference is

Many ob jects have standard external representations but

the value stored in the lo cation to which the variable is

some such as pro cedures do not have standard represen

b ound It is an error to reference an unbound variable

tations although particular implementations may dene

representations for them

define x

x

An external representation may b e written in a program to

obtain the corresp onding ob ject see quote section

Expressions

Literal expressions Note In many dialects of Lisp the empty combination

is a legitimate expression In Scheme combinations must have

quote hdatumi essential syntax

at least one sub expression so is not a syntactically valid

hdatumi essential syntax

expression

hconstanti essential syntax

Lambda expressions

quote hdatumi evaluates to hdatumi hDatumi may b e

any external representation of a Scheme ob ject see sec

lambda hformalsi hb o dyi essential syntax

tion This notation is used to include literal constants

Syntax hFormalsi should b e a formal arguments list as

in Scheme co de

describ ed b elow and hb o dyi should b e a sequence of one

quote a a

or more expressions

quote a b c a b c

Semantics A lambda expression evaluates to a pro cedure

quote

The environment in eect when the lambda expression was

quote hdatumi may b e abbreviated as hdatumi The

evaluated is remembered as part of the pro cedure When

two notations are equivalent in all resp ects

the pro cedure is later called with some actual arguments

the environment in which the lambda expression was evalu

a a

ated will b e extended by binding the variables in the formal

a b c a b c

argument list to fresh lo cations the corresp onding actual

quote a quote a

argument values will b e stored in those lo cations and the

a quote a

expressions in the b o dy of the lambda expression will b e

evaluated sequentially in the extended environment The

Numeric constants string constants character constants

result of the last expression in the b o dy will b e returned

and b o olean constants evaluate to themselves they need

as the result of the pro cedure call

not b e quoted

lambda x x x a procedure

abc abc

lambda x x x

abc abc

define reversesubtract

lambda x y y x

t t

reversesubtract

t t

define foo

It is an error to alter a constant ie the value of a literal

let x

expression using a mutation pro cedure like setcar or

lambda y x y

stringset

foo

Pro cedure calls

hFormalsi should have one of the following forms

hvariable i The pro cedure takes a xed num

hop eratori hop erand i essential syntax

b er of arguments when the pro cedure is called the

A pro cedure call is written by simply enclosing in parenthe

arguments will b e stored in the bindings of the corre

ses expressions for the pro cedure to b e called and the ar

sp onding variables

guments to b e passed to it The op erator and op erand ex

pressions are evaluated in an indeterminate order and the

hvariablei The pro cedure takes any number of ar

resulting pro cedure is passed the resulting arguments

guments when the pro cedure is called the sequence

of actual arguments is converted into a newly allo

if f

cated list and the list is stored in the binding of the

hvariablei

A number of pro cedures are available as the values of vari

ables in the initial environment for example the addition

hvariable i hvariable i hvariable i If a

n n

and multiplication pro cedures in the ab ove examples are

spacedelimited p erio d precedes the last variable then

the values of the variables and New pro cedures are cre

the value stored in the binding of the last variable will

ated by evaluating lambda expressions see section

b e a newly allo cated list of the actual arguments left

over after all the other actual arguments have b een

Pro cedure calls are also called combinations

matched up against the other formal arguments

Note In contrast to other dialects of Lisp the order of

lambda x x

evaluation is unsp ecied and the op erator expression and the

lambda x y z z

op erand expressions are always evaluated with the same evalu

ation rules

Revised Scheme

hclausei contains only the htesti and no hexpressionis then Conditionals

the value of the htesti is returned as the result If all htestis

if htesti hconsequenti halternatei essential syntax

evaluate to false values and there is no else clause then

if htesti hconsequenti syntax

the result of the conditional expression is unsp ecied if

there is an else clause then its hexpressionis are evaluated

Syntax hTesti hconsequenti and halternatei may b e arbi

and the value of the last one is returned

trary expressions

Semantics An if expression is evaluated as follows rst

cond greater

htesti is evaluated If it yields a true value see section

less greater

cond greater

then hconsequenti is evaluated and its value is returned

less

Otherwise halternatei is evaluated and its value is returned

else equal equal

If htesti yields a false value and no halternatei is sp ecied

then the result of the expression is unsp ecied

Some implementations supp ort an alternative hclausei syn

if yes no yes

tax htesti hrecipienti where hrecipienti is an expres

if yes no no

sion If htesti evaluates to a true value then hrecipienti is

if

evaluated Its value must b e a pro cedure of one argument

this pro cedure is then invoked on the value of the htesti

cond assv b a b cadr

Assignments

else f

set hvariablei hexpressioni essential syntax

hExpressioni is evaluated and the resulting value is stored

case hkeyi hclause i hclause i syntax

in the lo cation to which hvariablei is b ound hVariablei

Syntax hKeyi may b e any expression Each hclausei

must b e b ound either in some region enclosing the set

should have the form

expression or at top level The result of the set expression

is unsp ecied

hdatum i hexpression i hexpression i

define x

where each hdatumi is an external representation of some

x

ob ject All the hdatumis must b e distinct The last

set x unspecied

hclausei may b e an else clause which has the form

x

else hexpression i hexpression i

Derived expression types

Semantics A case expression is evaluated as follows

hKeyi is evaluated and its result is compared against each

For reference purp oses section gives rewrite rules that

hdatumi If the result of evaluating hkeyi is equivalent

will convert constructs describ ed in this section into the

in the sense of eqv see section to a hdatumi then

primitive constructs describ ed in the previous section

the expressions in the corresp onding hclausei are evaluated

from left to right and the result of the last expression in

Conditionals

the hclausei is returned as the result of the case expres

sion If the result of evaluating hkeyi is dierent from every

cond hclause i hclause i essential syntax

hdatumi then if there is an else clause its expressions are

Syntax Each hclausei should b e of the form

evaluated and the result of the last is the result of the case

expression otherwise the result of the case expression is

htesti hexpressioni

unsp ecied

where htesti is any expression The last hclausei may b e

an else clause which has the form

case

else hexpression i hexpression i

prime

composite composite

Semantics A cond expression is evaluated by evaluating

case car c d

the htesti expressions of successive hclauseis in order until

a a

one of them evaluates to a true value see section

b b unspecied

When a htesti evaluates to a true value then the remaining

case car c d

hexpressionis in its hclausei are evaluated in order and the

a e i o u vowel

result of the last hexpressioni in the hclausei is returned

w y semivowel

as the result of the entire cond expression If the selected else consonant consonant

Expressions

and htest i syntax let x y

x y

The htesti expressions are evaluated from left to right and

the value of the rst expression that evaluates to a false

let x y

value see section is returned Any remaining expres

let foo lambda z x y z

sions are not evaluated If all the expressions evaluate to

x

foo

true values the value of the last expression is returned If

there are no expressions then t is returned

See also named let section

and t

and f

and c f g f g

let hbindingsi hb o dyi syntax

and t

Syntax hBindingsi should have the form

hvariable i hinit i

or htest i syntax

and hb o dyi should b e a sequence of one or more expres

sions

The htesti expressions are evaluated from left to right and

the value of the rst expression that evaluates to a true

Semantics Let is similar to let but the bindings are

value see section is returned Any remaining expres

p erformed sequentially from left to right and the region of

sions are not evaluated If all expressions evaluate to false

a binding indicated by hvariablei hiniti is that part of

values the value of the last expression is returned If there

the let expression to the right of the binding Thus the

are no expressions then f is returned

second binding is done in an environment in which the rst

binding is visible and so on

or t

or t

let x y x

or f f f f

y

or memq b a b c

b c

letrec hbindingsi hb o dyi essential syntax

Binding constructs

Syntax hBindingsi should have the form

hvariable i hinit i

The three binding constructs let let and letrec give

Scheme a blo ck structure like Algol The syntax of the

and hb o dyi should b e a sequence of one or more expres

three constructs is identical but they dier in the regions

sions

they establish for their variable bindings In a let ex

pression the initial values are computed b efore any of the Semantics The hvariableis are b ound to fresh lo cations

variables b ecome b ound in a let expression the bind holding undened values the hinitis are evaluated in the

ings and evaluations are p erformed sequentially while in resulting environment in some unsp ecied order each

a letrec expression the bindings are in eect while their

hvariablei is assigned to the result of the corresp onding

initial values are b eing computed thus allowing mutually hiniti the hb o dyi is evaluated in the resulting environment

recursive denitions and the value of the last expression in hb o dyi is returned

Each binding of a hvariablei has the entire letrec expres

sion as its region making it p ossible to dene mutually

let hbindingsi hb o dyi essential syntax

recursive pro cedures

Syntax hBindingsi should have the form

letrec even

lambda n

hvariable i hinit i

if zero n

where each hiniti is an expression and hb o dyi should b e a

t

sequence of one or more expressions

odd n

odd

Semantics The hinitis are evaluated in the current envi

lambda n

ronment in some unsp ecied order the hvariableis are

if zero n

b ound to fresh lo cations holding the results the hb o dyi is

f

evaluated in the extended environment and the value of

even n

the last expression of hb o dyi is returned Each binding of

even

t a hvariablei has hb o dyi as its region

Revised Scheme

One restriction on letrec is very imp ortant it must b e The region of the binding of a hvariablei consists of the

p ossible to evaluate each hiniti without referring to the entire do expression except for the hinitis

value of any hvariablei If this restriction is violated then

A hstepi may b e omitted in which case the eect is the

the eect is undened and an error may b e signalled dur

same as if hvariablei hiniti hvariablei had b een written

ing evaluation of the hinitis The restriction is necessary

instead of hvariablei hiniti

b ecause Scheme passes arguments by value rather than by

name In the most common uses of letrec all the hinitis

do vec makevector

are lambda expressions and the restriction is satised au

i i

tomatically

i vec

vectorset vec i i

Sequencing

let x

do x x cdr x

begin hexpression i hexpression i essential syntax

sum sum car x

null x sum

The hexpressionis are evaluated sequentially from left to

right and the value of the last hexpressioni is returned

This expression type is used to sequence side eects such

let hvariablei hbindingsi hb o dyi syntax

as input and output

Some implementations of Scheme p ermit a variant on the

begin set x

syntax of let called named let which provides a more

x

general lo oping construct than do and may also b e used

to express recursions

begin display plus equals

display unspecied

Named let has the same syntax and semantics as ordi

and prints plus equals

nary let except that hvariablei is b ound within hb o dyi to

a pro cedure whose formal arguments are the b ound vari

Note uses the keyword sequence instead of begin

ables and whose b o dy is hb o dyi Thus the execution of

hb o dyi may b e rep eated by invoking the pro cedure named

Iteration

by hvariablei

do hvariable i hinit i hstep i syntax

let loop numbers

nonneg

htesti hexpressioni

neg

hcommandi

cond null numbers list nonneg neg

car numbers

Do is an iteration construct It sp ecies a set of variables

loop cdr numbers

to b e b ound how they are to b e initialized at the start

cons car numbers nonneg

and how they are to b e up dated on each iteration When a

neg

termination condition is met the lo op exits with a sp ecied

car numbers

result value

loop cdr numbers

nonneg

Do expressions are evaluated as follows The hiniti ex

cons car numbers neg

pressions are evaluated in some unsp ecied order the

hvariableis are b ound to fresh lo cations the results of

the hiniti expressions are stored in the bindings of the

hvariableis and then the iteration phase b egins

Delayed evaluation

Each iteration b egins by evaluating htesti if the result is

false see section then the hcommandi expressions are

delay hexpressioni syntax

evaluated in order for eect the hstepi expressions are eval

The delay construct is used together with the pro cedure

uated in some unsp ecied order the hvariableis are b ound

force to implement lazy evaluation or call by need delay

to fresh lo cations the results of the hstepis are stored in the

hexpressioni returns an ob ject called a promise which at

bindings of the hvariableis and the next iteration b egins

some p oint in the future may b e asked by the force pro

If htesti evaluates to a true value then the hexpressionis

cedure to evaluate hexpressioni and deliver the resulting

are evaluated from left to right and the value of the last

value

hexpressioni is returned as the value of the do expression

See the description of force section for a complete

If no hexpressionis are present then the value of the do

description of delay

expression is unsp ecied

Program structure

Program structure Quasiquotation

quasiquote htemplatei syntax

Programs

htemplatei syntax

A Scheme program consists of a sequence of expressions

Backquote or quasiquote expressions are useful for

and denitions Expressions are describ ed in chapter

constructing a list or vector structure when most but not

denitions are the sub ject of the rest of the present chapter

all of the desired structure is known in advance If no

Programs are typically stored in les or entered inter

commas app ear within the htemplatei the result of evalu

actively to a running Scheme system although other

ating htemplatei is equivalent to the result of evaluating

paradigms are p ossible questions of user interface lie out

htemplatei If a comma app ears within the htemplatei

side the scop e of this rep ort Indeed Scheme would still b e

however the expression following the comma is evaluated

useful as a notation for expressing computational metho ds

unquoted and its result is inserted into the structure

even in the absence of a mechanical implementation

instead of the comma and the expression If a comma ap

p ears followed immediately by an atsign then the fol

Denitions o ccurring at the top level of a program are inter

lowing expression must evaluate to a list the op ening and

preted declaratively They cause bindings to b e created in

closing parentheses of the list are then stripp ed away and

the top level environment Expressions o ccurring at the top

the elements of the list are inserted in place of the comma

level of a program are interpreted imp eratively they are

atsign expression sequence

executed in order when the program is invoked or loaded

and typically p erform some kind of initialization

list list

let name a list name name

list a quote a

Denitions

a map abs b

a b

Denitions are valid in some but not all contexts where

foo cdr c car cons

expressions are allowed They are valid only at the top

foo cons

level of a hprogrami and in some implementations at the

sqrt map sqrt

b eginning of a hb o dyi

A denition should have one of the following forms

Quasiquote forms may b e nested Substitutions are made

only for unquoted comp onents app earing at the same nest

define hvariablei hexpressioni

ing level as the outermost backquote The nesting level in

This syntax is essential

creases by one inside each successive quasiquotation and

decreases by one inside each unquotation

define hvariablei hformalsi hb o dyi

a b foo d e f

This syntax is not essential hFormalsi should b e ei

a b foo d e f

ther a sequence of zero or more variables or a sequence

of one or more variables followed by a spacedelimited let name x

name y

p erio d and another variable as in a lambda expres

a b name name d e

sion This form is equivalent to

a b x y d e

define hvariablei

lambda hformalsi hb o dyi

The notations htemplatei and quasiquote htemplatei

are identical in all resp ects hexpressioni is identical to

define hvariablei hformali hb o dyi

unquote hexpressioni and hexpressioni is identical to

This syntax is not essential hFormali should b e a

unquotesplicing hexpressioni The external syntax

single variable This form is equivalent to

generated by write for twoelement lists whose car is one

of these symbols may vary b etween implementations

define hvariablei

lambda hformali hb o dyi

quasiquote list unquote

list

Top level denitions

quasiquote list unquote

list

At the top level of a program a denition

ie quasiquote list unquote

define hvariablei hexpressioni

Unpredictable b ehavior can result if any of the symbols

has essentially the same eect as the assignment expres

quasiquote unquote or unquotesplicing app ear in

sion

p ositions within a htemplatei otherwise than as describ ed

ab ove

set hvariablei hexpressioni

Revised Scheme

if hvariablei is b ound If hvariablei is not b ound however Bo oleans

then the denition will bind hvariablei to a new lo cation

The standard b o olean ob jects for true and false are written

b efore p erforming the assignment whereas it would b e an

as t and f What really matters though are the ob jects

error to p erform a set on an unbound variable

that the Scheme conditional expressions if cond and

or do treat as true or false The phrase a true value

define add

or sometimes just true means any ob ject treated as

lambda x x

add true by the conditional expressions and the phrase a false

define first car

value or false means any ob ject treated as false by the

first

conditional expressions

Of all the standard Scheme values only f and the empty

All Scheme implementations must supp ort top level deni

list count as false in conditional expressions Everything

tions

else including t pairs symbols numbers strings vec

Some implementations of Scheme use an initial environ

tors and pro cedures counts as true

ment in which all p ossible variables are b ound to lo cations

The empty list counts as false for compatibility with exist

most of which contain undened values Top level deni

ing programs and implementations that assume this to b e

tions in such an implementation are truly equivalent to

the case

assignments

Programmers accustomed to other dialects of Lisp should

b eware that Scheme distinguishes false and the empty list

Internal denitions

from the symbol nil

Some implementations of Scheme p ermit denitions to o c

Bo olean constants evaluate to themselves so they dont

cur at the b eginning of a hb o dyi that is the b o dy of a

need to b e quoted in programs

lambda let let letrec or define expression Such

t t

denitions are known as internal denitions as opp osed to

f f

the top level denitions describ ed ab ove The variable de

f f

ned by an internal denition is lo cal to the hb o dyi That

is hvariablei is b ound rather than assigned and the region

of the binding is the entire hb o dyi For example

not obj essential pro cedure

let x

Not returns t if obj is false and returns f otherwise

define foo lambda y bar x y

not t f

define bar lambda a b a b a

not f

foo x

not list f

not f t

A hb o dyi containing internal denitions can always b e con

not t

verted into a completely equivalent letrec expression For

not list t

example the let expression in the ab ove example is equiv

alent to

boolean obj essential pro cedure

let x

letrec foo lambda y bar x y

Boolean returns t if obj is either t or f and returns

bar lambda a b a b a

f otherwise

foo x

boolean f t

boolean f

Standard pro cedures

nil variable

This chapter describ es Schemes builtin pro cedures The

t variable

initial or top level Scheme environment starts out with

a number of variables b ound to lo cations containing useful

Some implementations provide variables nil and t whose

values most of which are primitive pro cedures that manip

values in the initial environment are f and t resp ectively

ulate data For example the variable abs is b ound to a

t t

lo cation initially containing a pro cedure of one argument

nil f

that computes the absolute value of a number and the

nil nil

variable is b ound to a pro cedure that computes sums

Standard pro cedures

Equivalence predicates prove that obj and obj are op erationally equivalent If it

cant it always errs on the conservative side and returns

A predicate is a pro cedure that always returns a b o olean

f

value t or f An equivalence predicate is the compu

The only situation in which it might fail to prove is when

tational analogue of a mathematical equivalence relation

obj and obj are op erationally equivalent pro cedures that

it is symmetric reexive and transitive Of the equiva

were created at dierent times In general op erational

lence predicates describ ed in this section eq is the nest

equivalence of pro cedures is uncomputable but it is guar

or most discriminating and equal is the coarsest Eqv

anteed that eqv can recognize a pro cedure created at a

is slightly less discriminating than eq

given time by a given lambda expression as b eing itself

Two ob jects are operationally equivalent if and only if there

This is useful for applications in which pro cedures are b e

is no way that they can b e distinguished using Scheme

ing used to implement ob jects with lo cal state

primitives other than eqv or eq or those like memq and

eqv a a t

assv whose meaning is dened explicitly in terms of eqv

eqv a b f

or eq It is guaranteed that ob jects maintain their op era

eqv t

tional identity despite b eing named by variables or fetched

eqv t

from or stored into data structures

eqv t

This denition can b e interpreted in the following ways for

eqv t

various kinds of ob jects

eqv cons cons f

eqv lambda

The two b o olean values t and f are op erationally

lambda f

distinct b ecause they b ehave in opp osite ways in con

eqv f nil f

ditionals

let p lambda x x

eqv p p t

Two symbols are op erationally equivalent if they print

the same way

The following examples illustrate cases in which eqv is

p ermitted to fail to prove op erational equivalence dep end

Two numbers are op erationally equivalent if they are

ing on the implementation In every case it will return

numerically equal see section and are either

either t or f but which one it returns is implementation

b oth exact or b oth inexact see section

dep endent Compare with the last example in the previ

ous set

Two characters are op erationally equivalent if they are

the same character according to char section

eqv lambda x x

lambda x x unspecied

Two structured mutable ob jectspairs vectors or

eqv lambda x x

stringsare op erationally equivalent if they have op

lambda y y unspecied

erationally equivalent values in corresp onding p osi

The next set of examples shows the use of eqv with pro

tions and applying a mutation pro cedure to one

cedures that have lo cal state Gencounter must return a

causes the other to change as well A mutation pro

distinct pro cedure every time since each pro cedure has its

cedure is one like setcar which alters a data struc

own internal counter Genloser however returns equiv

ture For example two pairs are not op erationally

alent pro cedures each time since the lo cal state do es not

equivalent if a setcar op eration on one do es not

aect the value or side eects of the pro cedures

change the car eld of the other

define gencounter

There is only one empty list and it is op erationally

lambda

equivalent to itself All empty vectors are op era

let n

tionally equivalent to each other All empty strings

lambda set n n n

are op erationally equivalent to each other Whether

let g gencounter

there is more than one empty vector or string is

eqv g g t

implementationdependent

eqv gencounter gencounter

f

Two pro cedures are op erationally equivalent if when

define genloser

called on op erationally equivalent arguments they re

lambda

turn the same value and p erform the same side eects

let n

lambda set n n

let g genloser

eqv obj obj essential pro cedure

eqv g g t

The eqv pro cedure implements an approximation to the

eqv genloser genloser

unspecied relation of op erational equivalence It returns t if it can

Revised Scheme

Note It will usually b e p ossible to implement eq much more Ob jects of distinct types are never op erationally equiva

eciently than eqv for example as a simple p ointer compari lent except that false and the empty list are p ermitted to

son instead of as some more complicated op eration One reason b e identical and the character type need not b e disjoint

is that it may not b e p ossible to compute eqv of two numbers from other types

in constant time whereas eq implemented as p ointer compar

eqv f unspecied

ison will always nish in constant time Eq may b e used like

eqv A unspecied

eqv in applications using pro cedures to implement ob jects with

state since it ob eys the same constraints as eqv

Since it is an error to mo dify constant ob jects those re

turned by literal expressions implementations are p er

mitted though not required to share structure b etween

equal obj obj essential pro cedure

constants where appropriate Thus the value of eqv on

Equal recursively compares the contents of pairs vectors

constants is sometimes implementationdependent

and strings applying eqv on other ob jects such as num

let x a

b ers and symbols A rule of thumb is that ob jects are

eqv x x t

generally equal if they print the same Equal may fail

eqv a a unspecied

to terminate if its arguments are circular data structures

eqv a a unspecied

eqv b cdr a b unspecied

equal a a t

equal a a t

Note The ab ove denition of eqv allows implementations

equal a b c

latitude in their treatment of pro cedures and literals imple

a b c t

mentations are free to either detect or fail to detect that two

equal abc abc t

pro cedures or two literals are op erationally equivalent to each

equal t

other and can decide whether or not to merge representations

equal makevector a

of equivalent ob jects by using the same p ointer or bit pattern

makevector a t

equal lambda x x

to represent b oth

lambda y y unspecied

eq obj obj essential pro cedure

Pairs and lists

Eq is similar to eqv except that in some cases it is capable

of discerning distinctions ner than those detectable by

A pair sometimes called a dotted pair is a record structure

eqv

with two elds called the car and cdr elds for historical

reasons Pairs are created by the pro cedure cons The

Eq and eqv are guaranteed to have the same b ehavior

car and cdr elds are accessed by the pro cedures car and

on symbols b o oleans the empty list pairs and nonempty

cdr The car and cdr elds are assigned by the pro cedures

strings and vectors Eqs b ehavior on numbers and charac

setcar and setcdr

ters is implementationdependent but it will always return

either true or false and will return true only when eqv

Pairs are used primarily to represent lists A list can b e

would also return true Eq may also b ehave dierently

dened recursively as either the empty list or a pair whose

from eqv on empty vectors and empty strings

cdr is a list The ob jects in the car elds of successive

pairs of a list are the elements of the list For example

eq a a t

a twoelement list is a pair whose car is the rst element

eq a a unspecied

and whose cdr is a pair whose car is the second element

eq list a list a f

and whose cdr is the empty list The length of a list is the

eq a a unspecied

eq unspecied

number of elements which is the same as the number of

eq t

pairs

eq unspecied

The empty list is a sp ecial ob ject of its own type it is not

eq A A unspecied

a pair it has no elements and its length is zero

eq car car t

let n

The most general notation external representation for

eq n n unspecied

Scheme pairs is the dotted notation c c where c

let x a

is the value of the car eld and c is the value of the cdr

eq x x t

eld For example is a pair whose car is and

let x

whose cdr is Note that is the external repre

eq x x t

sentation of a pair not an expression that evaluates to a

let p lambda x x

eq p p t pair

Standard pro cedures

A more streamlined notation can b e used for lists the pair obj essential pro cedure

elements of the list are simply enclosed in parentheses and

Pair returns t if obj is a pair and otherwise returns f

separated by spaces The empty list is written For

pair a b t

example

pair a b c t

a b c d e

pair f

pair a b f

and

a b c d e

cons obj obj essential pro cedure

are b oth representations of the same list of symbols

Returns a newly allo cated pair whose car is obj and whose

A chain of pairs not ending in the empty list is called an

cdr is obj The pair is guaranteed to b e dierent in the

improper list Note that an improp er list is not a list

sense of eqv from every existing ob ject

The list and dotted notations can b e combined to represent

cons a a

improp er lists

cons a b c d a b c d

cons a b c a b c

a b c d

cons a a

is equivalent to

cons a b c a b c

a b c d

car pair essential pro cedure

Whether a given pair is a list dep ends up on what is stored

in the cdr eld When the setcdr pro cedure is used an

Returns the contents of the car eld of pair Note that it

ob ject can b e a list one moment and not the next

is an error to take the car of the empty list

car a b c a

define x list a b c

car a b c d a

define y x

car

y a b c

car error

setcdr x unspecied

x a

eqv x y t

cdr pair essential pro cedure

y a

Returns the contents of the cdr eld of pair Note that it

It is often convenient to sp eak of a homogeneous list of ob

is an error to take the cdr of the empty list

jects of some particular data type as for example

is a list of integers To b e more precise supp ose D is some

cdr a b c d b c d

data type Any predicate denes a data type consisting

cdr

of those ob jects of which the predicate is true Then

cdr error

The empty list is a list of D

setcar pair obj essential pro cedure

If list is a list of D then any pair whose cdr is list and

Stores obj in the car eld of pair The value returned by

whose car is an element of the data type D is also a

setcar is unsp ecied

list of D

There are no other lists of D

setcdr pair obj essential pro cedure

Within literal expressions and representations of ob

Stores obj in the cdr eld of pair The value returned by

jects read by the read pro cedure the forms hdatumi

setcdr is unsp ecied

hdatumi hdatumi and hdatumi denote twoele

ment lists whose rst elements are the symbols quote

quasiquote unquote and unquotesplicing resp ec

caar pair essential pro cedure

tively The second element in each case is hdatumi This

cadr pair essential pro cedure

convention is supp orted so that arbitrary Scheme pro

grams may b e represented as lists That is according

cdddar pair essential pro cedure

to Schemes grammar every hexpressioni is also a hdatumi

cddddr pair essential pro cedure

see section Among other things this p ermits the

These pro cedures are comp ositions of car and cdr where use of the read pro cedure to parse Scheme programs See

for example caddr could b e dened by section

Revised Scheme

define caddr lambda x car cdr cdr x define listtail

lambda x k

Arbitrary comp ositions up to four deep are provided

if zero k

There are twentyeight of these pro cedures in all

x

listtail cdr x k

null obj essential pro cedure

listref list k pro cedure

Returns t if obj is the empty list otherwise returns f

Returns the k th element of list This is the same as the

In implementations in which the empty list is the same as

car of listtail list k

f null will return t if obj is f

listref a b c d c

list obj essential pro cedure

lastpair list pro cedure

Returns a list of its arguments

Returns the last pair in the nonempty p ossibly improp er

list a c a c

list list Lastpair could b e dened by

list

define lastpair

lambda x

length list essential pro cedure

if pair cdr x

lastpair cdr x

Returns the length of list

x

length a b c

length a b c d e

memq obj list essential pro cedure

length

memv obj list essential pro cedure

member obj list essential pro cedure

append list list essential pro cedure

These pro cedures return the rst sublist of list whose car

append list pro cedure

is obj If obj do es not o ccur in list f nb not the empty

list is returned Memq uses eq to compare obj with the

Returns a list consisting of the elements of the rst list

elements of list while memv uses eqv and member uses

followed by the elements of the other list s

equal

append x y x y

memq a a b c a b c

append a b c d a b c d

memq b a b c b c

append a b c a b c

memq a b c d f

memq list a b a c f

The resulting list is always newly allo cated except that

member list a

it shares structure with the last list argument The last

b a c a c

argument may actually b e any ob ject an improp er list

memq unspecied

results if it is not a prop er list

memv

append a b c d a b c d

append a a

assq obj alist essential pro cedure

assv obj alist essential pro cedure

assoc obj alist essential pro cedure

reverse list pro cedure

Alist for asso ciation list must b e a list of pairs These

Returns a newly allo cated list consisting of the elements of

pro cedures nd the rst pair in alist whose car eld is obj

list in reverse order

and returns that pair If no pair in alist has obj as its car

reverse a b c c b a

f is returned Assq uses eq to compare obj with the car

reverse a b c d e f

elds of the pairs in alist while assv uses eqv and assoc

e f d b c a

uses equal

define e a b c

assq a e a

listtail list k pro cedure

assq b e b

Returns the sublist of list obtained by omitting the rst k

assq d e f

assq list a a b c elements Listtail could b e dened by

Standard pro cedures

f its name contains alphab etic characters then the string

assoc list a a b c

returned will contain characters in the implementations

a

preferred standard casesome implementations will prefer

assq

upp er case others lower case If the symbol was returned

unspecied

by stringsymbol the case of characters in the string

assv

returned will b e the same as the case in the string that

was passed to stringsymbol It is an error to apply

Note Although they are ordinarily used as predicates memq

mutation pro cedures like stringset to strings returned

memv member assq assv and assoc do not have question

by this pro cedure

marks in their names b ecause they return useful values rather

The following examples assume that the implementations

than just t or f

standard case is lower case

symbolstring flyingfish

Symbols

flyingfish

symbolstring Martin martin

Symbols are ob jects whose usefulness rests on the fact that

symbolstring

two symbols are identical in the sense of eqv if and only

stringsymbol Malvina

if their names are sp elled the same way This is exactly the

Malvina

prop erty needed to represent identiers in programs and

so most implementations of Scheme use them internally for

that purp ose Symbols are useful for many other applica

stringsymbol string essential pro cedure

tions for instance they may b e used the way enumerated

Returns the symbol whose name is string This pro cedure

values are used in Pascal

can create symbols with names containing sp ecial charac

The rules for writing a symbol are exactly the same as the

ters or letters in the nonstandard case but it is usually

rules for writing an identier see sections and

a bad idea to create such symbols b ecause in some imple

It is guaranteed that any symbol that has b een returned as

mentations of Scheme they cannot b e read as themselves

part of a literal expression or read using the read pro ce

See symbolstring

dure and subsequently written out using the write pro ce

The following examples assume that the implementations

dure will read back in as the identical symbol in the sense

standard case is lower case

of eqv The stringsymbol pro cedure however can

eq mISSISSIppi mississippi

create symbols for which this writeread invariance may

t

not hold b ecause their names contain sp ecial characters or

stringsymbol mISSISSIppi

letters in the nonstandard case

the symbol with name mISSISSIppi

Note Some implementations of Scheme have a feature known

eq bitBlt stringsymbol bitBlt

as slashication in order to guarantee writeread invariance

f

for all symbols but historically the most imp ortant use of this

eq JollyWog

feature has b een to comp ensate for the lack of a string data

stringsymbol

type

symbolstring JollyWog

t

Some implementations also have uninterned symbols which

string K Harper MD

defeat writeread invariance even in implementations with

symbolstring

slashication and also generate exceptions to the rule that two

stringsymbol K Harper MD

symbols are the same if and only if their names are sp elled the

t

same

Numbers

symbol obj essential pro cedure

Numerical computation has traditionally b een neglected by

Returns t if obj is a symbol otherwise returns f

the Lisp community Until Common Lisp there has b een

symbol foo t

no carefully thought out strategy for organizing numeri

symbol car a b t

cal computation and with the exception of the

symbol bar f

system there has b een little eort to execute numeri

cal co de eciently We applaud the excellent work of the

symbolstring symbol essential pro cedure

Common Lisp committee and we accept many of their rec

ommendations In some ways we simplify and generalize Returns the name of symbol as a string If the symbol was

their prop osals in a manner consistent with the purp oses part of an ob ject returned as the value of a literal expres

of Scheme sion section or by a call to the read pro cedure and

Revised Scheme

Schemes numerical op erations treat numbers as abstract Not all implementations of Scheme must provide the whole

data as indep endent of their representation as is p ossible tower but they must implement a coherent subset consis

Thus the casual user should b e able to write simple pro tent with b oth the purp oses of the implementation and the

grams without having to know that the implementation spirit of the Scheme language

may use xedp oint oatingp oint and p erhaps other rep

resentations for his data Unfortunately this illusion of

Exactness

uniformity can b e sustained only approximatelythe im

Numbers are either exact or inexact A number is exact

plementation of numbers will leak out of its abstraction

if it was derived from exact numbers using only exact

whenever the user must b e in control of precision or accu

op erations A number is inexact if it mo dels a quantity

racy or when he must construct esp ecially ecient com

eg a measurement known only approximately if it was

putations Thus the language must also provide escap e

derived using inexact ingredients or if it was derived us

mechanisms so that a sophisticated programmer can exer

ing inexact op erations Thus inexactness is a contagious

cise more control over the execution of his co de and the

prop erty of a number Some op erations such as the square

representation of his data when necessary

ro ot of nonsquare numbers must b e inexact b ecause of

It is imp ortant to distinguish b etween the abstract num

the nite precision of our representations Other op era

b ers their machine representations and their written rep

tions are inexact b ecause of implementation requirements

resentations We will use mathematical terms number

We emphasize that exactness is indep endent of the p osi

complex real rational and integer for prop erties of

tion of the number on the tower It is p erfectly p ossible to

the abstract numbers the names fixnum bignum ratnum

have an inexact integer or an exact real may

and flonum for machine representations and the names

b e an exact rational or it may b e an inexact rational

int fix flo sci rat polar and rect for inputoutput

approximation to pi dep ending on the application

formats

Op erationally it is the systems resp onsibility to combine

exact numbers using exact metho ds such as innite pre

cision integer and rational arithmetic where p ossible An

Numbers

implementation may not b e able to do this if it do es not

A Scheme system provides data of type number which is

use innite precision integers and rationals but if a num

the most general numerical type supp orted by that sys

b er b ecomes inexact for implementation reasons there is

tem Number is likely to b e a complicated union type im

likely to b e an imp ortant error condition such as integer

plemented in terms of fixnums bignums flonums and so

overow to b e rep orted Arithmetic on inexact numbers

forth but this should not b e apparent to a naive user

is not so constrained The system may use oating p oint

What the user should see is that the usual op erations

and other illb ehaved representation strategies for inexact

on numbers pro duce the mathematically exp ected results

numbers This is not to say that implementors need not

within the limits of the implementation Thus if the user

use the b est known algorithms for inexact computations

divides the exact number by the exact number he

only that approximate metho ds of high quality are allowed

should get something like or the exact fraction

In a system that cannot explicitly distinguish exact from

If he adds that result to itself and the implementation is

inexact numbers the system must do its b est to main

go o d enough he should get an exact

tain precision Scheme systems must not burden users

with numerical op erations describ ed in terms of hardware

Mathematically numbers may b e arranged into a tower of

and op eratingsystem dep endent representations such as

subtypes with pro jections and injections relating adjacent

fixnum and flonum however b ecause these representation

levels of the tower

issues are hardly ever germane to the users problems

We highly recommend that the IEEE bit and bit

number

oatingp oint standards b e adopted for implementations

complex

that use oatingp oint representations internally To min

real

imize loss of precision we adopt the following rules If an

rational

implementation uses several dierent sizes of oatingp oint

integer

formats the results of any op eration with a oatingp oint

result must b e expressed in the largest format used to ex

We imp ose a uniform rule of downward co erciona num press any of the oatingp oint arguments to that op eration

b er of one type is also of a lower type if the injection up It is desirable but not required for p otentially irrational

of the pro jection down of a number leaves the number op erations such as sqrt when applied to exact arguments

unchanged Since this tower is a genuine mathematical to pro duce exact answers whenever p ossible for example

structure Scheme provides predicates and pro cedures to the square ro ot of an exact ought to b e an exact If

access the tower an exact number or an inexact number represented as

Standard pro cedures

a fixnum a bignum or a ratnum is op erated up on so as number obj essential pro cedure

to pro duce an inexact result as by sqrt and if the re complex obj essential pro cedure

sult is represented as a flonum then the largest available real obj essential pro cedure

flonum format must b e used but if the result is expressed rational obj essential pro cedure

as a ratnum then the rational approximation must have at integer obj essential pro cedure

least as much precision as the largest available flonum

These numerical type predicates can b e applied to any kind

of argument including nonnumbers They return true if

the ob ject is of the named type In general if a type pred

Number syntax

icate is true of a number then all higher type predicates

Scheme allows the traditional ways of writing numerical

are also true of that number Not every system supp orts

constants though any particular implementation may sup

all of these types for example it is entirely p ossible to

p ort only some of them These syntaxes are intended to

have a Scheme system that has only integers Nonethe

b e purely notational any kind of number may b e written

less every implementation of Scheme must have all of these

in any form that the user deems convenient Of course

predicates

writing as a limitedprecision decimal fraction will not

express the number exactly but this approximate form of

zero z essential pro cedure

expression may b e just what the user wants to see

positive x essential pro cedure

The syntax of numbers is describ ed formally in sec

negative x essential pro cedure

tion See section for many examples of rep

odd n essential pro cedure

resentations of numbers

even n essential pro cedure

exact z essential pro cedure

A numerical constant may b e represented in binary o ctal

inexact z essential pro cedure

decimal or hex by the use of a radix prex The radix

These numerical predicates test a number for a particular

prexes are b binary o o ctal d decimal and x

prop erty returning t or f

hex With no radix prex a number is assumed to b e

expressed in decimal

z z essential pro cedure

A numerical constant may b e sp ecied to b e either exact

x x essential pro cedure

or inexact by a prex The prexes are e for exact and

x x essential pro cedure

i for inexact An exactness prex may app ear b efore or

x x essential pro cedure

after any radix prex that is used If the representation of

x x essential pro cedure

a numerical constant has no exactness prex the constant

Some implementations allow these pro cedures to take many

may b e assumed to b e exact or inexact at the discretion of

arguments to facilitate range checks These pro cedures

the implementation except that integers expressed without

return t if their arguments are resp ectively numeri

decimal p oints and without use of exp onential notation are

cally equal monotonically increasing monotonically de

assumed exact

creasing monotonically nondecreasing or monotonically

In systems with b oth single and double precision flonums

nonincreasing Warning on inexact numbers the equal

we may want to sp ecify which size we want to use to rep

ity tests will give unreliable results and the other numer

resent a constant internally For example we may want

ical comparisons will b e useful only heuristically when in

a constant that has the value of pi rounded to the single

doubt consult a numerical analyst

precision length or we might want a long number that has

the value In either case we are sp ecifying an explicit

max x x essential pro cedure

way to represent an inexact number For this purp ose we

max x x pro cedure

may express a number with a prex that indicates short or

min x x essential pro cedure

long flonum representation

min x x pro cedure

S

These pro cedures return the maximum or minimum of their

Round to short

arguments

L

Extend to long

z z essential pro cedure

z pro cedure

Numerical op erations

z z essential pro cedure

z pro cedure

The reader is referred to section for a summary of

the naming conventions used to sp ecify restrictions on the These pro cedures return the sum or pro duct of their argu

types of arguments to numerical routines ments

Revised Scheme

numerator q pro cedure

denominator q pro cedure

These pro cedures return the numerator or denominator of

their argument

numerator

denominator

z z essential pro cedure

z z pro cedure

z z essential pro cedure

gcd n pro cedure

z z pro cedure

lcm n pro cedure

With two or more arguments these pro cedures return the

These pro cedures return the greatest common divisor or

dierence or quotient of their arguments asso ciating to the

least common multiple of their arguments The result is

left With one argument however they return the additive

always nonnegative

or multiplicative inverse of their argument

gcd

gcd

lcm

lcm

floor x pro cedure

abs z essential pro cedure

ceiling x pro cedure

truncate x pro cedure

Abs returns the magnitude of its argument

round x pro cedure

abs

rationalize x y pro cedure

abs i

rationalize x pro cedure

quotient n n essential pro cedure

These pro cedures create integers and rationals Their re

remainder n n essential pro cedure

sults are exact if and only if their arguments are exact

modulo n n pro cedure

Floor returns the largest integer not larger than x

These are intended to implement numbertheoretic inte

Ceiling returns the smallest integer not smaller than x

ger division For p ositive integers n and n if n and n

Truncate returns the integer of maximal absolute value

are integers such that n n n n and n n

not larger than the absolute value of x Round returns the

then

closest integer to x rounding to even when x is halfway

b etween two integers With two arguments rationalize

quotient n n n

pro duces the rational number with smallest denominator remainder n n n

modulo n n n

diering from x by no more than y With one argument

rationalize pro duces the b est rational approximation to

For all integers n and n with n not equal to

x preserving all of the precision in its representation

n n quotient n n

Note Round rounds to even for consistency with the rounding

remainder n n

mo des required by the IEEE oating p oint standard

t

The value returned by quotient always has the sign of the

pro duct of its arguments Remainder and modulo dier on

exp z pro cedure

negative argumentsthe remainder always has the sign of

log z pro cedure

the dividend the modulo always has the sign of the divisor

sin z pro cedure

cos z pro cedure

modulo

tan z pro cedure

remainder

asin z pro cedure

modulo

acos z pro cedure

remainder

atan z pro cedure

atan y x pro cedure

modulo

These pro cedures are part of every implementation that

remainder

supp orts real numbers they compute the usual transcen

dental functions Log computes the natural logarithm of

modulo

remainder z not the base logarithm Asin acos and atan

Standard pro cedures

compute arcsine sin arccosine cos and arctan Note Magnitude is the same as abs but abs must b e present

gent tan resp ectively The twoargument variant of in all implementations whereas magnitude will only b e present

atan computes angle makerectangular x y see in implementations that supp ort complex numbers

b elow even in implementations that dont supp ort com

plex numbers

exactinexact z pro cedure

In general the mathematical functions log arcsine arcco

inexactexact z pro cedure

sine and arctangent are multiply dened For nonzero real

Exactinexact returns an inexact representation of z

x the value of log x is dened to b e the one whose imagi

which is a fairly harmless thing to do Inexactexact

nary part lies in the range exclusive to inclusive

returns an exact representation of z Since the law of

log is undened The value of log z when z is complex is

garbage in garbage out remains in force inexact

dened according to the formula

exact should not b e used casually

log z log magnitudez i anglez

With log dened this way the values of sin z cos z

Numerical input and output

and tan z are according to the following formulae

p

sin z i logiz z

numberstring number format pro cedure

p

z cos z i logz i

The conventions used to pro duce the printed representation

p

of a number can b e sp ecied by a format as describ ed

z tan z i log iz

in section The pro cedure numberstring takes a

number and a format and returns as a string the printed

The ab ove sp ecication follows which in turn fol

representation of the given number in the given format

lows refer to these sources for more detailed discussion

This pro cedure will mostly b e used by sophisticated users

of branch cuts b oundary conditions and implementation

and in system programs In general a naive user will need

of these functions

to know nothing ab out the formats b ecause the system

printer will have reasonable default formats for all types of

sqrt z pro cedure

numbers

Returns the principal square ro ot of z The result will have

either p ositive real part or zero real part and nonnegative

stringnumber string exactness radix pro cedure

imaginary part

The system reader will construct reasonable default numer

ical types for numbers expressed in each of the formats it

expt z z pro cedure

recognizes A user who needs control of the co ercion from

strings to numbers will use stringnumber Exactness

Returns z raised to the p ower z

must b e a symbol either E for exact or I for inexact

z log z z

2 1 2

e z

Radix must also b e a symbol B for binary O for o ctal D for

is dened to b e equal to

decimal and X for hexadecimal Returns a number of the

maximally precise representation expressed by the given

string It is an error if string do es not express a number

makerectangular x x pro cedure

according to the grammar in section

makepolar x x pro cedure

realpart z pro cedure

Formats

imagpart z pro cedure

magnitude z pro cedure

A format is a list b eginning with a format descriptor which

angle z pro cedure

is a symbol such as sci Following the descriptor are pa

rameters used by that descriptor such as the number of

These pro cedures are part of every implementation that

signicant digits to b e used Default values are supplied

supp orts complex numbers Supp ose x x x and x

for any parameters that are omitted Mo diers may app ear

are real numbers and z is a complex number such that

after the parameters such as the radix and exactness for

ix

z x x i x e

mats describ ed b elow which themselves take parameters

Then makerectangular and makepolar return z

Details of particular formats such as sci and fix are given

realpart returns x imagpart returns x magnitude

in section

returns x and angle returns x In the case of angle

whose value is not uniquely determined by the preceding For example the format sci exactness s sp ec

rule the value returned will b e the one in the range ies that a number is to b e expressed in Fortran scien

exclusive to inclusive tic format with signicant places and two places after

Revised Scheme

the radix p oint and that its exactness prex is to b e sup

pressed

In the following examples the comment shows the format

rat n format

that was used to pro duce the output shown

Express as a rational fraction n sp ecies the largest de

int

nominator to b e used in constructing a rational approxi

int

mation to the number b eing expressed If n is omitted it

rat

defaults to innity

fix

fix

flo

fix n format

flo

Express with a xed radix p oint n sp ecies the number of

e sci

places to the right of the radix p oint n defaults to the size

e e e sci

of a singleprecision flonum If there are not enough signif

i rect int int

icant places then insignicant digits will b e agged For

polar fix

flo

example an inexact represented internally as

a digit flonum would b e printed with a fix format

A format may sp ecify that a number should b e expressed

as

in a particular radix The radix prex may also b e sup

pressed For example one may express a complex number

in p olar form with the magnitude in o ctal and the angle in

decimal as follows

flo n format

od polar flo radix o

Express with a oating radix p oint n sp ecies the total

flo radix d

number of places to b e displayed n defaults to the size of

o polar flo radix o

a singleprecision flonum If the number is out of range

flo radix d s

it is converted to sci flo h expresses n in oating

A format may sp ecify that a number should b e expressed

p oint format heuristically for human consumption

with an explicit exactness prex exactness e or it

may force the exactness to b e suppressed exactness

sci n m format

s For example the following are ways to express an

inexact value for pi

Express in exp onential notation n sp ecies the total num

b er of places to b e displayed n defaults to the size of a

i rat exactness e

singleprecision flonum m sp ecies the number of places

rat exactness s

to the right of the radix p oint m defaults to n sci

i fix exactness e

h do es heuristic expression

An attempt to pro duce more digits than are available in

the internal machine representation of a number will b e

rect r i format

marked with a lling the extra digits This is not a

statement that the implementation knows or keeps track

Express as a rectangular form complex number r and i

of the signicance of a number just that the machine will

are formats for the real and imaginary parts resp ectively

ag attempts to pro duce digits of a number that has

They default to heur

only digits of machine representation

flo exactness s

polar m a format

Express as a p olar form complex number m and a are

Details of formats

formats for the magnitude and angle resp ectively m and

a default to heur The format descriptors are

heur format int format

Express heuristically using the minimum number of digits Express as an integer The radix p oint is implicit If

required to get an expression that when co erced back to there are not enough signicant places then insignicant

a number pro duces the original machine representation digits will b e agged For example an inexact integer

Exact numbers are expressed as int or rat Inexact represented internally as a digit flonum

numbers are expressed as flo h or sci h dep ending would b e printed as

Standard pro cedures

on their range Complex numbers are expressed in rect implementations that supp ort the notation for input do

This is the normal default of the system printer not have to supp ort it for output

Some of the pro cedures that op erate on characters ignore

the dierence b etween upp er case and lower case The pro

The following mo diers may b e added to a numerical for

cedures that ignore case have the sux ci for case in

mat sp ecication

sensitive If the op eration is a predicate then the ci

sux precedes the at the end of the name

exactness s format

This controls the expression of the exactness prex of a

char obj essential pro cedure

number s must b e a symbol either E or S indicating

Returns t if obj is a character otherwise returns f

whether the exactness is to b e expressed or suppressed re

sp ectively If no exactness mo dier is sp ecied for a format

char char char essential pro cedure

then the exactness is by default suppressed

char char char essential pro cedure

char char char essential pro cedure

char char char essential pro cedure

radix r s format

char char char essential pro cedure

This forces a number to b e expressed in the radix r r may

These pro cedures imp ose a total ordering on the set of

b e the symbol B binary O o ctal D decimal or X hex

characters It is guaranteed that under this ordering

s must b e a symbol either E or S indicating whether the

radix prex is to b e expressed or suppressed resp ectively

The upp er case characters are in order For example

s defaults to E expressed If no radix mo dier is sp ecied

char A B returns t

then the default is decimal and the prex is suppressed

The lower case characters are in order For example

char a b returns t

Characters

The digits are in order For example char

returns t

Characters are ob jects that represent printed characters

such as letters and digits There is no requirement that the

Either all the digits precede all the upp er case letters

data type of characters b e disjoint from other data types

or vice versa

implementations are encouraged to have a separate char

acter data type but may choose to represent characters as

Either all the digits precede all the lower case letters

integers strings or some other type

or vice versa

Characters are written using the notation hcharacteri or Some implementations may generalize these pro cedures to

take more than two arguments as with the corresp onding

hcharacter namei For example

numeric predicates

a lower case letter

charci char char pro cedure

A upp er case letter

charci char char pro cedure

left parenthesis

charci char char pro cedure

the space character

charci char char pro cedure

space the preferred way to write a space

charci char char pro cedure

newline the newline character

These pro cedures are similar to char et cetera but they

Case is signicant in hcharacteri but not in hcharacter treat upp er case and lower case letters as the same For

namei If hcharacteri in hcharacteri is alphab etic then

example charci A a returns t Some imple

the character following hcharacteri must b e a delimiter

mentations may generalize these pro cedures to take more

character such as a space or parenthesis This rule resolves

than two arguments as with the corresp onding numeric

the ambiguous case where for example the sequence of

predicates

characters space could b e taken to b e either a repre

sentation of the space character or a representation of the

charalphabetic char pro cedure

character s followed by a representation of the symbol

charnumeric char pro cedure

pace

charwhitespace char pro cedure

Characters written in the notation are selfevaluating These pro cedures return t if their arguments are alpha

That is they do not have to b e quoted in programs The b etic numeric or whitespace characters resp ectively oth

notation is not an essential part of Scheme however Even erwise they return f The following remarks which are

Revised Scheme

sp ecic to the ASCI I character set are intended only as A backslash can b e written inside a string only by escaping

a guide The alphab etic characters are the upp er and it with another backslash Scheme do es not sp ecify the

lower case letters The numeric characters are the ten dec eect of a backslash within a string that is not followed by

imal digits The whitespace characters are space tab line a doublequote or backslash

feed form feed and carriage return

A string may continue from one line to the next but this is

usually a bad idea b ecause the exact eect may vary from

one computer system to another

charuppercase letter pro cedure

The length of a string is the number of characters that

charlowercase letter pro cedure

it contains This number is a nonnegative integer that

Letter must b e an alphab etic character These pro cedures

is xed when the string is created The valid indexes of

return t if their arguments are upp er case or lower case

a string are the exact nonnegative integers less than the

characters resp ectively otherwise they return f

length of the string The rst character of a string has

index the second has index and so on

In phrases such as the characters of string b eginning with

charinteger char essential pro cedure

index start and ending with index end it is understo o d

integerchar n essential pro cedure

that the index start is inclusive and the index end is ex

Given a character charinteger returns an integer rep

clusive Thus if start and end are the same index a null

resentation of the character Given an integer that is the

substring is referred to and if start is zero and end is the

image of a character under charinteger integer

length of string then the entire string is referred to

char returns a character These pro cedures implement or

Some of the pro cedures that op erate on strings ignore the

der isomorphisms b etween the set of characters under the

dierence b etween upp er and lower case The versions that

char ordering and some subset of the integers under

ignore case have the sux ci for case insensitive If

the ordering That is if

the op eration is a predicate then the ci sux precedes

the at the end of the name

char a b t and x y t

and x and y are in the range of charinteger then

string obj essential pro cedure

Returns t if obj is a string otherwise returns f

charinteger a

charinteger b t

makestring k pro cedure

char integerchar x

makestring k char pro cedure

integerchar y t

k must b e a nonnegative integer and char must b e a char

acter Makestring returns a newly allo cated string of

length k If char is given then all elements of the string

charupcase char pro cedure

are initialized to char otherwise the contents of the string

chardowncase char pro cedure

are unsp ecied

These pro cedures return a character char such that

charci char char In addition if char is alpha

stringlength string essential pro cedure

b etic then the result of charupcase is upp er case and

Returns the number of characters in the given string

the result of chardowncase is lower case

stringref string k essential pro cedure

k must b e a valid index of string Stringref returns

Strings

character k of string using zeroorigin indexing

Strings are sequences of characters In some implemen

tations of Scheme they are immutable other implementa

stringset string k char pro cedure

tions provide destructive pro cedures such as stringset

k must b e a valid index of string Stringset stores char

that alter string ob jects

in element k of string and returns an unsp ecied value

Strings are written as sequences of characters enclosed

within doublequotes A doublequote can b e written

string string string essential pro cedure

inside a string only by escaping it with a backslash as

stringci string string pro cedure

in

Returns t if the two strings are the same length and con

The word recursion has many meanings tain the same characters in the same p ositions otherwise

Standard pro cedures

returns f Stringci treats upp er and lower case let Vectors

ters as though they were the same character but string

Vectors are heterogenous mutable structures whose ele

treats upp er and lower case as distinct characters

ments are indexed by integers

The length of a vector is the number of elements that it

string string string essential pro cedure

contains This number is a nonnegative integer that is

string string string essential pro cedure

xed when the vector is created The valid indexes of a

string string string essential pro cedure

vector are the exact nonnegative integers less than the

string string string essential pro cedure

length of the vector The rst element in a vector is indexed

stringci string string pro cedure

by zero and the last element is indexed by one less than

stringci string string pro cedure

the length of the vector

stringci string string pro cedure

stringci string string pro cedure

Vectors are written using the notation obj For

example a vector of length containing the number zero

These pro cedures are the lexicographic extensions to

in element the list in element and the

strings of the corresp onding orderings on characters For

string Anna in element can b e written as following

example string is the lexicographic ordering on strings

induced by the ordering char on characters If two

Anna

strings dier in length but are the same up to the length

Note that this is the external representation of a vector not

of the shorter string the shorter string is considered to b e

an expression evaluating to a vector Like list constants

lexicographically less than the longer string

vector constants must b e quoted

Implementations may generalize these and the string

Anna

and stringci pro cedures to take more than two argu

Anna

ments as with the corresp onding numeric predicates

substring string start end essential pro cedure

vector obj essential pro cedure

String must b e a string and start and end must b e exact

Returns t if obj is a vector otherwise returns f

integers satisfying

start end stringlength string

makevector k essential pro cedure

makevector k l l pro cedure

Substring returns a newly allo cated string formed from

the characters of string b eginning with index start inclu

Returns a newly allo cated vector of k elements If a second

sive and ending with index end exclusive

argument is given then each element is initialized to l l

Otherwise the initial contents of each element is unsp eci

stringappend string string essential pro cedure

ed

stringappend string pro cedure

Returns a new string whose characters form the concate

vector obj essential pro cedure

nation of the given strings

Returns a newly allo cated vector whose elements contain

the given arguments Analogous to list

stringlist string essential pro cedure

vector a b c a b c

liststring chars essential pro cedure

Stringlist returns a newly allo cated list of the char

vectorlength vector essential pro cedure

acters that make up the given string Liststring re

turns a string formed from the characters in the list chars

Returns the number of elements in vector

Stringlist and liststring are inverses so far as

equal is concerned Implementations that provide de

vectorref vector k essential pro cedure

structive op erations on strings should ensure that the re

k must b e a valid index of vector Vectorref returns the

sult of liststring is newly allo cated

contents of element k of vector

vectorref

stringcopy string pro cedure

Returns a newly allo cated copy of the given string

vectorset vector k obj essential pro cedure

stringfill string char pro cedure

k must b e a valid index of vector Vectorset stores obj

in element k of vector The value returned by vectorset

Stores char in every element of the given string and returns

is unsp ecied

an unsp ecied value

Revised Scheme

let vec vector Anna map proc list essential pro cedure

vectorset vec Sue Sue

map proc list list pro cedure

vec

The list s must b e lists and proc must b e a pro cedure taking

Sue Sue Anna

as many arguments as there are lists If more than one list

is given then they must all b e the same length Map applies

vectorlist vector essential pro cedure

proc elementwise to the elements of the list s and returns

listvector list essential pro cedure

a list of the results The order in which proc is applied to

the elements of the list s is unsp ecied

Vectorlist returns a newly created list of the ob jects

contained in the elements of vector Listvector returns

map cadr a b d e g h

a newly created vector initialized to the elements of the list

b e h

list

map lambda n expt n n

vectorlist dah dah didah

dah dah didah

listvector dididit dah

dididit dah

map

let count

vectorfill vector l l pro cedure

map lambda ignored

Stores l l in every element of vector The value returned

set count count

by vectorfill is unsp ecied

count

a b c unspecied

Control features

foreach proc list essential pro cedure

This chapter describ es various primitive pro cedures which

foreach proc list list pro cedure

control the ow of program execution in sp ecial ways The

procedure predicate is also describ ed here

The arguments to foreach are like the arguments to map

but foreach calls proc for its side eects rather than for

its values Unlike map foreach is guaranteed to call proc

procedure obj essential pro cedure

on the elements of the list s in order from the rst element to

Returns t if obj is a pro cedure otherwise returns f

the last and the value returned by foreach is unsp ecied

procedure car t

let v makevector

procedure car f

foreach lambda i

procedure lambda x x x

vectorset v i i i

t

procedure lambda x x x

v

f

callwithcurrentcontinuati on procedure

t

force promise pro cedure

Forces the value of promise see delay section If

apply proc args essential pro cedure

no value has b een computed for the promise then a value

apply proc arg args pro cedure

is computed and returned The value of the promise is

Proc must b e a pro cedure and args must b e a list The

cached or memoized so that if it is forced a second

rst essential form calls proc with the elements of args as

time the previously computed value is returned without

the actual arguments The second form is a generalization

any recomputation

of the rst that calls proc with the elements of the list

force delay

append list arg args as the actual arguments

let p delay

apply list list force p force p

define compose

lambda f g define astream

lambda args letrec next

f apply g args lambda n

cons n delay next n

compose sqrt next

Standard pro cedures

eqv delay unspecied define head car

pair delay cons unspecied define tail

lambda stream force cdr stream

Some implementations will implement implicit forc

ing where the value of a promise is forced by primi

head tail tail astream

tive pro cedures like cdr and

delay

Force and delay are mainly intended for programs writ

ten in functional style The following examples should not

b e considered to illustrate go o d programming style but

callwithcurrentcontinuation proc

they illustrate the prop erty that the value of a promise is

essential pro cedure

computed at most once

Proc must b e a pro cedure of one argument The pro cedure

define count

callwithcurrentcontinuation packages up the cur

define p delay begin set count count

rent continuation see the rationale b elow as an escap e

x

pro cedure and passes it as an argument to proc The

define x

escap e pro cedure is a Scheme pro cedure of one argument

count

that if it is later passed a value will ignore whatever con

p a promise

tinuation is in eect at that later time and will give the

force p

value instead to the continuation that was in eect when

p a promise stil l

the escap e pro cedure was created

count

force p

The escap e pro cedure created by

count

callwithcurrentcontinuation has unlimited extent

just like any other pro cedure in Scheme It may b e stored

Here is a p ossible implementation of delay and force We

in variables or data structures and may b e called as many

dene the expression

times as desired

delay hexpressioni

The following examples show only the most common

uses of callwithcurrentcontinuation If all real

to have the same meaning as the pro cedure call

programs were as simple as these examples there

makepromise lambda hexpressioni

would b e no need for a pro cedure with the p ower of

callwithcurrentcontinuation

where makepromise is dened as follows

callwithcurrentcontinuat ion

define makepromise

lambda exit

lambda proc

foreach lambda x

let alreadyrun f result f

if negative x

lambda

exit x

cond not alreadyrun

set result proc

t

set alreadyrun t

result

define listlength

Promises are implemented here as pro cedures of no argu

lambda obj

callwithcurrentcontinuati on

ments and force simply calls its argument

lambda return

define force

letrec r

lambda object

lambda obj

object

cond null obj

pair obj

Various extensions to this semantics of delay and force

r cdr obj

are supp orted in some implementations

else return f

r obj

Calling force on an ob ject that is not a promise may

simply return the ob ject

listlength

It may b e the case that there is no means by which

listlength a b c f

a promise can b e op erationally distinguished from its

forced value That is expressions like the following

Rationale A

may evaluate to either t or to f dep ending on the

common use of callwithcurrentcontinuat ion is for struc

implementation tured nonlo cal exits from lo ops or pro cedure b o dies but in

Revised Scheme

fact callwithcurrentcontinuation is extremely useful for automatically and the value yielded by the pro cedure is

implementing a wide variety of advanced control structures

returned If the pro cedure do es not return then Scheme

will not close the p ort unless it can prove that the p ort will

Whenever a Scheme expression is evaluated there is a contin

never again b e used for a read or write op eration

uation wanting the result of the expression The continuation

represents an entire default future for the computation If

Rationale Because Schemes escap e pro cedures have un

the expression is evaluated at top level for example then the

limited extent it is p ossible to escap e from the current con

continuation will take the result print it on the screen prompt

tinuation but later to escap e back in If implementations

for the next input evaluate it and so on forever Most of the

were p ermitted to close the p ort on any escap e from the

time the continuation includes actions sp ecied by user co de

current continuation then it would b e imp ossible to write

as in a continuation that will take the result multiply it by

p ortable co de using b oth callwithcurrentcontinuati on

the value stored in a lo cal variable add seven and give the

and callwithinputfile or callwithoutputfile

answer to the top level continuation to b e printed Normally

these ubiquitous continuations are hidden b ehind the scenes and

programmers dont think much ab out them On rare o ccasions

inputport obj essential pro cedure

however a programmer may need to deal with continuations ex

outputport obj essential pro cedure

plicitly Callwithcurrentcontinuatio n allows Scheme pro

grammers to do that by creating a pro cedure that acts just like

Returns t if obj is an input p ort or output p ort resp ec

the current continuation

tively otherwise returns f

Most programming languages incorp orate one or more sp ecial

purp ose escap e constructs with names like exit return or

currentinputport essential pro cedure

even goto In however Peter Landin invented a

currentoutputport essential pro cedure

general purp ose escap e op erator called the Jop erator John

Reynolds describ ed a simpler but equally p owerful con

Returns the current default input or output p ort

struct in The catch sp ecial form describ ed by Sussman

and Steele in the rep ort on Scheme is exactly the same as

Reynoldss construct though its name came from a less general

withinputfromfile string thunk pro cedure

construct in MacLisp Several Scheme implementors noticed

withoutputtofile string thunk pro cedure

that the full p ower of the catch construct could b e provided by

Thunk must b e a pro cedure of no arguments and

a pro cedure instead of by a sp ecial syntactic construct and the

string must b e a string naming a le For

name callwithcurrentcontinuation was coined in

withinputfromfile the le must already exist for

This name is descriptive but opinions dier on the merits of

withoutputtofile the eect is unsp ecied if the le

such a long name and some p eople use the name callcc in

already exists The le is op ened for input or out

stead

put an input or output p ort connected to it is made

the default value returned by currentinputport or

currentoutputport and the thunk is called with no ar

Input and output

guments When the thunk returns the p ort is closed and

Ports

the previous default is restored Withinputfromfile

and withoutputtofile return the value yielded by

Ports represent input and output devices To Scheme an

thunk If an escap e pro cedure is used to escap e from the

input device is a Scheme ob ject that can deliver characters

continuation of these pro cedures their b ehavior is imple

up on command while an output device is a Scheme ob ject

mentation dep endent

that can accept characters

openinputfile lename pro cedure

callwithinputfile string proc

essential pro cedure

Takes a string naming an existing le and returns an input

callwithoutputfile string proc

p ort capable of delivering characters from the le If the

essential pro cedure

le cannot b e op ened an error is signalled

Proc should b e a pro cedure of one argument and

string should b e a string naming a le For

openoutputfile lename pro cedure

callwithinputfile the le must already exist for

callwithoutputfile the eect is unsp ecied if the Takes a string naming an output le to b e created and

le already exists These pro cedures call proc with one ar returns an output p ort capable of writing characters to a

gument the p ort obtained by op ening the named le for new le by that name If the le cannot b e op ened an

input or output If the le cannot b e op ened an error is error is signalled If a le with the given name already

signalled If the pro cedure returns then the p ort is closed exists the eect is unsp ecied

Standard pro cedures

closeinputport port pro cedure b e indistinguishable from an interactive p ort that has no ready

closeoutputport port pro cedure characters

Closes the le asso ciated with port rendering the port in

eofobject obj essential pro cedure

capable of delivering or accepting characters These rou

tines have no eect if the le has already b een closed The

Returns t if obj is an end of le ob ject otherwise returns

value returned is unsp ecied

f The precise set of end of le ob jects will vary among

implementations but in any case no end of le ob ject will

ever b e a character or an ob ject that can b e read in using

Input

read

read essential pro cedure

Output

read port essential pro cedure

Read converts written representations of Scheme ob jects

write obj essential pro cedure

into the ob jects themselves That is it is a parser for the

write obj port essential pro cedure

nonterminal hdatumi see section Read returns the

Writes a representation of obj to the given port Strings

next ob ject parsable from the given input port up dating

that app ear in the written representation are enclosed in

port to p oint to the rst character past the end of the

doublequotes and within those strings backslash and dou

written representation of the ob ject

blequote characters are escap ed by backslashes Write re

turns an unsp ecied value The port argument may b e

If an end of le is encountered in the input b efore any char

omitted in which case it defaults to the value returned by

acters are found that can b egin an ob ject then an end of

currentoutputport

le ob ject is returned The p ort remains op en and fur

ther attempts to read will also return an end of le ob ject

If an end of le is encountered after the b eginning of an

display obj essential pro cedure

ob jects written representation but the written represen

display obj port essential pro cedure

tation is incomplete and therefore not parsable an error is

Writes a representation of obj to the given port Strings

signalled

that app ear in the written representation are not enclosed

The port argument may b e omitted in which case it de

in doublequotes and no characters are escap ed within

faults to the value returned by currentinputport It is

those strings In those implementations that have a dis

an error to read from a closed p ort

tinct character type character ob jects app ear in the repre

sentation as if written by writechar instead of by write

Display returns an unsp ecied value The port argument

readchar essential pro cedure

may b e omitted in which case it defaults to the value re

readchar port essential pro cedure

turned by currentoutputport

Returns the next character available from the input port

Rationale Write is intended for pro ducing machinereadable

up dating the port to p oint to the following character If

output and display is for pro ducing humanreadable output

no more characters are available an end of le ob ject is

Implementations that allow slashication within symbols will

returned Port may b e omitted in which case it defaults

probably want write but not display to slashify funny charac

to the value returned by currentinputport

ters in symbols

charready pro cedure

newline essential pro cedure

charready port pro cedure

newline port essential pro cedure

Writes an end of line to port Exactly how this is done

Returns t if a character is ready on the input port and

diers from one op erating system to another Returns

returns f otherwise If charready returns t then the

an unsp ecied value The port argument may b e omit

next readchar op eration on the given port is guaranteed

ted in which case it defaults to the value returned by

not to hang If the port is at end of le then charready

currentoutputport

returns t Port may b e omitted in which case it defaults

to the value returned by currentinputport

writechar char essential pro cedure

Rationale Charready exists to make it p ossible for a pro

writechar char port essential pro cedure

gram to accept characters from interactive p orts without getting

stuck waiting for input Any input editors asso ciated with such

Writes the character char not a written representation of

p orts must ensure that characters whose existence has b een as

the character to the given port and returns an unsp ecied

serted by charready cannot b e rubb ed out If charready

value The port argument may b e omitted in which case it

were to return f at end of le a p ort at end of le would

defaults to the value returned by currentoutputport

Revised Scheme

Formal syntax and semantics User interface

Questions of user interface generally fall outside of the do

This chapter provides formal descriptions of what has al

main of this rep ort However the following op erations are

ready b een describ ed informally in previous chapters of this

imp ortant enough to deserve description here

rep ort

load lename essential pro cedure

Formal syntax

Filename should b e a string naming an existing le con

This section provides a formal syntax for Scheme written

taining Scheme source co de The load pro cedure reads ex

in an extended BNF The syntax for the entire language

pressions and denitions from the le and evaluates them

including features which are not essential is given here

sequentially It is unsp ecied whether the results of the

All spaces in the grammar are for legibility Case is insignif

expressions are printed The load pro cedure do es not

icant for example xA and Xa are equivalent hemptyi

aect the values returned by currentinputport and

stands for the empty string

currentoutputport Load returns an unsp ecied value

The following extensions to BNF are used to make the de

Note For p ortability load must op erate on source les Its

scription more concise hthingi means zero or more o ccur

op eration on other kinds of les necessarily varies among im

rences of hthingi and hthingi means at least one hthingi

plementations

Lexical structure

transcripton lename pro cedure

This section describ es how individual tokens identiers

transcriptoff pro cedure

numbers etc are formed from sequences of characters

Filename must b e a string naming an output le to b e cre

The following sections describ e how expressions and pro

ated The eect of transcripton is to op en the named

grams are formed from sequences of tokens

le for output and to cause a transcript of subsequent

hIntertoken spacei may o ccur on either side of any token

interaction b etween the user and the Scheme system to

but not within a token

b e written to the le The transcript is ended by a call

to transcriptoff which closes the transcript le Only

Tokens which require implicit termination identiers

one transcript may b e in progress at any time though some

numbers characters and dot may b e terminated by any

implementations may relax this restriction The values re

hdelimiteri but not necessarily by anything else

turned by these pro cedures are unsp ecied

htokeni hidentieri j hb o oleani j hnumberi

j hcharacteri j hstringi

j j j j j j j j

hdelimiteri hwhitespacei j j j j

hwhitespacei hspace or newlinei

hcommenti hall subsequent characters up to a

line breaki

hatmospherei hwhitespacei j hcommenti

hintertoken spacei hatmospherei

hidentieri hinitiali hsubsequenti

j hp eculiar identieri

hinitiali hletteri j hsp ecial initiali

hletteri a j b j c j j z

hsp ecial initiali j j j j j j j j

j j j j j

hsubsequenti hinitiali j hdigiti

j hsp ecial subsequenti

hdigiti j j j j j j j j j

hsp ecial subsequenti j j

hp eculiar identieri j

hsyntactic keywordi hexpression keywordi

j else j j define

j unquote j unquotesplicing

hexpression keywordi quote j lambda j if

Formal syntax and semantics

j set j begin j cond j and j or j case hsimple datumi hb o oleani j hnumberi

j let j let j letrec j do j delay j hcharacteri j hstringi j hsymboli

j quasiquote hsymboli hidentieri

hcomp ound datumi hlisti j hvectori

hvariablei h any hidentieri which isnt hlisti hdatumi j hdatumi hdatumi

also a hsyntactic keywordii j habbreviationi

habbreviationi habbrev prexi hdatumi

hb o oleani t j f habbrev prexi j j j

hcharacteri hany characteri hvectori hdatumi

j hcharacter namei

hcharacter namei space j newline

Expressions

hexpressioni hvariablei

hstringi hstring elementi

j hliterali

hstring elementi hany character other than or i

j hpro cedure calli

j j

j hlambda expressioni

j hconditionali

hnumberi hreali j hreali hureali i

j hassignmenti

j hreali hureali i j hreali hreali

j hderived expressioni

hreali hsigni hureali

hureali hureal i j hureal i j hureal i j hureal i

hliterali hquotationi j hselfevaluatingi

hselfevaluatingi hb o oleani j hnumberi

The following rules for hureal R i huinteger R i and hprex

j hcharacteri j hstringi

R i should b e replicated for R and

hquotationi hdatumi j quote hdatumi

hureal R i hprex R i huinteger R i hsuxi

hpro cedure calli hop eratori hop erandi

j hprex R i huinteger R i huinteger R i hsuxi

hop eratori hexpressioni

j hprex R i hdigit R i hsuxi

hop erandi hexpressioni

j hprex R i hdigit R i hdigit R i hsuxi

j hprex R i hdigit R i hsuxi

hlambda expressioni lambda hformalsi hb o dyi

hprex R i hradix R i hexactnessi hprecisioni

hformalsi hvariablei j hvariablei

j hradix R i hprecisioni hexactnessi

j hvariablei hvariablei

j hexactnessi hradix R i hprecisioni

hb o dyi hdenitioni hsequencei

j hexactnessi hprecisioni hradix R i

hsequencei hcommandi hexpressioni

j hprecisioni hradix R i hexactnessi

hcommandi hexpressioni

j hprecisioni hexactnessi hradix R i

huinteger R i hdigit R i

hconditionali if htesti hconsequenti halternatei

htesti hexpressioni

hsigni hemptyi j j

hconsequenti hexpressioni

hsuxi hemptyi j e hsigni hdigiti

halternatei hexpressioni j hemptyi

hexactnessi hemptyi j i j e

hprecisioni hemptyi j s j l

hassignmenti set hvariablei hexpressioni

hradix i b

hradix i o

hderived expressioni

hradix i hemptyi j d

cond hcond clausei

hradix i x

j cond hcond clausei else hsequencei

hdigit i j

j case hexpressioni

hdigit i j j j j j j j

hcase clausei

hdigit i hdigiti

j case hexpressioni

hdigit i hdigiti j a j b j c j d j e j f

hcase clausei

else hsequencei

External representations

j and htesti

j or htesti

hDatumi is what the read pro cedure section suc

j let hbinding sp eci hb o dyi

cessfully parses Note that any string which parses as an

j let hvariablei hbinding sp eci hb o dyi

hexpressioni will also parse as a hdatumi

j let hbinding sp eci hb o dyi

hdatumi hsimple datumi j hcomp ound datumi j letrec hbinding sp eci hb o dyi

Revised Scheme

j begin hsequencei hcommand or denitioni hcommandi j hdenitioni

j do hiteration sp eci hdenitioni define hvariablei hexpressioni

htesti hsequencei j define hvariablei hdef formalsi hb o dyi

hcommandi hdef formalsi hvariablei

j delay hexpressioni j hvariablei hvariablei

j hquasiquotationi

Formal semantics

hcond clausei htesti hsequencei

j else hsequencei

This section provides a formal denotational semantics for

j htesti

the primitive expressions of Scheme and selected builtin

j htesti hrecipienti

pro cedures The concepts and notation used here are de

hrecipienti hexpressioni

scrib ed in the notation is summarized b elow

hcase clausei hdatumi hsequencei

h i sequence formation

j else hsequencei

s k k th member of the sequence s based

s length of sequence s

hbinding sp eci hvariablei hexpressioni

s x t concatenation of sequences s and t

hiteration sp eci hvariablei hiniti hstepi

s y k drop the rst k members of sequence s

j hvariablei hiniti

t a b McCarthy conditional if t then a else b

hiniti hexpressioni

xi substitution with x for i

hstepi hexpressioni

x in D injection of x into domain D

x j D pro jection of x to domain D

Quasiquotations

To avoid sp ecial treatment for a toplevel environment the

The following grammar for quasiquote expressions is not

semantics assumes that environments assign lo cations to all

contextfree It is presented as a recip e for generating an

variables

innite number of pro duction rules Imagine a copy of the

The reason that expression continuations take sequences

following rules for D D keeps track of the

of values instead of single values is to simplify the formal

nesting depth

treatment of pro cedure calls and to make it easy to add

multiple return values

hquasiquotationi hquasiquotation i

htemplate i hexpressioni

The order of evaluation within a call is unsp ecied We

hquasiquotation D i htemplate D i

mimic that here by applying arbitrary p ermutations per

j quasiquote htemplate D i

mute and unpermute which must b e inverses to the ar

htemplate D i hsimple datumi

guments in a call b efore and after they are evaluated

j hlist template D i

This still requires that the order of evaluation b e con

j hvector template D i

stant throughout a program for any given number of ar

j hunquotation D i

guments but it is a closer approximation to the intended

hlist template D i htemplate or splice D i

semantics than a lefttoright evaluation would b e

j htemplate or splice D i htemplate D i

The storage allo cator new is implementationdependent

j hquasiquotation D i

2

but it must ob ey the following axiom if new L then

j hquasiquotation D i

new j L false

hvector template D i htemplate or splice D i

hunquotation D i htemplate D i

The semantics in this section was translated by machine

j unquote htemplate D i

from an executable version of the semantics written in

htemplate or splice D i htemplate D i

Scheme itself

j hsplicing unquotation D i

hsplicing unquotation D i htemplate D i

Abstract syntax

j unquotesplicing htemplate D i

2

K Con constants including quotations

In hquasiquotationis a hlist template D i can sometimes b e

2

I Ide identiers variables

confused with an hunquotation D i or hsplicing unquotation

2

E Exp expressions

D i The interpretation as an hunquotationi or hsplicing

2

Com Exp commands

unquotation D i takes precedence

Exp K j I j E E

Programs and denitions

j lambda I E

hprogrami hcommand or denitioni j lambda I I E

Formal syntax and semantics

j lambda I E

update new j L unspecied

j if E E E j if E E

wrong out of memory

j set I E

E lambda I . I E

2

Domain equations

new L

send hnew j L

2

L lo cations

0

I

2

N natural numbers

tievalsrest

0 0 0 0

T ffalse trueg b o oleans

C E E

0

Q symbols

extends I x hI i

H characters

I

R numbers

wrong to o few argumentsi in E

E L L pairs

p

E L vectors

v

update new j L unspecied

E L strings

s

wrong out of memory

M ffalse true nul l undened unspeciedg

miscellaneous

E lambda I E E lambda . I E

2

F L E K C pro cedure values

E if E E E

2

E Q H R E E E M F

p v s

E E single truish E E

expressed values

E E

2

S L E T stores

2

U Ide L environments

E if E E

E E single truish E E 2

C S A command continuations

send unspecied

2

K E C expression continuations

A answers

Here and elsewhere any expressed value other than undened

X errors

may b e used in place of unspecied

E set I E

Semantic functions

E E single assign lookup I

K Con E

E Exp U K C

send unspecied

E Exp U K C

E h i

C Com U C C

E E E

Denition of K delib erately omitted

E E single E E h i x

E K send K K

C

E I hold lookup I

C E C

single undened

wrong undened variable

Auxiliary functions

send

lookup U Ide L

E E E

lookup I I

E permute hE i x E

extends U Ide L U

applicate y

extends

unpermute

I I

extends I I y y

E lambda I E

wrong X C implementationdependent

2

new L

send hnew j L

send E K C

0

I

send hi

0 0 0 0

tievals C E E

single E C K

extends I

single

wrong wrong number of argumentsi

wrong wrong number of return values

in E

Revised Scheme

less E K C new S L ferror g implementationdependent

less

hold L K C

2 2

twoarg R R

hold send

send j R j R true false

wrong nonnumeric argument to

assign L E C C

assign update

add E K C

add

update L E S S

2 2

twoarg R R

update h true i

send j R j R in E

wrong nonnumeric argument to

tievals L C E C

tievals

car E K C

h i

car

2

2

new L tievals hnew j Li x

onearg E hold j E

p p

y

wrong nonpair argument to car

update new j L

cdr E K C similar to car

wrong out of memory

setcar E K C

tievalsrest L C E N C

setcar

tievalsrest

2

twoarg E assign j E

p p

list droprst

single tievals takerst x hi

send unspecied

wrong nonpair argument to setcar

droprst l n n l droprst l y n

eqv E K C

takerst l n n h i hl i x takerst l y n

eqv

2 2

twoarg M M

truish E T

send j M j M true false

truish false nul l false true

2 2

Q Q

send j Q j Q true false

permute Exp Exp implementationdependent

2 2

H H

unpermute E E inverse of permute

send j H j H true false

2 2

R R

applicate E E K C

send j R j R true false

applicate

2 2

E E

p p

2

F j F wrong bad pro cedure

send p p p p

p p true

onearg E K C E K C

false

onearg

j E

p

j E

p

wrong wrong number of arguments

2 2

E E

v v

twoarg E E K C E K C

2 2

E E

s s

twoarg

2 2

F F

send j F j F true false

wrong wrong number of arguments

list E K C

send false

list

apply E K C

send nul l

apply

list y single cons h i

2

twoarg F valueslist h i applicate

wrong bad pro cedure argument to apply

cons E K C

cons

valueslist E K C

2

twoarg new L

valueslist

0 0

2

new L

2

onearg E

p

0

send hnew j L new j Li in E

cdr hi

valueslist

0 0

update new j L

0

wrong out of memory

car hisingle hi x

update new j L

nul l h i

wrong out of memory

wrong nonlist argument to valueslist

Formal syntax and semantics

thunk lambda hsequencei cwcc E K C callwithcurrentcontinu ation

cwcc

2

elsethunk lambda onearg F

2

cond hmemvi key d thunk new L

applicate

0

else elsethunk hhnew j L i in Ei

where hmemvi is an expression evaluating to the memv pro

update new j L

cedure

unspecied

and t

wrong out of memory

and htesti htesti

wrong bad pro cedure argument

and htest i htest i

let x htest i

Derived expression types

thunk lambda and htest i

if x thunk x

This section gives rewrite rules for the derived expression

types By the application of these rules any expression

or f

can b e reduced to a semantically equivalent expression in

or htesti htesti

which only the primitive expression types literal variable

or htest i htest i

let x htest i

call lambda if set o ccur

thunk lambda or htest i

cond htesti hsequencei

if x x thunk

hclause i

if htesti

let hvariable i hinit i

begin hsequencei

hb o dyi

cond hclause i

lambda hvariable i hb o dyi hinit i

cond htesti

let hb o dyi

hclause i

lambda hb o dyi

or htesti cond hclause i

let hvariable i hinit i

hvariable i hinit i

cond htesti hrecipienti

hclause i

hb o dyi

let testresult htesti

let hvariable i hinit i

thunk lambda hrecipienti

let hvariable i hinit i

thunk lambda cond hclause i

if testresult

hb o dyi

thunk testresult

thunk

letrec hvariable i hinit i

cond else hsequencei

hb o dyi

begin hsequencei

let hvariable i hundenedi

cond

let htemp i hinit i

hsome expression returning an unsp ecied valuei

set hvariable i htemp i

case hkeyi

d hsequencei

hb o dyi

let key hkeyi

where htemp i htemp i are variables distinct from

thunk lambda hsequencei

hvariable i which do not free o ccur in the original

hiniti expressions and hundenedi is an expression which

cond hmemvi key d thunk

returns something which when stored in a lo cation makes

it an error to try to obtain the value stored in the lo cation

No such expression is dened but one is assumed to ex

case hkeyi

ist for the purp oses of this rewrite rule The second let

d hsequencei

expression in the expansion is not strictly necessary but it

serves to preserve the prop erty that the hiniti expressions

else f f

are evaluated in an arbitrary order let key hkeyi

Revised Scheme

NOTES

begin hsequencei

lambda hsequencei

Language changes

The following alternative expansion for begin do es not

This section enumerates the changes that have b een made

make use of the ability to write more than one expres

to Scheme since the Revised revised rep ort was pub

sion in the b o dy of a lambda expression In any case note

lished

that these rules apply only if hsequencei contains no de

The character circumex is now an extended al

nitions

phab etic character

begin hexpressioni hexpressioni

begin hcommandi hsequencei

The ob jects returned by literal expressions are p ermit

lambda ignore thunk thunk

ted to b e immutable

hcommandi

lambda begin hsequencei

The list to which a restargument b ecomes b ound must

b e newly allo cated

do hvariable i hinit i hstep i

Do variables are up dated by rebinding rather than by

htesti hsequencei

assignment

hcommand i

letrec hlo opi

New expression type delay

lambda hvariable i

Quasiquote backquote has b een improved in several

if htesti

ways vectors are allowed nesting is allowed and an

begin hsequencei

external syntax for quasiquote expressions analogous

begin hcommand i

to that for quote has b een dened

hlo opi hstep i

The semantics of denitions of the form define

hlo opi hinit i

hvariablei hformalsi hb o dyi no longer involves an

where hlo opi is any variable which is distinct from

implicit rec or letrec

hvariable i and which do es not o ccur free in the do

The curried denition syntax has b een removed

expression

The b o olean constants are now written t and f in

let hvariable i hvariable i hinit i

stead of true and false

hb o dyi

letrec hvariable i lambda hvariable i

The syntax null for the empty list has b een re

hb o dyi

moved

hvariable i

hinit i

New pro cedures boolean procedure and force

delay hexpressioni

The value of eq on numbers and characters is now

hmakepromisei lambda hexpressioni

unsp ecied

where hmakepromisei is an expression evaluating to some

Eq and eqv now explicitly p ermit op erationally

pro cedure which b ehaves appropriately with resp ect to the

equivalent pro cedures to b e identied

force pro cedure see section

Eqv distinguishes exact numbers from inexact ones

even if they are equal according to

List string and vector indexes must b e exact integers

Atan now admits either one or two arguments

Expression types removed namedlambda rec

sequence

Pro cedures

removed append stringnull substringfill

substringmoveleft substringmoveright

objecthash objectunhash

Redundant pro cedure names removed

and

Example

Keywords as variable names EXAMPLE

Some implementations allow arbitrary syntactic keywords

Integratesystem integrates the system

to b e used as variable names instead of reserving them

0

as this rep ort would have it But this creates ambiguities y f y y y k n

k n

k

in the interpretation of expressions for example in the

of dierential equations with the metho d of RungeKutta

following its not clear whether the expression if

The parameter systemderivative is a function that

should b e treated as a pro cedure call or as a conditional

takes a system state a vector of values for the state vari

define if list

ables y y and pro duces a system derivative the val

n

if or

0 0

ues y y The parameter initialstate provides

n

an initial system state and h is an initial guess for the

These ambiguities are usually resolved in some consistent

length of the integration step

way within any given implementation but no particular

treatment stands out as b eing clearly sup erior to any other

The value returned by integratesystem is an innite

so these situations were excluded for the purp oses of this

stream of system states

rep ort

define integratesystem

lambda systemderivative initialstate h

Macros

let next rungekutta systemderivative h

letrec states

Scheme do es not have any standard facility for dening

cons initialstate

new kinds of expressions

delay mapstreams next

The ability to alter the syntax of the language creates nu

states

merous problems All current implementations of Scheme

states

have macro facilities that solve those problems to one de

RungeKutta takes a function f that pro duces a system

gree or another but the solutions are quite dierent and

derivative from a system state RungeKutta pro duces

it isnt clear at this time which solution is b est or indeed

a function that takes a system state and pro duces a new

whether any of the solutions are truly adequate Rather

system state

than standardize we are encouraging implementations to

continue to exp eriment with dierent solutions

define rungekutta

lambda f h

The main problems with traditional macros are They

let h scalevector h

must b e dened to the system b efore any co de using them

scalevector

is loaded this is a common source of obscure bugs They

scalevector

are usually global macros can b e made to follow lexical

scalevector

scop e rules but many p eople nd the resulting scop e rules

lambda y

confusing Unless they are written very carefully macros

y is a system state

are vulnerable to inadvertant capture of free variables to

let k h f y

get around this for example macros may have to generate

k h f addvectors y k

co de in which pro cedure values app ear as quoted constants

k h f addvectors y k

k h f addvectors y k

There is a similar problem with syntactic keywords if the

addvectors y

keywords of sp ecial forms are not reserved If keywords are

addvectors k

reserved then either macros introduce new reserved words

k

invalidating old co de or else sp ecial forms dened by the

k

programmer do not have the same status as sp ecial forms

k

dened by the system

define elementwise

lambda f

lambda vectors

generatevector

vectorlength car vectors

lambda i

apply f

map lambda v vectorref v i

vectors

define generatevector

lambda size proc

Revised Scheme

BIBLIOGRAPHY AND REFERENCES let ans makevector size

letrec loop

Harold Ab elson and Gerald Jay Sussman with Julie

lambda i

cond i size ans

Sussman Structure and Interpretation of Computer

else

Programs MIT Press Cambridge

vectorset ans i proc i

David H Bartley and John C Jensen The imple

loop i

loop

mentation of PC Scheme In Proceedings of the

ACM Conference and Functional Program

define addvectors elementwise

ming pages

define scalevector

John Batali Edmund Go o dhue Chris Hanson Howie

lambda s

Shrob e Richard M Stallman and Gerald Jay Suss

elementwise lambda x x s

man The Scheme architecturesystem and chip

In Proceedings Conference on Advanced Research in

Mapstreams is analogous to map it applies its rst argu

VLSI pages Paul Peneld Jr editor Artech

ment a pro cedure to all the elements of its second argu

House Washington Street Dedham MA

ment a stream

William Clinger editor The revised revised rep ort on

define mapstreams

Scheme or an uncommon Lisp MIT Articial Intel

lambda f s

ligence Memo August Also published as

cons f head s

delay mapstreams f tail s

Computer Science Department Technical Rep ort

Indiana University June

Innite streams are implemented as pairs whose car holds

the rst element of the stream and whose cdr holds a

William Clinger The Scheme compiler An exer

promise to deliver the rest of the stream

cise in denotational semantics In Conference Record

of the ACM Symposium on Lisp and Functional

define head car

Programming pages

define tail

lambda stream force cdr stream

R Kent Dybvig Daniel P Friedman and Christopher

T Haynes Expansionpassing style Beyond conven

tional macros In Proceedings of the ACM Con

The following illustrates the use of integratesystem in

ference on Lisp and Functional Programming pages

integrating the system

dv v

C C

C i

L

dt R

Michael A Eisenberg Bo chser an integrated Scheme

programming system MIT Lab oratory for Computer

di

L

v L

C

Science Technical Rep ort Octob er

dt

which mo dels a damp ed oscillator

Marc Feeley Deux appro ches a limplantation

du language Scheme MSc thesis Departement

define dampedoscillator

dInformatique et de Recherche Operationelle Univer

lambda R L C

sity of Montreal May

lambda state

let Vc vectorref state

Daniel P Friedman Eugene

Il vectorref state

Kohlb ecker and Bruce Duba Reasoning with con

vector Vc R C Il C

tinuations In Proceedings of the Symposium on Logic

Vc L

in Computer Science pages IEEE Computer

So ciety Press Washigton DC

define thestates

integratesystem

Carol Fessenden William Clinger Daniel P Fried

dampedoscillator

man and Christopher Haynes Scheme version

reference manual Indiana University Computer

Science Technical Rep ort February Su

p erceded by

Daniel P Friedman and Matthias Felleisen The Little

LISPer Science Research Asso ciates second edition

Bibliography

Daniel P Friedman Christopher T Haynes and Eu Steven S Muchnick and Uwe F Pleban A semantic

gene Kohlb ecker Programming with continuations In comparison of Lisp and Scheme In Conference Record

Program Transformation and Programming Environ of the Lisp Conference pages The Lisp

ments pages P Pepper editor Springer Conference

Verlag

Peter Naur et al Revised rep ort on the algorith

D Friedman C Haynes E Kohlb ecker and

mic language Algol Communications of the ACM

M Wand Scheme interim reference manual In

January

diana University Computer Science Technical Rep ort

Paul Peneld Jr Principal values and branch cuts

January

in complex APL In APL Conference Proceed

Daniel P Friedman and Christopher T Haynes Con

ings pages ACM SIGAPL San Francisco

straining control In Proceedings of the Twelfth Annual

September Pro ceedings published as APL Quote

Symposium on Principles of Programming Languages

Quad ACM September

pages ACM January

Kent M Pitman Exceptional situations in Lisp MIT

Christopher T Haynes Daniel P Friedman and

Articial Intelligence Lab oratory Working Paper

Mitchell Wand Continuations and coroutines In Con

February

ference Record of the ACM Symposium on Lisp

Kent M Pitman The revised MacLisp manual satur

and Functional Programming pages

day evening edition MIT Articial Intelligence Lab

Christopher T Haynes Logic continuations In Pro

oratory Technical Rep ort May

ceedings of the Third International Conference on

Kent M Pitman Sp ecial forms in Lisp In Conference

Logic Programming pages SpringerVerlag

Record of the Lisp Conference pages

July

The Lisp Conference

Christopher T Haynes and Daniel P Friedman En

Jonathan A Rees and Norman I Adams IV T A

gines build pro cess abstracions In Conference Record

dialect of Lisp or lambda The ultimate software to ol

of the ACM Symposium on Lisp and Functional

In Conference Record of the ACM Symposium on

Programming pages

Lisp and Functional Programming pages

Peter Henderson Functional Geometry In Confer

ence Record of the ACM Symposium on Lisp and

Jonathan A Rees Norman I Adams IV and James

Functional Programming pages

R Meehan The T manual fourth edition Yale Uni

versity Computer Science Department January

Eugene Edmund Kohlb ecker Jr Syntactic Extensions

in the Programming Language Lisp PhD thesis Indi

John Reynolds Denitional interpreters for higher or

ana University August

der programming languages In ACM Conference Pro

ceedings pages ACM

David Kranz Richard Kelsey Jonathan Rees Paul

Hudak James Philbin and Norman Adams Orbit

Guillermo J Rozas Liar an Algollike compiler for

An optimizing compiler for Scheme In Proceedings of

Scheme S B thesis MIT Department of Electrical

the SIGPLAN Symposium on Compiler Construc

Engineering and Computer Science January

tion pages ACM June Pro ceedings

Brian C Smith Reection and semantics in a pro

published as SIGPLAN Notices July

cedural language MIT Lab oratory for Computer Sci

Peter Landin A corresp ondence b etween Algol and

ence Technical Rep ort January

Churchs lambda notation Part I Communications of

Amitabh Srivastava Don Oxley and Aditya Srivas

the ACM February

tava Another integration of logic and functional pro

Drew McDermott An ecient environment allo cation

gramming In Proceedings of the Symposium on Logic

scheme in an interpreter for a lexicallyscop ed lisp

Programming pages IEEE

In Conference Record of the Lisp Conference

Richard M Stallman Phantom stacksif you lo ok

pages The Lisp Conference PO Box

to o hard they arent there MIT Articial Intelligence

Redwoo d Estates CA Pro ceedings reprinted by

Memo July

ACM

MIT Department of Electrical Engineering and Com Guy Lewis Steele Jr and Gerald Jay Sussman

puter Science Scheme manual seventh edition Lambda the ultimate imp erative MIT Articial In

September telligence Memo March

Revised Scheme

Guy Lewis Steele Jr Lambda the ultimate declara Texas Instruments Inc TI Scheme Language Refer

tive MIT Articial Intelligence Memo November ence Manual Preliminary version November

Mitchell Wand Continuationbased program transfor

mation strategies Journal of the ACM

Guy Lewis Steele Jr Debunking the exp ensive pro

cedure call myth or pro cedure call implementa

tions considered harmful or lambda the ultimate

Mitchell Wand Continuationbased multiprocessing

GOTO In ACM Conference Proceedings pages

In Conference Record of the Lisp Conference

ACM

pages The Lisp Conference

Guy Lewis Steele Jr Macaroni is b etter than

spaghetti In Proceedings of the Symposium on Arti

cial Intel ligence and Programming Languages pages

These pro ceedings were published as a sp ecial

joint issue of SIGPLAN Notices and SIGART

Newsletter August

Guy Lewis Steele Jr Rabbit a compiler for Scheme

MIT Articial Intelligence Lab oratory Technical Re

p ort May

Guy Lewis Steele Jr An overview of Common Lisp

In Conference Record of the ACM Symposium on

Lisp and Functional Programming pages

Guy Lewis Steele Jr Common Lisp The Language

Digital Press Burlington MA

Guy Lewis Steele Jr and Gerald Jay Sussman The

revised rep ort on Scheme a dialect of Lisp MIT Ar

ticial Intelligence Memo January

Guy Lewis Steele Jr and Gerald Jay Sussman The

art of the interpreter or the mo dularity complex

parts zero one and two MIT Articial Intelligence

Memo May

Guy Lewis Steele Jr and Gerald Jay Sussman De

sign of a Lispbased pro cessor Communications of the

ACM November

Guy Lewis Steele Jr and Gerald Jay Sussman The

dream of a lifetime a lazy variable extent mechanism

In Conference Record of the Lisp Conference

pages The Lisp Conference

Gerald Jay Sussman and Guy Lewis Steele Jr

Scheme an interpreter for extended lambda calcu

lus MIT Articial Intelligence Memo December

Gerald Jay Sussman Jack Holloway Guy Lewis

Steele Jr and Alan Bell SchemeLisp on a chip

IEEE Computer July

Joseph E Stoy Denotational Semantics The Scott

Strachey Approach to Programming Language Theory

MIT Press Cambridge

Index

ALPHABETIC INDEX OF DEFINITIONS OF CONCEPTS

KEYWORDS AND PROCEDURES

The principal entry for each term pro cedure or keyword is cddddr

listed rst separated from the other entries by a semicolon cdr

ceiling

charinteger

charalphabetic

charci

charci

charci

charci

charci

chardowncase

charlowercase

charnumeric

charready

charready

charupcase

charuppercase

charwhitespace

char

abs

char

acos

char

and

char

angle

char

append

char

apply

closeinputport

asin

closeoutputport

assoc

combination

assq

comma

assv

comment

atsign

complex

atan

cond

cons

b

cos

backquote

currentinputport

begin

currentoutputport

binding

binding construct

d

boolean

define

b ound

delay

denominator

caar

display

caddr

do

cadr

dotted pair

call

call by need

e

callwithcurrentcontinuation

else

callwithinputfile

empty list

callwithoutputfile

eofobject

callcc

eq

car

case equal

catch equivalence predicate

cdddar eqv

Revised Scheme

error listref

escap e pro cedure listtail

essential load

even log

exactinexact

macros

exact

magnitude

exactness

makepolar

exactness

makepromise

exp

makerectangular

expt

makestring

f makevector

false map

fix mapstreams

flo max

floor member

foo memq

foreach memv

force min

modulo

gcd

mutation pro cedure

gencounter

genloser negative

newline

heur

nil

not

i

null

identier

number

if

numberstring

imagpart

number

improp er list

numerator

inexactexact

inexact

o

initial environment

odd

inputport

openinputfile

int

openoutputfile

integerchar

op erationally equivalent

integer

or

integratesystem

outputport

internal denition

pair

keyword

pair

polar

l

positive

lambda

predicate

lambda expression

pro cedure call

lastpair

procedure

lazy evaluation

promise

lcm

length

quasiquote

let

quote

let

quotient

letrec

list radix

liststring rat

listvector rational

Index

rationalize unbound

read unquote

unquotesplicing

readchar

realpart

valid indexes

real

valueslist

rect

variable

region

vector

remainder

vectorlist

return

vectorfill

reverse

vectorlength

round

vectorref

rungekutta

vectorset

vector

s

sci

whitespace

sequence

withinputfromfile

set

withoutputtofile

setcar

write

setcdr

writechar

sin

sqrt

x

stringlist

stringnumber

zero

stringsymbol

stringappend

stringci

stringci

stringci

stringci

stringci

stringcopy

stringfill

stringlength

stringref

stringset

string

string

string

string

string

string

substring

symbolstring

symbol

syntactic keyword

t

t

tan

token

top level environment

transcriptoff

transcripton

true

truncate