r5rs-doc-20010328.orig/0040755001167100001440000000000007266743543013070 5ustar cphusersr5rs-doc-20010328.orig/basic.tex0100644001167100001440000003503306473103745014665 0ustar cphusers%\vfill\eject \chapter{Basic concepts} \label{basicchapter} \section{Variables, syntactic keywords, and regions} \label{specialformsection} \label{variablesection} An identifier\index{identifier} may name a type of syntax, or it may name a location where a value can be stored. An identifier that names a type of syntax is called a {\em syntactic keyword}\mainindex{syntactic keyword} and is said to be {\em bound} to that syntax. An identifier that names a location is called a {\em variable}\mainindex{variable} and is said to be {\em bound} to that location. The set of all visible bindings\mainindex{binding} in effect at some point in a program is known as the {\em environment} in effect at that point. The value stored in the location to which a variable is bound is called the variable's value. By abuse of terminology, the variable is sometimes said to name the value or to be bound to the value. This is not quite accurate, but confusion rarely results from this practice. \todo{Define ``assigned'' and ``unassigned'' perhaps?} \todo{In programs without side effects, one can safely pretend that the variables are bound directly to the arguments. Or: In programs without \ide{set!}, one can safely pretend that the variable is bound directly to the value. } \vest Certain expression types are used to create new kinds of syntax and bind syntactic keywords to those new syntaxes, while other expression types create new locations and bind variables to those locations. These expression types are called {\em binding constructs}. \mainindex{binding construct} Those that bind syntactic keywords are listed in section~\ref{macrosection}. The most fundamental of the variable binding constructs is the {\cf lambda} expression, because all other variable binding constructs can be explained in terms of {\cf lambda} expressions. The other variable binding constructs are {\cf let}, {\cf let*}, {\cf letrec}, and {\cf do} expressions (see sections~\ref{lambda}, \ref{letrec}, and \ref{do}). %Note: internal definitions not mentioned here. \vest Like Algol and Pascal, and unlike most other dialects of Lisp except for Common Lisp, Scheme is a statically scoped language with block structure. To each place where an identifier is bound in a program there corresponds a \defining{region} of the program text within which the binding is visible. The region is determined by the particular binding construct that establishes the binding; if the binding is established by a {\cf lambda} expression, for example, then its region is the entire {\cf lambda} expression. Every mention of an identifier refers to the binding of the identifier that established the innermost of the regions containing the use. If there is no binding of the identifier whose region contains the use, then the use refers to the binding for the variable in the top level environment, if any (chapters~\ref{expressionchapter} and \ref{initialenv}); if there is no binding for the identifier, it is said to be \defining{unbound}.\mainindex{bound}\index{top level environment} \todo{Mention that some implementations have multiple top level environments?} \todo{Pitman sez: needs elaboration in case of {\tt(let ...)}} \todo{Pitman asks: say something about vars created after scheme starts? {\tt (define x 3) (define (f) x) (define (g) y) (define y 4)} Clinger replies: The language was explicitly designed to permit a view in which no variables are created after Scheme starts. In files, you can scan out the definitions beforehand. I think we're agreed on the principle that interactive use should approximate that behavior as closely as possible, though we don't yet agree on which programming environment provides the best approximation.} \section{Disjointness of types} \label{disjointness} No object satisfies more than one of the following predicates: \begin{scheme} boolean? pair? symbol? number? char? string? vector? port? procedure?% \end{scheme} These predicates define the types {\em boolean}, {\em pair}, {\em symbol}, {\em number}, {\em char} (or {\em character}), {\em string}, {\em vector}, {\em port}, and {\em procedure}. The empty list is a special object of its own type; it satisfies none of the above predicates. \mainindex{type}\schindex{boolean?}\schindex{pair?}\schindex{symbol?} \schindex{number?}\schindex{char?}\schindex{string?}\schindex{vector?} \schindex{port?}\schindex{procedure?}\index{empty list} Although there is a separate boolean type, any Scheme value can be used as a boolean value for the purpose of a conditional test. As explained in section~\ref{booleansection}, all values count as true in such a test except for \schfalse{}. % and possibly the empty list. % The only value that is guaranteed to count as % false is \schfalse{}. It is explicitly unspecified whether the empty list % counts as true or as false. This report uses the word ``true'' to refer to any Scheme value except \schfalse{}, and the word ``false'' to refer to \schfalse{}. \mainindex{true} \mainindex{false} \section{External representations} \label{externalreps} An important concept in Scheme (and Lisp) is that of the {\em external representation} of an object as a sequence of characters. For example, an external representation of the integer 28 is the sequence of characters ``{\tt 28}'', and an external representation of a list consisting of the integers 8 and 13 is the sequence of characters ``{\tt(8 13)}''. The external representation of an object is not necessarily unique. The integer 28 also has representations ``{\tt \#e28.000}'' and ``{\tt\#x1c}'', and the list in the previous paragraph also has the representations ``{\tt( 08 13 )}'' and ``{\tt(8 .\ (13 .\ ()))}'' (see section~\ref{listsection}). Many objects have standard external representations, but some, such as procedures, do not have standard representations (although particular implementations may define representations for them). An external representation may be written in a program to obtain the corresponding object (see {\cf quote}, section~\ref{quote}). External representations can also be used for input and output. The procedure {\cf read} (section~\ref{read}) parses external representations, and the procedure {\cf write} (section~\ref{write}) generates them. Together, they provide an elegant and powerful input/output facility. Note that the sequence of characters ``{\tt(+ 2 6)}'' is {\em not} an external representation of the integer 8, even though it {\em is} an expression evaluating to the integer 8; rather, it is an external representation of a three-element list, the elements of which are the symbol {\tt +} and the integers 2 and 6. Scheme's syntax has the property that any sequence of characters that is an expression is also the external representation of some object. This can lead to confusion, since it may not be obvious out of context whether a given sequence of characters is intended to denote data or program, but it is also a source of power, since it facilitates writing programs such as interpreters and compilers that treat programs as data (or vice versa). The syntax of external representations of various kinds of objects accompanies the description of the primitives for manipulating the objects in the appropriate sections of chapter~\ref{initialenv}. \section{Storage model} \label{storagemodel} Variables and objects such as pairs, vectors, and strings implicitly denote locations\mainindex{location} or sequences of locations. A string, for example, denotes as many locations as there are characters in the string. (These locations need not correspond to a full machine word.) A new value may be stored into one of these locations using the {\tt string-set!} procedure, but the string continues to denote the same locations as before. An object fetched from a location, by a variable reference or by a procedure such as {\cf car}, {\cf vector-ref}, or {\cf string-ref}, is equivalent in the sense of \ide{eqv?} % and \ide{eq?} ?? (section~\ref{equivalencesection}) to the object last stored in the location before the fetch. Every location is marked to show whether it is in use. No variable or object ever refers to a location that is not in use. Whenever this report speaks of storage being allocated for a variable or object, what is meant is that an appropriate number of locations are chosen from the set of locations that are not in use, and the chosen locations are marked to indicate that they are now in use before the variable or object is made to denote them. In many systems it is desirable for constants\index{constant} (i.e. the values of literal expressions) to reside in read-only-memory. To express this, it is convenient to imagine that every object that denotes locations is associated with a flag telling whether that object is mutable\index{mutable} or immutable\index{immutable}. In such systems literal constants and the strings returned by \ide{symbol->string} are immutable objects, while all objects created by the other procedures listed in this report are mutable. It is an error to attempt to store a new value into a location that is denoted by an immutable object. \section{Proper tail recursion} \label{proper tail recursion} Implementations of Scheme are required to be {\em properly tail-recursive}\mainindex{proper tail recursion}. Procedure calls that occur in certain syntactic contexts defined below are `tail calls'. A Scheme implementation is properly tail-recursive if it supports an unbounded number of active tail calls. A call is {\em active} if the called procedure may still return. Note that this includes calls that may be returned from either by the current continuation or by continuations captured earlier by {\cf call-with-current-continuation} that are later invoked. In the absence of captured continuations, calls could return at most once and the active calls would be those that had not yet returned. A formal definition of proper tail recursion can be found in~\cite{propertailrecursion}. \begin{rationale} Intuitively, no space is needed for an active tail call because the continuation that is used in the tail call has the same semantics as the continuation passed to the procedure containing the call. Although an improper implementation might use a new continuation in the call, a return to this new continuation would be followed immediately by a return to the continuation passed to the procedure. A properly tail-recursive implementation returns to that continuation directly. Proper tail recursion was one of the central ideas in Steele and Sussman's original version of Scheme. Their first Scheme interpreter implemented both functions and actors. Control flow was expressed using actors, which differed from functions in that they passed their results on to another actor instead of returning to a caller. In the terminology of this section, each actor finished with a tail call to another actor. Steele and Sussman later observed that in their interpreter the code for dealing with actors was identical to that for functions and thus there was no need to include both in the language. \end{rationale} A {\em tail call}\mainindex{tail call} is a procedure call that occurs in a {\em tail context}. Tail contexts are defined inductively. Note that a tail context is always determined with respect to a particular lambda expression. \begin{itemize} \item The last expression within the body of a lambda expression, shown as \hyper{tail expression} below, occurs in a tail context. \begin{grammar}% (l\=ambda \meta{formals} \>\arbno{\meta{definition}} \arbno{\meta{expression}} \meta{tail expression}) \end{grammar}% \item If one of the following expressions is in a tail context, then the subexpressions shown as \meta{tail expression} are in a tail context. These were derived from rules in the grammar given in chapter~\ref{formalchapter} by replacing some occurrences of \meta{expression} with \meta{tail expression}. Only those rules that contain tail contexts are shown here. \begin{grammar}% (if \meta{expression} \meta{tail expression} \meta{tail expression}) (if \meta{expression} \meta{tail expression}) (cond \atleastone{\meta{cond clause}}) (cond \arbno{\meta{cond clause}} (else \meta{tail sequence})) (c\=ase \meta{expression} \>\atleastone{\meta{case clause}}) (c\=ase \meta{expression} \>\arbno{\meta{case clause}} \>(else \meta{tail sequence})) (and \arbno{\meta{expression}} \meta{tail expression}) (or \arbno{\meta{expression}} \meta{tail expression}) (let (\arbno{\meta{binding spec}}) \meta{tail body}) (let \meta{variable} (\arbno{\meta{binding spec}}) \meta{tail body}) (let* (\arbno{\meta{binding spec}}) \meta{tail body}) (letrec (\arbno{\meta{binding spec}}) \meta{tail body}) (let-syntax (\arbno{\meta{syntax spec}}) \meta{tail body}) (letrec-syntax (\arbno{\meta{syntax spec}}) \meta{tail body}) (begin \meta{tail sequence}) (d\=o \=(\arbno{\meta{iteration spec}}) \> \>(\meta{test} \meta{tail sequence}) \>\arbno{\meta{expression}}) {\rm where} \meta{cond clause} \: (\meta{test} \meta{tail sequence}) \meta{case clause} \: ((\arbno{\meta{datum}}) \meta{tail sequence}) \meta{tail body} \: \arbno{\meta{definition}} \meta{tail sequence} \meta{tail sequence} \: \arbno{\meta{expression}} \meta{tail expression} \end{grammar}% \item If a {\cf cond} expression is in a tail context, and has a clause of the form {\cf (\hyperi{expression} => \hyperii{expression})} then the (implied) call to the procedure that results from the evaluation of \hyperii{expression} is in a tail context. \hyperii{expression} itself is not in a tail context. \end{itemize} Certain built-in procedures are also required to perform tail calls. The first argument passed to \ide{apply} and to \ide{call-with-current-continuation}, and the second argument passed to \ide{call-with-values}, must be called via a tail call. Similarly, \ide{eval} must evaluate its argument as if it were in tail position within the \ide{eval} procedure. In the following example the only tail call is the call to {\cf f}. None of the calls to {\cf g} or {\cf h} are tail calls. The reference to {\cf x} is in a tail context, but it is not a call and thus is not a tail call. \begin{scheme}% (lambda () (if (g) (let ((x (h))) x) (and (g) (f)))) \end{scheme}% \begin{note} Implementations are allowed, but not required, to recognize that some non-tail calls, such as the call to {\cf h} above, can be evaluated as though they were tail calls. In the example above, the {\cf let} expression could be compiled as a tail call to {\cf h}. (The possibility of {\cf h} returning an unexpected number of values can be ignored, because in that case the effect of the {\cf let} is explicitly unspecified and implementation-dependent.) \end{note} r5rs-doc-20010328.orig/bib.tex0100644001167100001440000001615606473331167014346 0ustar cphusers % My reference for proper reference format is: % Mary-Claire van Leunen. % {\em A Handbook for Scholars.} % Knopf, 1978. % I think the references list would look better in ``open'' format, % i.e. with the three blocks for each entry appearing on separate % lines. I used the compressed format for SIGPLAN in the interest of % space. In open format, when a block runs over one line, % continuation lines should be indented; this could probably be done % using some flavor of latex list environment. Maybe the right thing % to do in the long run would be to convert to Bibtex, which probably % does the right thing, since it was implemented by one of van % Leunen's colleagues at DEC SRC. % -- Jonathan % I tried to follow Jonathan's format, insofar as I understood it. % I tried to order entries lexicographically by authors (with singly % authored papers first), then by date. % In some cases I replaced a technical report or conference paper % by a subsequent journal article, but I think there are several % more such replacements that ought to be made. % -- Will, 1991. % This is just a personal remark on your question on the RRRS: % The language CUCH (Curry-Church) was implemented by 1964 and % is a practical version of the lambda-calculus (call-by-name). % One reference you may find in Formal Language Description Languages % for Computer Programming T.~B.~Steele, 1965 (or so). % -- Matthias Felleisen % Rather than try to keep the bibliography up-to-date, which is hopeless % given the time between updates, I replaced the bulk of the references % with a pointer to the Scheme Repository. Ozan Yigit's bibliography in % the repository is a superset of the R4RS one. % The bibliography now contains only items referenced within the report. % -- Richard, 1996. \begin{thebibliography}{999} \bibitem{SICP} Harold Abelson and Gerald Jay Sussman with Julie Sussman. {\em Structure and Interpretation of Computer Programs, second edition.} MIT Press, Cambridge, 1996. \bibitem{Bawden88} %new Alan Bawden and Jonathan Rees. Syntactic closures. In {\em Proceedings of the 1988 ACM Symposium on Lisp and Functional Programming}, pages 86--95. \bibitem{howtoprint} Robert G. Burger~and R. Kent Dybvig. Printing floating-point numbers quickly and accurately. In {\em Proceedings of the ACM SIGPLAN '96 Conference on Programming Language Design and Implementation}, pages~108--116. \bibitem{RRRS} William Clinger, editor. The revised revised report on Scheme, or an uncommon Lisp. MIT Artificial Intelligence Memo 848, August 1985. Also published as Computer Science Department Technical Report 174, Indiana University, June 1985. \bibitem{howtoread} %new William Clinger. How to read floating point numbers accurately. In {\em Proceedings of the ACM SIGPLAN '90 Conference on Programming Language Design and Implementation}, pages 92--101. Proceedings published as {\em SIGPLAN Notices} 25(6), June 1990. \bibitem{R4RS} William Clinger and Jonathan Rees, editors. The revised$^4$ report on the algorithmic language Scheme. In {\em ACM Lisp Pointers} 4(3), pages~1--55, 1991. \bibitem{macrosthatwork} %new William Clinger and Jonathan Rees. Macros that work. In {\em Proceedings of the 1991 ACM Conference on Principles of Programming Languages}, pages~155--162. \bibitem{propertailrecursion} %new William Clinger. Proper Tail Recursion and Space Efficiency. To appear in {\em Proceedings of the 1998 ACM Conference on Programming Language Design and Implementation}, June 1998. \bibitem{syntacticabstraction} R.~Kent Dybvig, Robert Hieb, and Carl Bruggeman. Syntactic abstraction in Scheme. {\em Lisp and Symbolic Computation} 5(4):295--326, 1993. \bibitem{Scheme311} Carol Fessenden, William Clinger, Daniel P.~Friedman, and Christopher Haynes. Scheme 311 version 4 reference manual. Indiana University Computer Science Technical Report 137, February 1983. Superseded by~\cite{Scheme84}. \bibitem{Scheme84} D.~Friedman, C.~Haynes, E.~Kohlbecker, and M.~Wand. Scheme 84 interim reference manual. Indiana University Computer Science Technical Report 153, January 1985. \bibitem{IEEE} {\em IEEE Standard 754-1985. IEEE Standard for Binary Floating-Point Arithmetic.} IEEE, New York, 1985. \bibitem{IEEEScheme} {\em IEEE Standard 1178-1990. IEEE Standard for the Scheme Programming Language.} IEEE, New York, 1991. \bibitem{Kohlbecker86} Eugene E. Kohlbecker~Jr. {\em Syntactic Extensions in the Programming Language Lisp.} PhD thesis, Indiana University, August 1986. \bibitem{hygienic} Eugene E.~Kohlbecker~Jr., Daniel P.~Friedman, Matthias Felleisen, and Bruce Duba. Hygienic macro expansion. In {\em Proceedings of the 1986 ACM Conference on Lisp and Functional Programming}, pages 151--161. \bibitem{Landin65} Peter Landin. A correspondence between Algol 60 and Church's lambda notation: Part I. {\em Communications of the ACM} 8(2):89--101, February 1965. \bibitem{MITScheme} MIT Department of Electrical Engineering and Computer Science. Scheme manual, seventh edition. September 1984. \bibitem{Naur63} Peter Naur et al. Revised report on the algorithmic language Algol 60. {\em Communications of the ACM} 6(1):1--17, January 1963. \bibitem{Penfield81} Paul Penfield, Jr. Principal values and branch cuts in complex APL. In {\em APL '81 Conference Proceedings,} pages 248--256. ACM SIGAPL, San Francisco, September 1981. Proceedings published as {\em APL Quote Quad} 12(1), ACM, September 1981. \bibitem{Pitman83} Kent M.~Pitman. The revised MacLisp manual (Saturday evening edition). MIT Laboratory for Computer Science Technical Report 295, May 1983. \bibitem{Rees82} Jonathan A.~Rees and Norman I.~Adams IV. T: A dialect of Lisp or, lambda: The ultimate software tool. In {\em Conference Record of the 1982 ACM Symposium on Lisp and Functional Programming}, pages 114--122. \bibitem{Rees84} Jonathan A.~Rees, Norman I.~Adams IV, and James R.~Meehan. The T manual, fourth edition. Yale University Computer Science Department, January 1984. \bibitem{R3RS} Jonathan Rees and William Clinger, editors. The revised$^3$ report on the algorithmic language Scheme. In {\em ACM SIGPLAN Notices} 21(12), pages~37--79, December 1986. \bibitem{Reynolds72} John Reynolds. Definitional interpreters for higher order programming languages. In {\em ACM Conference Proceedings}, pages 717--740. ACM, \todo{month?}~1972. \bibitem{Scheme78} Guy Lewis Steele Jr.~and Gerald Jay Sussman. The revised report on Scheme, a dialect of Lisp. MIT Artificial Intelligence Memo 452, January 1978. \bibitem{Rabbit} Guy Lewis Steele Jr. Rabbit: a compiler for Scheme. MIT Artificial Intelligence Laboratory Technical Report 474, May 1978. \bibitem{CLtL} Guy Lewis Steele Jr. {\em Common Lisp: The Language, second edition.} Digital Press, Burlington MA, 1990. \bibitem{Scheme75} Gerald Jay Sussman and Guy Lewis Steele Jr. Scheme: an interpreter for extended lambda calculus. MIT Artificial Intelligence Memo 349, December 1975. \bibitem{Stoy77} Joseph E.~Stoy. {\em Denotational Semantics: The Scott-Strachey Approach to Programming Language Theory.} MIT Press, Cambridge, 1977. \bibitem{TImanual85} Texas Instruments, Inc. TI Scheme Language Reference Manual. Preliminary version 1.0, November 1985. \end{thebibliography} r5rs-doc-20010328.orig/commands.tex0100644001167100001440000001520206470160211015365 0ustar cphusers% Macros for R^nRS. \makeatletter \newcommand{\topnewpage}{\@topnewpage} \newcommand{\authorsc}[1]{{\scriptsize\scshape #1}} % Chapters, sections, etc. \newcommand{\extrapart}[1]{ % \chapter{#1} \chapter*{#1} \markboth{#1}{#1} \vskip 1ex \addcontentsline{toc}{chapter}{#1}} \newcommand{\clearchapterstar}[1]{ \clearpage \topnewpage[ \centerline{\large\bf\uppercase{#1}} \bigskip]} \newcommand{\clearextrapart}[1]{ \clearchapterstar{#1} \markboth{#1}{#1} \addcontentsline{toc}{chapter}{#1}} \newcommand{\vest}{} \newcommand{\dotsfoo}{$\ldots\,$} \newcommand{\sharpfoo}[1]{{\tt\##1}} \newcommand{\schfalse}{\sharpfoo{f}} \newcommand{\schtrue}{\sharpfoo{t}} \newcommand{\singlequote}{{\tt'}} %\char19 \newcommand{\doublequote}{{\tt"}} \newcommand{\backquote}{{\tt\char18}} \newcommand{\backwhack}{{\tt\char`\\}} \newcommand{\atsign}{{\tt\char`\@}} \newcommand{\sharpsign}{{\tt\#}} \newcommand{\verticalbar}{{\tt|}} \newcommand{\coerce}{\discretionary{->}{}{->}} % Knuth's \in sucks big boulders \def\elem{\hbox{\raise.13ex\hbox{$\scriptstyle\in$}}} \newcommand{\meta}[1]{{\noindent\hbox{\rm$\langle$#1$\rangle$}}} \let\hyper=\meta \newcommand{\hyperi}[1]{\hyper{#1$_1$}} \newcommand{\hyperii}[1]{\hyper{#1$_2$}} \newcommand{\hyperj}[1]{\hyper{#1$_i$}} \newcommand{\hypern}[1]{\hyper{#1$_n$}} \newcommand{\var}[1]{\noindent\hbox{\it{}#1\/}} % Careful, is \/ always the right thing? \newcommand{\vari}[1]{\var{#1$_1$}} \newcommand{\varii}[1]{\var{#1$_2$}} \newcommand{\variii}[1]{\var{#1$_3$}} \newcommand{\variv}[1]{\var{#1$_4$}} \newcommand{\varj}[1]{\var{#1$_j$}} \newcommand{\varn}[1]{\var{#1$_n$}} \newcommand{\vr}[1]{{\noindent\hbox{$#1$\/}}} % Careful, is \/ always the right thing? \newcommand{\vri}[1]{\vr{#1_1}} \newcommand{\vrii}[1]{\vr{#1_2}} \newcommand{\vriii}[1]{\vr{#1_3}} \newcommand{\vriv}[1]{\vr{#1_4}} \newcommand{\vrv}[1]{\vr{#1_5}} \newcommand{\vrj}[1]{\vr{#1_j}} \newcommand{\vrn}[1]{\vr{#1_n}} \newcommand{\defining}[1]{\mainindex{#1}{\em #1}} \newcommand{\ide}[1]{{\schindex{#1}\frenchspacing\tt{#1}}} \newcommand{\lambdaexp}{{\cf lambda} expression} \newcommand{\Lambdaexp}{{\cf Lambda} expression} \newcommand{\callcc}{{\tt call-with-current-continuation}} % \reallyindex{SORTKEY}{HEADCS}{TYPE} % writes (index-entry "SORTKEY" "HEADCS" TYPE PAGENUMBER) % which becomes \item \HEADCS{SORTKEY} mainpagenumber ; auxpagenumber ... \global\def\reallyindex#1#2#3{% \write\@indexfile{"#1" "#2" #3 \thepage}} \newcommand{\mainschindex}[1]{\label{#1}\reallyindex{#1}{tt}{main}} \newcommand{\mainindex}[1]{\reallyindex{#1}{rm}{main}} \newcommand{\schindex}[1]{\reallyindex{#1}{tt}{aux}} \newcommand{\sharpindex}[1]{\reallyindex{#1}{sharpfoo}{aux}} \renewcommand{\index}[1]{\reallyindex{#1}{rm}{aux}} \newcommand{\domain}[1]{#1} \newcommand{\nodomain}[1]{} %\newcommand{\todo}[1]{{\rm$[\![$!!~#1$]\!]$}} \newcommand{\todo}[1]{} % \frobq will make quote and backquote look nicer. \def\frobqcats{%\catcode`\'=13 \catcode`\`=13{}} {\frobqcats \gdef\frobqdefs{%\def'{\singlequote} \def`{\backquote}}} \def\frobq{\frobqcats\frobqdefs} % \cf = code font % Unfortunately, \cf \cf won't work at all, so don't even attempt to % next constructions which use them... \newcommand{\cf}{\frenchspacing\frobq\tt} % Same as \obeycr, but doesn't do a \@gobblecr. {\catcode`\^^M=13 \gdef\myobeycr{\catcode`\^^M=13 \def^^M{\\}}% \gdef\restorecr{\catcode`\^^M=5 }} {\catcode`\^^I=13 \gdef\obeytabs{\catcode`\^^I=13 \def^^I{\hbox{\hskip 4em}}}} {\obeyspaces\gdef {\hbox{\hskip0.5em}}} \gdef\gobblecr{\@gobblecr} \def\setupcode{\@makeother\^} % Scheme example environment % At 11 points, one column, these are about 56 characters wide. % That's 32 characters to the left of the => and about 20 to the right. \newenvironment{schemenoindent}{ % Commands for scheme examples \newcommand{\ev}{\>\>\evalsto} \newcommand{\lev}{\\\>\evalsto} \newcommand{\unspecified}{{\em{}unspecified}} \newcommand{\scherror}{{\em{}error}} \setupcode \small \cf \obeytabs \obeyspaces \myobeycr \begin{tabbing}% \qquad\=\hspace*{5em}\=\hspace*{9em}\=\kill% was 16em \gobblecr}{\unskip\end{tabbing}} %\newenvironment{scheme}{\begin{schemenoindent}\+\kill}{\end{schemenoindent}} \newenvironment{scheme}{ % Commands for scheme examples \newcommand{\ev}{\>\>\evalsto} \newcommand{\lev}{\\\>\evalsto} \renewcommand{\em}{\rmfamily\itshape} \newcommand{\unspecified}{{\em{}unspecified}} \newcommand{\scherror}{{\em{}error}} \setupcode \small \cf \obeyspaces \myobeycr \begin{tabbing}% \qquad\=\hspace*{5em}\=\hspace*{9em}\=\+\kill% was 16em \gobblecr}{\unskip\end{tabbing}} \newcommand{\evalsto}{$\Longrightarrow$} % Rationale \newenvironment{rationale}{% \bgroup\small\noindent{\em Rationale:}\space}{% \egroup} % Notes \newenvironment{note}{% \bgroup\small\noindent{\em Note:}\space}{% \egroup} % Manual entries \newenvironment{entry}[1]{ \vspace{3.1ex plus .5ex minus .3ex}\noindent#1% \unpenalty\nopagebreak}{\vspace{0ex plus 1ex minus 1ex}} \newcommand{\exprtype}{syntax} % Primitive prototype \newcommand{\pproto}[2]{\unskip% \hbox{\cf\spaceskip=0.5em#1}\hfill\penalty 0% \hbox{ }\nobreak\hfill\hbox{\rm #2}\break} % Parenthesized prototype \newcommand{\proto}[3]{\pproto{(\mainschindex{#1}\hbox{#1}{\it#2\/})}{#3}} % Variable prototype \newcommand{\vproto}[2]{\mainschindex{#1}\pproto{#1}{#2}} % Extending an existing definition (\proto without the index entry) \newcommand{\rproto}[3]{\pproto{(\hbox{#1}{\it#2\/})}{#3}} % Grammar environment \newenvironment{grammar}{ \def\:{\goesto{}} \def\|{$\vert$} \cf \myobeycr \begin{tabbing} %\qquad\quad \= \qquad \= $\vert$ \= \kill }{\unskip\end{tabbing}} %\newcommand{\unsection}{\unskip} \newcommand{\unsection}{{\vskip -2ex}} % Commands for grammars \newcommand{\arbno}[1]{#1\hbox{\rm*}} \newcommand{\atleastone}[1]{#1\hbox{$^+$}} \newcommand{\goesto}{$\longrightarrow$} % The index \def\theindex{%\@restonecoltrue\if@twocolumn\@restonecolfalse\fi %\columnseprule \z@ %!! \columnsep 35pt \clearpage \@topnewpage[ \centerline{\large\bf\uppercase{Alphabetic index of definitions of concepts,}} \centerline{\large\bf\uppercase{keywords, and procedures}} \vskip 1ex \bigskip] \markboth{Index}{Index} \addcontentsline{toc}{chapter}{Alphabetic index of definitions of concepts,\hfil\penalty0 \hbox{\hspace*{2em} keywords, and procedures}} \bgroup %\small \parindent\z@ \parskip\z@ plus .1pt\relax\let\item\@idxitem} \def\@idxitem{\par\hangindent 40pt} \def\subitem{\par\hangindent 40pt \hspace*{20pt}} \def\subsubitem{\par\hangindent 40pt \hspace*{30pt}} \def\endtheindex{%\if@restonecol\onecolumn\else\clearpage\fi \egroup} \def\indexspace{\par \vskip 10pt plus 5pt minus 3pt\relax} \makeatother r5rs-doc-20010328.orig/derive.tex0100644001167100001440000001263406473076313015064 0ustar cphusers\section{Derived expression types} \label{derivedsection} This section gives macro definitions for the derived expression types in terms of the primitive expression types (literal, variable, call, {\cf lambda}, {\cf if}, {\cf set!}). See section~\ref{proceduresection} for a possible definition of {\cf delay}. \begin{scheme} (define-syntax \ide{cond} (syntax-rules (else =>) ((cond (else result1 result2 ...)) (begin result1 result2 ...)) ((cond (test => result)) (let ((temp test)) (if temp (result temp)))) ((cond (test => result) clause1 clause2 ...) (let ((temp test)) (if temp (result temp) (cond clause1 clause2 ...)))) ((cond (test)) test) ((cond (test) clause1 clause2 ...) (let ((temp test)) (if temp temp (cond clause1 clause2 ...)))) ((cond (test result1 result2 ...)) (if test (begin result1 result2 ...))) ((cond (test result1 result2 ...) clause1 clause2 ...) (if test (begin result1 result2 ...) (cond clause1 clause2 ...))))) \end{scheme} \begin{scheme} (define-syntax \ide{case} (syntax-rules (else) ((case (key ...) clauses ...) (let ((atom-key (key ...))) (case atom-key clauses ...))) ((case key (else result1 result2 ...)) (begin result1 result2 ...)) ((case key ((atoms ...) result1 result2 ...)) (if (memv key '(atoms ...)) (begin result1 result2 ...))) ((case key ((atoms ...) result1 result2 ...) clause clauses ...) (if (memv key '(atoms ...)) (begin result1 result2 ...) (case key clause clauses ...))))) \end{scheme} \begin{scheme} (define-syntax \ide{and} (syntax-rules () ((and) \sharpfoo{t}) ((and test) test) ((and test1 test2 ...) (if test1 (and test2 ...) \sharpfoo{f})))) \end{scheme} \begin{scheme} (define-syntax \ide{or} (syntax-rules () ((or) \sharpfoo{f}) ((or test) test) ((or test1 test2 ...) (let ((x test1)) (if x x (or test2 ...)))))) \end{scheme} \begin{scheme} (define-syntax \ide{let} (syntax-rules () ((let ((name val) ...) body1 body2 ...) ((lambda (name ...) body1 body2 ...) val ...)) ((let tag ((name val) ...) body1 body2 ...) ((letrec ((tag (lambda (name ...) body1 body2 ...))) tag) val ...)))) \end{scheme} \begin{scheme} (define-syntax \ide{let*} (syntax-rules () ((let* () body1 body2 ...) (let () body1 body2 ...)) ((let* ((name1 val1) (name2 val2) ...) body1 body2 ...) (let ((name1 val1)) (let* ((name2 val2) ...) body1 body2 ...))))) \end{scheme} The following {\cf letrec} macro uses the symbol {\cf } in place of an expression which returns something that when stored in a location makes it an error to try to obtain the value stored in the location (no such expression is defined in Scheme). A trick is used to generate the temporary names needed to avoid specifying the order in which the values are evaluated. This could also be accomplished by using an auxiliary macro. \begin{scheme} (define-syntax \ide{letrec} (syntax-rules () ((letrec ((var1 init1) ...) body ...) (letrec "generate\_temp\_names" (var1 ...) () ((var1 init1) ...) body ...)) ((letrec "generate\_temp\_names" () (temp1 ...) ((var1 init1) ...) body ...) (let ((var1 ) ...) (let ((temp1 init1) ...) (set! var1 temp1) ... body ...))) ((letrec "generate\_temp\_names" (x y ...) (temp ...) ((var1 init1) ...) body ...) (letrec "generate\_temp\_names" (y ...) (newtemp temp ...) ((var1 init1) ...) body ...)))) \end{scheme} \begin{scheme} (define-syntax \ide{begin} (syntax-rules () ((begin exp ...) ((lambda () exp ...))))) \end{scheme} The following alternative expansion for {\cf begin} does not make use of the ability to write more than one expression in the body of a lambda expression. In any case, note that these rules apply only if the body of the {\cf begin} contains no definitions. \begin{scheme} (define-syntax begin (syntax-rules () ((begin exp) exp) ((begin exp1 exp2 ...) (let ((x exp1)) (begin exp2 ...))))) \end{scheme} The following definition of {\cf do} uses a trick to expand the variable clauses. As with {\cf letrec} above, an auxiliary macro would also work. The expression {\cf (if \#f \#f)} is used to obtain an unspecific value. \begin{scheme} (define-syntax \ide{do} (syntax-rules () ((do ((var init step ...) ...) (test expr ...) command ...) (letrec ((loop (lambda (var ...) (if test (begin (if \#f \#f) expr ...) (begin command ... (loop (do "step" var step ...) ...)))))) (loop init ...))) ((do "step" x) x) ((do "step" x y) y))) \end{scheme} % `a = Q_1[a] % `(a b c ... . z) = `(a . (b c ...)) % `(a . b) = (append Q*_0[a] `b) % `(a) = Q*_0[a] % Q*_0[a] = (list 'a) % Q*_0[,a] = (list a) % Q*_0[,@a] = a % Q*_0[`a] = (list 'quasiquote Q*_1[a]) % `#(a b ...) = (list->vector `(a b ...)) % ugh. r5rs-doc-20010328.orig/example.tex0100644001167100001440000001031406473330636015233 0ustar cphusers \extrapart{Example} % -*- Mode: Lisp; Package: SCHEME; Syntax: Common-lisp -*- \nobreak {\cf Integrate-system} integrates the system $$y_k^\prime = f_k(y_1, y_2, \ldots, y_n), \; k = 1, \ldots, n$$ of differential equations with the method of Runge-Kutta. The parameter {\tt system-derivative} is a function that takes a system state (a vector of values for the state variables $y_1, \ldots, y_n$) and produces a system derivative (the values $y_1^\prime, \ldots, y_n^\prime$). The parameter {\tt initial-state} provides an initial system state, and {\tt h} is an initial guess for the length of the integration step. The value returned by {\cf integrate-system} is an infinite stream of system states. \begin{schemenoindent} (define integrate-system (lambda (system-derivative initial-state h) (let ((next (runge-kutta-4 system-derivative h))) (letrec ((states (cons initial-state (delay (map-streams next states))))) states))))% \end{schemenoindent} {\cf Runge-Kutta-4} takes a function, {\tt f}, that produces a system derivative from a system state. {\cf Runge-Kutta-4} produces a function that takes a system state and produces a new system state. \begin{schemenoindent} (define runge-kutta-4 (lambda (f h) (let ((*h (scale-vector h)) (*2 (scale-vector 2)) (*1/2 (scale-vector (/ 1 2))) (*1/6 (scale-vector (/ 1 6)))) (lambda (y) ;; y {\rm{}is a system state} (let* ((k0 (*h (f y))) (k1 (*h (f (add-vectors y (*1/2 k0))))) (k2 (*h (f (add-vectors y (*1/2 k1))))) (k3 (*h (f (add-vectors y k2))))) (add-vectors y (*1/6 (add-vectors k0 (*2 k1) (*2 k2) k3)))))))) %|--------------------------------------------------| (define elementwise (lambda (f) (lambda vectors (generate-vector (vector-length (car vectors)) (lambda (i) (apply f (map (lambda (v) (vector-ref v i)) vectors))))))) %|--------------------------------------------------| (define generate-vector (lambda (size proc) (let ((ans (make-vector size))) (letrec ((loop (lambda (i) (cond ((= i size) ans) (else (vector-set! ans i (proc i)) (loop (+ i 1))))))) (loop 0))))) (define add-vectors (elementwise +)) (define scale-vector (lambda (s) (elementwise (lambda (x) (* x s)))))% \end{schemenoindent} {\cf Map-streams} is analogous to {\cf map}: it applies its first argument (a procedure) to all the elements of its second argument (a stream). \begin{schemenoindent} (define map-streams (lambda (f s) (cons (f (head s)) (delay (map-streams f (tail s))))))% \end{schemenoindent} Infinite streams are implemented as pairs whose car holds the first element of the stream and whose cdr holds a promise to deliver the rest of the stream. \begin{schemenoindent} (define head car) (define tail (lambda (stream) (force (cdr stream))))% \end{schemenoindent} \bigskip The following illustrates the use of {\cf integrate-system} in integrating the system $$ C {dv_C \over dt} = -i_L - {v_C \over R}$$\nobreak $$ L {di_L \over dt} = v_C$$ which models a damped oscillator. \begin{schemenoindent} (define damped-oscillator (lambda (R L C) (lambda (state) (let ((Vc (vector-ref state 0)) (Il (vector-ref state 1))) (vector (- 0 (+ (/ Vc (* R C)) (/ Il C))) (/ Vc L)))))) (define the-states (integrate-system (damped-oscillator 10000 1000 .001) '\#(1 0) .01))% \end{schemenoindent} \todo{Show some output?} % (letrec ((loop (lambda (s) % (newline) % (write (head s)) % (loop (tail s))))) % (loop the-states)) % #(1 0) % #(0.99895054 9.994835e-6) % #(0.99780226 1.9978681e-5) % #(0.9965554 2.9950552e-5) % #(0.9952102 3.990946e-5) % #(0.99376684 4.985443e-5) % #(0.99222565 5.9784474e-5) % #(0.9905868 6.969862e-5) % #(0.9888506 7.9595884e-5) % #(0.9870173 8.94753e-5) r5rs-doc-20010328.orig/prog.tex0100644001167100001440000001576006471137662014563 0ustar cphusers\chapter{Program structure} \label{programchapter} \section{Programs} A Scheme program consists of a sequence of expressions, definitions, and syntax definitions. Expressions are described in chapter~\ref{expressionchapter}; definitions and syntax definitions are the subject of the rest of the present chapter. Programs are typically stored in files or entered interactively to a running Scheme system, although other paradigms are possible; questions of user interface lie outside the scope of this report. (Indeed, Scheme would still be useful as a notation for expressing computational methods even in the absence of a mechanical implementation.) Definitions and syntax definitions occurring at the top level of a program can be interpreted declaratively. They cause bindings to be created in the top level environment or modify the value of existing top-level bindings. Expressions occurring at the top level of a program are interpreted imperatively; they are executed in order when the program is invoked or loaded, and typically perform some kind of initialization. At the top level of a program {\tt(begin \hyperi{form} \dotsfoo)} is equivalent to the sequence of expressions, definitions, and syntax definitions that form the body of the \ide{begin}. \todo{Cromarty, etc.: disclaimer about top level?} \section{Definitions} \label{defines} Definitions are valid in some, but not all, contexts where expressions are allowed. They are valid only at the top level of a \hyper{program} and at the beginning of a \hyper{body}. \mainindex{definition} A definition should have one of the following forms:\mainschindex{define} \begin{itemize} \item{\tt(define \hyper{variable} \hyper{expression})} \item{\tt(define (\hyper{variable} \hyper{formals}) \hyper{body})} \hyper{Formals} should be either a sequence of zero or more variables, or a sequence of one or more variables followed by a space-delimited period and another variable (as in a lambda expression). This form is equivalent to \begin{scheme} (define \hyper{variable} (lambda (\hyper{formals}) \hyper{body}))\rm.% \end{scheme} \item{\tt(define (\hyper{variable} .\ \hyper{formal}) \hyper{body})} \hyper{Formal} should be a single variable. This form is equivalent to \begin{scheme} (define \hyper{variable} (lambda \hyper{formal} \hyper{body}))\rm.% \end{scheme} \end{itemize} \subsection{Top level definitions} At the top level of a program, a definition \begin{scheme} (define \hyper{variable} \hyper{expression})% \end{scheme} has essentially the same effect as the assignment expression \begin{scheme} (\ide{set!}\ \hyper{variable} \hyper{expression})% \end{scheme} if \hyper{variable} is bound. If \hyper{variable} is not bound, however, then the definition will bind \hyper{variable} to a new location before performing the assignment, whereas it would be an error to perform a {\cf set!}\ on an unbound\index{unbound} variable. \begin{scheme} (define add3 (lambda (x) (+ x 3))) (add3 3) \ev 6 (define first car) (first '(1 2)) \ev 1% \end{scheme} Some implementations of Scheme use an initial environment in which all possible variables are bound to locations, most of which contain undefined values. Top level definitions in such an implementation are truly equivalent to assignments. \todo{Rozas: equal time for opposition semantics?} \subsection{Internal definitions} \label{internaldefines} Definitions may occur at the beginning of a \hyper{body} (that is, the body of a \ide{lambda}, \ide{let}, \ide{let*}, \ide{letrec}, \ide{let-syntax}, or \ide{letrec-syntax} expression or that of a definition of an appropriate form). Such definitions are known as {\em internal definitions} \mainindex{internal definition} as opposed to the top level definitions described above. The variable defined by an internal definition is local to the \hyper{body}. That is, \hyper{variable} is bound rather than assigned, and the region of the binding is the entire \hyper{body}. For example, \begin{scheme} (let ((x 5)) (define foo (lambda (y) (bar x y))) (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3))) \ev 45% \end{scheme} A \hyper{body} containing internal definitions can always be converted into a completely equivalent {\cf letrec} expression. For example, the {\cf let} expression in the above example is equivalent to \begin{scheme} (let ((x 5)) (letrec ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3))))% \end{scheme} Just as for the equivalent {\cf letrec} expression, it must be possible to evaluate each \hyper{expression} of every internal definition in a \hyper{body} without assigning or referring to the value of any \hyper{variable} being defined. Wherever an internal definition may occur {\tt(begin \hyperi{definition} \dotsfoo)} is equivalent to the sequence of definitions that form the body of the \ide{begin}. \section{Syntax definitions} Syntax definitions are valid only at the top level of a \hyper{program}. \mainindex{syntax definition} They have the following form:\mainschindex{define-syntax} {\tt(define-syntax \hyper{keyword} \hyper{transformer spec})} \hyper{Keyword} is an identifier, and the \hyper{transformer spec} should be an instance of \ide{syntax-rules}. The top-level syntactic environment is extended by binding the \hyper{keyword} to the specified transformer. There is no {\cf define-syntax} analogue of internal definitions. %[Rationale flushed because it may or may not be true and isn't the % real rationale anyway. -RK] %\begin{rationale} %As discussed below, the syntax and scope rules for syntax definitions %can give rise to syntactic ambiguities when syntactic keywords are %shadowed. %Further ambiguities would arise if {\cf define-syntax} %were permitted at the beginning of a \meta{body}, with scope %rules analogous to those for internal definitions. %\end{rationale} % It is an error for a program to contain more than one top-level % \meta{definition} or \meta{syntax definition} of any identifier. % % [I flushed this because it isn't an error for a program to % contain more than one top-level definition of an identifier, % and I didn't want to introduce any gratuitous incompatibilities % with the existing Scheme language. -- Will] Although macros may expand into definitions and syntax definitions in any context that permits them, it is an error for a definition or syntax definition to shadow a syntactic keyword whose meaning is needed to determine whether some form in the group of forms that contains the shadowing definition is in fact a definition, or, for internal definitions, is needed to determine the boundary between the group and the expressions that follow the group. For example, the following are errors: \begin{scheme} (define define 3) (begin (define begin list)) (let-syntax ((foo (syntax-rules () ((foo (proc args ...) body ...) (define proc (lambda (args ...) body ...)))))) (let ((x 3)) (foo (plus x y) (+ x y)) (define foo x) (plus foo x))) \end{scheme} r5rs-doc-20010328.orig/first.tex0100644001167100001440000000540706472060413014726 0ustar cphusers% First page \thispagestyle{empty} % \todo{"another" report?} \topnewpage[{ \begin{center} {\huge\bf Revised{\Huge$^{\mathbf{5}}$} Report on the Algorithmic Language \\ \vskip 3pt Scheme} \vskip 1ex $$ \begin{tabular}{l@{\extracolsep{.5in}}lll} \multicolumn{4}{c}{R\authorsc{ICHARD} K\authorsc{ELSEY}, W\authorsc{ILLIAM} C\authorsc{LINGER, AND} J\authorsc{ONATHAN} R\authorsc{EES} ({\itshape Editors\/})} \\ H. A\authorsc{BELSON} & R. K. D\authorsc{YBVIG} & C. T. H\authorsc{AYNES} & G. J. R\authorsc{OZAS} \\ N. I. A\authorsc{DAMS IV} & D. P. F\authorsc{RIEDMAN} & E. K\authorsc{OHLBECKER} & G. L. S\authorsc{TEELE} J\authorsc{R}. \\ D. H. B\authorsc{ARTLEY} & R. H\authorsc{ALSTEAD} & D. O\authorsc{XLEY} & G. J. S\authorsc{USSMAN} \\ G. B\authorsc{ROOKS} & C. H\authorsc{ANSON} & K. M. P\authorsc{ITMAN} & M. W\authorsc{AND} \\ \end{tabular} $$ \vskip 2ex % {\it Dedicated to the Memory of ALGOL 60} {\it Dedicated to the Memory of Robert Hieb} % [For the macros in R5RS -RK] \vskip 2.6ex \end{center} }] \chapter*{Summary} The report gives a defining description of the programming language Scheme. Scheme is a statically scoped and properly tail-recursive dialect of the Lisp programming language invented by Guy Lewis Steele~Jr.\ and Gerald Jay~Sussman. It was designed to have an exceptionally clear and simple semantics and few different ways to form expressions. A wide variety of programming paradigms, including imperative, functional, and message passing styles, find convenient expression in Scheme. \vest The introduction offers a brief history of the language and of the report. \vest The first three chapters present the fundamental ideas of the language and describe the notational conventions used for describing the language and for writing programs in the language. \vest Chapters~\ref{expressionchapter} and~\ref{programchapter} describe the syntax and semantics of expressions, programs, and definitions. \vest Chapter~\ref{builtinchapter} describes Scheme's built-in procedures, which include all of the language's data manipulation and input/output primitives. \vest Chapter~\ref{formalchapter} provides a formal syntax for Scheme written in extended BNF, along with a formal denotational semantics. An example of the use of the language follows the formal syntax and semantics. \vest The report concludes with a list of references and an alphabetic index. \todo{expand the summary so that it fills up the column.} %\vfill %\begin{center} %{\large \bf %*** DRAFT*** \\ %%August 31, 1989 %\today %}\end{center} \vfill \eject \chapter*{Contents} \addvspace{3.5pt} % don't shrink this gap \renewcommand{\tocshrink}{-3.5pt} % value determined experimentally {\footnotesize \tableofcontents } \vfill \eject r5rs-doc-20010328.orig/index.sch0100644001167100001440000001104606334417232014661 0ustar cphusers; Program to process r4rs.idx entries. ; Script for running this in Chez (delete the old index.tex first): ; ; (define (sort-list list pred) (sort pred list)) ; (load "index.sch") ; (call-with-input-file "r5rs.idx" read-entries) ; (call-with-output-file "index.tex" create-index) (define main 0) (define aux 1) (define (make-entry key font main/aux page) (list key font main/aux page)) (define (entry-key x) (car x)) (define (entry-font x) (cadr x)) (define (entry-main/aux x) (caddr x)) (define (entry-page x) (cadddr x)) (define *database* '()) (define (read-entries in) (let ((next (read-char in))) (cond ((eof-object? next)) ((char=? next #\") (let* ((key (read-rest-of-string in)) (font (read in)) (main/aux (if (eq? 'main (read in)) 0 1)) (page (read in))) (index-entry key font main/aux page) (read-entries in))) (else (read-entries in))))) ; For reading in strings that contain \. (define (read-rest-of-string in) (let loop ((chars '())) (let ((next (read-char in))) (if (char=? next #\") (list->string (reverse chars)) (loop (cons next chars)))))) (define (index-entry key font main/aux page) (set! *database* (cons (make-entry (string-downcase key) font main/aux page) *database*)) #t) (define (string-downcase string) (list->string (map char-downcase (string->list string)))) (define (create-index p) (define (loop) (if (null? *database*) 'done (begin (process-key (collect-entries) p) (loop)))) (set! *database* (sort-list *database* (lambda (x y) (stringstring '(#\\)))) (define *s2* "{") (define *s3* "}}{\\hskip .75em}") (define *semi* "\; ") (define *comma* ", ") (define (write-entries key font main pages p) (if (and (char-alphabetic? (string-ref key 0)) (not (char=? (string-ref *last-key* 0) (string-ref key 0)))) (begin (display "\\indexspace" p) (newline p))) (set! *last-key* key) (display (string-append *s1* font *s2* key *s3*) p) (if main (begin (write main p) (if (not (null? pages)) (display *semi* p)))) (if (not (null? pages)) (begin (write (car pages) p) (for-each (lambda (page) (display *comma* p) (write page p)) (cdr pages)))) (newline p)) r5rs-doc-20010328.orig/index.tex0100644001167100001440000002614206473334546014721 0ustar cphusers\item{\tt{!}}{\hskip .75em}5 \item{\tt{'}}{\hskip .75em}8; 26 \item{\tt{*}}{\hskip .75em}22 \item{\tt{+}}{\hskip .75em}22; 5, 42 \item{\tt{,}}{\hskip .75em}13; 26 \item{\tt{,@}}{\hskip .75em}13 \item{\tt{-}}{\hskip .75em}22; 5 \item{\tt{->}}{\hskip .75em}5 \item{\tt{...}}{\hskip .75em}5; 14 \item{\tt{/}}{\hskip .75em}22 \item{\tt{;}}{\hskip .75em}5 \item{\tt{<}}{\hskip .75em}21; 42 \item{\tt{<=}}{\hskip .75em}21 \item{\tt{=}}{\hskip .75em}21; 22 \item{\tt{=>}}{\hskip .75em}10 \item{\tt{>}}{\hskip .75em}21 \item{\tt{>=}}{\hskip .75em}21 \item{\tt{?}}{\hskip .75em}4 \item{\tt{`}}{\hskip .75em}13 \indexspace \item{\tt{abs}}{\hskip .75em}22; 24 \item{\tt{acos}}{\hskip .75em}23 \item{\tt{and}}{\hskip .75em}11; 43 \item{\tt{angle}}{\hskip .75em}24 \item{\tt{append}}{\hskip .75em}27 \item{\tt{apply}}{\hskip .75em}32; 8, 43 \item{\tt{asin}}{\hskip .75em}23 \item{\tt{assoc}}{\hskip .75em}27 \item{\tt{assq}}{\hskip .75em}27 \item{\tt{assv}}{\hskip .75em}27 \item{\tt{atan}}{\hskip .75em}23 \indexspace \item{\sharpfoo{b}}{\hskip .75em}21; 38 \item{\rm{backquote}}{\hskip .75em}13 \item{\tt{begin}}{\hskip .75em}12; 16, 44 \item{\rm{binding}}{\hskip .75em}6 \item{\rm{binding construct}}{\hskip .75em}6 \item{\tt{boolean?}}{\hskip .75em}25; 6 \item{\rm{bound}}{\hskip .75em}6 \indexspace \item{\tt{caar}}{\hskip .75em}26 \item{\tt{cadr}}{\hskip .75em}26 \item{\rm{call}}{\hskip .75em}9 \item{\rm{call by need}}{\hskip .75em}13 \item{\tt{call-with-current-continuation}}{\hskip .75em}33; 8, 34, 43 \item{\tt{call-with-input-file}}{\hskip .75em}35 \item{\tt{call-with-output-file}}{\hskip .75em}35 \item{\tt{call-with-values}}{\hskip .75em}34; 8, 43 \item{\tt{call/cc}}{\hskip .75em}34 \item{\tt{car}}{\hskip .75em}26; 42 \item{\tt{case}}{\hskip .75em}10; 43 \item{\tt{catch}}{\hskip .75em}34 \item{\tt{cdddar}}{\hskip .75em}26 \item{\tt{cddddr}}{\hskip .75em}26 \item{\tt{cdr}}{\hskip .75em}26 \item{\tt{ceiling}}{\hskip .75em}23 \item{\tt{char->integer}}{\hskip .75em}29 \item{\tt{char-alphabetic?}}{\hskip .75em}29 \item{\tt{char-ci<=?}}{\hskip .75em}29 \item{\tt{char-ci=?}}{\hskip .75em}29 \item{\tt{char-ci>?}}{\hskip .75em}29 \item{\tt{char-downcase}}{\hskip .75em}29 \item{\tt{char-lower-case?}}{\hskip .75em}29 \item{\tt{char-numeric?}}{\hskip .75em}29 \item{\tt{char-ready?}}{\hskip .75em}36 \item{\tt{char-upcase}}{\hskip .75em}29 \item{\tt{char-upper-case?}}{\hskip .75em}29 \item{\tt{char-whitespace?}}{\hskip .75em}29 \item{\tt{char<=?}}{\hskip .75em}29 \item{\tt{char=?}}{\hskip .75em}29 \item{\tt{char>?}}{\hskip .75em}29 \item{\tt{char?}}{\hskip .75em}29; 6 \item{\tt{close-input-port}}{\hskip .75em}36 \item{\tt{close-output-port}}{\hskip .75em}36 \item{\rm{combination}}{\hskip .75em}9 \item{\rm{comma}}{\hskip .75em}13 \item{\rm{comment}}{\hskip .75em}5; 38 \item{\tt{complex?}}{\hskip .75em}21; 19 \item{\tt{cond}}{\hskip .75em}10; 15, 43 \item{\tt{cons}}{\hskip .75em}26 \item{\rm{constant}}{\hskip .75em}7 \item{\rm{continuation}}{\hskip .75em}33 \item{\tt{cos}}{\hskip .75em}23 \item{\tt{current-input-port}}{\hskip .75em}35 \item{\tt{current-output-port}}{\hskip .75em}35 \indexspace \item{\sharpfoo{d}}{\hskip .75em}21 \item{\tt{define}}{\hskip .75em}16; 14 \item{\tt{define-syntax}}{\hskip .75em}17 \item{\rm{definition}}{\hskip .75em}16 \item{\tt{delay}}{\hskip .75em}13; 32 \item{\tt{denominator}}{\hskip .75em}23 \item{\tt{display}}{\hskip .75em}37 \item{\tt{do}}{\hskip .75em}12; 44 \item{\rm{dotted pair}}{\hskip .75em}25 \item{\tt{dynamic-wind}}{\hskip .75em}34; 33 \indexspace \item{\sharpfoo{e}}{\hskip .75em}21; 38 \item{\tt{else}}{\hskip .75em}10 \item{\rm{empty list}}{\hskip .75em}25; 6, 26 \item{\tt{eof-object?}}{\hskip .75em}36 \item{\tt{eq?}}{\hskip .75em}18; 10 \item{\tt{equal?}}{\hskip .75em}19 \item{\rm{equivalence predicate}}{\hskip .75em}17 \item{\tt{eqv?}}{\hskip .75em}17; 7, 10, 42 \item{\rm{error}}{\hskip .75em}4 \item{\rm{escape procedure}}{\hskip .75em}33 \item{\tt{eval}}{\hskip .75em}35; 8 \item{\tt{even?}}{\hskip .75em}22 \item{\rm{exact}}{\hskip .75em}17 \item{\tt{exact->inexact}}{\hskip .75em}24 \item{\tt{exact?}}{\hskip .75em}21 \item{\rm{exactness}}{\hskip .75em}19 \item{\tt{exp}}{\hskip .75em}23 \item{\tt{expt}}{\hskip .75em}24 \indexspace \item{\sharpfoo{f}}{\hskip .75em}25 \item{\rm{false}}{\hskip .75em}6; 25 \item{\tt{floor}}{\hskip .75em}23 \item{\tt{for-each}}{\hskip .75em}32 \item{\tt{force}}{\hskip .75em}32; 13 \indexspace \item{\tt{gcd}}{\hskip .75em}23 \indexspace \item{\rm{hygienic}}{\hskip .75em}13 \indexspace \item{\sharpfoo{i}}{\hskip .75em}21; 38 \item{\rm{identifier}}{\hskip .75em}5; 6, 28, 38 \item{\tt{if}}{\hskip .75em}10; 41 \item{\tt{imag-part}}{\hskip .75em}24 \item{\rm{immutable}}{\hskip .75em}7 \item{\rm{implementation restriction}}{\hskip .75em}4; 20 \item{\rm{improper list}}{\hskip .75em}26 \item{\rm{inexact}}{\hskip .75em}17 \item{\tt{inexact->exact}}{\hskip .75em}24; 20 \item{\tt{inexact?}}{\hskip .75em}21 \item{\rm{initial environment}}{\hskip .75em}17 \item{\tt{input-port?}}{\hskip .75em}35 \item{\tt{integer->char}}{\hskip .75em}29 \item{\tt{integer?}}{\hskip .75em}21; 19 \item{\tt{interaction-environment}}{\hskip .75em}35 \item{\rm{internal definition}}{\hskip .75em}16 \indexspace \item{\rm{keyword}}{\hskip .75em}13; 38 \indexspace \item{\tt{lambda}}{\hskip .75em}9; 16, 41 \item{\rm{lazy evaluation}}{\hskip .75em}13 \item{\tt{lcm}}{\hskip .75em}23 \item{\tt{length}}{\hskip .75em}27; 20 \item{\tt{let}}{\hskip .75em}11; 12, 15, 16, 43 \item{\tt{let*}}{\hskip .75em}11; 16, 44 \item{\tt{let-syntax}}{\hskip .75em}14; 16 \item{\tt{letrec}}{\hskip .75em}11; 16, 44 \item{\tt{letrec-syntax}}{\hskip .75em}14; 16 \item{\rm{library}}{\hskip .75em}3 \item{\rm{library procedure}}{\hskip .75em}17 \item{\tt{list}}{\hskip .75em}27 \item{\tt{list->string}}{\hskip .75em}30 \item{\tt{list->vector}}{\hskip .75em}31 \item{\tt{list-ref}}{\hskip .75em}27 \item{\tt{list-tail}}{\hskip .75em}27 \item{\tt{list?}}{\hskip .75em}26 \item{\tt{load}}{\hskip .75em}37 \item{\rm{location}}{\hskip .75em}7 \item{\tt{log}}{\hskip .75em}23 \indexspace \item{\rm{macro}}{\hskip .75em}13 \item{\rm{macro keyword}}{\hskip .75em}13 \item{\rm{macro transformer}}{\hskip .75em}13 \item{\rm{macro use}}{\hskip .75em}13 \item{\tt{magnitude}}{\hskip .75em}24 \item{\tt{make-polar}}{\hskip .75em}24 \item{\tt{make-rectangular}}{\hskip .75em}24 \item{\tt{make-string}}{\hskip .75em}30 \item{\tt{make-vector}}{\hskip .75em}31 \item{\tt{map}}{\hskip .75em}32 \item{\tt{max}}{\hskip .75em}22 \item{\tt{member}}{\hskip .75em}27 \item{\tt{memq}}{\hskip .75em}27 \item{\tt{memv}}{\hskip .75em}27 \item{\tt{min}}{\hskip .75em}22 \item{\tt{modulo}}{\hskip .75em}22 \item{\rm{mutable}}{\hskip .75em}7 \indexspace \item{\tt{negative?}}{\hskip .75em}22 \item{\tt{newline}}{\hskip .75em}37 \item{\tt{nil}}{\hskip .75em}25 \item{\tt{not}}{\hskip .75em}25 \item{\tt{null-environment}}{\hskip .75em}35 \item{\tt{null?}}{\hskip .75em}26 \item{\rm{number}}{\hskip .75em}19 \item{\tt{number->string}}{\hskip .75em}24 \item{\tt{number?}}{\hskip .75em}21; 6, 19 \item{\tt{numerator}}{\hskip .75em}23 \item{\rm{numerical types}}{\hskip .75em}19 \indexspace \item{\sharpfoo{o}}{\hskip .75em}21; 38 \item{\rm{object}}{\hskip .75em}3 \item{\tt{odd?}}{\hskip .75em}22 \item{\tt{open-input-file}}{\hskip .75em}36 \item{\tt{open-output-file}}{\hskip .75em}36 \item{\rm{optional}}{\hskip .75em}3 \item{\tt{or}}{\hskip .75em}11; 43 \item{\tt{output-port?}}{\hskip .75em}35 \indexspace \item{\rm{pair}}{\hskip .75em}25 \item{\tt{pair?}}{\hskip .75em}26; 6 \item{\tt{peek-char}}{\hskip .75em}36 \item{\rm{port}}{\hskip .75em}35 \item{\tt{port?}}{\hskip .75em}6 \item{\tt{positive?}}{\hskip .75em}22 \item{\rm{predicate}}{\hskip .75em}17 \item{\rm{procedure call}}{\hskip .75em}9 \item{\tt{procedure?}}{\hskip .75em}31; 6 \item{\rm{promise}}{\hskip .75em}13; 32 \item{\rm{proper tail recursion}}{\hskip .75em}7 \indexspace \item{\tt{quasiquote}}{\hskip .75em}13; 26 \item{\tt{quote}}{\hskip .75em}8; 26 \item{\tt{quotient}}{\hskip .75em}22 \indexspace \item{\tt{rational?}}{\hskip .75em}21; 19 \item{\tt{rationalize}}{\hskip .75em}23 \item{\tt{read}}{\hskip .75em}36; 26, 39 \item{\tt{read-char}}{\hskip .75em}36 \item{\tt{real-part}}{\hskip .75em}24 \item{\tt{real?}}{\hskip .75em}21; 19 \item{\rm{referentially transparent}}{\hskip .75em}13 \item{\rm{region}}{\hskip .75em}6; 10, 11, 12 \item{\tt{remainder}}{\hskip .75em}22 \item{\tt{reverse}}{\hskip .75em}27 \item{\tt{round}}{\hskip .75em}23 \indexspace \item{\tt{scheme-report-environment}}{\hskip .75em}35 \item{\tt{set!}}{\hskip .75em}10; 16, 41 \item{\tt{set-car!}}{\hskip .75em}26 \item{\tt{set-cdr!}}{\hskip .75em}26 \item{\tt{setcar}}{\hskip .75em}42 \item{\rm{simplest rational}}{\hskip .75em}23 \item{\tt{sin}}{\hskip .75em}23 \item{\tt{sqrt}}{\hskip .75em}24 \item{\tt{string}}{\hskip .75em}30 \item{\tt{string->list}}{\hskip .75em}30 \item{\tt{string->number}}{\hskip .75em}24 \item{\tt{string->symbol}}{\hskip .75em}28 \item{\tt{string-append}}{\hskip .75em}30 \item{\tt{string-ci<=?}}{\hskip .75em}30 \item{\tt{string-ci=?}}{\hskip .75em}30 \item{\tt{string-ci>?}}{\hskip .75em}30 \item{\tt{string-copy}}{\hskip .75em}30 \item{\tt{string-fill!}}{\hskip .75em}31 \item{\tt{string-length}}{\hskip .75em}30; 20 \item{\tt{string-ref}}{\hskip .75em}30 \item{\tt{string-set!}}{\hskip .75em}30; 28 \item{\tt{string<=?}}{\hskip .75em}30 \item{\tt{string=?}}{\hskip .75em}30 \item{\tt{string>?}}{\hskip .75em}30 \item{\tt{string?}}{\hskip .75em}30; 6 \item{\tt{substring}}{\hskip .75em}30 \item{\tt{symbol->string}}{\hskip .75em}28; 7 \item{\tt{symbol?}}{\hskip .75em}28; 6 \item{\rm{syntactic keyword}}{\hskip .75em}6; 5, 13, 38 \item{\rm{syntax definition}}{\hskip .75em}17 \item{\tt{syntax-rules}}{\hskip .75em}14; 17 \indexspace \item{\sharpfoo{t}}{\hskip .75em}25 \item{\rm{tail call}}{\hskip .75em}7 \item{\tt{tan}}{\hskip .75em}23 \item{\rm{token}}{\hskip .75em}38 \item{\rm{top level environment}}{\hskip .75em}17; 6 \item{\tt{transcript-off}}{\hskip .75em}37 \item{\tt{transcript-on}}{\hskip .75em}37 \item{\rm{true}}{\hskip .75em}6; 10, 25 \item{\tt{truncate}}{\hskip .75em}23 \item{\rm{type}}{\hskip .75em}6 \indexspace \item{\rm{unbound}}{\hskip .75em}6; 8, 16 \item{\tt{unquote}}{\hskip .75em}13; 26 \item{\tt{unquote-splicing}}{\hskip .75em}13; 26 \item{\rm{unspecified}}{\hskip .75em}4 \indexspace \item{\rm{valid indexes}}{\hskip .75em}30; 31 \item{\tt{values}}{\hskip .75em}34; 9 \item{\rm{variable}}{\hskip .75em}6; 5, 8, 38 \item{\tt{vector}}{\hskip .75em}31 \item{\tt{vector->list}}{\hskip .75em}31 \item{\tt{vector-fill!}}{\hskip .75em}31 \item{\tt{vector-length}}{\hskip .75em}31; 20 \item{\tt{vector-ref}}{\hskip .75em}31 \item{\tt{vector-set!}}{\hskip .75em}31 \item{\tt{vector?}}{\hskip .75em}31; 6 \indexspace \item{\rm{whitespace}}{\hskip .75em}5 \item{\tt{with-input-from-file}}{\hskip .75em}35 \item{\tt{with-output-to-file}}{\hskip .75em}35 \item{\tt{write}}{\hskip .75em}37; 13 \item{\tt{write-char}}{\hskip .75em}37 \indexspace \item{\sharpfoo{x}}{\hskip .75em}21; 39 \indexspace \item{\tt{zero?}}{\hskip .75em}22 r5rs-doc-20010328.orig/lex.tex0100644001167100001440000001341606467633305014400 0ustar cphusers% Lexical structure %%\vfill\eject \chapter{Lexical conventions} This section gives an informal account of some of the lexical conventions used in writing Scheme programs. For a formal syntax of Scheme, see section~\ref{BNF}. \vest Upper and lower case forms of a letter are never distinguished except within character and string constants. For example, {\cf Foo} is the same identifier as {\cf FOO}, and {\tt\#x1AB} is the same number as {\tt\#X1ab}. \section{Identifiers} \label{syntaxsection} Most identifiers\mainindex{identifier} allowed by other programming languages are also acceptable to Scheme. The precise rules for forming identifiers vary among implementations of Scheme, but in all implementations a sequence of letters, digits, and ``extended alphabetic characters'' that begins with a character that cannot begin a number is an identifier. In addition, \ide{+}, \ide{-}, and \ide{...} are identifiers. Here are some examples of identifiers: \begin{scheme} lambda q list->vector soup {+} V17a <=? a34kTMNs the-word-recursion-has-many-meanings% \end{scheme} Extended alphabetic characters may be used within identifiers as if they were letters. The following are extended alphabetic characters: \begin{scheme} !\ \$ \% \verb"&" * + - . / :\ < = > ? @ \verb"^" \verb"_" \verb"~" % \end{scheme} See section~\ref{extendedalphas} for a formal syntax of identifiers. \vest Identifiers have two uses within Scheme programs: \begin{itemize} \item Any identifier may be used as a variable\index{variable} or as a syntactic keyword\index{syntactic keyword} (see sections~\ref{variablesection} and~\ref{macrosection}). \item When an identifier appears as a literal or within a literal (see section~\ref{quote}), it is being used to denote a {\em symbol} (see section~\ref{symbolsection}). \end{itemize} %\label{keywordsection} %The following identifiers are syntactic keywords, and should not be used %as variables: % %\begin{scheme} %=> do or %and else quasiquote %begin if quote %case lambda set! %cond let unquote %define let* unquote-splicing %delay letrec% %\end{scheme} % %Some implementations allow all identifiers, including syntactic %keywords, to be used as variables. This is a compatible extension to %the language, but ambiguities in the language result when the %restriction is relaxed, and the ways in which these ambiguities are %resolved vary between implementations. \section{Whitespace and comments} \defining{Whitespace} characters are spaces and newlines. (Implementations typically provide additional whitespace characters such as tab or page break.) Whitespace is used for improved readability and as necessary to separate tokens from each other, a token being an indivisible lexical unit such as an identifier or number, but is otherwise insignificant. Whitespace may occur between any two tokens, but not within a token. Whitespace may also occur inside a string, where it is significant. A semicolon ({\tt;}) indicates the start of a comment.\mainindex{comment}\mainschindex{;} The comment continues to the end of the line on which the semicolon appears. Comments are invisible to Scheme, but the end of the line is visible as whitespace. This prevents a comment from appearing in the middle of an identifier or number. \begin{scheme} ;;; The FACT procedure computes the factorial ;;; of a non-negative integer. (define fact (lambda (n) (if (= n 0) 1 ;Base case: return 1 (* n (fact (- n 1))))))% \end{scheme} \section{Other notations} \todo{Rewrite?} For a description of the notations used for numbers, see section~\ref{numbersection}. \begin{description}{}{} \item[{\tt.\ + -}] These are used in numbers, and may also occur anywhere in an identifier except as the first character. A delimited plus or minus sign by itself is also an identifier. A delimited period (not occurring within a number or identifier) is used in the notation for pairs (section~\ref{listsection}), and to indicate a rest-parameter in a formal parameter list (section~\ref{lambda}). A delimited sequence of three successive periods is also an identifier. \item[\tt( )] Parentheses are used for grouping and to notate lists (section~\ref{listsection}). \item[\singlequote] The single quote character is used to indicate literal data (section~\ref{quote}). \item[\backquote] The backquote character is used to indicate almost-constant data (section~\ref{quasiquote}). \item[\tt, ,@] The character comma and the sequence comma at-sign are used in conjunction with backquote (section~\ref{quasiquote}). \item[\tt"] The double quote character is used to delimit strings (section~\ref{stringsection}). \item[\backwhack] Backslash is used in the syntax for character constants (section~\ref{charactersection}) and as an escape character within string constants (section~\ref{stringsection}). % A box used because \verb is not allowed in command arguments. \setbox0\hbox{\tt \verb"[" \verb"]" \verb"{" \verb"}" \verb"|"} \item[\copy0] Left and right square brackets and curly braces and vertical bar are reserved for possible future extensions to the language. \item[\sharpsign] Sharp sign is used for a variety of purposes depending on the character that immediately follows it: \item[\schtrue{} \schfalse{}] These are the boolean constants (section~\ref{booleansection}). \item[\sharpsign\backwhack] This introduces a character constant (section~\ref{charactersection}). \item[\sharpsign\tt(] This introduces a vector constant (section~\ref{vectorsection}). Vector constants are terminated by~{\tt)}~. \item[{\tt\#e \#i \#b \#o \#d \#x}] These are used in the notation for numbers (section~\ref{numbernotations}). \end{description} r5rs-doc-20010328.orig/procs.tex0100644001167100001440000034734206473110347014737 0ustar cphusers% Initial environment %\vfill\eject \chapter{Standard procedures} \label{initialenv} \label{builtinchapter} \mainindex{initial environment} \mainindex{top level environment} \mainindex{library procedure} This chapter describes Scheme's built-in procedures. The initial (or ``top level'') Scheme environment starts out with a number of variables bound to locations containing useful values, most of which are primitive procedures that manipulate data. For example, the variable {\cf abs} is bound to (a location initially containing) a procedure of one argument that computes the absolute value of a number, and the variable {\cf +} is bound to a procedure that computes sums. Built-in procedures that can easily be written in terms of other built-in procedures are identified as ``library procedures''. A program may use a top-level definition to bind any variable. It may subsequently alter any such binding by an assignment (see \ref{assignment}). These operations do not modify the behavior of Scheme's built-in procedures. Altering any top-level binding that has not been introduced by a definition has an unspecified effect on the behavior of the built-in procedures. \section{Equivalence predicates} \label{equivalencesection} A \defining{predicate} is a procedure that always returns a boolean value (\schtrue{} or \schfalse). An \defining{equivalence predicate} is the computational analogue of a mathematical equivalence relation (it is symmetric, reflexive, and transitive). Of the equivalence predicates described in this section, {\cf eq?}\ is the finest or most discriminating, and {\cf equal?}\ is the coarsest. {\cf Eqv?}\ is slightly less discriminating than {\cf eq?}. \todo{Pitman doesn't like this paragraph. Lift the discussion from the Maclisp manual. Explain why there's more than one predicate.} \begin{entry}{% \proto{eqv?}{ \vari{obj} \varii{obj}}{procedure}} The {\cf eqv?} procedure defines a useful equivalence relation on objects. Briefly, it returns \schtrue{} if \vari{obj} and \varii{obj} should normally be regarded as the same object. This relation is left slightly open to interpretation, but the following partial specification of {\cf eqv?} holds for all implementations of Scheme. The {\cf eqv?} procedure returns \schtrue{} if: \begin{itemize} \item \vari{obj} and \varii{obj} are both \schtrue{} or both \schfalse. \item \vari{obj} and \varii{obj} are both symbols and \begin{scheme} (string=? (symbol->string obj1) (symbol->string obj2)) \ev \schtrue% \end{scheme} \begin{note} This assumes that neither \vari{obj} nor \varii{obj} is an ``uninterned symbol'' as alluded to in section~\ref{symbolsection}. This report does not presume to specify the behavior of {\cf eqv?} on implementation-dependent extensions. \end{note} \item \vari{obj} and \varii{obj} are both numbers, are numerically equal (see {\cf =}, section~\ref{numbersection}), and are either both exact\index{exact} or both inexact\index{inexact}. \item \vari{obj} and \varii{obj} are both characters and are the same character according to the {\cf char=?} procedure (section~\ref{charactersection}). \item both \vari{obj} and \varii{obj} are the empty list. \item \vari{obj} and \varii{obj} are pairs, vectors, or strings that denote the same locations in the store (section~\ref{storagemodel}). \item \vari{obj} and \varii{obj} are procedures whose location tags are equal (section~\ref{lambda}). \end{itemize} The {\cf eqv?} procedure returns \schfalse{} if: \begin{itemize} \item \vari{obj} and \varii{obj} are of different types (section~\ref{disjointness}). \item one of \vari{obj} and \varii{obj} is \schtrue{} but the other is \schfalse{}. \item \vari{obj} and \varii{obj} are symbols but \begin{scheme} (string=? (symbol->string \vari{obj}) (symbol->string \varii{obj})) \ev \schfalse% \end{scheme} \item one of \vari{obj} and \varii{obj} is an exact number but the other is an inexact number. \item \vari{obj} and \varii{obj} are numbers for which the {\cf =} procedure returns \schfalse{}. \item \vari{obj} and \varii{obj} are characters for which the {\cf char=?} procedure returns \schfalse{}. \item one of \vari{obj} and \varii{obj} is the empty list but the other is not. \item \vari{obj} and \varii{obj} are pairs, vectors, or strings that denote distinct locations. \item \vari{obj} and \varii{obj} are procedures that would behave differently (return different value(s) or have different side effects) for some arguments. \end{itemize} \begin{scheme} (eqv? 'a 'a) \ev \schtrue (eqv? 'a 'b) \ev \schfalse (eqv? 2 2) \ev \schtrue (eqv? '() '()) \ev \schtrue (eqv? 100000000 100000000) \ev \schtrue (eqv? (cons 1 2) (cons 1 2)) \ev \schfalse (eqv? (lambda () 1) (lambda () 2)) \ev \schfalse (eqv? \#f 'nil) \ev \schfalse (let ((p (lambda (x) x))) (eqv? p p)) \ev \schtrue% \end{scheme} The following examples illustrate cases in which the above rules do not fully specify the behavior of {\cf eqv?}. All that can be said about such cases is that the value returned by {\cf eqv?} must be a boolean. \begin{scheme} (eqv? "" "") \ev \unspecified (eqv? '\#() '\#()) \ev \unspecified (eqv? (lambda (x) x) (lambda (x) x)) \ev \unspecified (eqv? (lambda (x) x) (lambda (y) y)) \ev \unspecified% \end{scheme} The next set of examples shows the use of {\cf eqv?}\ with procedures that have local state. {\cf Gen-counter} must return a distinct procedure every time, since each procedure has its own internal counter. {\cf Gen-loser}, however, returns equivalent procedures each time, since the local state does not affect the value or side effects of the procedures. \begin{scheme} (define gen-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (let ((g (gen-counter))) (eqv? g g)) \ev \schtrue (eqv? (gen-counter) (gen-counter)) \ev \schfalse (define gen-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (let ((g (gen-loser))) (eqv? g g)) \ev \schtrue (eqv? (gen-loser) (gen-loser)) \ev \unspecified (letrec ((f (lambda () (if (eqv? f g) 'both 'f))) (g (lambda () (if (eqv? f g) 'both 'g)))) (eqv? f g)) \ev \unspecified (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (eqv? f g)) \ev \schfalse% \end{scheme} % Objects of distinct types must never be regarded as the same object, % except that \schfalse{} and the empty list\index{empty list} are permitted to % be identical. % % \begin{scheme} % (eqv? '() \schfalse) \ev \unspecified% % \end{scheme} Since it is an error to modify constant objects (those returned by literal expressions), implementations are permitted, though not required, to share structure between constants where appropriate. Thus the value of {\cf eqv?} on constants is sometimes implementation-dependent. \begin{scheme} (eqv? '(a) '(a)) \ev \unspecified (eqv? "a" "a") \ev \unspecified (eqv? '(b) (cdr '(a b))) \ev \unspecified (let ((x '(a))) (eqv? x x)) \ev \schtrue% \end{scheme} \begin{rationale} The above definition of {\cf eqv?} allows implementations latitude in their treatment of procedures and literals: implementations are free either to detect or to fail to detect that two procedures or two literals are equivalent to each other, and can decide whether or not to merge representations of equivalent objects by using the same pointer or bit pattern to represent both. \end{rationale} \end{entry} \begin{entry}{% \proto{eq?}{ \vari{obj} \varii{obj}}{procedure}} {\cf Eq?}\ is similar to {\cf eqv?}\ except that in some cases it is capable of discerning distinctions finer than those detectable by {\cf eqv?}. \vest {\cf Eq?}\ and {\cf eqv?}\ are guaranteed to have the same behavior on symbols, booleans, the empty list, pairs, procedures, and non-empty strings and vectors. {\cf Eq?}'s behavior on numbers and characters is implementation-dependent, but it will always return either true or false, and will return true only when {\cf eqv?}\ would also return true. {\cf Eq?} may also behave differently from {\cf eqv?} on empty vectors and empty strings. \begin{scheme} (eq? 'a 'a) \ev \schtrue (eq? '(a) '(a)) \ev \unspecified (eq? (list 'a) (list 'a)) \ev \schfalse (eq? "a" "a") \ev \unspecified (eq? "" "") \ev \unspecified (eq? '() '()) \ev \schtrue (eq? 2 2) \ev \unspecified (eq? \#\backwhack{}A \#\backwhack{}A) \ev \unspecified (eq? car car) \ev \schtrue (let ((n (+ 2 3))) (eq? n n)) \ev \unspecified (let ((x '(a))) (eq? x x)) \ev \schtrue (let ((x '\#())) (eq? x x)) \ev \schtrue (let ((p (lambda (x) x))) (eq? p p)) \ev \schtrue% \end{scheme} \todo{Needs to be explained better above. How can this be made to be not confusing? A table maybe?} \begin{rationale} It will usually be possible to implement {\cf eq?}\ much more efficiently than {\cf eqv?}, for example, as a simple pointer comparison instead of as some more complicated operation. One reason is that it may not be possible to compute {\cf eqv?}\ of two numbers in constant time, whereas {\cf eq?}\ implemented as pointer comparison will always finish in constant time. {\cf Eq?}\ may be used like {\cf eqv?}\ in applications using procedures to implement objects with state since it obeys the same constraints as {\cf eqv?}. \end{rationale} \end{entry} \begin{entry}{% \proto{equal?}{ \vari{obj} \varii{obj}}{library procedure}} {\cf Equal?} recursively compares the contents of pairs, vectors, and strings, applying {\cf eqv?} on other objects such as numbers and symbols. A rule of thumb is that objects are generally {\cf equal?} if they print the same. {\cf Equal?}\ may fail to terminate if its arguments are circular data structures. \begin{scheme} (equal? 'a 'a) \ev \schtrue (equal? '(a) '(a)) \ev \schtrue (equal? '(a (b) c) '(a (b) c)) \ev \schtrue (equal? "abc" "abc") \ev \schtrue (equal? 2 2) \ev \schtrue (equal? (make-vector 5 'a) (make-vector 5 'a)) \ev \schtrue (equal? (lambda (x) x) (lambda (y) y)) \ev \unspecified% \end{scheme} \end{entry} \section{Numbers} \label{numbersection} \index{number} %%R4%% The excessive use of the code font in this section was % confusing, somewhat obnoxious, and inconsistent with the rest % of the report and with parts of the section itself. I added % a \tupe no-op, and changed most old uses of \type to \tupe, % to make it easier to change the fonts back if people object % to the change. \newcommand{\type}[1]{{\it#1}} \newcommand{\tupe}[1]{{#1}} Numerical computation has traditionally been neglected by the Lisp community. Until Common Lisp there was no carefully thought out strategy for organizing numerical computation, and with the exception of the MacLisp system \cite{Pitman83} little effort was made to execute numerical code efficiently. This report recognizes the excellent work of the Common Lisp committee and accepts many of their recommendations. In some ways this report simplifies and generalizes their proposals in a manner consistent with the purposes of Scheme. It is important to distinguish between the mathematical numbers, the Scheme numbers that attempt to model them, the machine representations used to implement the Scheme numbers, and notations used to write numbers. This report uses the types \type{number}, \type{complex}, \type{real}, \type{rational}, and \type{integer} to refer to both mathematical numbers and Scheme numbers. Machine representations such as fixed point and floating point are referred to by names such as \type{fixnum} and \type{flonum}. %%R4%% I did some reorganizing here to move the discussion of mathematical % numbers before the discussion of the Scheme numbers, hoping that this % would help to motivate the discussion of representation independence. \subsection{Numerical types} \label{numericaltypes} \index{numerical types} %%R4%% A Scheme system provides data of type \type{number}, which is the most %general numerical type supported by that system. %\type{Number} is %likely to be a complicated union type implemented in terms of %\type{fixnum}s, \type{bignum}s, \type{flonum}s, and so forth, but this %should not be apparent to a naive user. What the user should see is %that the usual operations on numbers produce the mathematically %expected results, within the limits of the implementation. %%R4%% I rewrote the following paragraph to make the various levels of % the tower into subsets of each other, instead of relating them by % injections. I think the injections tended to put people in the frame % of mind of thinking about coercions between non-overlapping numeric % types in mainstream programming languages. \vest Mathematically, numbers may be arranged into a tower of subtypes %%R4%% with injections relating adjacent levels of the tower: in which each level is a subset of the level above it: \begin{tabbing} \ \ \ \ \ \ \ \ \ \=\tupe{number} \\ \> \tupe{complex} \\ \> \tupe{real} \\ \> \tupe{rational} \\ \> \tupe{integer} \end{tabbing} For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex. The same is true of the Scheme numbers that model 3. For Scheme numbers, these types are defined by the predicates \ide{number?}, \ide{complex?}, \ide{real?}, \ide{rational?}, and \ide{integer?}. There is no simple relationship between a number's type and its representation inside a computer. Although most implementations of Scheme will offer at least two different representations of 3, these different representations denote the same integer. %%R4%% I moved "Implementations of Scheme are not required to implement % the whole tower..." to the subsection on implementation restrictions. Scheme's numerical operations treat numbers as abstract data, as independent of their representation as possible. Although an implementation of Scheme may use fixnum, flonum, and perhaps other representations for numbers, this should not be apparent to a casual programmer writing simple programs. It is necessary, however, to distinguish between numbers that are represented exactly and those that may not be. For example, indexes into data structures must be known exactly, as must some polynomial coefficients in a symbolic algebra system. On the other hand, the results of measurements are inherently inexact, and irrational numbers may be approximated by rational and therefore inexact approximations. In order to catch uses of inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact from inexact numbers. This distinction is orthogonal to the dimension of type. \subsection{Exactness} %%R4%% I tried to direct the following paragraph away from philosophizing % about the exactness of mathematical numbers, and toward philosophizing % about the exactness of Scheme numbers. \mainindex{exactness} \label{exactly} Scheme numbers are either \type{exact} or \type{inexact}. A number is \tupe{exact} if it was written as an exact constant or was derived from \tupe{exact} numbers using only \tupe{exact} operations. A number is \tupe{inexact} if it was written as an inexact constant, %%R4%% models a quantity (e.g., a measurement) known only approximately, if it was derived using \tupe{inexact} ingredients, or if it was derived using \tupe{inexact} operations. Thus \tupe{inexact}ness is a contagious property of a number. %%R4%% The rest of this paragraph (from R3RS) has been dropped. \vest If two implementations produce \tupe{exact} results for a computation that did not involve \tupe{inexact} intermediate results, the two ultimate results will be mathematically equivalent. This is generally not true of computations involving \tupe{inexact} numbers since approximate methods such as floating point arithmetic may be used, but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result. \vest Rational operations such as {\cf +} should always produce \tupe{exact} results when given \tupe{exact} arguments. %%R4%%If an implementation is %unable to represent an \tupe{exact} result (for example, if it does not %support infinite precision integers and rationals) If the operation is unable to produce an \tupe{exact} result, then it may either report the violation of an implementation restriction or it may silently coerce its result to an \tupe{inexact} value. %%R4%%Such a coercion may cause an error later. See section~\ref{restrictions}. \vest With the exception of \ide{inexact->exact}, the operations described in this section must generally return inexact results when given any inexact arguments. An operation may, however, return an \tupe{exact} result if it can prove that the value of the result is unaffected by the inexactness of its arguments. For example, multiplication of any number by an \tupe{exact} zero may produce an \tupe{exact} zero result, even if the other argument is \tupe{inexact}. \subsection{Implementation restrictions} \index{implementation restriction}\label{restrictions} \vest Implementations of Scheme are not required to implement the whole tower of subtypes given in section~\ref{numericaltypes}, but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, an implementation in which all numbers are \tupe{real} may still be quite useful. \vest Implementations may also support only a limited range of numbers of any type, subject to the requirements of this section. The supported range for \tupe{exact} numbers of any type may be different from the supported range for \tupe{inexact} numbers of that type. For example, an implementation that uses flonums to represent all its \tupe{inexact} \tupe{real} numbers may support a practically unbounded range of \tupe{exact} \tupe{integer}s and \tupe{rational}s while limiting the range of \tupe{inexact} \tupe{real}s (and therefore the range of \tupe{inexact} \tupe{integer}s and \tupe{rational}s) to the dynamic range of the flonum format. Furthermore the gaps between the representable \tupe{inexact} \tupe{integer}s and \tupe{rational}s are likely to be very large in such an implementation as the limits of this range are approached. \vest An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists, vectors, and strings or that may result from computing the length of a list, vector, or string. The \ide{length}, \ide{vector-length}, and \ide{string-length} procedures must return an exact integer, and it is an error to use anything but an exact integer as an index. Furthermore any integer constant within the index range, if expressed by an exact integer syntax, will indeed be read as an exact integer, regardless of any implementation restrictions that may apply outside this range. Finally, the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation: \begin{scheme} + - * quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt% \end{scheme} \vest Implementations are encouraged, but not required, to support \tupe{exact} \tupe{integer}s and \tupe{exact} \tupe{rational}s of practically unlimited size and precision, and to implement the above procedures and the {\cf /} procedure in such a way that they always return \tupe{exact} results when given \tupe{exact} arguments. If one of these procedures is unable to deliver an \tupe{exact} result when given \tupe{exact} arguments, then it may either report a violation of an implementation restriction or it may silently coerce its result to an \tupe{inexact} number. Such a coercion may cause an error later. %%R4%% I moved this stuff here. % It seems to me that the only thing that this requires is that % implementations that support inexact numbers have to have both % exact and inexact representations for the integers 0 through 15. % If that's what it's saying, I'd rather say it that way. % On the other hand, letting the limit be as small as 15 sounds a % tad silly, though I think I understand how that number was arrived at. % (Or is 35 the number?) % %Implementations are encouraged, but not required, to support \tupe{inexact} %numbers. For any implementation that supports \tupe{inexact} numbers, %there is a subset of the integers for which there are both \tupe{exact} and %\tupe{inexact} representations. This subset must include all non-negative %integers up to some limit specified by the implementation. This limit %must be 16 or greater. The %\ide{exact\coerce{}inexact} and \ide{inexact\coerce{}exact} %procedures implement the natural one-to-one correspondence between %the \tupe{inexact} and \tupe{exact} integers within this range. \vest An implementation may use floating point and other approximate representation strategies for \tupe{inexact} numbers. %%R4%% The following sentence seemed a bit condescending as well as % awkward. It didn't seem to be very enforceable, so I flushed it. % %This is not to %say that implementors need not use the best known algorithms for %\tupe{inexact} computations---only that approximate methods of high %quality are allowed. % This report recommends, but does not require, that the IEEE 32-bit and 64-bit floating point standards be followed by implementations that use flonum representations, and that implementations using other representations should match or exceed the precision achievable using these floating point standards~\cite{IEEE}. \vest In particular, implementations that use flonum representations must follow these rules: A \tupe{flonum} result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation. It is desirable (but not required) for potentially inexact operations such as {\cf sqrt}, when applied to \tupe{exact} arguments, to produce \tupe{exact} answers whenever possible (for example the square root of an \tupe{exact} 4 ought to be an \tupe{exact} 2). If, however, an \tupe{exact} number is operated upon so as to produce an \tupe{inexact} result (as by {\cf sqrt}), and if the result is represented as a \tupe{flonum}, then the most precise \tupe{flonum} format available must be used; but if the result is represented in some other way then the representation must have at least as much precision as the most precise \tupe{flonum} format available. Although Scheme allows a variety of written %%R4%% representations of notations for numbers, any particular implementation may support only some of them. %%R4%% For example, an implementation in which all numbers are \tupe{real} need not support the rectangular and polar notations for complex numbers. If an implementation encounters an \tupe{exact} numerical constant that it cannot represent as an \tupe{exact} number, then it may either report a violation of an implementation restriction or it may silently represent the constant by an \tupe{inexact} number. \subsection{Syntax of numerical constants} \label{numbernotations} %@@@@LOSE@@@@ %%R4%% I removed the following paragraph in an attempt to tighten up % this subsection. Except for its first sentence, which I moved to % the subsection on implementation restrictions, I think its content % is implied by the rest of the section. % %Although Scheme allows a variety of written representations of numbers, %any particular implementation may support only some of them. %These syntaxes are intended to be purely notational; any kind of number %may be written in any form that the user deems convenient. Of course, %writing 1/7 as a limited-precision decimal fraction will not express the %number exactly, but this approximate form of expression may be just what %the user wants to see. The syntax of the written representations for numbers is described formally in section~\ref{numbersyntax}. Note that case is not significant in numerical constants. %%R4%% See section~\ref{numberformats} for many examples. A number may be written in binary, octal, decimal, or hexadecimal by the use of a radix prefix. The radix prefixes are {\cf \#b}\sharpindex{b} (binary), {\cf \#o}\sharpindex{o} (octal), {\cf \#d}\sharpindex{d} (decimal), and {\cf \#x}\sharpindex{x} (hexadecimal). With no radix prefix, a number is assumed to be expressed in decimal. A %%R4%% % simple numerical constant may be specified to be either \tupe{exact} or \tupe{inexact} by a prefix. The prefixes are {\cf \#e}\sharpindex{e} for \tupe{exact}, and {\cf \#i}\sharpindex{i} for \tupe{inexact}. An exactness prefix may appear before or after any radix prefix that is used. If the written representation of a number has no exactness prefix, the constant may be either \tupe{inexact} or \tupe{exact}. It is \tupe{inexact} if it contains a decimal point, an exponent, or a ``\sharpsign'' character in the place of a digit, otherwise it is \tupe{exact}. %%R4%% With our new syntax, the following sentence is redundant: % %The written representation of a %compound number, such as a ratio or a complex, is exact if and only if %all of its constituents are exact. In systems with \tupe{inexact} numbers of varying precisions it may be useful to specify the precision of a constant. For this purpose, numerical constants may be written with an exponent marker that indicates the desired precision of the \tupe{inexact} representation. The letters {\cf s}, {\cf f}, {\cf d}, and {\cf l} specify the use of \var{short}, \var{single}, \var{double}, and \var{long} precision, respectively. (When fewer than four internal %%R4%%\tupe{flonum} \tupe{inexact} representations exist, the four size specifications are mapped onto those available. For example, an implementation with two internal representations may map short and single together and long and double together.) In addition, the exponent marker {\cf e} specifies the default precision for the implementation. The default precision has at least as much precision as \var{double}, but implementations may wish to allow this default to be set by the user. \begin{scheme} 3.14159265358979F0 {\rm Round to single ---} 3.141593 0.6L0 {\rm Extend to long ---} .600000000000000% \end{scheme} \subsection{Numerical operations} The reader is referred to section~\ref{typeconventions} for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines. %%R4%% The following sentence has already been said twice, and the % term "exactness-preserving" is no longer defined by the Report. % % Remember that %an exactness-preserving operation may coerce its result to inexact if the %implementation is unable to represent it exactly. The examples used in this section assume that any numerical constant written using an \tupe{exact} notation is indeed represented as an \tupe{exact} number. Some examples also assume that certain numerical constants written using an \tupe{inexact} notation can be represented without loss of accuracy; the \tupe{inexact} constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers. \todo{Scheme provides the usual set of operations for manipulating numbers, etc.} \begin{entry}{% \proto{number?}{ obj}{procedure} \proto{complex?}{ obj}{procedure} \proto{real?}{ obj}{procedure} \proto{rational?}{ obj}{procedure} \proto{integer?}{ obj}{procedure}} These numerical type predicates can be applied to any kind of argument, including non-numbers. They return \schtrue{} if the object is of the named type, and otherwise they return \schfalse{}. In general, if a type predicate is true of a number then all higher type predicates are also true of that number. Consequently, if a type predicate is false of a number, then all lower type predicates are also false of that number. %%R4%% The new section on implementation restrictions subsumes: % Not every system %supports all of these types; for example, it is entirely possible to have a %Scheme system that has only \tupe{integer}s. Nonetheless every implementation %of Scheme must have all of these predicates. If \vr{z} is an inexact complex number, then {\cf (real? \vr{z})} is true if and only if {\cf (zero? (imag-part \vr{z}))} is true. If \vr{x} is an inexact real number, then {\cf (integer? \vr{x})} is true if and only if {\cf (= \vr{x} (round \vr{x}))}. \begin{scheme} (complex? 3+4i) \ev \schtrue (complex? 3) \ev \schtrue (real? 3) \ev \schtrue (real? -2.5+0.0i) \ev \schtrue (real? \#e1e10) \ev \schtrue (rational? 6/10) \ev \schtrue (rational? 6/3) \ev \schtrue (integer? 3+0i) \ev \schtrue (integer? 3.0) \ev \schtrue (integer? 8/4) \ev \schtrue% \end{scheme} \begin{note} The behavior of these type predicates on \tupe{inexact} numbers is unreliable, since any inaccuracy may affect the result. \end{note} \begin{note} In many implementations the \ide{rational?} procedure will be the same as \ide{real?}, and the \ide{complex?} procedure will be the same as \ide{number?}, but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non-complex numbers. \end{note} \end{entry} \begin{entry}{% \proto{exact?}{ \vr{z}}{procedure} \proto{inexact?}{ \vr{z}}{procedure}} These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of these predicates is true. \end{entry} \begin{entry}{% \proto{=}{ \vri{z} \vrii{z} \vriii{z} \dotsfoo}{procedure} \proto{<}{ \vri{x} \vrii{x} \vriii{x} \dotsfoo}{procedure} \proto{>}{ \vri{x} \vrii{x} \vriii{x} \dotsfoo}{procedure} \proto{<=}{ \vri{x} \vrii{x} \vriii{x} \dotsfoo}{procedure} \proto{>=}{ \vri{x} \vrii{x} \vriii{x} \dotsfoo}{procedure}} %- Some implementations allow these procedures to take many arguments, to %- facilitate range checks. These procedures return \schtrue{} if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing. These predicates are required to be transitive. \begin{note} The traditional implementations of these predicates in Lisp-like languages are not transitive. \end{note} \begin{note} While it is not an error to compare \tupe{inexact} numbers using these predicates, the results may be unreliable because a small inaccuracy may affect the result; this is especially true of \ide{=} and \ide{zero?}. When in doubt, consult a numerical analyst. \end{note} \end{entry} \begin{entry}{% \proto{zero?}{ \vr{z}}{library procedure} \proto{positive?}{ \vr{x}}{library procedure} \proto{negative?}{ \vr{x}}{library procedure} \proto{odd?}{ \vr{n}}{library procedure} \proto{even?}{ \vr{n}}{library procedure}} These numerical predicates test a number for a particular property, returning \schtrue{} or \schfalse. See note above. \end{entry} \begin{entry}{% \proto{max}{ \vri{x} \vrii{x} \dotsfoo}{library procedure} \proto{min}{ \vri{x} \vrii{x} \dotsfoo}{library procedure}} These procedures return the maximum or minimum of their arguments. \begin{scheme} (max 3 4) \ev 4 ; exact (max 3.9 4) \ev 4.0 ; inexact% \end{scheme} \begin{note} If any argument is inexact, then the result will also be inexact (unless the procedure can prove that the inaccuracy is not large enough to affect the result, which is possible only in unusual implementations). If {\cf min} or {\cf max} is used to compare numbers of mixed exactness, and the numerical value of the result cannot be represented as an inexact number without loss of accuracy, then the procedure may report a violation of an implementation restriction. \end{note} \end{entry} \begin{entry}{% \proto{+}{ \vri{z} \dotsfoo}{procedure} \proto{*}{ \vri{z} \dotsfoo}{procedure}} These procedures return the sum or product of their arguments. %- These procedures are exactness preserving. \begin{scheme} (+ 3 4) \ev 7 (+ 3) \ev 3 (+) \ev 0 (* 4) \ev 4 (*) \ev 1% \end{scheme} \end{entry} \begin{entry}{% \proto{-}{ \vri{z} \vrii{z}}{procedure} \rproto{-}{ \vr{z}}{procedure} \rproto{-}{ \vri{z} \vrii{z} \dotsfoo}{optional procedure} \proto{/}{ \vri{z} \vrii{z}}{procedure} \rproto{/}{ \vr{z}}{procedure} \rproto{/}{ \vri{z} \vrii{z} \dotsfoo}{optional procedure}} With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument. %- These procedures are exactness preserving, except that division may %- coerce its result to inexact in implementations that do not support %- \tupe{ratnum}s. \begin{scheme} (- 3 4) \ev -1 (- 3 4 5) \ev -6 (- 3) \ev -3 (/ 3 4 5) \ev 3/20 (/ 3) \ev 1/3% \end{scheme} \end{entry} \begin{entry}{% \proto{abs}{ x}{library procedure}} {\cf Abs} returns the absolute value of its argument. %- {\cf Abs} is exactness preserving when its argument is real. \begin{scheme} (abs -7) \ev 7 \end{scheme} \end{entry} \begin{entry}{% \proto{quotient}{ \vri{n} \vrii{n}}{procedure} \proto{remainder}{ \vri{n} \vrii{n}}{procedure} \proto{modulo}{ \vri{n} \vrii{n}}{procedure}} These procedures implement number-theoretic (integer) division. \vrii{n} should be non-zero. All three procedures return integers. If \vri{n}/\vrii{n} is an integer: \begin{scheme} (quotient \vri{n} \vrii{n}) \ev \vri{n}/\vrii{n} (remainder \vri{n} \vrii{n}) \ev 0 (modulo \vri{n} \vrii{n}) \ev 0 \end{scheme} If \vri{n}/\vrii{n} is not an integer: \begin{scheme} (quotient \vri{n} \vrii{n}) \ev \vr{n_q} (remainder \vri{n} \vrii{n}) \ev \vr{n_r} (modulo \vri{n} \vrii{n}) \ev \vr{n_m} \end{scheme} where \vr{n_q} is $\vri{n}/\vrii{n}$ rounded towards zero, $0 < |\vr{n_r}| < |\vrii{n}|$, $0 < |\vr{n_m}| < |\vrii{n}|$, \vr{n_r} and \vr{n_m} differ from \vri{n} by a multiple of \vrii{n}, \vr{n_r} has the same sign as \vri{n}, and \vr{n_m} has the same sign as \vrii{n}. From this we can conclude that for integers \vri{n} and \vrii{n} with \vrii{n} not equal to 0, \begin{scheme} (= \vri{n} (+ (* \vrii{n} (quotient \vri{n} \vrii{n})) (remainder \vri{n} \vrii{n}))) \ev \schtrue% \end{scheme} provided all numbers involved in that computation are exact. \begin{scheme} (modulo 13 4) \ev 1 (remainder 13 4) \ev 1 (modulo -13 4) \ev 3 (remainder -13 4) \ev -1 (modulo 13 -4) \ev -3 (remainder 13 -4) \ev 1 (modulo -13 -4) \ev -1 (remainder -13 -4) \ev -1 (remainder -13 -4.0) \ev -1.0 ; inexact% \end{scheme} \end{entry} \begin{entry}{% \proto{gcd}{ \vri{n} \dotsfoo}{library procedure} \proto{lcm}{ \vri{n} \dotsfoo}{library procedure}} These procedures return the greatest common divisor or least common multiple of their arguments. The result is always non-negative. %- These procedures are exactness preserving. %%R4%% I added the inexact example. \begin{scheme} (gcd 32 -36) \ev 4 (gcd) \ev 0 (lcm 32 -36) \ev 288 (lcm 32.0 -36) \ev 288.0 ; inexact (lcm) \ev 1% \end{scheme} \end{entry} \begin{entry}{% \proto{numerator}{ \vr{q}}{procedure} \proto{denominator}{ \vr{q}}{procedure}} These procedures return the numerator or denominator of their argument; the result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1. %- The remarks about denominators are new. %- Clearly, they are exactness-preserving procedures. \todo{More description and examples needed.} \begin{scheme} (numerator (/ 6 4)) \ev 3 (denominator (/ 6 4)) \ev 2 (denominator (exact->inexact (/ 6 4))) \ev 2.0% \end{scheme} \end{entry} \begin{entry}{% \proto{floor}{ x}{procedure} \proto{ceiling}{ x}{procedure} \proto{truncate}{ x}{procedure} \proto{round}{ x}{procedure} } These procedures return integers. \vest {\cf Floor} returns the largest integer not larger than \vr{x}. {\cf Ceiling} returns the smallest integer not smaller than~\vr{x}. {\cf Truncate} returns the integer closest to \vr{x} whose absolute value is not larger than the absolute value of \vr{x}. {\cf Round} returns the closest integer to \vr{x}, rounding to even when \vr{x} is halfway between two integers. \begin{rationale} {\cf Round} rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard. \end{rationale} \begin{note} If the argument to one of these procedures is inexact, then the result will also be inexact. If an exact value is needed, the result should be passed to the {\cf inexact->exact} procedure. \end{note} \begin{scheme} (floor -4.3) \ev -5.0 (ceiling -4.3) \ev -4.0 (truncate -4.3) \ev -4.0 (round -4.3) \ev -4.0 (floor 3.5) \ev 3.0 (ceiling 3.5) \ev 4.0 (truncate 3.5) \ev 3.0 (round 3.5) \ev 4.0 ; inexact (round 7/2) \ev 4 ; exact (round 7) \ev 7% \end{scheme} \end{entry} \begin{entry}{% \proto{rationalize}{ x y}{library procedure} %- \proto{rationalize}{ x}{procedure} } {\cf Rationalize} returns the {\em simplest} rational number differing from \vr{x} by no more than \vr{y}. A rational number $r_1$ is {\em simpler} \mainindex{simplest rational} than another rational number $r_2$ if $r_1 = p_1/q_1$ and $r_2 = p_2/q_2$ (in lowest terms) and $|p_1| \leq |p_2|$ and $|q_1| \leq |q_2|$. Thus $3/5$ is simpler than $4/7$. Although not all rationals are comparable in this ordering (consider $2/7$ and $3/5$) any interval contains a rational number that is simpler than every other rational number in that interval (the simpler $2/5$ lies between $2/7$ and $3/5$). Note that $0 = 0/1$ is the simplest rational of all. \begin{scheme} (rationalize (inexact->exact .3) 1/10) \ev 1/3 ; exact (rationalize .3 1/10) \ev \#i1/3 ; inexact% \end{scheme} \end{entry} \begin{entry}{% \proto{exp}{ \vr{z}}{procedure} \proto{log}{ \vr{z}}{procedure} \proto{sin}{ \vr{z}}{procedure} \proto{cos}{ \vr{z}}{procedure} \proto{tan}{ \vr{z}}{procedure} \proto{asin}{ \vr{z}}{procedure} \proto{acos}{ \vr{z}}{procedure} \proto{atan}{ \vr{z}}{procedure} \rproto{atan}{ \vr{y} \vr{x}}{procedure}} These procedures are part of every implementation that supports %%R4%% general real numbers; they compute the usual transcendental functions. {\cf Log} computes the natural logarithm of \vr{z} (not the base ten logarithm). {\cf Asin}, {\cf acos}, and {\cf atan} compute arcsine ($\sin^{-1}$), arccosine ($\cos^{-1}$), and arctangent ($\tan^{-1}$), respectively. The two-argument variant of {\cf atan} computes {\tt (angle (make-rectangular \vr{x} \vr{y}))} (see below), even in implementations that don't support general complex numbers. In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. The value of $\log z$ is defined to be the one whose imaginary part lies in the range from $-\pi$ (exclusive) to $\pi$ (inclusive). $\log 0$ is undefined. With $\log$ defined this way, the values of $\sin^{-1} z$, $\cos^{-1} z$, and $\tan^{-1} z$ are according to the following formul\ae: $$\sin^{-1} z = -i \log (i z + \sqrt{1 - z^2})$$ $$\cos^{-1} z = \pi / 2 - \sin^{-1} z$$ $$\tan^{-1} z = (\log (1 + i z) - \log (1 - i z)) / (2 i)$$ The above specification follows~\cite{CLtL}, which in turn cites~\cite{Penfield81}; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions. When it is possible these procedures produce a real result from a real argument. %%R4%% \todo{The cited references are likely to change their branch cuts soon to allow for the possibility of distinct positive and negative zeroes, as in IEEE floating point. We may not want to follow those changes, since we may want a complex number with zero imaginary part (whether positive or negative zero) to be treated as a real. I don't think there are any better standards for complex arithmetic than the ones cited, so we're really on our own here.} \end{entry} \begin{entry}{% \proto{sqrt}{ \vr{z}}{procedure}} Returns the principal square root of \vr{z}. The result will have either positive real part, or zero real part and non-negative imaginary part. \end{entry} \begin{entry}{% \proto{expt}{ \vri{z} \vrii{z}}{procedure}} Returns \vri{z} raised to the power \vrii{z}. For $z_1 \neq 0$ $${z_1}^{z_2} = e^{z_2 \log {z_1}}$$ $0^z$ is 1 if $z = 0$ and 0 otherwise. \end{entry} %- \begin{entry}{%- %- \proto{approximate}{ z x}{procedure}} %- %- Returns an approximation to \vr{z} in a representation whose precision is %- the same as that %- of the representation of \vr{x}, which must be an inexact number. The %- result is always inexact. %- %- \begin{scheme} %- (approximate 3.1415926535 1F10) %- \ev 3.14159F0 %- (approximate 3.1415926535 \#I65535) %- \ev \#I3 %- (approximate 3.14F0 1L8) %- \ev 3.14L0 %- (approximate 3.1415926535F0 1L8) %- \ev 3.14159L0 %- \end{scheme} %- \end{entry} \begin{entry}{% \proto{make-rectangular}{ \vri{x} \vrii{x}}{procedure} \proto{make-polar}{ \vriii{x} \vriv{x}}{procedure} \proto{real-part}{ \vr{z}}{procedure} \proto{imag-part}{ \vr{z}}{procedure} \proto{magnitude}{ \vr{z}}{procedure} \proto{angle}{ \vr{z}}{procedure}} These procedures are part of every implementation that supports %%R4%% general complex numbers. Suppose \vri{x}, \vrii{x}, \vriii{x}, and \vriv{x} are real numbers and \vr{z} is a complex number such that $$ \vr{z} = \vri{x} + \vrii{x}\hbox{$i$} = \vriii{x} \cdot e^{{\displaystyle{\hbox{$i$}} \vriv{x}}}$$ Then \begin{scheme} (make-rectangular \vri{x} \vrii{x}) \ev \vr{z} (make-polar \vriii{x} \vriv{x}) \ev \vr{z} (real-part \vr{z}) \ev \vri{x} (imag-part \vr{z}) \ev \vrii{x} (magnitude \vr{z}) \ev $|\vriii{x}|$ (angle \vr{z}) \ev $x_{angle}$ \end{scheme} where $-\pi < x_{angle} \le \pi$ with $x_{angle} = \vriv{x} + 2\pi n$ for some integer $n$. \begin{rationale} {\cf Magnitude} is the same as \ide{abs} for a real argument, but {\cf abs} must be present in all implementations, whereas {\cf magnitude} need only be present in implementations that support general complex numbers. \end{rationale} \end{entry} \begin{entry}{% \proto{exact->inexact}{ \vr{z}}{procedure} \proto{inexact->exact}{ \vr{z}}{procedure}} {\cf Exact\coerce{}inexact} returns an \tupe{inexact} representation of \vr{z}. The value returned is the \tupe{inexact} number that is numerically closest to the argument. %%R4%%For %\tupe{exact} arguments which have no reasonably close \tupe{inexact} equivalent, %it is permissible to signal an error. If an \tupe{exact} argument has no reasonably close \tupe{inexact} equivalent, then a violation of an implementation restriction may be reported. {\cf Inexact\coerce{}exact} returns an \tupe{exact} representation of \vr{z}. The value returned is the \tupe{exact} number that is numerically closest to the argument. %%R4%% For \tupe{inexact} arguments which have no %reasonably close \tupe{exact} equivalent, it is permissible to signal %an error. If an \tupe{inexact} argument has no reasonably close \tupe{exact} equivalent, then a violation of an implementation restriction may be reported. %%R%% I moved this to the section on implementation restrictions. %For any implementation that supports \tupe{inexact} quantities, %there is a subset of the integers for which there are both \tupe{exact} and %\tupe{inexact} representations. This subset must include the non-negative %integers up to a limit specified by the implementation. The limit %must be big enough to represent all digits in reasonable radices, and %may correspond to some natural word size for the implementation. For %such integers, these procedures implement the natural one-to-one %correspondence between the representations. These procedures implement the natural one-to-one correspondence between \tupe{exact} and \tupe{inexact} integers throughout an implementation-dependent range. See section~\ref{restrictions}. \end{entry} \medskip \subsection{Numerical input and output} \begin{entry}{% \proto{number->string}{ z}{procedure} \rproto{number->string}{ z radix}{procedure}} \vr{Radix} must be an exact integer, either 2, 8, 10, or 16. If omitted, \vr{radix} defaults to 10. The procedure {\cf number\coerce{}string} takes a number and a radix and returns as a string an external representation of the given number in the given radix such that \begin{scheme} (let ((number \vr{number}) (radix \vr{radix})) (eqv? number (string->number (number->string number radix) radix))) \end{scheme} is true. It is an error if no possible result makes this expression true. If \vr{z} is inexact, the radix is 10, and the above expression can be satisfied by a result that contains a decimal point, then the result contains a decimal point and is expressed using the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the above expression true~\cite{howtoprint,howtoread}; otherwise the format of the result is unspecified. The result returned by {\cf number\coerce{}string} never contains an explicit radix prefix. \begin{note} The error case can occur only when \vr{z} is not a complex number or is a complex number with a non-rational real or imaginary part. \end{note} \begin{rationale} If \vr{z} is an inexact number represented using flonums, and the radix is 10, then the above expression is normally satisfied by a result containing a decimal point. The unspecified case allows for infinities, NaNs, and non-flonum representations. \end{rationale} \end{entry} \begin{entry}{% \proto{string->number}{ string}{procedure} \rproto{string->number}{ string radix}{procedure}} %%R4%% I didn't include the (string->number string radix exactness) % case, since I haven't heard any resolution of the coding to be used % for the third argument. Returns a number of the maximally precise representation expressed by the given \vr{string}. \vr{Radix} must be an exact integer, either 2, 8, 10, or 16. If supplied, \vr{radix} is a default radix that may be overridden by an explicit radix prefix in \vr{string} (e.g. {\tt "\#o177"}). If \vr{radix} is not supplied, then the default radix is 10. If \vr{string} is not a syntactically valid notation for a number, then {\cf string->number} returns \schfalse{}. \begin{scheme} (string->number "100") \ev 100 (string->number "100" 16) \ev 256 (string->number "1e2") \ev 100.0 (string->number "15\#\#") \ev 1500.0% \end{scheme} \begin{note} The domain of {\cf string->number} may be restricted by implementations in the following ways. {\cf String->number} is permitted to return \schfalse{} whenever \vr{string} contains an explicit radix prefix. If all numbers supported by an implementation are real, then {\cf string->number} is permitted to return \schfalse{} whenever \vr{string} uses the polar or rectangular notations for complex numbers. If all numbers are integers, then {\cf string->number} may return \schfalse{} whenever the fractional notation is used. If all numbers are exact, then {\cf string->number} may return \schfalse{} whenever an exponent marker or explicit exactness prefix is used, or if a {\tt \#} appears in place of a digit. If all inexact numbers are integers, then {\cf string->number} may return \schfalse{} whenever a decimal point is used. \end{note} \end{entry} \section{Other data types} This section describes operations on some of Scheme's non-numeric data types: booleans, pairs, lists, symbols, characters, strings and vectors. \subsection{Booleans} \label{booleansection} The standard boolean objects for true and false are written as \schtrue{} and \schfalse.\sharpindex{t}\sharpindex{f} What really matters, though, are the objects that the Scheme conditional expressions ({\cf if}, {\cf cond}, {\cf and}, {\cf or}, {\cf do}) treat as true\index{true} or false\index{false}. The phrase ``a true value''\index{true} (or sometimes just ``true'') means any object treated as true by the conditional expressions, and the phrase ``a false value''\index{false} (or ``false'') means any object treated as false by the conditional expressions. \vest Of all the standard Scheme values, only \schfalse{} % is guaranteed to count counts as false in conditional expressions. % It is not % specified whether the empty list\index{empty list} counts as false % or as true in conditional expressions. Except for \schfalse{}, % and possibly the empty list, all standard Scheme values, including \schtrue, pairs, the empty list, symbols, numbers, strings, vectors, and procedures, count as true. %\begin{note} %In some implementations the empty list counts as false, contrary %to the above. %Nonetheless a few examples in this report assume that the %empty list counts as true, as in \cite{IEEEScheme}. %\end{note} % \begin{rationale} % For historical reasons some implementations regard \schfalse{} and the % empty list as the same object. These implementations therefore cannot % make the empty list count as true in conditional expressions. % \end{rationale} \begin{note} Programmers accustomed to other dialects of Lisp should be aware that Scheme distinguishes both \schfalse{} and the empty list \index{empty list} from the symbol \ide{nil}. \end{note} \vest Boolean constants evaluate to themselves, so they do not need to be quoted in programs. \begin{scheme} \schtrue \ev \schtrue \schfalse \ev \schfalse '\schfalse \ev \schfalse% \end{scheme} \begin{entry}{% \proto{not}{ obj}{library procedure}} {\cf Not} returns \schtrue{} if \var{obj} is false, and returns \schfalse{} otherwise. \begin{scheme} (not \schtrue) \ev \schfalse (not 3) \ev \schfalse (not (list 3)) \ev \schfalse (not \schfalse) \ev \schtrue (not '()) \ev \schfalse (not (list)) \ev \schfalse (not 'nil) \ev \schfalse% \end{scheme} \end{entry} \begin{entry}{% \proto{boolean?}{ obj}{library procedure}} {\cf Boolean?} returns \schtrue{} if \var{obj} is either \schtrue{} or \schfalse{} and returns \schfalse{} otherwise. \begin{scheme} (boolean? \schfalse) \ev \schtrue (boolean? 0) \ev \schfalse (boolean? '()) \ev \schfalse% \end{scheme} \end{entry} \subsection{Pairs and lists} \label{listsection} A \defining{pair} (sometimes called a \defining{dotted pair}) is a record structure with two fields called the car and cdr fields (for historical reasons). Pairs are created by the procedure {\cf cons}. The car and cdr fields are accessed by the procedures {\cf car} and {\cf cdr}. The car and cdr fields are assigned by the procedures {\cf set-car!}\ and {\cf set-cdr!}. Pairs are used primarily to represent lists. A list can be defined recursively as either the empty list\index{empty list} or a pair whose cdr is a list. More precisely, the set of lists is defined as the smallest set \var{X} such that \begin{itemize} \item The empty list is in \var{X}. \item If \var{list} is in \var{X}, then any pair whose cdr field contains \var{list} is also in \var{X}. \end{itemize} The objects in the car fields of successive pairs of a list are the elements of the list. For example, a two-element list is a pair whose car is the first element and whose cdr is a pair whose car is the second element and whose cdr is the empty list. The length of a list is the number of elements, which is the same as the number of pairs. The empty list\mainindex{empty list} is a special object of its own type (it is not a pair); it has no elements and its length is zero. \begin{note} The above definitions imply that all lists have finite length and are terminated by the empty list. \end{note} The most general notation (external representation) for Scheme pairs is the ``dotted'' notation \hbox{\cf (\vari{c} .\ \varii{c})} where \vari{c} is the value of the car field and \varii{c} is the value of the cdr field. For example {\cf (4 .\ 5)} is a pair whose car is 4 and whose cdr is 5. Note that {\cf (4 .\ 5)} is the external representation of a pair, not an expression that evaluates to a pair. A more streamlined notation can be used for lists: the elements of the list are simply enclosed in parentheses and separated by spaces. The empty list\index{empty list} is written {\tt()} . For example, \begin{scheme} (a b c d e)% \end{scheme} and \begin{scheme} (a . (b . (c . (d . (e . ())))))% \end{scheme} are equivalent notations for a list of symbols. A chain of pairs not ending in the empty list is called an \defining{improper list}. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists: \begin{scheme} (a b c . d)% \end{scheme} is equivalent to \begin{scheme} (a . (b . (c . d)))% \end{scheme} Whether a given pair is a list depends upon what is stored in the cdr field. When the \ide{set-cdr!} procedure is used, an object can be a list one moment and not the next: \begin{scheme} (define x (list 'a 'b 'c)) (define y x) y \ev (a b c) (list? y) \ev \schtrue (set-cdr! x 4) \ev \unspecified x \ev (a . 4) (eqv? x y) \ev \schtrue y \ev (a . 4) (list? y) \ev \schfalse (set-cdr! x x) \ev \unspecified (list? x) \ev \schfalse% \end{scheme} %It is often convenient to speak of a homogeneous list of objects %of some particular data type, as for example \hbox{\cf (1 2 3)} is a list of %integers. To be more precise, suppose \var{D} is some data type. (Any %predicate defines a data type consisting of those objects of which the %predicate is true.) Then % %\begin{itemize} %\item The empty list is a list of \var{D}. %\item If \var{list} is a list of \var{D}, then any pair whose cdr is % \var{list} and whose car is an element of the data type \var{D} is also a % list of \var{D}. %\item There are no other lists of \var{D}. %\end{itemize} Within literal expressions and representations of objects read by the \ide{read} procedure, the forms \singlequote\hyper{datum}\schindex{'}, \backquote\hyper{datum}, {\tt,}\hyper{datum}\schindex{,}, and {\tt,@}\hyper{datum} denote two-ele\-ment lists whose first elements are the symbols \ide{quote}, \ide{quasiquote}, \hbox{\ide{unquote}}, and \ide{unquote-splicing}, respectively. The second element in each case is \hyper{datum}. This convention is supported so that arbitrary Scheme programs may be represented as lists. \todo{Can or need this be stated more carefully?} That is, according to Scheme's grammar, every \meta{expression} is also a \meta{datum} (see section~\ref{datum}). Among other things, this permits the use of the {\cf read} procedure to parse Scheme programs. See section~\ref{externalreps}. \begin{entry}{% \proto{pair?}{ obj}{procedure}} {\cf Pair?} returns \schtrue{} if \var{obj} is a pair, and otherwise returns \schfalse. \begin{scheme} (pair? '(a . b)) \ev \schtrue (pair? '(a b c)) \ev \schtrue (pair? '()) \ev \schfalse (pair? '\#(a b)) \ev \schfalse% \end{scheme} \end{entry} \begin{entry}{% \proto{cons}{ \vari{obj} \varii{obj}}{procedure}} Returns a newly allocated pair whose car is \vari{obj} and whose cdr is \varii{obj}. The pair is guaranteed to be different (in the sense of {\cf eqv?}) from every existing object. \begin{scheme} (cons 'a '()) \ev (a) (cons '(a) '(b c d)) \ev ((a) b c d) (cons "a" '(b c)) \ev ("a" b c) (cons 'a 3) \ev (a . 3) (cons '(a b) 'c) \ev ((a b) . c)% \end{scheme} \end{entry} \begin{entry}{% \proto{car}{ pair}{procedure}} \nodomain{\var{Pair} must be a pair.} Returns the contents of the car field of \var{pair}. Note that it is an error to take the car of the empty list\index{empty list}. \begin{scheme} (car '(a b c)) \ev a (car '((a) b c d)) \ev (a) (car '(1 . 2)) \ev 1 (car '()) \ev \scherror% \end{scheme} \end{entry} \begin{entry}{% \proto{cdr}{ pair}{procedure}} \nodomain{\var{Pair} must be a pair.} Returns the contents of the cdr field of \var{pair}. Note that it is an error to take the cdr of the empty list. \begin{scheme} (cdr '((a) b c d)) \ev (b c d) (cdr '(1 . 2)) \ev 2 (cdr '()) \ev \scherror% \end{scheme} \end{entry} \begin{entry}{% \proto{set-car!}{ pair obj}{procedure}} \nodomain{\var{Pair} must be a pair.} Stores \var{obj} in the car field of \var{pair}. The value returned by {\cf set-car!}\ is unspecified. % %This procedure can be very confusing if used indiscriminately. \begin{scheme} (define (f) (list 'not-a-constant-list)) (define (g) '(constant-list)) (set-car! (f) 3) \ev \unspecified (set-car! (g) 3) \ev \scherror% \end{scheme} \end{entry} \begin{entry}{% \proto{set-cdr!}{ pair obj}{procedure}} \nodomain{\var{Pair} must be a pair.} Stores \var{obj} in the cdr field of \var{pair}. The value returned by {\cf set-cdr!}\ is unspecified. % %This procedure can be very confusing if used indiscriminately. \end{entry} \setbox0\hbox{\tt(cadr \var{pair})} \setbox1\hbox{library procedure} \begin{entry}{% \proto{caar}{ pair}{library procedure} \proto{cadr}{ pair}{library procedure} \pproto{\hbox to 1\wd0 {\hfil$\vdots$\hfil}}{\hbox to 1\wd1 {\hfil$\vdots$\hfil}} \proto{cdddar}{ pair}{library procedure} \proto{cddddr}{ pair}{library procedure}} These procedures are compositions of {\cf car} and {\cf cdr}, where for example {\cf caddr} could be defined by \begin{scheme} (define caddr (lambda (x) (car (cdr (cdr x))))){\rm.}% \end{scheme} Arbitrary compositions, up to four deep, are provided. There are twenty-eight of these procedures in all. \end{entry} \begin{entry}{% \proto{null?}{ obj}{library procedure}} Returns \schtrue{} if \var{obj} is the empty list\index{empty list}, otherwise returns \schfalse. % \begin{note} % In implementations in which the empty % list is the same as \schfalse{}, {\cf null?} will return \schtrue{} % if \var{obj} is \schfalse{}. % \end{note} \end{entry} \begin{entry}{% \proto{list?}{ obj}{library procedure}} Returns \schtrue{} if \var{obj} is a list, otherwise returns \schfalse{}. By definition, all lists have finite length and are terminated by the empty list. \begin{scheme} (list? '(a b c)) \ev \schtrue (list? '()) \ev \schtrue (list? '(a . b)) \ev \schfalse (let ((x (list 'a))) (set-cdr! x x) (list? x)) \ev \schfalse% \end{scheme} \end{entry} \begin{entry}{% \proto{list}{ \var{obj} \dotsfoo}{library procedure}} Returns a newly allocated list of its arguments. \begin{scheme} (list 'a (+ 3 4) 'c) \ev (a 7 c) (list) \ev ()% \end{scheme} \end{entry} \begin{entry}{% \proto{length}{ list}{library procedure}} \nodomain{\var{List} must be a list.} Returns the length of \var{list}. \begin{scheme} (length '(a b c)) \ev 3 (length '(a (b) (c d e))) \ev 3 (length '()) \ev 0% \end{scheme} \end{entry} \begin{entry}{% \proto{append}{ list \dotsfoo}{library procedure}} \nodomain{All \var{list}s should be lists.} Returns a list consisting of the elements of the first \var{list} followed by the elements of the other \var{list}s. \begin{scheme} (append '(x) '(y)) \ev (x y) (append '(a) '(b c d)) \ev (a b c d) (append '(a (b)) '((c))) \ev (a (b) (c))% \end{scheme} The resulting list is always newly allocated, except that it shares structure with the last \var{list} argument. The last argument may actually be any object; an improper list results if the last argument is not a proper list. \todo{This is pretty awkward. I should get Bartley to fix this.} \begin{scheme} (append '(a b) '(c . d)) \ev (a b c . d) (append '() 'a) \ev a% \end{scheme} \end{entry} \begin{entry}{% \proto{reverse}{ list}{library procedure}} \nodomain{\var{List} must be a list.} Returns a newly allocated list consisting of the elements of \var{list} in reverse order. \begin{scheme} (reverse '(a b c)) \ev (c b a) (reverse '(a (b c) d (e (f)))) \lev ((e (f)) d (b c) a)% \end{scheme} \end{entry} \begin{entry}{% \proto{list-tail}{ list \vr{k}}{library procedure}} Returns the sublist of \var{list} obtained by omitting the first \vr{k} elements. It is an error if \var{list} has fewer than \vr{k} elements. {\cf List-tail} could be defined by \begin{scheme} (define list-tail (lambda (x k) (if (zero? k) x (list-tail (cdr x) (- k 1)))))% \end{scheme} \end{entry} \begin{entry}{% \proto{list-ref}{ list \vr{k}}{library procedure}} Returns the \vr{k}th element of \var{list}. (This is the same as the car of {\tt(list-tail \var{list} \vr{k})}.) It is an error if \var{list} has fewer than \vr{k} elements. \begin{scheme} (list-ref '(a b c d) 2) \ev c (list-ref '(a b c d) (inexact->exact (round 1.8))) \lev c% \end{scheme} \end{entry} %\begin{entry}{% %\proto{last-pair}{ list}{library procedure}} % %Returns the last pair in the nonempty, possibly improper, list \var{list}. %{\cf Last-pair} could be defined by % %\begin{scheme} %(define last-pair % (lambda (x) % (if (pair? (cdr x)) % (last-pair (cdr x)) % x)))% %\end{scheme} % %\end{entry} \begin{entry}{% \proto{memq}{ obj list}{library procedure} \proto{memv}{ obj list}{library procedure} \proto{member}{ obj list}{library procedure}} These procedures return the first sublist of \var{list} whose car is \var{obj}, where the sublists of \var{list} are the non-empty lists returned by {\tt (list-tail \var{list} \var{k})} for \var{k} less than the length of \var{list}. If \var{obj} does not occur in \var{list}, then \schfalse{} (not the empty list) is returned. {\cf Memq} uses {\cf eq?}\ to compare \var{obj} with the elements of \var{list}, while {\cf memv} uses {\cf eqv?}\ and {\cf member} uses {\cf equal?}. \begin{scheme} (memq 'a '(a b c)) \ev (a b c) (memq 'b '(a b c)) \ev (b c) (memq 'a '(b c d)) \ev \schfalse (memq (list 'a) '(b (a) c)) \ev \schfalse (member (list 'a) '(b (a) c)) \ev ((a) c) (memq 101 '(100 101 102)) \ev \unspecified (memv 101 '(100 101 102)) \ev (101 102)% \end{scheme} \end{entry} \begin{entry}{% \proto{assq}{ obj alist}{library procedure} \proto{assv}{ obj alist}{library procedure} \proto{assoc}{ obj alist}{library procedure}} \domain{\var{Alist} (for ``association list'') must be a list of pairs.} These procedures find the first pair in \var{alist} whose car field is \var{obj}, and returns that pair. If no pair in \var{alist} has \var{obj} as its car, then \schfalse{} (not the empty list) is returned. {\cf Assq} uses {\cf eq?}\ to compare \var{obj} with the car fields of the pairs in \var{alist}, while {\cf assv} uses {\cf eqv?}\ and {\cf assoc} uses {\cf equal?}. \begin{scheme} (define e '((a 1) (b 2) (c 3))) (assq 'a e) \ev (a 1) (assq 'b e) \ev (b 2) (assq 'd e) \ev \schfalse (assq (list 'a) '(((a)) ((b)) ((c)))) \ev \schfalse (assoc (list 'a) '(((a)) ((b)) ((c)))) \ev ((a)) (assq 5 '((2 3) (5 7) (11 13))) \ev \unspecified (assv 5 '((2 3) (5 7) (11 13))) \ev (5 7)% \end{scheme} \begin{rationale} Although they are ordinarily used as predicates, {\cf memq}, {\cf memv}, {\cf member}, {\cf assq}, {\cf assv}, and {\cf assoc} do not have question marks in their names because they return useful values rather than just \schtrue{} or \schfalse{}. \end{rationale} \end{entry} \subsection{Symbols} \label{symbolsection} Symbols are objects whose usefulness rests on the fact that two symbols are identical (in the sense of {\cf eqv?}) if and only if their names are spelled the same way. This is exactly the property needed to represent identifiers\index{identifier} in programs, and so most implementations of Scheme use them internally for that purpose. Symbols are useful for many other applications; for instance, they may be used the way enumerated values are used in Pascal. \vest The rules for writing a symbol are exactly the same as the rules for writing an identifier; see sections~\ref{syntaxsection} and~\ref{identifiersyntax}. \vest It is guaranteed that any symbol that has been returned as part of a literal expression, or read using the {\cf read} procedure, and subsequently written out using the {\cf write} procedure, will read back in as the identical symbol (in the sense of {\cf eqv?}). The {\cf string\coerce{}symbol} procedure, however, can create symbols for which this write/read invariance may not hold because their names contain special characters or letters in the non-standard case. \begin{note} Some implementations of Scheme have a feature known as ``slashification'' in order to guarantee write/read invariance for all symbols, but historically the most important use of this feature has been to compensate for the lack of a string data type. \vest Some implementations also have ``uninterned symbols'', which defeat write/read invariance even in implementations with slashification, and also generate exceptions to the rule that two symbols are the same if and only if their names are spelled the same. \end{note} \begin{entry}{% \proto{symbol?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is a symbol, otherwise returns \schfalse. \begin{scheme} (symbol? 'foo) \ev \schtrue (symbol? (car '(a b))) \ev \schtrue (symbol? "bar") \ev \schfalse (symbol? 'nil) \ev \schtrue (symbol? '()) \ev \schfalse (symbol? \schfalse) \ev \schfalse% \end{scheme} \end{entry} \begin{entry}{% \proto{symbol->string}{ symbol}{procedure}} Returns the name of \var{symbol} as a string. If the symbol was part of an object returned as the value of a literal expression (section~\ref{literalsection}) or by a call to the {\cf read} procedure, and its name contains alphabetic characters, then the string returned will contain characters in the implementation's preferred standard case---some implementations will prefer upper case, others lower case. If the symbol was returned by {\cf string\coerce{}symbol}, the case of characters in the string returned will be the same as the case in the string that was passed to {\cf string\coerce{}symbol}. It is an error to apply mutation procedures like \ide{string-set!} to strings returned by this procedure. The following examples assume that the implementation's standard case is lower case: \begin{scheme} (symbol->string 'flying-fish) \ev "flying-fish" (symbol->string 'Martin) \ev "martin" (symbol->string (string->symbol "Malvina")) \ev "Malvina"% \end{scheme} \end{entry} \begin{entry}{% \proto{string->symbol}{ string}{procedure}} Returns the symbol whose name is \var{string}. This procedure can create symbols with names containing special characters or letters in the non-standard case, but it is usually a bad idea to create such symbols because in some implementations of Scheme they cannot be read as themselves. See {\cf symbol\coerce{}string}. The following examples assume that the implementation's standard case is lower case: \begin{scheme} (eq? 'mISSISSIppi 'mississippi) \lev \schtrue (string->symbol "mISSISSIppi") \lev% {\rm{}the symbol with name} "mISSISSIppi" (eq? 'bitBlt (string->symbol "bitBlt")) \lev \schfalse (eq? 'JollyWog (string->symbol (symbol->string 'JollyWog))) \lev \schtrue (string=? "K. Harper, M.D." (symbol->string (string->symbol "K. Harper, M.D."))) \lev \schtrue% \end{scheme} \end{entry} \subsection{Characters} \label{charactersection} Characters are objects that represent printed characters such as letters and digits. %There is no requirement that the data type of %characters be disjoint from other data types; implementations are %encouraged to have a separate character data type, but may choose to %represent characters as integers, strings, or some other type. Characters are written using the notation \sharpsign\backwhack\hyper{character} or \sharpsign\backwhack\hyper{character name}. For example: $$ \begin{tabular}{ll} {\tt \#\backwhack{}a}&; lower case letter\\ {\tt \#\backwhack{}A}&; upper case letter\\ {\tt \#\backwhack{}(}&; left parenthesis\\ {\tt \#\backwhack{} }&; the space character\\ {\tt \#\backwhack{}space}&; the preferred way to write a space\\ {\tt \#\backwhack{}newline}&; the newline character\\ \end{tabular} $$ Case is significant in \sharpsign\backwhack\hyper{character}, but not in \sharpsign\backwhack{\rm$\langle$character name$\rangle$}. % \hyper doesn't % allow a linebreak If \hyper{character} in \sharpsign\backwhack\hyper{character} is alphabetic, then the character following \hyper{character} must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of characters ``{\tt\sharpsign\backwhack space}'' could be taken to be either a representation of the space character or a representation of the character ``{\tt\sharpsign\backwhack s}'' followed by a representation of the symbol ``{\tt pace}.'' \todo{Fix} Characters written in the \sharpsign\backwhack{} notation are self-evaluating. That is, they do not have to be quoted in programs. %The \sharpsign\backwhack{} %notation is not an essential part of Scheme, however. Even implementations %that support the \sharpsign\backwhack{} notation for input do not have to %support it for output. \vest Some of the procedures that operate on characters ignore the difference between upper case and lower case. The procedures that ignore case have \hbox{``{\tt -ci}''} (for ``case insensitive'') embedded in their names. \begin{entry}{% \proto{char?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is a character, otherwise returns \schfalse. \end{entry} \begin{entry}{% \proto{char=?}{ \vari{char} \varii{char}}{procedure} \proto{char?}{ \vari{char} \varii{char}}{procedure} \proto{char<=?}{ \vari{char} \varii{char}}{procedure} \proto{char>=?}{ \vari{char} \varii{char}}{procedure}} \label{characterequality} \nodomain{Both \vari{char} and \varii{char} must be characters.} These procedures impose a total ordering on the set of characters. It is guaranteed that under this ordering: \begin{itemize} \item The upper case characters are in order. For example, {\cf (char?}{ \vari{char} \varii{char}}{library procedure} \proto{char-ci<=?}{ \vari{char} \varii{char}}{library procedure} \proto{char-ci>=?}{ \vari{char} \varii{char}}{library procedure}} \nodomain{Both \vari{char} and \varii{char} must be characters.} These procedures are similar to {\cf char=?}\ et cetera, but they treat upper case and lower case letters as the same. For example, {\cf (char-ci=?\ \#\backwhack{}A \#\backwhack{}a)} returns \schtrue. Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numerical predicates. \end{entry} \begin{entry}{% \proto{char-alphabetic?}{ char}{library procedure} \proto{char-numeric?}{ char}{library procedure} \proto{char-whitespace?}{ char}{library procedure} \proto{char-upper-case?}{ letter}{library procedure} \proto{char-lower-case?}{ letter}{library procedure}} These procedures return \schtrue{} if their arguments are alphabetic, numeric, whitespace, upper case, or lower case characters, respectively, otherwise they return \schfalse. The following remarks, which are specific to the ASCII character set, are intended only as a guide: The alphabetic characters are the 52 upper and lower case letters. The numeric characters are the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and carriage return. \end{entry} %%R4%%\begin{entry}{% %\proto{char-upper-case?}{ letter}{procedure} %\proto{char-lower-case?}{ letter}{procedure}} % %\domain{\var{Letter} must be an alphabetic character.} %These procedures return \schtrue{} if their arguments are upper case or %lower case characters, respectively, otherwise they return \schfalse. %\end{entry} \begin{entry}{% \proto{char->integer}{ char}{procedure} \proto{integer->char}{ \vr{n}}{procedure}} Given a character, {\cf char\coerce{}integer} returns an exact integer representation of the character. Given an exact integer that is the image of a character under {\cf char\coerce{}integer}, {\cf integer\coerce{}char} returns that character. These procedures implement order-preserving isomorphisms between the set of characters under the \ide{char<=?}\ ordering and some subset of the integers under the {\cf <=}\ ordering. That is, if \begin{scheme} (char<=? \vr{a} \vr{b}) \evalsto \schtrue {\rm{}and} % (<= \vr{x} \vr{y}) \evalsto \schtrue% \end{scheme} \noindent and \vr{x} and \vr{y} are in the domain of {\cf integer\coerce{}char}, then \begin{scheme} (<= (char\coerce{}integer \vr{a}) (char\coerce{}integer \vr{b})) \ev \schtrue (char<=? (integer\coerce{}char \vr{x}) (integer\coerce{}char \vr{y})) \ev \schtrue% \end{scheme} \end{entry} \begin{entry}{% \proto{char-upcase}{ char}{library procedure} \proto{char-downcase}{ char}{library procedure}} \nodomain{\var{Char} must be a character.} These procedures return a character \varii{char} such that {\cf (char-ci=? \var{char} \varii{char})}. In addition, if \var{char} is alphabetic, then the result of {\cf char-upcase} is upper case and the result of {\cf char-downcase} is lower case. \end{entry} \subsection{Strings} \label{stringsection} Strings are sequences of characters. %In some implementations of Scheme %they are immutable; other implementations provide destructive procedures %such as {\cf string-set!}\ that alter string objects. \vest Strings are written as sequences of characters enclosed within doublequotes ({\cf "}). A doublequote can be written inside a string only by escaping it with a backslash (\backwhack{}), as in \begin{scheme} "The word \backwhack{}"recursion\backwhack{}" has many meanings."% \end{scheme} A backslash can be written inside a string only by escaping it with another backslash. Scheme does not specify the effect of a backslash within a string that is not followed by a doublequote or backslash. \vest A string constant may continue from one line to the next, but the exact contents of such a string are unspecified. % this is %usually a bad idea because %the exact effect may vary from one computer %system to another. \vest The {\em length} of a string is the number of characters that it contains. This number is an exact, non-negative integer that is fixed when the string is created. The \defining{valid indexes} of a string are the exact non-negative integers less than the length of the string. The first character of a string has index 0, the second has index 1, and so on. \vest In phrases such as ``the characters of \var{string} beginning with index \var{start} and ending with index \var{end},'' it is understood that the index \var{start} is inclusive and the index \var{end} is exclusive. Thus if \var{start} and \var{end} are the same index, a null substring is referred to, and if \var{start} is zero and \var{end} is the length of \var{string}, then the entire string is referred to. \vest Some of the procedures that operate on strings ignore the difference between upper and lower case. The versions that ignore case have \hbox{``{\cf -ci}''} (for ``case insensitive'') embedded in their names. \begin{entry}{% \proto{string?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is a string, otherwise returns \schfalse. \end{entry} \begin{entry}{% \proto{make-string}{ \vr{k}}{procedure} \rproto{make-string}{ \vr{k} char}{procedure}} %\domain{\vr{k} must be a non-negative integer, and \var{char} must be %a character.} {\cf Make-string} returns a newly allocated string of length \vr{k}. If \var{char} is given, then all elements of the string are initialized to \var{char}, otherwise the contents of the \var{string} are unspecified. \end{entry} \begin{entry}{% \proto{string}{ char \dotsfoo}{library procedure}} Returns a newly allocated string composed of the arguments. \end{entry} \begin{entry}{% \proto{string-length}{ string}{procedure}} Returns the number of characters in the given \var{string}. \end{entry} \begin{entry}{% \proto{string-ref}{ string \vr{k}}{procedure}} \domain{\vr{k} must be a valid index of \var{string}.} {\cf String-ref} returns character \vr{k} of \var{string} using zero-origin indexing. \end{entry} \begin{entry}{% \proto{string-set!}{ string k char}{procedure}} \domain{%\var{String} must be a string, \vr{k} must be a valid index of \var{string}%, and \var{char} must be a character .} {\cf String-set!} stores \var{char} in element \vr{k} of \var{string} and returns an unspecified value. % \begin{scheme} (define (f) (make-string 3 \sharpsign\backwhack{}*)) (define (g) "***") (string-set! (f) 0 \sharpsign\backwhack{}?) \ev \unspecified (string-set! (g) 0 \sharpsign\backwhack{}?) \ev \scherror (string-set! (symbol->string 'immutable) 0 \sharpsign\backwhack{}?) \ev \scherror% \end{scheme} \end{entry} \begin{entry}{% \proto{string=?}{ \vari{string} \varii{string}}{library procedure} \proto{string-ci=?}{ \vari{string} \varii{string}}{library procedure}} Returns \schtrue{} if the two strings are the same length and contain the same characters in the same positions, otherwise returns \schfalse. {\cf String-ci=?}\ treats upper and lower case letters as though they were the same character, but {\cf string=?}\ treats upper and lower case as distinct characters. \end{entry} \begin{entry}{% \proto{string?}{ \vari{string} \varii{string}}{library procedure} \proto{string<=?}{ \vari{string} \varii{string}}{library procedure} \proto{string>=?}{ \vari{string} \varii{string}}{library procedure} \proto{string-ci?}{ \vari{string} \varii{string}}{library procedure} \proto{string-ci<=?}{ \vari{string} \varii{string}}{library procedure} \proto{string-ci>=?}{ \vari{string} \varii{string}}{library procedure}} These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, {\cf stringlist}{ string}{library procedure} \proto{list->string}{ list}{library procedure}} {\cf String\coerce{}list} returns a newly allocated list of the characters that make up the given string. {\cf List\coerce{}string} returns a newly allocated string formed from the characters in the list \var{list}, which must be a list of characters. {\cf String\coerce{}list} and {\cf list\coerce{}string} are inverses so far as {\cf equal?}\ is concerned. %Implementations that provide %destructive operations on strings should ensure that the result of %{\cf list\coerce{}string} is newly allocated. \end{entry} \begin{entry}{% \proto{string-copy}{ string}{library procedure}} Returns a newly allocated copy of the given \var{string}. \end{entry} \begin{entry}{% \proto{string-fill!}{ string char}{library procedure}} Stores \var{char} in every element of the given \var{string} and returns an unspecified value. % \end{entry} \subsection{Vectors} \label{vectorsection} Vectors are heterogenous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time required to access a randomly chosen element is typically less for the vector than for the list. \vest The {\em length} of a vector is the number of elements that it contains. This number is a non-negative integer that is fixed when the vector is created. The {\em valid indexes}\index{valid indexes} of a vector are the exact non-negative integers less than the length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than the length of the vector. Vectors are written using the notation {\tt\#(\var{obj} \dotsfoo)}. For example, a vector of length 3 containing the number zero in element 0, the list {\cf(2 2 2 2)} in element 1, and the string {\cf "Anna"} in element 2 can be written as following: \begin{scheme} \#(0 (2 2 2 2) "Anna")% \end{scheme} Note that this is the external representation of a vector, not an expression evaluating to a vector. Like list constants, vector constants must be quoted: \begin{scheme} '\#(0 (2 2 2 2) "Anna") \lev \#(0 (2 2 2 2) "Anna")% \end{scheme} \todo{Pitman sez: The visual similarity to lists is bound to be confusing to some. Elaborate on the distinction.} \begin{entry}{% \proto{vector?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is a vector, otherwise returns \schfalse. \end{entry} \begin{entry}{% \proto{make-vector}{ k}{procedure} \rproto{make-vector}{ k fill}{procedure}} Returns a newly allocated vector of \var{k} elements. If a second argument is given, then each element is initialized to \var{fill}. Otherwise the initial contents of each element is unspecified. \end{entry} \begin{entry}{% \proto{vector}{ obj \dotsfoo}{library procedure}} Returns a newly allocated vector whose elements contain the given arguments. Analogous to {\cf list}. \begin{scheme} (vector 'a 'b 'c) \ev \#(a b c)% \end{scheme} \end{entry} \begin{entry}{% \proto{vector-length}{ vector}{procedure}} Returns the number of elements in \var{vector} as an exact integer. \end{entry} \begin{entry}{% \proto{vector-ref}{ vector k}{procedure}} \domain{\vr{k} must be a valid index of \var{vector}.} {\cf Vector-ref} returns the contents of element \vr{k} of \var{vector}. \begin{scheme} (vector-ref '\#(1 1 2 3 5 8 13 21) 5) \lev 8 (vector-ref '\#(1 1 2 3 5 8 13 21) (let ((i (round (* 2 (acos -1))))) (if (inexact? i) (inexact->exact i) i))) \lev 13% \end{scheme} \end{entry} \begin{entry}{% \proto{vector-set!}{ vector k obj}{procedure}} \domain{\vr{k} must be a valid index of \var{vector}.} {\cf Vector-set!} stores \var{obj} in element \vr{k} of \var{vector}. The value returned by {\cf vector-set!}\ is unspecified. % \begin{scheme} (let ((vec (vector 0 '(2 2 2 2) "Anna"))) (vector-set! vec 1 '("Sue" "Sue")) vec) \lev \#(0 ("Sue" "Sue") "Anna") (vector-set! '\#(0 1 2) 1 "doe") \lev \scherror ; constant vector% \end{scheme} \end{entry} \begin{entry}{% \proto{vector->list}{ vector}{library procedure} \proto{list->vector}{ list}{library procedure}} {\cf Vector->list} returns a newly allocated list of the objects contained in the elements of \var{vector}. {\cf List->vector} returns a newly created vector initialized to the elements of the list \var{list}. \begin{scheme} (vector->list '\#(dah dah didah)) \lev (dah dah didah) (list->vector '(dididit dah)) \lev \#(dididit dah)% \end{scheme} \end{entry} \begin{entry}{% \proto{vector-fill!}{ vector fill}{library procedure}} Stores \var{fill} in every element of \var{vector}. The value returned by {\cf vector-fill!}\ is unspecified. % \end{entry} \section{Control features} \label{proceduresection} % Intro flushed; not very a propos any more. % Procedures should be discussed somewhere, however. This chapter describes various primitive procedures which control the flow of program execution in special ways. The {\cf procedure?}\ predicate is also described here. \todo{{\tt Procedure?} doesn't belong in a section with the name ``control features.'' What to do?} \begin{entry}{% \proto{procedure?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is a procedure, otherwise returns \schfalse. \begin{scheme} (procedure? car) \ev \schtrue (procedure? 'car) \ev \schfalse (procedure? (lambda (x) (* x x))) \ev \schtrue (procedure? '(lambda (x) (* x x))) \ev \schfalse (call-with-current-continuation procedure?) \ev \schtrue% \end{scheme} \end{entry} \begin{entry}{% \proto{apply}{ proc \vari{arg} $\ldots$ args}{procedure}} \domain{\var{Proc} must be a procedure and \var{args} must be a list.} Calls \var{proc} with the elements of the list {\cf(append (list \vari{arg} \dotsfoo) \var{args})} as the actual arguments. \begin{scheme} (apply + (list 3 4)) \ev 7 (define compose (lambda (f g) (lambda args (f (apply g args))))) ((compose sqrt *) 12 75) \ev 30% \end{scheme} \end{entry} \begin{entry}{% \proto{map}{ proc \vari{list} \varii{list} \dotsfoo}{library procedure}} \domain{The \var{list}s must be lists, and \var{proc} must be a procedure taking as many arguments as there are {\it list}s and returning a single value. If more than one \var{list} is given, then they must all be the same length.} {\cf Map} applies \var{proc} element-wise to the elements of the \var{list}s and returns a list of the results, in order. The dynamic order in which \var{proc} is applied to the elements of the \var{list}s is unspecified. \begin{scheme} (map cadr '((a b) (d e) (g h))) \lev (b e h) (map (lambda (n) (expt n n)) '(1 2 3 4 5)) \lev (1 4 27 256 3125) (map + '(1 2 3) '(4 5 6)) \ev (5 7 9) (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) '(a b))) \ev (1 2) \var{or} (2 1) \end{scheme} \end{entry} \begin{entry}{% \proto{for-each}{ proc \vari{list} \varii{list} \dotsfoo}{library procedure}} The arguments to {\cf for-each} are like the arguments to {\cf map}, but {\cf for-each} calls \var{proc} for its side effects rather than for its values. Unlike {\cf map}, {\cf for-each} is guaranteed to call \var{proc} on the elements of the \var{list}s in order from the first element(s) to the last, and the value returned by {\cf for-each} is unspecified. \begin{scheme} (let ((v (make-vector 5))) (for-each (lambda (i) (vector-set! v i (* i i))) '(0 1 2 3 4)) v) \ev \#(0 1 4 9 16)% \end{scheme} \end{entry} \begin{entry}{% \proto{force}{ promise}{library procedure}} Forces the value of \var{promise} (see \ide{delay}, section~\ref{delay}).\index{promise} If no value has been computed for the promise, then a value is computed and returned. The value of the promise is cached (or ``memoized'') so that if it is forced a second time, the previously computed value is returned. % without any recomputation. % [As pointed out by Marc Feeley, the "without any recomputation" % isn't necessarily true. --Will] \begin{scheme} (force (delay (+ 1 2))) \ev 3 (let ((p (delay (+ 1 2)))) (list (force p) (force p))) \ev (3 3) (define a-stream (letrec ((next (lambda (n) (cons n (delay (next (+ n 1))))))) (next 0))) (define head car) (define tail (lambda (stream) (force (cdr stream)))) (head (tail (tail a-stream))) \ev 2% \end{scheme} {\cf Force} and {\cf delay} are mainly intended for programs written in functional style. The following examples should not be considered to illustrate good programming style, but they illustrate the property that only one value is computed for a promise, no matter how many times it is forced. % the value of a promise is computed at most once. % [As pointed out by Marc Feeley, it may be computed more than once, % but as I observed we can at least insist that only one value be % used! -- Will] \begin{scheme} (define count 0) (define p (delay (begin (set! count (+ count 1)) (if (> count x) count (force p))))) (define x 5) p \ev {\it{}a promise} (force p) \ev 6 p \ev {\it{}a promise, still} (begin (set! x 10) (force p)) \ev 6% \end{scheme} Here is a possible implementation of {\cf delay} and {\cf force}. Promises are implemented here as procedures of no arguments, and {\cf force} simply calls its argument: \begin{scheme} (define force (lambda (object) (object)))% \end{scheme} We define the expression \begin{scheme} (delay \hyper{expression})% \end{scheme} to have the same meaning as the procedure call \begin{scheme} (make-promise (lambda () \hyper{expression}))\rm \end{scheme} as follows \begin{scheme} (define-syntax delay (syntax-rules () ((delay expression) (make-promise (lambda () expression))))),% \end{scheme} where {\cf make-promise} is defined as follows: % \begin{scheme} % (define make-promise % (lambda (proc) % (let ((already-run? \schfalse) (result \schfalse)) % (lambda () % (cond ((not already-run?) % (set! result (proc)) % (set! already-run? \schtrue))) % result))))% % \end{scheme} \begin{scheme} (define make-promise (lambda (proc) (let ((result-ready? \schfalse) (result \schfalse)) (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? \schtrue) (set! result x) result))))))))% \end{scheme} \begin{rationale} A promise may refer to its own value, as in the last example above. Forcing such a promise may cause the promise to be forced a second time before the value of the first force has been computed. This complicates the definition of {\cf make-promise}. \end{rationale} Various extensions to this semantics of {\cf delay} and {\cf force} are supported in some implementations: \begin{itemize} \item Calling {\cf force} on an object that is not a promise may simply return the object. \item It may be the case that there is no means by which a promise can be operationally distinguished from its forced value. That is, expressions like the following may evaluate to either \schtrue{} or to \schfalse{}, depending on the implementation: \begin{scheme} (eqv? (delay 1) 1) \ev \unspecified (pair? (delay (cons 1 2))) \ev \unspecified% \end{scheme} \item Some implementations may implement ``implicit forcing,'' where the value of a promise is forced by primitive procedures like \cf{cdr} and \cf{+}: \begin{scheme} (+ (delay (* 3 7)) 13) \ev 34% \end{scheme} \end{itemize} \end{entry} \begin{entry}{% \proto{call-with-current-continuation}{ proc}{procedure}} \label{continuations} \domain{\var{Proc} must be a procedure of one argument.} The procedure {\cf call-with-current-continuation} packages up the current continuation (see the rationale below) as an ``escape procedure''\mainindex{escape procedure} and passes it as an argument to \var{proc}. The escape procedure is a Scheme procedure that, if it is later called, will abandon whatever continuation is in effect at that later time and will instead use the continuation that was in effect when the escape procedure was created. Calling the escape procedure may cause the invocation of \var{before} and \var{after} thunks installed using \ide{dynamic-wind}. The escape procedure accepts the same number of arguments as the continuation to the original call to \callcc. Except for continuations created by the {\cf call-with-values} procedure, all continuations take exactly one value. The effect of passing no value or more than one value to continuations that were not created by {\tt call-with-values} is unspecified. \vest The escape procedure that is passed to \var{proc} has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired. \vest The following examples show only the most common ways in which {\cf call-with-current-continuation} is used. If all real uses were as simple as these examples, there would be no need for a procedure with the power of {\cf call-with-current-continuation}. \begin{scheme} (call-with-current-continuation (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) '(54 0 37 -3 245 19)) \schtrue)) \ev -3 (define list-length (lambda (obj) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (obj) (cond ((null? obj) 0) ((pair? obj) (+ (r (cdr obj)) 1)) (else (return \schfalse)))))) (r obj)))))) (list-length '(1 2 3 4)) \ev 4 (list-length '(a b . c)) \ev \schfalse% \end{scheme} \begin{rationale} \vest A common use of {\cf call-with-current-continuation} is for structured, non-local exits from loops or procedure bodies, but in fact {\cf call-with-current-continuation} is extremely useful for implementing a wide variety of advanced control structures. \vest Whenever a Scheme expression is evaluated there is a \defining{continuation} wanting the result of the expression. The continuation represents an entire (default) future for the computation. If the expression is evaluated at top level, for example, then the continuation might take the result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions specified by user code, as in a continuation that will take the result, multiply it by the value stored in a local variable, add seven, and give the answer to the top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and programmers do not think much about them. On rare occasions, however, a programmer may need to deal with continuations explicitly. {\cf Call-with-current-continuation} allows Scheme programmers to do that by creating a procedure that acts just like the current continuation. \vest Most programming languages incorporate one or more special-purpose escape constructs with names like {\tt exit}, \hbox{{\cf return}}, or even {\tt goto}. In 1965, however, Peter Landin~\cite{Landin65} invented a general purpose escape operator called the J-operator. John Reynolds~\cite{Reynolds72} described a simpler but equally powerful construct in 1972. The {\cf catch} special form described by Sussman and Steele in the 1975 report on Scheme is exactly the same as Reynolds's construct, though its name came from a less general construct in MacLisp. Several Scheme implementors noticed that the full power of the \ide{catch} construct could be provided by a procedure instead of by a special syntactic construct, and the name {\cf call-with-current-continuation} was coined in 1982. This name is descriptive, but opinions differ on the merits of such a long name, and some people use the name \ide{call/cc} instead. \end{rationale} \end{entry} \begin{entry}{% \proto{values}{ obj $\ldots$}{procedure}} Delivers all of its arguments to its continuation. Except for continuations created by the \ide{call-with-values} procedure, all continuations take exactly one value. {\tt Values} might be defined as follows: \begin{scheme} (define (values . things) (call-with-current-continuation (lambda (cont) (apply cont things)))) \end{scheme} \end{entry} \begin{entry}{% \proto{call-with-values}{ producer consumer}{procedure}} Calls its \var{producer} argument with no values and a continuation that, when passed some values, calls the \var{consumer} procedure with those values as arguments. The continuation for the call to \var{consumer} is the continuation of the call to {\tt call-with-values}. \begin{scheme} (call-with-values (lambda () (values 4 5)) (lambda (a b) b)) \ev 5 (call-with-values * -) \ev -1 \end{scheme} \end{entry} \begin{entry}{% \proto{dynamic-wind}{ before thunk after}{procedure}} Calls \var{thunk} without arguments, returning the result(s) of this call. \var{Before} and \var{after} are called, also without arguments, as required by the following rules (note that in the absence of calls to continuations captured using \ide{call-with-current-continuation} the three arguments are called once each, in order). \var{Before} is called whenever execution enters the dynamic extent of the call to \var{thunk} and \var{after} is called whenever it exits that dynamic extent. The dynamic extent of a procedure call is the period between when the call is initiated and when it returns. In Scheme, because of {\cf call-with-current-continuation}, the dynamic extent of a call may not be a single, connected time period. It is defined as follows: \begin{itemize} \item The dynamic extent is entered when execution of the body of the called procedure begins. \item The dynamic extent is also entered when execution is not within the dynamic extent and a continuation is invoked that was captured (using {\cf call-with-current-continuation}) during the dynamic extent. \item It is exited when the called procedure returns. \item It is also exited when execution is within the dynamic extent and a continuation is invoked that was captured while not within the dynamic extent. \end{itemize} If a second call to {\cf dynamic-wind} occurs within the dynamic extent of the call to \var{thunk} and then a continuation is invoked in such a way that the \var{after}s from these two invocations of {\cf dynamic-wind} are both to be called, then the \var{after} associated with the second (inner) call to {\cf dynamic-wind} is called first. If a second call to {\cf dynamic-wind} occurs within the dynamic extent of the call to \var{thunk} and then a continuation is invoked in such a way that the \var{before}s from these two invocations of {\cf dynamic-wind} are both to be called, then the \var{before} associated with the first (outer) call to {\cf dynamic-wind} is called first. If invoking a continuation requires calling the \var{before} from one call to {\cf dynamic-wind} and the \var{after} from another, then the \var{after} is called first. The effect of using a captured continuation to enter or exit the dynamic extent of a call to \var{before} or \var{after} is undefined. \begin{scheme} (let ((path '()) (c \#f)) (let ((add (lambda (s) (set! path (cons s path))))) (dynamic-wind (lambda () (add 'connect)) (lambda () (add (call-with-current-continuation (lambda (c0) (set! c c0) 'talk1)))) (lambda () (add 'disconnect))) (if (< (length path) 4) (c 'talk2) (reverse path)))) \lev (connect talk1 disconnect connect talk2 disconnect) \end{scheme} \end{entry} \section{\tt{Eval}} \begin{entry}{% \proto{eval}{ expression environment-specifier}{procedure}} Evaluates \var{expression} in the specified environment and returns its value. \var{Expression} must be a valid Scheme expression represented as data, and \var{environment-specifier} must be a value returned by one of the three procedures described below. Implementations may extend {\cf eval} to allow non-expression programs (definitions) as the first argument and to allow other values as environments, with the restriction that {\cf eval} is not allowed to create new bindings in the environments associated with {\cf null-environment} or {\cf scheme-report-environment}. \begin{scheme} (eval '(* 7 3) (scheme-report-environment 5)) \ev 21 (let ((f (eval '(lambda (f x) (f x x)) (null-environment 5)))) (f + 10)) \ev 20 \end{scheme} \end{entry} \begin{entry}{% \proto{scheme-report-environment}{ version}{procedure} \proto{null-environment}{ version}{procedure}} \var{Version} must be the exact integer {\cf \integerversion}, corresponding to this revision of the Scheme report (the Revised$^\integerversion$ Report on Scheme). {\cf Scheme-report-environment} returns a specifier for an environment that is empty except for all bindings defined in this report that are either required or both optional and supported by the implementation. {\cf Null-environment} returns a specifier for an environment that is empty except for the (syntactic) bindings for all syntactic keywords defined in this report that are either required or both optional and supported by the implementation. Other values of \var{version} can be used to specify environments matching past revisions of this report, but their support is not required. An implementation will signal an error if \var{version} is neither {\cf \integerversion} nor another value supported by the implementation. The effect of assigning (through the use of {\cf eval}) a variable bound in a {\cf scheme-report-environment} (for example {\cf car}) is unspecified. Thus the environments specified by {\cf scheme-report-environment} may be immutable. \end{entry} \begin{entry}{% \proto{interaction-environment}{}{optional procedure}} This procedure returns a specifier for the environment that contains imple\-men\-ta\-tion-defined bindings, typically a superset of those listed in the report. The intent is that this procedure will return the environment in which the implementation would evaluate expressions dynamically typed by the user. \end{entry} \section{Input and output} \subsection{Ports} \label{portsection} Ports represent input and output devices. To Scheme, an input port is a Scheme object that can deliver characters upon command, while an output port is a Scheme object that can accept characters. \mainindex{port} \todo{Haase: Mention that there are alternatives to files?} \begin{entry}{% \proto{call-with-input-file}{ string proc}{library procedure} \proto{call-with-output-file}{ string proc}{library procedure}} \var{String} should be a string naming a file, and \var{proc} should be a procedure that accepts one argument. For {\cf call-with-input-file}, the file should already exist; for {\cf call-with-output-file}, the effect is unspecified if the file already exists. These procedures call \var{proc} with one argument: the port obtained by opening the named file for input or output. If the file cannot be opened, an error is signalled. If \var{proc} returns, then the port is closed automatically and the value(s) yielded by the \var{proc} is(are) returned. If \var{proc} does not return, then the port will not be closed automatically unless it is possible to prove that the port will never again be used for a read or write operation. %Scheme %will not close the port unless it can prove that the port will never %again be used for a read or write operation. \begin{rationale} Because Scheme's escape procedures have unlimited extent, it is possible to escape from the current continuation but later to escape back in. If implementations were permitted to close the port on any escape from the current continuation, then it would be impossible to write portable code using both {\cf call-with-current-continuation} and {\cf call-with-input-file} or {\cf call-with-output-file}. \todo{Pitman wants more said here; maybe encourage users to call \var{close-foo-port}; maybe talk about process switches (?).} \end{rationale} \end{entry} \begin{entry}{% \proto{input-port?}{ obj}{procedure} \proto{output-port?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is an input port or output port respectively, otherwise returns \schfalse. \todo{Won't necessarily return true after port is closed.} \end{entry} \begin{entry}{% \proto{current-input-port}{}{procedure} \proto{current-output-port}{}{procedure}} Returns the current default input or output port. \end{entry} \begin{entry}{% \proto{with-input-from-file}{ string thunk}{optional procedure} \proto{with-output-to-file}{ string thunk}{optional procedure}} \var{String} should be a string naming a file, and \var{proc} should be a procedure of no arguments. For {\cf with-input-from-file}, the file should already exist; for {\cf with-output-to-file}, the effect is unspecified if the file already exists. The file is opened for input or output, an input or output port connected to it is made the default value returned by {\cf current-input-port} or {\cf current-output-port} (and is used by {\tt (read)}, {\tt (write \var{obj})}, and so forth), and the \var{thunk} is called with no arguments. When the \var{thunk} returns, the port is closed and the previous default is restored. {\cf With-input-from-file} and {\cf with-output-to-file} return(s) the value(s) yielded by \var{thunk}. If an escape procedure is used to escape from the continuation of these procedures, their behavior is implementation dependent. \todo{OK this with authors??} %current continuation changes in such a way %as to make it doubtful that the \var{thunk} will ever return. \todo{Freeman: Throughout this section I wanted to see ``the value of {\tt(current-input-port)}'' instead of ``the value returned by \var{current-input-port}''. (Same for \var{current-output-port}.)} \end{entry} \begin{entry}{% \proto{open-input-file}{ filename}{procedure}} Takes a string naming an existing file and returns an input port capable of delivering characters from the file. If the file cannot be opened, an error is signalled. \end{entry} \begin{entry}{% \proto{open-output-file}{ filename}{procedure}} Takes a string naming an output file to be created and returns an output port capable of writing characters to a new file by that name. If the file cannot be opened, an error is signalled. If a file with the given name already exists, the effect is unspecified. \end{entry} \begin{entry}{% \proto{close-input-port}{ port}{procedure} \proto{close-output-port}{ port}{procedure}} Closes the file associated with \var{port}, rendering the \var{port} incapable of delivering or accepting characters. \todo{But maybe a no-op on some ports, e.g. terminals or editor buffers.} These routines have no effect if the file has already been closed. The value returned is unspecified. \todo{Ramsdell: Some note is needed explaining why there are two different close procedures.} \todo{A port isn't necessarily still a port after it has been closed?} \end{entry} \subsection{Input} \label{inputsection} \noindent \hbox{ } %??? \vspace{-5ex} \todo{The input routines have some things in common, maybe explain here.} \begin{entry}{% \proto{read}{}{library procedure} \rproto{read}{ port}{library procedure}} {\cf Read} converts external representations of Scheme objects into the objects themselves. That is, it is a parser for the nonterminal \meta{datum} (see sections~\ref{datum} and \ref{listsection}). {\cf Read} returns the next object parsable from the given input \var{port}, updating \var{port} to point to the first character past the end of the external representation of the object. \vest If an end of file is encountered in the input before any characters are found that can begin an object, then an end of file object is returned. \todo{} The port remains open, and further attempts to read will also return an end of file object. If an end of file is encountered after the beginning of an object's external representation, but the external representation is incomplete and therefore not parsable, an error is signalled. The \var{port} argument may be omitted, in which case it defaults to the value returned by {\cf current-input-port}. It is an error to read from a closed port. \end{entry} \begin{entry}{% \proto{read-char}{}{procedure} \rproto{read-char}{ port}{procedure}} Returns the next character available from the input \var{port}, updating the \var{port} to point to the following character. If no more characters are available, an end of file object is returned. \var{Port} may be omitted, in which case it defaults to the value returned by {\cf current-input-port}. \end{entry} \begin{entry}{% \proto{peek-char}{}{procedure} \rproto{peek-char}{ port}{procedure}} Returns the next character available from the input \var{port}, {\em without} updating the \var{port} to point to the following character. If no more characters are available, an end of file object is returned. \var{Port} may be omitted, in which case it defaults to the value returned by {\cf current-input-port}. \begin{note} The value returned by a call to {\cf peek-char} is the same as the value that would have been returned by a call to {\cf read-char} with the same \var{port}. The only difference is that the very next call to {\cf read-char} or {\cf peek-char} on that \var{port} will return the value returned by the preceding call to {\cf peek-char}. In particular, a call to {\cf peek-char} on an interactive port will hang waiting for input whenever a call to {\cf read-char} would have hung. \end{note} \end{entry} \begin{entry}{% \proto{eof-object?}{ obj}{procedure}} Returns \schtrue{} if \var{obj} is an end of file object, otherwise returns \schfalse. The precise set of end of file objects will vary among implementations, but in any case no end of file object will ever be an object that can be read in using {\cf read}. \end{entry} \begin{entry}{% \proto{char-ready?}{}{procedure} \rproto{char-ready?}{ port}{procedure}} Returns \schtrue{} if a character is ready on the input \var{port} and returns \schfalse{} otherwise. If {\cf char-ready} returns \schtrue{} then the next {\cf read-char} operation on the given \var{port} is guaranteed not to hang. If the \var{port} is at end of file then {\cf char-ready?}\ returns \schtrue. \var{Port} may be omitted, in which case it defaults to the value returned by {\cf current-input-port}. \begin{rationale} {\cf Char-ready?}\ exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input. Any input editors associated with such ports must ensure that characters whose existence has been asserted by {\cf char-ready?}\ cannot be rubbed out. If {\cf char-ready?}\ were to return \schfalse{} at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters. \end{rationale} \end{entry} \subsection{Output} \label{outputsection} % We've got to put something here to fix the indentation!! \noindent \hbox{} \vspace{-5ex} \begin{entry}{% \proto{write}{ obj}{library procedure} \rproto{write}{ obj port}{library procedure}} Writes a written representation of \var{obj} to the given \var{port}. Strings that appear in the written representation are enclosed in doublequotes, and within those strings backslash and doublequote characters are escaped by backslashes. Character objects are written using the {\cf \#\backwhack} notation. {\cf Write} returns an unspecified value. The \var{port} argument may be omitted, in which case it defaults to the value returned by {\cf current-output-port}. \end{entry} \begin{entry}{% \proto{display}{ obj}{library procedure} \rproto{display}{ obj port}{library procedure}} Writes a representation of \var{obj} to the given \var{port}. Strings that appear in the written representation are not enclosed in doublequotes, and no characters are escaped within those strings. Character objects appear in the representation as if written by {\cf write-char} instead of by {\cf write}. {\cf Display} returns an unspecified value. The \var{port} argument may be omitted, in which case it defaults to the value returned by {\cf current-output-port}. \begin{rationale} {\cf Write} is intended for producing mach\-ine-readable output and {\cf display} is for producing human-readable output. Implementations that allow ``slashification'' within symbols will probably want {\cf write} but not {\cf display} to slashify funny characters in symbols. \end{rationale} \end{entry} \begin{entry}{% \proto{newline}{}{library procedure} \rproto{newline}{ port}{library procedure}} Writes an end of line to \var{port}. Exactly how this is done differs from one operating system to another. Returns an unspecified value. The \var{port} argument may be omitted, in which case it defaults to the value returned by {\cf current-output-port}. \end{entry} \begin{entry}{% \proto{write-char}{ char}{procedure} \rproto{write-char}{ char port}{procedure}} Writes the character \var{char} (not an external representation of the character) to the given \var{port} and returns an unspecified value. The \var{port} argument may be omitted, in which case it defaults to the value returned by {\cf current-output-port}. \end{entry} \subsection{System interface} Questions of system interface generally fall outside of the domain of this report. However, the following operations are important enough to deserve description here. \begin{entry}{% \proto{load}{ filename}{optional procedure}} \todo{Fix} %\domain{\var{Filename} should be a string naming an existing file %containing Scheme source code.} The {\cf load} procedure reads \var{Filename} should be a string naming an existing file containing Scheme source code. The {\cf load} procedure reads expressions and definitions from the file and evaluates them sequentially. It is unspecified whether the results of the expressions are printed. The {\cf load} procedure does not affect the values returned by {\cf current-input-port} and {\cf current-output-port}. {\cf Load} returns an unspecified value. \begin{rationale} For portability, {\cf load} must operate on source files. Its operation on other kinds of files necessarily varies among implementations. \end{rationale} \end{entry} \begin{entry}{% \proto{transcript-on}{ filename}{optional procedure}\nopagebreak{} \proto{transcript-off}{}{optional procedure}} \domain{\var{Filename} must be a string naming an output file to be created.} The effect of {\cf transcript-on} is to open the named file for output, and to cause a transcript of subsequent interaction between the user and the Scheme system to be written to the file. The transcript is ended by a call to {\cf transcript-off}, which closes the transcript file. Only one transcript may be in progress at any time, though some implementations may relax this restriction. The values returned by these procedures are unspecified. %\begin{note} %These procedures are redundant in some systems, but %systems that need them should provide them. %\end{note} \end{entry} r5rs-doc-20010328.orig/notes.tex0100644001167100001440000001166506472645144014744 0ustar cphusers\extrapart{Notes} \todo{Perhaps this section should be made to disappear. Can these remarks be moved somewhere else?} \subsection*{Language changes} \label{differences} This section enumerates the changes that have been made to Scheme since the ``Revised$^4$ report''~\cite{R4RS} was published. \begin{itemize} \item The report is now a superset of the IEEE standard for Scheme \cite{IEEEScheme}: implementations that conform to the report will also conform to the standard. This required the following changes: \begin{itemize} \item The empty list is now required to count as true. \item The classification of features as essential or inessential has been removed. There are now three classes of built-in procedures: primitive, library, and optional. The optional procedures are {\cf load}, {\cf with-input-from-file}, {\cf with-output-\linebreak[0]to-file}, {\cf transcript-\linebreak[0]on}, {\cf transcript-\linebreak[0]off}, and {\cf interaction-\linebreak[0]environment}, and {\cf -} and {\cf /} with more than two arguments. None of these are in the IEEE standard. \item Programs are allowed to redefine built-in procedures. Doing so will not change the behavior of other built-in procedures. \end{itemize} \item {\em Port} has been added to the list of disjoint types. \item The macro appendix has been removed. High-level macros are now part of the main body of the report. The rewrite rules for derived expressions have been replaced with macro definitions. There are no reserved identifiers. \item {\cf Syntax-rules} now allows vector patterns. \item Multiple-value returns, {\cf eval}, and {\cf dynamic-wind} have been added. \item The calls that are required to be implemented in a properly tail-recursive fashion are defined explicitly. \item `{\cf @}' can be used within identifiers. `{\cf \verb"|"}' is reserved for possible future extensions. \end{itemize} %%R4%% %\subsection*{Keywords as variable names} % %Some implementations allow arbitrary syntactic %keywords \index{keyword}\index{syntactic keyword}to be used as variable %names, instead of reserving them, as this report would have %it.\index{variable} But this creates ambiguities in the interpretation %of expressions: for example, in the following, it's not clear whether %the expression {\tt (if 1 2 3)} should be treated as a procedure call or %as a conditional. % %\begin{scheme} %(define if list) %(if 1 2 3) \ev 2 {\em{}or} (1 2 3)% %\end{scheme} % %These ambiguities are usually resolved in some consistent way within any %given implementation, but no particular treatment stands out as being %clearly superior to any other, so these situations were excluded for the %purposes of this report. %%R4%% %\subsection*{Macros} % %Scheme does not have any standard facility for defining new kinds of %expressions.\index{macros} % %\vest The ability to alter the syntax of the language creates %numerous problems. All current implementations of Scheme have macro %facilities that solve those problems to one degree or another, but the %solutions are quite different and it isn't clear at this time which %solution is best, or indeed whether any of the solutions are truly %adequate. Rather than standardize, we are encouraging implementations %to continue to experiment with different solutions. % %\vest The main problems with traditional macros are: They must be %defined to the system before any code using them is loaded; this is a %common source of obscure bugs. They are usually global; macros can be %made to follow lexical scope rules \todo{flushed: ``as in Common %Lisp's {\tt macrolet}''; OK?}, but many people find the resulting scope rules %confusing. Unless they are written very carefully, macros are %vulnerable to inadvertent capture of free variables; to get around this, %for example, macros may have to generate code in which procedure values %appear as quoted constants. There is a similar problem with syntactic %keywords if the keywords of special forms are not reserved. If keywords %are reserved, then either macros introduce new reserved words, %invalidating old code, or else special forms defined by the programmer %do not have the same status as special forms defined by the system. % %\todo{Refer to Pitman's special forms paper.} %\todo{Pitman sez: Discuss importance of having a small number of special forms %so that programs can inspect each other.} \todo{Move cwcc history back here? --- Andy Cromarty is concerned about confusion over who the audience is.} \todo{Cromarty: 23. NOTES, p.35ff.: This material should stay somehow. We need to make it clear that R$^3$ Scheme is not being touted as Yet Another Ultimate Solution To The Programming Language Problem, but rather as a snapshot of a *process* of good design, for which not all answers have yet been found. We also ought to use the opportunity for publicity afforded us by SIGPLAN to advertise some of the thorny unsolved problems that need further research, and encourage language designers to work on them.} r5rs-doc-20010328.orig/r5rs.tex0100644001167100001440000000441006473332742014473 0ustar cphusers\documentclass[twoside,twocolumn]{algol60} %\documentclass[twoside]{algol60} \pagestyle{headings} \showboxdepth=0 \makeindex \input{commands} \def\headertitle{Revised$^{5}$ Scheme} \def\integerversion{5} % Sizes and dimensions \topmargin -.375in % Nominal distance from top of page to top of % box containing running head. \headsep 15pt % Space between running head and text. \textheight 663pt % Height of text (including footnotes and figures, % excluding running head and foot). \textwidth 523pt % Width of text line. \columnsep 15pt % Space between columns \columnseprule 0pt % Width of rule between columns. \parskip 5pt plus 2pt minus 2pt % Extra vertical space between paragraphs. \parindent 0pt % Width of paragraph indentation. \topsep 0pt plus 2pt % Extra vertical space, in addition to % \parskip, added above and below list and % paragraphing environments. \oddsidemargin -.5in % Left margin on odd-numbered pages. \evensidemargin -.5in % Left margin on even-numbered pages. %% End of sizes and dimensions \begin{document} \parindent 0pt %!! 15pt % Width of paragraph indentation. \hfil {\bf 20 February 1998} %\hfil \today{} \input{first} \par \input{intro} \par \vskip 2ex \clearchapterstar{Description of the language} %\unskip\vskip -2ex \input{struct} \par \input{lex} \par \input{basic} \par \input{expr} \par \vfill\eject \input{prog} \par \input{procs} \par \vfill\eject \input{syn} \par \input{sem} \par \input{derive} \par \vfill\eject \input{notes} \par \input{repository} \par \vfill\eject \input{example} \par \vfill\eject %\newpage % Put bib on it's own page (it's just one) %\twocolumn[\vspace{-.18in}]% Last bib item was on a page by itself. \renewcommand{\bibname}{References} \input{bib} \par \vfill\eject % Adjustment to avoid having the last index entry on a page by itself. %\addtolength{\baselineskip}{-0.1pt} \begin{theindex} The principal entry for each term, procedure, or keyword is listed first, separated from the other entries by a semicolon. \bigskip \input{index} \end{theindex} \end{document} r5rs-doc-20010328.orig/sem.tex0100644001167100001440000006032706470371154014372 0ustar cphusers%\vfill\eject \section{Formal semantics} \label{formalsemanticssection} \bgroup \newcommand{\sembrack}[1]{[\![#1]\!]} \newcommand{\fun}[1]{\hbox{\it #1}} \newenvironment{semfun}{\begin{tabbing}$}{$\end{tabbing}} \newcommand\LOC{{\tt{}L}} \newcommand\NAT{{\tt{}N}} \newcommand\TRU{{\tt{}T}} \newcommand\SYM{{\tt{}Q}} \newcommand\CHR{{\tt{}H}} \newcommand\NUM{{\tt{}R}} \newcommand\FUN{{\tt{}F}} \newcommand\EXP{{\tt{}E}} \newcommand\STV{{\tt{}E}} \newcommand\STO{{\tt{}S}} \newcommand\ENV{{\tt{}U}} \newcommand\ANS{{\tt{}A}} \newcommand\ERR{{\tt{}X}} \newcommand\EC{{\tt{}K}} \newcommand\CC{{\tt{}C}} \newcommand\MSC{{\tt{}M}} \newcommand\PAI{\hbox{\EXP$_{\rm p}$}} \newcommand\VEC{\hbox{\EXP$_{\rm v}$}} \newcommand\STR{\hbox{\EXP$_{\rm s}$}} \newcommand\elt{\downarrow} \newcommand\drop{\dagger} %\newcommand\injekt{\hbox{ \rm in }} %\newcommand\projekt{\,\vert\,} This section provides a formal denotational semantics for the primitive expressions of Scheme and selected built-in procedures. The concepts and notation used here are described in~\cite{Stoy77}; the notation is summarized below: \begin{tabular}{ll} $\langle\,\ldots\,\rangle$ & sequence formation \\ $s \elt k$ & $k$th member of the sequence $s$ (1-based) \\ $\#s$ & length of sequence $s$ \\ $s \:\S\: t$ & concatenation of sequences $s$ and $t$ \\ $s \drop k$ & drop the first $k$ members of sequence $s$ \\ $t \rightarrow a, b$ & McCarthy conditional ``if $t$ then $a$ else $b$'' \\ $\rho[x/i]$ & substitution ``$\rho$ with $x$ for $i$'' \\ $x\hbox{ \rm in }{\tt{}D}$ & injection of $x$ into domain ${\tt{}D}$ \\ $x\,\vert\,{\tt{}D}$ & projection of $x$ to domain ${\tt{}D}$ \end{tabular} The reason that expression continuations take sequences of values instead of single values is to simplify the formal treatment of procedure calls and multiple return values. The boolean flag associated with pairs, vectors, and strings will be true for mutable objects and false for immutable objects. The order of evaluation within a call is unspecified. We mimic that here by applying arbitrary permutations {\it permute} and {\it unpermute}, which must be inverses, to the arguments in a call before and after they are evaluated. This is not quite right since it suggests, incorrectly, that the order of evaluation is constant throughout a program (for any given number of arguments), but it is a closer approximation to the intended semantics than a left-to-right evaluation would be. The storage allocator {\it new} is implementation-dependent, but it must obey the following axiom: if \hbox{$\fun{new}\:\sigma\:\elem\:\LOC$}, then $\sigma\:(\fun{new}\:\sigma\:\vert\:\LOC)\elt 2 = {\it false}$. \def\P{\hbox{\rm P}} \def\I{\hbox{\rm I}} \def\Ksem{\hbox{$\cal K$}} \def\Esem{\hbox{$\cal E$}} The definition of $\Ksem$ is omitted because an accurate definition of $\Ksem$ would complicate the semantics without being very interesting. If \P{} is a program in which all variables are defined before being referenced or assigned, then the meaning of \P{} is $$\Esem\sembrack{\hbox{\tt((lambda (\arbno{\I}) \P') \hyper{undefined} \dotsfoo)}}$$ where \arbno{\I} is the sequence of variables defined in \P, $\P'$ is the sequence of expressions obtained by replacing every definition in \P{} by an assignment, \hyper{undefined} is an expression that evaluates to \fun{undefined}, and $\Esem$ is the semantic function that assigns meaning to expressions. %The semantics in this section was translated by machine from an %executable version of the semantics written in Scheme itself. %[This was once true, but then I modified the semantics without %going back to the executable version. -- Will] \subsection{Abstract syntax} \def\K{\hbox{\rm K}} \def\I{\hbox{\rm I}} \def\E{\hbox{\rm E}} \def\C{\hbox{$\Gamma$}} \def\Con{\hbox{\rm Con}} \def\Ide{\hbox{\rm Ide}} \def\Exp{\hbox{\rm Exp}} \def\Com{\hbox{\rm Com}} \def\|{$\vert$} \begin{tabular}{r@{ }c@{ }l@{\qquad}l} \K & \elem & \Con & constants, including quotations \\ \I & \elem & \Ide & identifiers (variables) \\ \E & \elem & \Exp & expressions\\ \C & \elem & \Com{} $=$ \Exp & commands \end{tabular} \setbox0=\hbox{\tt\Exp{} \goesto{}} %\tt for spacing \setbox1=\hbox to 1\wd0{\hfil \|} \begin{grammar} \Exp{} \goesto{} \K{} \| \I{} \| (\E$_0$ \arbno{\E}) \copy1{} (lambda (\arbno{\I}) \arbno{\C} \E$_0$) \copy1{} (lambda (\arbno{\I} {\bf.}\ \I) \arbno{\C} \E$_0$) \copy1{} (lambda \I{} \arbno{\C} \E$_0$) \copy1{} (if \E$_0$ \E$_1$ \E$_2$) \| (if \E$_0$ \E$_1$) \copy1{} (set! \I{} \E) \end{grammar} \subsection{Domain equations} \begin{tabular}{@{}r@{ }c@{ }l@{ }l@{ }ll} $\alpha$ & \elem & \LOC & & & locations \\ $\nu$ & \elem & \NAT & & & natural numbers \\ & & \TRU &=& $\{$\it false, true$\}$ & booleans \\ & & \SYM & & & symbols \\ & & \CHR & & & characters \\ & & \NUM & & & numbers \\ & & \PAI &=& $\LOC \times \LOC \times \TRU$ & pairs \\ & & \VEC &=& $\arbno{\LOC} \times \TRU$ & vectors \\ & & \STR &=& $\arbno{\LOC} \times \TRU$ & strings \\ & & \MSC &=& \makebox[0pt][l]{$\{$\it false, true, null, undefined, unspecified$\}$} \\ & & & & & miscellaneous \\ $\phi$ & \elem & \FUN &=& $\LOC\times(\arbno{\EXP} \to \EC \to \CC)$ & procedure values \\ $\epsilon$ & \elem & \EXP &=& \makebox[0pt][l]{$\SYM+\CHR+\NUM+\PAI+\VEC+\STR+\MSC+\FUN$}\\ & & & & & expressed values \\ % & & \STV &=& \EXP & stored values \\ $\sigma$ & \elem & \STO &=& $\LOC\to(\STV\times\TRU)$ & stores \\ $\rho$ & \elem & \ENV &=& $\Ide\to\LOC$ & environments \\ $\theta$ & \elem & \CC &=& $\STO\to\ANS$ & command continuations \\ $\kappa$ & \elem & \EC &=& $\arbno{\EXP}\to\CC$ & expression continuations \\ & & \ANS & & & answers \\ & & \ERR & & & errors \end{tabular} \subsection{Semantic functions} \def\Ksem{\hbox{$\cal K$}} \def\Esem{\hbox{$\cal E$}} \def\Csem{\hbox{$\cal C$}} \begin{tabular}{@{}r@{ }l} $\Ksem:$ & $\Con\to\EXP$ \\ $\Esem:$ & $\Exp\to\ENV\to\EC\to\CC$ \\ $\arbno{\Esem}:$ & $\arbno{\Exp}\to\ENV\to\EC\to\CC$ \\ $\Csem:$ & $\arbno{\Com}\to\ENV\to\CC\to\CC$ \end{tabular} % thin \, medium \> [or \:] thick \; \renewcommand{\:}{\mskip\medmuskip} \newcommand{\wrong}[1]{\fun{wrong }\hbox{\rm``#1''}} \newcommand{\go}[1]{\hbox{\hspace*{#1em}}} \bgroup\small \vspace{1ex} Definition of \Ksem{} deliberately omitted. \begin{semfun} \Esem\sembrack{\K} = \lambda\rho\kappa\:.\:\fun{send}\,(\Ksem\sembrack{\K})\,\kappa \end{semfun} \begin{semfun} \Esem\sembrack{\I} = \lambda\rho\kappa\:.\:\fun{hold}\: $\=$(\fun{lookup}\:\rho\:\I)$\\ \>$(\fun{single}(\lambda\epsilon\:.\: $\=$\epsilon = \fun{undefined}\rightarrow$\\ \> \> \go{2}$\wrong{undefined variable},$\\ \> \>\go{1}$\fun{send}\:\epsilon\:\kappa)) \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt($\E_0$ \arbno{\E})}} =$\\ \go{1}$\lambda\rho\kappa\:.\:\arbno{\Esem} $\=$(\fun{permute}(\langle\E_0\rangle\:\S\:\arbno{\E}))$\\ \>$\rho\:$\\ \>$(\lambda\arbno{\epsilon}\:.\: ($\=$(\lambda\arbno{\epsilon}\:.\: \fun{applicate}\:(\arbno{\epsilon}\elt 1) \:(\arbno{\epsilon}\drop 1) \:\kappa)$\\ \> \>$(\fun{unpermute}\:\arbno{\epsilon}))) \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt(\ide{lambda} (\arbno{\I}) \arbno{\C} $\E_0$)}} =$\\ \go{1}$\lambda\rho\kappa\:.\:\lambda\sigma\:.\:$\\ \go{2}$\fun{new}\:\sigma\:\elem\:\LOC\rightarrow$\\ \go{3}$\fun{send}\: $\=$(\langle $\=$\fun{new}\:\sigma\,\vert\,\LOC,$\\ \> \>$\lambda\arbno{\epsilon}\kappa^\prime\:.\: $\=$\#\arbno{\epsilon} = \#{\arbno{\I}}\rightarrow$\\ \> \> \>$\go{1}\fun{tievals} $\=$(\lambda\arbno{\alpha}\:.\: $\=$(\lambda\rho^\prime\:.\:\Csem\sembrack{\arbno{\C}}\rho^\prime (\Esem\sembrack{\E_0}\rho^\prime\kappa^\prime))$\\ \> \> \> \> \>$(\fun{extends}\:\rho\:{\arbno{\I}}\:\arbno{\alpha}))$\\ \> \> \> \>$\arbno{\epsilon},$\\ \> \> \>\go{1}$\wrong{wrong number of arguments}\rangle$\\ \> \>$\hbox{ \rm in }\EXP)$\\ \>$\kappa$\\ \>$(\fun{update}\:(\fun{new}\:\sigma\,\vert\,\LOC) \:\fun{unspecified} \:\sigma),$\\ \go{3}$\wrong{out of memory}\:\sigma \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt(lambda (\arbno{\I} {\bf.}\ \I) \arbno{\C} $\E_0$)}} =$\\ \go{1}$\lambda\rho\kappa\:.\:\lambda\sigma\:.\:$\\ \go{2}$\fun{new}\:\sigma\:\elem\:\LOC\rightarrow$\\ \go{3}$\fun{send}\: $\=$(\langle $\=$\fun{new}\:\sigma\,\vert\,\LOC,$\\ \> \>$\lambda\arbno{\epsilon}\kappa^\prime\:.\: $\=$\#\arbno{\epsilon} \geq \#\arbno{\I}\rightarrow$\\ \> \> \>\go{1}$\fun{tievalsrest}$\\ \> \> \>\go{2}\=$(\lambda\arbno{\alpha}\:.\: $\=$(\lambda\rho^\prime\:.\:\Csem\sembrack{\arbno{\C}}\rho^\prime (\Esem\sembrack{\E_0}\rho^\prime\kappa^\prime))$\\ \> \> \> \> \>$(\fun{extends}\:\rho \:(\arbno{\I}\:\S\:\langle\I\rangle) \:\arbno{\alpha}))$\\ \> \> \> \>$\arbno{\epsilon}$\\ \> \> \> \>$(\#\arbno{\I}),$\\ \> \> \>\go{1}$\wrong{too few arguments}\rangle\hbox{ \rm in }\EXP)$\\ \>$\kappa$\\ \>$(\fun{update}\:(\fun{new}\:\sigma\,\vert\,\LOC) \:\fun{unspecified} \:\sigma),$\\ \go{3}$\wrong{out of memory}\:\sigma \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt(lambda \I{} \arbno{\C} $\E_0$)}} = \Esem\sembrack{\hbox{\tt(lambda ({\bf.}\ \I) \arbno{\C} $\E_0$)}} \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt(\ide{if} $\E_0$ $\E_1$ $\E_2$)}} =$\\ \go{1}$\lambda\rho\kappa\:.\: \Esem\sembrack{\E_0}\:\rho\:(\fun{single}\:(\lambda\epsilon\:.\: $\=$\fun{truish}\:\epsilon\rightarrow\Esem\sembrack{\E_1}\rho\kappa,$\\ \>\go{1}$\Esem\sembrack{\E_2}\rho\kappa)) \end{semfun} \begin{semfun} \Esem\sembrack{\hbox{\tt(if $\E_0$ $\E_1$)}} =$\\ \go{1}$\lambda\rho\kappa\:.\: \Esem\sembrack{\E_0}\:\rho\:(\fun{single}\:(\lambda\epsilon\:.\: $\=$\fun{truish}\:\epsilon\rightarrow\Esem\sembrack{\E_1}\rho\kappa,$\\ \>\go{1}$\fun{send}\:\fun{unspecified}\:\kappa)) \end{semfun} Here and elsewhere, any expressed value other than {\it undefined} may be used in place of {\it unspecified}. \begin{semfun} \Esem\sembrack{\hbox{\tt(\ide{set!} \I{} \E)}} =$\\ \go{1}$\lambda\rho\kappa\:.\:\Esem\sembrack{\E}\:\rho\: (\fun{single}(\lambda\epsilon\:.\:\fun{assign}\: $\=$(\fun{lookup}\:\rho\:\I)$\\ \>$\epsilon$\\ \>$(\fun{send}\:\fun{unspecified}\:\kappa))) \end{semfun} \begin{semfun} \arbno{\Esem}\sembrack{\:} = \lambda\rho\kappa\:.\:\kappa\langle\:\rangle \end{semfun} \begin{semfun} \arbno{\Esem}\sembrack{\E_0\:\arbno{\E}} =$\\ \go{1}$\lambda\rho\kappa\:.\: \Esem\sembrack{\E_0}\:\rho\: (\fun{single} (\lambda\epsilon_0\:.\:\arbno{\Esem}\sembrack{\arbno{\E}} \:\rho\:(\lambda\arbno{\epsilon}\:.\: \kappa\:(\langle\epsilon_0\rangle\:\S\:\arbno{\epsilon})))) \end{semfun} \begin{semfun} \Csem\sembrack{\:} = \lambda\rho\theta\,.\:\theta \end{semfun} \begin{semfun} \Csem\sembrack{\C_0\:\arbno{\C}} = \lambda\rho\theta\:.\:\Esem\sembrack{\C_0}\:\rho\:(\lambda\arbno{\epsilon}\:.\: \Csem\sembrack{\arbno{\C}}\rho\theta) \end{semfun} \egroup % end smallish \subsection{Auxiliary functions} \bgroup\small \begin{semfun} \fun{lookup} : \ENV \to \Ide \to \LOC$\\$ \fun{lookup} = \lambda\rho\I\:.\:\rho\I \end{semfun} \begin{semfun} \fun{extends} : \ENV \to \arbno{\Ide} \to \arbno{\LOC} \to \ENV$\\$ \fun{extends} =$\\ \go{1}$\lambda\rho\arbno{\I}\arbno{\alpha}\:.\: $\=$\#\arbno{\I}=0\rightarrow\rho,$\\ \>$\go{1}\fun{extends}\:(\rho[(\arbno{\alpha}\elt 1)/(\arbno{\I}\elt 1)]) \:(\arbno{\I}\drop 1) \:(\arbno{\alpha}\drop 1) \end{semfun} \begin{semfun} \fun{wrong} : \ERR \to \CC \hbox{\qquad [implementation-dependent]} \end{semfun} \begin{semfun} \fun{send} : \EXP \to \EC \to \CC$\\$ \fun{send} = \lambda\epsilon\kappa\:.\:\kappa\langle\epsilon\rangle \end{semfun} \begin{semfun} \fun{single} : (\EXP \to \CC) \to \EC$\\$ \fun{single} =$\\ \go{1}$\lambda\psi\arbno{\epsilon}\:.\: $\=$\#\arbno{\epsilon}=1\rightarrow\psi(\arbno{\epsilon}\elt 1),$\\ \>$\go{1}\wrong{wrong number of return values} \end{semfun} \begin{semfun} \fun{new} : \STO \to (\LOC + \{ \fun{error} \}) \hbox{\qquad [implementation-dependent]} \end{semfun} \begin{semfun} \fun{hold} : \LOC \to \EC \to \CC$\\$ \fun{hold} = \lambda\alpha\kappa\sigma\:.\:\fun{send}\,(\sigma\alpha\elt 1)\kappa\sigma \end{semfun} \begin{semfun} \fun{assign} : \LOC \to \EXP \to \CC \to \CC$\\$ \fun{assign} = \lambda\alpha\epsilon\theta\sigma\:.\:\theta(\fun{update}\:\alpha\epsilon\sigma) \end{semfun} \begin{semfun} \fun{update} : \LOC \to \EXP \to \STO \to \STO$\\$ \fun{update} = \lambda\alpha\epsilon\sigma\:.\:\sigma[\langle\epsilon,\fun{true}\rangle/\alpha] \end{semfun} \begin{semfun} \fun{tievals} : (\arbno{\LOC} \to \CC) \to \arbno{\EXP} \to \CC$\\$ \fun{tievals} =$\\ \go{1}$\lambda\psi\arbno{\epsilon}\sigma\:.\: $\=$\#\arbno{\epsilon}=0\rightarrow\psi\langle\:\rangle\sigma,$\\ \>$\fun{new}\:\sigma\:\elem\:\LOC\rightarrow\fun{tievals}\, $\=$(\lambda\arbno{\alpha}\:.\:\psi(\langle\fun{new}\:\sigma\:\vert\:\LOC\rangle \:\S\:\arbno{\alpha}))$\\ \> \>$(\arbno{\epsilon}\drop 1)$\\ \> \>$(\fun{update}(\fun{new}\:\sigma\:\vert\:\LOC) (\arbno{\epsilon}\elt 1) \sigma),$\\ \>$\go{1}\wrong{out of memory}\sigma \end{semfun} \begin{semfun} \fun{tievalsrest} : (\arbno{\LOC} \to \CC) \to \arbno{\EXP} \to \NAT \to \CC$\\$ \fun{tievalsrest} =$\\ \go{1}$\lambda\psi\arbno{\epsilon}\nu\:.\:\fun{list}\: $\=$(\fun{dropfirst}\:\arbno{\epsilon}\nu)$\\ \>$(\fun{single}(\lambda\epsilon\:.\:\fun{tievals}\:\psi\: ((\fun{takefirst}\:\arbno{\epsilon}\nu)\:\S\:\langle\epsilon\rangle))) \end{semfun} \begin{semfun} \fun{dropfirst} = \lambda l n \:.\: n=0 \rightarrow l, \fun{dropfirst}\,(l \drop 1)(n - 1) \end{semfun} \begin{semfun} \fun{takefirst} = \lambda l n \:.\: n=0 \rightarrow \langle\:\rangle, \langle l \elt 1\rangle\:\S\:(\fun{takefirst}\,(l \drop 1)(n - 1)) \end{semfun} \begin{semfun} \fun{truish} : \EXP \to \TRU$\\$ \fun{truish} = \lambda\epsilon\:.\: % (\epsilon = \fun{false}\vee\epsilon = \fun{null})\rightarrow \epsilon = \fun{false}\rightarrow \fun{false}, \fun{true} \end{semfun} \begin{semfun} \fun{permute} : \arbno{\Exp} \to \arbno{\Exp} \hbox{\qquad [implementation-dependent]} \end{semfun} \begin{semfun} \fun{unpermute} : \arbno{\EXP} \to \arbno{\EXP} \hbox{\qquad [inverse of \fun{permute}]} \end{semfun} \begin{semfun} \fun{applicate} : \EXP \to \arbno{\EXP} \to \EC \to \CC$\\$ \fun{applicate} =$\\ \go{1}$\lambda\epsilon\arbno{\epsilon}\kappa\:.\: $\=$\epsilon\:\elem\:\FUN\rightarrow(\epsilon\:\vert\:\FUN\elt 2)\arbno{\epsilon}\kappa, \wrong{bad procedure} \end{semfun} \begin{semfun} \fun{onearg} : (\EXP \to \EC \to \CC) \to (\arbno{\EXP} \to \EC \to \CC)$\\$ \fun{onearg} =$\\ \go{1}$\lambda\zeta\arbno{\epsilon}\kappa\:.\: $\=$\#\arbno{\epsilon}=1\rightarrow\zeta(\arbno{\epsilon}\elt 1)\kappa,$\\ \>$\go{1}\wrong{wrong number of arguments} \end{semfun} \begin{semfun} \fun{twoarg} : (\EXP \to \EXP \to \EC \to \CC) \to (\arbno{\EXP} \to \EC \to \CC)$\\$ \fun{twoarg} =$\\ \go{1}$\lambda\zeta\arbno{\epsilon}\kappa\:.\: $\=$\#\arbno{\epsilon}=2\rightarrow\zeta(\arbno{\epsilon}\elt 1)(\arbno{\epsilon}\elt 2)\kappa,$\\ \>$\go{1}\wrong{wrong number of arguments} \end{semfun} \begin{semfun} \fun{list} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{list} =$\\ \go{1}$\lambda\arbno{\epsilon}\kappa\:.\: $\=$\#\arbno{\epsilon}=0\rightarrow\fun{send}\:\fun{null}\:\kappa,$\\ \>$\go{1}\fun{list}\,(\arbno{\epsilon}\drop 1) (\fun{single}(\lambda\epsilon\:.\: \fun{cons}\langle\arbno{\epsilon}\elt 1,\epsilon\rangle\kappa)) \end{semfun} \begin{semfun} \fun{cons} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{cons} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\sigma\:.\: $\=$\fun{new}\:\sigma\:\elem\:\LOC\rightarrow$\\ \> \go{1} \=$(\lambda\sigma^\prime\:.\: $\=$\fun{new}\:\sigma^\prime\:\elem\:\LOC\rightarrow$\\ \> \> \>$\go{1}\fun{send}\, $\=$($\=$\langle\fun{new}\:\sigma\:\vert\:\LOC, \fun{new}\:\sigma^\prime\:\vert\:\LOC, \fun{true}\rangle$\\ \> \> \> \> \>$\hbox{ \rm in }\EXP)$\\ \> \> \> \>$\kappa$\\ \> \> \> \>$(\fun{update}(\fun{new}\:\sigma^\prime\:\vert\:\LOC) \epsilon_2 \sigma^\prime),$\\ \> \> \>$\go{1}\wrong{out of memory}\sigma^\prime)$\\ \> \>$(\fun{update}(\fun{new}\:\sigma\:\vert\:\LOC)\epsilon_1\sigma),$\\ \>$\go{1}\wrong{out of memory}\sigma) \end{semfun} \schindex{<} \begin{semfun} \fun{less} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{less} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$(\epsilon_1\:\elem\:\NUM\wedge\epsilon_2\:\elem\:\NUM)\rightarrow$\\ \>$\go{1}\fun{send}\, (\epsilon_1\:\vert\:\NUM<\epsilon_2\:\vert\:\NUM\rightarrow \fun{true}, \fun{false}) \kappa,$\\ \>$\go{1}\wrong{non-numeric argument to {\cf <}}) \end{semfun} \schindex{+} \begin{semfun} \fun{add} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{add} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$(\epsilon_1\:\elem\:\NUM\wedge\epsilon_2\:\elem\:\NUM)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$((\epsilon_1\:\vert\:\NUM+\epsilon_2\:\vert\:\NUM)\hbox{ \rm in }\EXP) \kappa,$\\ \>$\go{1}\wrong{non-numeric argument to {\cf +}}) \end{semfun} \schindex{car} \begin{semfun} \fun{car} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{car} =$\\ \go{1}$\fun{onearg}\,(\lambda\epsilon\kappa\:.\: $\=$\epsilon\:\elem\:\PAI\rightarrow \fun{hold}\, (\epsilon\:\vert\:\PAI\elt 1) \kappa,$\\ \>$\go{1}\wrong{non-pair argument to {\cf car}}) \end{semfun} \begin{semfun} \fun{cdr} : \arbno{\EXP} \to \EC \to \CC %$\\$ \hbox{\qquad [similar to \fun{car}]} \end{semfun} \schindex{setcar} \begin{semfun} \fun{setcar} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{setcar} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$\epsilon_1\:\elem\:\PAI\rightarrow$\\ \>$(\epsilon_1\:\vert\:\PAI\elt 3)\rightarrow \fun{assign}\,$\=$(\epsilon_1\:\vert\:\PAI\elt 1)$\\ \> \>$\epsilon_2$\\ \> \>$(\fun{send}\:\fun{unspecified}\:\kappa),$\\ \>$\wrong{immutable argument to {\cf set-car!}},$\\ \>$\wrong{non-pair argument to {\cf set-car!}}) \end{semfun} \schindex{eqv?} \begin{semfun} \fun{eqv} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{eqv} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$(\epsilon_1\:\elem\:\MSC\wedge\epsilon_2\:\elem\:\MSC)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$(\epsilon_1\:\vert\:\MSC = \epsilon_2\:\vert\:\MSC\rightarrow\fun{true}, \fun{false})\kappa,$\\ \>$(\epsilon_1\:\elem\:\SYM\wedge\epsilon_2\:\elem\:\SYM)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$(\epsilon_1\:\vert\:\SYM = \epsilon_2\:\vert\:\SYM\rightarrow\fun{true}, \fun{false})\kappa,$\\ \>$(\epsilon_1\:\elem\:\CHR\wedge\epsilon_2\:\elem\:\CHR)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$(\epsilon_1\:\vert\:\CHR = \epsilon_2\:\vert\:\CHR \rightarrow\fun{true}, \fun{false})\kappa,$\\ \>$(\epsilon_1\:\elem\:\NUM\wedge\epsilon_2\:\elem\:\NUM)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$(\epsilon_1\:\vert\:\NUM=\epsilon_2\:\vert\:\NUM\rightarrow\fun{true}, \fun{false})\kappa,$\\ \>$(\epsilon_1\:\elem\:\PAI\wedge\epsilon_2\:\elem\:\PAI)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$($\=$(\lambda{p_1}{p_2}\:.\: ($\=$({p_1}\elt 1) = ({p_2}\elt 1)\wedge$\\ \> \> \> \>$({p_1}\elt 2) = ({p_2}\elt 2)) \rightarrow\fun{true},$\\ \> \> \> \>$\go{1}\fun{false})$\\ \> \> \>$(\epsilon_1\:\vert\:\PAI)$\\ \> \> \>$(\epsilon_2\:\vert\:\PAI))$\\ \> \>$\kappa,$\\ \>$(\epsilon_1\:\elem\:\VEC\wedge\epsilon_2\:\elem\:\VEC)\rightarrow %\fun{send}\, % $\=$((\#(\epsilon_1\:\vert\:\VEC)=\#(\epsilon_2\:\vert\:\VEC) % \wedge\hbox{\rm Y}(\lambda\fun{loop}\:.\:\lambda\fun{v1}\fun{v2}\:.\: % $\=$\#\fun{v1}=0\rightarrow\fun{true},$\\ % \> \> \>$(\fun{v1}\elt 1) = (\fun{v2}\elt 1)\rightarrow % \fun{loop}(\fun{v1}\drop 1)(\fun{v2}\drop 1),$\\ % \> \> \>$\go{1}\fun{false})(\epsilon_1\:\vert\:\VEC)(\epsilon_2\:\vert\:\VEC)) % \rightarrow\fun{true},$\\ % \> \>$\go{1}\fun{false})\kappa \ldots,$\\ \>$(\epsilon_1\:\elem\:\STR\wedge\epsilon_2\:\elem\:\STR)\rightarrow %\fun{send}\, % $\=$((\#(\epsilon_1\:\vert\:\STR)=\#(\epsilon_2\:\vert\:\STR)\wedge % \hbox{\rm Y}(\lambda\fun{loop}\:.\:\lambda\fun{v1}\fun{v2}\:.\: % $\=$\#\fun{v1}=0\rightarrow\fun{true},$\\ % \> \> \>$(\fun{v1}\elt 1) = (\fun{v2}\elt 1)\rightarrow % \fun{loop}(\fun{v1}\drop 1)(\fun{v2}\drop 1),$\\ % \> \> \>$\go{1}\fun{false})(\epsilon_1\:\vert\:\STR)(\epsilon_2\:\vert\:\STR)) % \rightarrow\fun{true},$\\ % \> \>$\go{1}\fun{false})\kappa \ldots,$\\ \>$(\epsilon_1\:\elem\:\FUN\wedge\epsilon_2\:\elem\:\FUN)\rightarrow$\\ \>$\go{1}\fun{send}\, $\=$((\epsilon_1\:\vert\:\FUN\elt 1) = (\epsilon_2\:\vert\:\FUN\elt 1) \rightarrow\fun{true}, \fun{false})$\\ \> \>$\kappa,$\\ \>$\go{1}\fun{send}\,\:\fun{false}\:\kappa) \end{semfun} \schindex{apply} \begin{semfun} \fun{apply} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{apply} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$\epsilon_1\:\elem\:\FUN\rightarrow \fun{valueslist}\,\langle\epsilon_2\rangle (\lambda\arbno{\epsilon}\:.\:\fun{applicate}\:\epsilon_1\arbno{\epsilon}\kappa),$\\ \>$\go{1}\wrong{bad procedure argument to {\cf apply}}) \end{semfun} \begin{semfun} \fun{valueslist} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{valueslist} =$\\ \go{1}$\fun{onearg}\,(\lambda\epsilon\kappa\:.\: $\=$\epsilon\:\elem\:\PAI\rightarrow$\\ \>$\go{1}\fun{cdr} $\=$\langle\epsilon\rangle$\\ \> \>$(\lambda\arbno{\epsilon}\:.\: $\=$\fun{valueslist}\:$\\ \> \> \>$\arbno{\epsilon}$\\ \> \> \>$(\lambda\arbno{\epsilon}\:.\:\fun{car}\langle\epsilon\rangle (\fun{single}(\lambda\epsilon\:.\: \kappa(\langle\epsilon\rangle\:\S\:\arbno{\epsilon}))))),$\\ \>$\epsilon = \fun{null}\rightarrow\kappa\langle\:\rangle,$\\ \>$\go{1}\wrong{non-list argument to {\cf values-list}}) \end{semfun} \begin{semfun} \fun{cwcc} : \arbno{\EXP} \to \EC \to \CC \hbox{\qquad [\ide{call-with-current-continuation}]}$\\$ \fun{cwcc} =$\\ \go{1}$\fun{onearg}\,(\lambda\epsilon\kappa\:.\: $\=$\epsilon\:\elem\:\FUN\rightarrow$\\ \>$\go{1}(\lambda\sigma\:.\: $\=$\fun{new}\:\sigma\:\elem\:\LOC\rightarrow$\\ \> \>$\go{1}\fun{applicate}\: $\=$\epsilon$\\ \> \> \>$\langle\langle\fun{new}\:\sigma\:\vert\:\LOC, \lambda\arbno{\epsilon}\kappa^\prime\:.\: \kappa\arbno{\epsilon}\rangle \hbox{ \rm in }\EXP\rangle$\\ \> \> \>$\kappa$\\ \> \> \>$(\fun{update}\, $\=$(\fun{new}\:\sigma\:\vert\:\LOC)$\\ \> \> \> \>$\fun{unspecified}$\\ \> \> \> \>$\sigma),$\\ \> \>$\go{1}\wrong{out of memory}\,\sigma),$\\ \>$\go{1}\wrong{bad procedure argument}) \end{semfun} \begin{semfun} \fun{values} : \arbno{\EXP} \to \EC \to \CC$\\$ \fun{values} = \lambda\arbno{\epsilon}\kappa\:.\:\kappa\arbno{\epsilon} \end{semfun} \begin{semfun} \fun{cwv} : \arbno{\EXP} \to \EC \to \CC \hbox{\qquad [\ide{call-with-values}]}$\\$ \fun{cwv} =$\\ \go{1}$\fun{twoarg}\,(\lambda\epsilon_1\epsilon_2\kappa\:.\: $\=$\fun{applicate}\:\epsilon_1\langle\:\rangle (\lambda\arbno{\epsilon}\:.\:\fun{applicate}\:\epsilon_2\:\arbno{\epsilon})) \end{semfun} \egroup % end smallish \egroup r5rs-doc-20010328.orig/struct.tex0100644001167100001440000002632306470154624015131 0ustar cphusers% 1. Structure of the language \chapter{Overview of Scheme} \section{Semantics} \label{semanticsection} This section gives an overview of Scheme's semantics. A detailed informal semantics is the subject of chapters~\ref{basicchapter} through~\ref{builtinchapter}. For reference purposes, section~\ref{formalsemanticssection} provides a formal semantics of Scheme. \vest Following Algol, Scheme is a statically scoped programming language. Each use of a variable is associated with a lexically apparent binding of that variable. \vest Scheme has latent as opposed to manifest types. Types are associated with values (also called objects\mainindex{object}) rather than with variables. (Some authors refer to languages with latent types as weakly typed or dynamically typed languages.) Other languages with latent types are APL, Snobol, and other dialects of Lisp. Languages with manifest types (sometimes referred to as strongly typed or statically typed languages) include Algol 60, Pascal, and~C. \vest All objects created in the course of a Scheme computation, including procedures and continuations, have unlimited extent. No Scheme object is ever destroyed. The reason that implementations of Scheme do not (usually!)\ run out of storage is that they are permitted to reclaim the storage occupied by an object if they can prove that the object cannot possibly matter to any future computation. Other languages in which most objects have unlimited extent include APL and other Lisp dialects. \vest Implementations of Scheme are required to be properly tail-recursive. This allows the execution of an iterative computation in constant space, even if the iterative computation is described by a syntactically recursive procedure. Thus with a properly tail-recursive implementation, iteration can be expressed using the ordinary procedure-call mechanics, so that special iteration constructs are useful only as syntactic sugar. See section~\ref{proper tail recursion}. \vest Scheme procedures are objects in their own right. Procedures can be created dynamically, stored in data structures, returned as results of procedures, and so on. Other languages with these properties include Common Lisp and ML. \todo{Rozas: Scheme had them first.} \vest One distinguishing feature of Scheme is that continuations, which in most other languages only operate behind the scenes, also have ``first-class'' status. Continuations are useful for implementing a wide variety of advanced control constructs, including non-local exits, backtracking, and coroutines. See section~\ref{continuations}. \vest Arguments to Scheme procedures are always passed by value, which means that the actual argument expressions are evaluated before the procedure gains control, whether the procedure needs the result of the evaluation or not. ML, C, and APL are three other languages that always pass arguments by value. This is distinct from the lazy-evaluation semantics of Haskell, or the call-by-name semantics of Algol 60, where an argument expression is not evaluated unless its value is needed by the procedure. \todo{Lisp's call by value should be explained more accurately. What's funny is that all values are references.} \vest Scheme's model of arithmetic is designed to remain as independent as possible of the particular ways in which numbers are represented within a computer. In Scheme, every integer is a rational number, every rational is a real, and every real is a complex number. Thus the distinction between integer and real arithmetic, so important to many programming languages, does not appear in Scheme. In its place is a distinction between exact arithmetic, which corresponds to the mathematical ideal, and inexact arithmetic on approximations. As in Common Lisp, exact arithmetic is not limited to integers. \section{Syntax} Scheme, like most dialects of Lisp, employs a fully parenthesized prefix notation for programs and (other) data; the grammar of Scheme generates a sublanguage of the language used for data. An important consequence of this simple, uniform representation is the susceptibility of Scheme programs and data to uniform treatment by other Scheme programs. For example, the {\cf eval} procedure evaluates a Scheme program expressed as data. The {\cf read} procedure performs syntactic as well as lexical decomposition of the data it reads. The {\cf read} procedure parses its input as data (section~\ref{datumsyntax}), not as program. The formal syntax of Scheme is described in section~\ref{BNF}. \section{Notation and terminology} \subsection{Primitive, library, and optional features} \label{qualifiers} It is required that every implementation of Scheme support all features that are not marked as being \defining{optional}. Implementations are free to omit optional features of Scheme or to add extensions, provided the extensions are not in conflict with the language reported here. In particular, implementations must support portable code by providing a syntactic mode that preempts no lexical conventions of this report. To aid in understanding and implementing Scheme, some features are marked as \defining{library}. These can be easily implemented in terms of the other, primitive, features. They are redundant in the strict sense of the word, but they capture common patterns of usage, and are therefore provided as convenient abbreviations. \subsection{Error situations and unspecified behavior} \mainindex{error} When speaking of an error situation, this report uses the phrase ``an error is signalled'' to indicate that implementations must detect and report the error. If such wording does not appear in the discussion of an error, then implementations are not required to detect or report the error, though they are encouraged to do so. An error situation that implementations are not required to detect is usually referred to simply as ``an error.'' \vest For example, it is an error for a procedure to be passed an argument that the procedure is not explicitly specified to handle, even though such domain errors are seldom mentioned in this report. Implementations may extend a procedure's domain of definition to include such arguments. \vest This report uses the phrase ``may report a violation of an implementation restriction'' to indicate circumstances under which an implementation is permitted to report that it is unable to continue execution of a correct program because of some restriction imposed by the implementation. Implementation restrictions are of course discouraged, but implementations are encouraged to report violations of implementation restrictions.\mainindex{implementation restriction} \vest For example, an implementation may report a violation of an implementation restriction if it does not have enough storage to run a program. \vest If the value of an expression is said to be ``unspecified,'' then the expression must evaluate to some object without signalling an error, but the value depends on the implementation; this report explicitly does not say what value should be returned. \mainindex{unspecified} \todo{Talk about unspecified behavior vs. unspecified values.} \todo{Look at KMP's situations paper.} \subsection{Entry format} Chapters~\ref{expressionchapter} and~\ref{builtinchapter} are organized into entries. Each entry describes one language feature or a group of related features, where a feature is either a syntactic construct or a built-in procedure. An entry begins with one or more header lines of the form \noindent\pproto{\var{template}}{\var{category}}\unpenalty for required, primitive features, or \noindent\pproto{\var{template}}{\var{qualifier} \var{category}}\unpenalty where \var{qualifier} is either ``library'' or ``optional'' as defined in section~\ref{qualifiers}. If \var{category} is ``\exprtype'', the entry describes an expression type, and the template gives the syntax of the expression type. Components of expressions are designated by syntactic variables, which are written using angle brackets, for example, \hyper{expression}, \hyper{variable}. Syntactic variables should be understood to denote segments of program text; for example, \hyper{expression} stands for any string of characters which is a syntactically valid expression. The notation \begin{tabbing} \qquad \hyperi{thing} $\ldots$ \end{tabbing} indicates zero or more occurrences of a \hyper{thing}, and \begin{tabbing} \qquad \hyperi{thing} \hyperii{thing} $\ldots$ \end{tabbing} indicates one or more occurrences of a \hyper{thing}. If \var{category} is ``procedure'', then the entry describes a procedure, and the header line gives a template for a call to the procedure. Argument names in the template are \var{italicized}. Thus the header line \noindent\pproto{(vector-ref \var{vector} \var{k})}{procedure}\unpenalty indicates that the built-in procedure {\tt vector-ref} takes two arguments, a vector \var{vector} and an exact non-negative integer \var{k} (see below). The header lines \noindent% \pproto{(make-vector \var{k})}{procedure} \pproto{(make-vector \var{k} \var{fill})}{procedure}\unpenalty indicate that the {\tt make-vector} procedure must be defined to take either one or two arguments. \label{typeconventions} It is an error for an operation to be presented with an argument that it is not specified to handle. For succinctness, we follow the convention that if an argument name is also the name of a type listed in section~\ref{disjointness}, then that argument must be of the named type. For example, the header line for {\tt vector-ref} given above dictates that the first argument to {\tt vector-ref} must be a vector. The following naming conventions also imply type restrictions: \newcommand{\foo}[1]{\vr{#1}, \vri{#1}, $\ldots$ \vrj{#1}, $\ldots$} $$ \begin{tabular}{ll} \var{obj}&any object\\ \foo{list}&list (see section~\ref{listsection})\\ \foo{z}&complex number\\ \foo{x}&real number\\ \foo{y}&real number\\ \foo{q}&rational number\\ \foo{n}&integer\\ \foo{k}&exact non-negative integer\\ \end{tabular} $$ \todo{Provide an example entry??} \subsection{Evaluation examples} The symbol ``\evalsto'' used in program examples should be read ``evaluates to.'' For example, \begin{scheme} (* 5 8) \ev 40% \end{scheme} means that the expression {\tt(* 5 8)} evaluates to the object {\tt 40}. Or, more precisely: the expression given by the sequence of characters ``{\tt(* 5 8)}'' evaluates, in the initial environment, to an object that may be represented externally by the sequence of characters ``{\tt 40}''. See section~\ref{externalreps} for a discussion of external representations of objects. \subsection{Naming conventions} By convention, the names of procedures that always return a boolean value usually end in ``\ide{?}''. Such procedures are called predicates. By convention, the names of procedures that store values into previously allocated locations (see section~\ref{storagemodel}) usually end in ``\ide{!}''. Such procedures are called mutation procedures. By convention, the value returned by a mutation procedure is unspecified. By convention, ``\ide{->}'' appears within the names of procedures that take an object of one type and return an analogous object of another type. For example, {\cf list->vector} takes a list and returns a vector whose elements are the same as those of the list. \todo{Terms that need defining: thunk, command (what else?).} r5rs-doc-20010328.orig/syn.tex0100644001167100001440000003146206471140075014412 0ustar cphusers\chapter{Formal syntax and semantics} \label{formalchapter} This chapter provides formal descriptions of what has already been described informally in previous chapters of this report. \todo{Allow grammar to say that else clause needn't be last?} \section{Formal syntax} \label{BNF} This section provides a formal syntax for Scheme written in an extended BNF. All spaces in the grammar are for legibility. Case is insignificant; for example, {\cf \#x1A} and {\cf \#X1a} are equivalent. \meta{empty} stands for the empty string. The following extensions to BNF are used to make the description more concise: \arbno{\meta{thing}} means zero or more occurrences of \meta{thing}; and \atleastone{\meta{thing}} means at least one \meta{thing}. \subsection{Lexical structure} This section describes how individual tokens\index{token} (identifiers, numbers, etc.) are formed from sequences of characters. The following sections describe how expressions and programs are formed from sequences of tokens. \meta{Intertoken space} may occur on either side of any token, but not within a token. \vest Tokens which require implicit termination (identifiers, numbers, characters, and dot) may be terminated by any \meta{delimiter}, but not necessarily by anything else. The following five characters are reserved for future extensions to the language: {\tt \verb"[" \verb"]" \verb"{" \verb"}" \verb"|"} \begin{grammar}% \meta{token} \: \meta{identifier} \| \meta{boolean} \| \meta{number}\index{identifier} \> \| \meta{character} \| \meta{string} \> \| ( \| ) \| \sharpsign( \| \singlequote{} \| \backquote{} \| , \| ,@ \| {\bf.} \meta{delimiter} \: \meta{whitespace} \| ( \| ) \| " \| ; \meta{whitespace} \: \meta{space or newline} \meta{comment} \: ; \= $\langle$\rm all subsequent characters up to a \>\ \rm line break$\rangle$\index{comment} \meta{atmosphere} \: \meta{whitespace} \| \meta{comment} \meta{intertoken space} \: \arbno{\meta{atmosphere}}% \end{grammar} \label{extendedalphas} \label{identifiersyntax} % This is a kludge, but \multicolumn doesn't work in tabbing environments. \setbox0\hbox{\cf\meta{variable} \goesto{} $\langle$} \begin{grammar}% \meta{identifier} \: \meta{initial} \arbno{\meta{subsequent}} \> \| \meta{peculiar identifier} \meta{initial} \: \meta{letter} \| \meta{special initial} \meta{letter} \: a \| b \| c \| ... \| z \meta{special initial} \: ! \| \$ \| \% \| \verb"&" \| * \| / \| : \| < \| = \> \| > \| ? \| \verb"^" \| \verb"_" \| \verb"~" \meta{subsequent} \: \meta{initial} \| \meta{digit} \> \| \meta{special subsequent} \meta{digit} \: 0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 \| 7 \| 8 \| 9 \meta{special subsequent} \: + \| - \| .\ \| @ \meta{peculiar identifier} \: + \| - \| ... %\| 1+ \| -1+ \meta{syntactic keyword} \: \meta{expression keyword}\index{keyword}\index{syntactic keyword} \> \| else \| => \| define \> \| unquote \| unquote-splicing \meta{expression keyword} \: quote \| lambda \| if \> \| set! \| begin \| cond \| and \| or \| case \> \| let \| let* \| letrec \| do \| delay \> \| quasiquote \copy0\rm any \meta{identifier} that isn't\index{variable} \hbox to 1\wd0{\hfill}\ \rm also a \meta{syntactic keyword}$\rangle$ \meta{boolean} \: \schtrue{} \| \schfalse{} \meta{character} \: \#\backwhack{} \meta{any character} \> \| \#\backwhack{} \meta{character name} \meta{character name} \: space \| newline \todo{Explain what happens in the ambiguous case.} \meta{string} \: " \arbno{\meta{string element}} " \meta{string element} \: \meta{any character other than \doublequote{} or \backwhack} \> \| \backwhack\doublequote{} \| \backwhack\backwhack % \end{grammar} \label{numbersyntax} \begin{grammar}% \meta{number} \: \meta{num $2$}% \| \meta{num $8$} \> \| \meta{num $10$}% \| \meta{num $16$} \end{grammar} The following rules for \meta{num $R$}, \meta{complex $R$}, \meta{real $R$}, \meta{ureal $R$}, \meta{uinteger $R$}, and \meta{prefix $R$} should be replicated for \hbox{$R = 2, 8, 10,$} and $16$. There are no rules for \meta{decimal $2$}, \meta{decimal $8$}, and \meta{decimal $16$}, which means that numbers containing decimal points or exponents must be in decimal radix. \todo{Mark Meyer and David Bartley want to fix this. (What? -- Will)} \begin{grammar}% \meta{num $R$} \: \meta{prefix $R$} \meta{complex $R$} \meta{complex $R$} \: % \meta{real $R$} % \| \meta{real $R$} @ \meta{real $R$} \> \| \meta{real $R$} + \meta{ureal $R$} i % \| \meta{real $R$} - \meta{ureal $R$} i \> \| \meta{real $R$} + i % \| \meta{real $R$} - i \> \| + \meta{ureal $R$} i % \| - \meta{ureal $R$} i % \| + i % \| - i \meta{real $R$} \: \meta{sign} \meta{ureal $R$} \meta{ureal $R$} \: % \meta{uinteger $R$} \> \| \meta{uinteger $R$} / \meta{uinteger $R$} \> \| \meta{decimal $R$} \meta{decimal $10$} \: % \meta{uinteger $10$} \meta{suffix} \> \| . \atleastone{\meta{digit $10$}} \arbno{\#} \meta{suffix} \> \| \atleastone{\meta{digit $10$}} . \arbno{\meta{digit $10$}} \arbno{\#} \meta{suffix} \> \| \atleastone{\meta{digit $10$}} \atleastone{\#} . \arbno{\#} \meta{suffix} \meta{uinteger $R$} \: \atleastone{\meta{digit $R$}} \arbno{\#} \meta{prefix $R$} \: % \meta{radix $R$} \meta{exactness} \> \| \meta{exactness} \meta{radix $R$} \end{grammar} \begin{grammar}% \meta{suffix} \: \meta{empty} \> \| \meta{exponent marker} \meta{sign} \atleastone{\meta{digit $10$}} \meta{exponent marker} \: e \| s \| f \| d \| l \meta{sign} \: \meta{empty} \| + \| - \meta{exactness} \: \meta{empty} \| \#i\sharpindex{i} \| \#e\sharpindex{e} \meta{radix 2} \: \#b\sharpindex{b} \meta{radix 8} \: \#o\sharpindex{o} \meta{radix 10} \: \meta{empty} \| \#d \meta{radix 16} \: \#x\sharpindex{x} \meta{digit 2} \: 0 \| 1 \meta{digit 8} \: 0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 \| 7 \meta{digit 10} \: \meta{digit} \meta{digit 16} \: \meta{digit $10$} \| a \| b \| c \| d \| e \| f % \end{grammar} \todo{Mark Meyer of TI sez, shouldn't we allow {\tt 1e3/2}?} \subsection{External representations} \label{datumsyntax} \meta{Datum} is what the \ide{read} procedure (section~\ref{read}) successfully parses. Note that any string that parses as an \meta{ex\-pres\-sion} will also parse as a \meta{datum}. \label{datum} \begin{grammar}% \meta{datum} \: \meta{simple datum} \| \meta{compound datum} \meta{simple datum} \: \meta{boolean} \| \meta{number} \> \| \meta{character} \| \meta{string} \| \meta{symbol} \meta{symbol} \: \meta{identifier} \meta{compound datum} \: \meta{list} \| \meta{vector} \meta{list} \: (\arbno{\meta{datum}}) \| (\atleastone{\meta{datum}} .\ \meta{datum}) \> \| \meta{abbreviation} \meta{abbreviation} \: \meta{abbrev prefix} \meta{datum} \meta{abbrev prefix} \: ' \| ` \| , \| ,@ \meta{vector} \: \#(\arbno{\meta{datum}}) % \end{grammar} \subsection{Expressions} \begin{grammar}% \meta{expression} \: \meta{variable} \> \| \meta{literal} \> \| \meta{procedure call} \> \| \meta{lambda expression} \> \| \meta{conditional} \> \| \meta{assignment} \> \| \meta{derived expression} \> \| \meta{macro use} \> \| \meta{macro block} \meta{literal} \: \meta{quotation} \| \meta{self-evaluating} \meta{self-evaluating} \: \meta{boolean} \| \meta{number} \> \| \meta{character} \| \meta{string} \meta{quotation} \: '\meta{datum} \| (quote \meta{datum}) \meta{procedure call} \: (\meta{operator} \arbno{\meta{operand}}) \meta{operator} \: \meta{expression} \meta{operand} \: \meta{expression} \meta{lambda expression} \: (lambda \meta{formals} \meta{body}) \meta{formals} \: (\arbno{\meta{variable}}) \| \meta{variable} \> \| (\atleastone{\meta{variable}} .\ \meta{variable}) \meta{body} \: \arbno{\meta{definition}} \meta{sequence} \meta{sequence} \: \arbno{\meta{command}} \meta{expression} \meta{command} \: \meta{expression} \meta{conditional} \: (if \meta{test} \meta{consequent} \meta{alternate}) \meta{test} \: \meta{expression} \meta{consequent} \: \meta{expression} \meta{alternate} \: \meta{expression} \| \meta{empty} \meta{assignment} \: (set! \meta{variable} \meta{expression}) \meta{derived expression} \: \> \> (cond \atleastone{\meta{cond clause}}) \> \| (cond \arbno{\meta{cond clause}} (else \meta{sequence})) \> \| (c\=ase \meta{expression} \> \>\atleastone{\meta{case clause}}) \> \| (c\=ase \meta{expression} \> \>\arbno{\meta{case clause}} \> \>(else \meta{sequence})) \> \| (and \arbno{\meta{test}}) \> \| (or \arbno{\meta{test}}) \> \| (let (\arbno{\meta{binding spec}}) \meta{body}) \> \| (let \meta{variable} (\arbno{\meta{binding spec}}) \meta{body}) \> \| (let* (\arbno{\meta{binding spec}}) \meta{body}) \> \| (letrec (\arbno{\meta{binding spec}}) \meta{body}) \> \| (begin \meta{sequence}) \> \| (d\=o \=(\arbno{\meta{iteration spec}}) \> \> \>(\meta{test} \meta{do result}) \> \>\arbno{\meta{command}}) \> \| (delay \meta{expression}) \> \| \meta{quasiquotation} \meta{cond clause} \: (\meta{test} \meta{sequence}) \> \| (\meta{test}) \> \| (\meta{test} => \meta{recipient}) \meta{recipient} \: \meta{expression} \meta{case clause} \: ((\arbno{\meta{datum}}) \meta{sequence}) \meta{binding spec} \: (\meta{variable} \meta{expression}) \meta{iteration spec} \: (\meta{variable} \meta{init} \meta{step}) \> \| (\meta{variable} \meta{init}) \meta{init} \: \meta{expression} \meta{step} \: \meta{expression} \meta{do result} \: \meta{sequence} \| \meta{empty} \meta{macro use} \: (\meta{keyword} \arbno{\meta{datum}}) \meta{keyword} \: \meta{identifier} \meta{macro block} \: \> (let-syntax (\arbno{\meta{syntax spec}}) \meta{body}) \> \| (letrec-syntax (\arbno{\meta{syntax spec}}) \meta{body}) \meta{syntax spec} \: (\meta{keyword} \meta{transformer spec}) \end{grammar} \subsection{Quasiquotations} The following grammar for quasiquote expressions is not context-free. It is presented as a recipe for generating an infinite number of production rules. Imagine a copy of the following rules for $D = 1, 2, 3, \ldots$. $D$ keeps track of the nesting depth. \begin{grammar}% \meta{quasiquotation} \: \meta{quasiquotation 1} \meta{qq template 0} \: \meta{expression} \meta{quasiquotation $D$} \: `\meta{qq template $D$} \> \| (quasiquote \meta{qq template $D$}) \meta{qq template $D$} \: \meta{simple datum} \> \| \meta{list qq template $D$} \> \| \meta{vector qq template $D$} \> \| \meta{unquotation $D$} \meta{list qq template $D$} \: (\arbno{\meta{qq template or splice $D$}}) \> \| (\atleastone{\meta{qq template or splice $D$}} .\ \meta{qq template $D$}) \> \| '\meta{qq template $D$} \> \| \meta{quasiquotation $D+1$} \meta{vector qq template $D$} \: \#(\arbno{\meta{qq template or splice $D$}}) \meta{unquotation $D$} \: ,\meta{qq template $D-1$} \> \| (unquote \meta{qq template $D-1$}) \meta{qq template or splice $D$} \: \meta{qq template $D$} \> \| \meta{splicing unquotation $D$} \meta{splicing unquotation $D$} \: ,@\meta{qq template $D-1$} \> \| (unquote-splicing \meta{qq template $D-1$}) % \end{grammar} In \meta{quasiquotation}s, a \meta{list qq template $D$} can sometimes be confused with either an \meta{un\-quota\-tion $D$} or a \meta{splicing un\-quo\-ta\-tion $D$}. The interpretation as an \meta{un\-quo\-ta\-tion} or \meta{splicing un\-quo\-ta\-tion $D$} takes precedence. \subsection{Transformers} \begin{grammar}% \meta{transformer spec} \: \> (syntax-rules (\arbno{\meta{identifier}}) \arbno{\meta{syntax rule}}) \meta{syntax rule} \: (\meta{pattern} \meta{template}) \meta{pattern} \: \meta{pattern identifier} \> \| (\arbno{\meta{pattern}}) \> \| (\atleastone{\meta{pattern}} . \meta{pattern}) \> \| (\arbno{\meta{pattern}} \meta{pattern} \meta{ellipsis}) \> \| \#(\arbno{\meta{pattern}}) \> \| \#(\arbno{\meta{pattern}} \meta{pattern} \meta{ellipsis}) \> \| \meta{pattern datum} \meta{pattern datum} \: \meta{string} \> \| \meta{character} \> \| \meta{boolean} \> \| \meta{number} \meta{template} \: \meta{pattern identifier} \> \| (\arbno{\meta{template element}}) \> \| (\atleastone{\meta{template element}} . \meta{template}) \> \| \#(\arbno{\meta{template element}}) \> \| \meta{template datum} \meta{template element} \: \meta{template} \> \| \meta{template} \meta{ellipsis} \meta{template datum} \: \meta{pattern datum} \meta{pattern identifier} \: \meta{any identifier except {\cf ...}} \meta{ellipsis} \: \meta{the identifier {\cf ...}} \end{grammar} \subsection{Programs and definitions} \begin{grammar}% \meta{program} \: \arbno{\meta{command or definition}} \meta{command or definition} \: \meta{command} \> \| \meta{definition} \> \| \meta{syntax definition} \> \| (begin \atleastone{\meta{command or definition}}) \meta{definition} \: (define \meta{variable} \meta{expression}) \> \| (define (\meta{variable} \meta{def formals}) \meta{body}) \> \| (begin \arbno{\meta{definition}}) \meta{def formals} \: \arbno{\meta{variable}} \> \| \arbno{\meta{variable}} .\ \meta{variable} \meta{syntax definition} \: \> (define-syntax \meta{keyword} \meta{transformer spec}) \end{grammar} r5rs-doc-20010328.orig/expr.tex0100644001167100001440000011506706471137065014570 0ustar cphusers%\vfill\eject \chapter{Expressions} \label{expressionchapter} \newcommand{\syntax}{{\em Syntax: }} \newcommand{\semantics}{{\em Semantics: }} %[Deleted for R5RS because of multiple-value returns. -RK] %A Scheme expression is a construct that returns a value, such as a %variable reference, literal, procedure call, or conditional. Expression types are categorized as {\em primitive} or {\em derived}. Primitive expression types include variables and procedure calls. Derived expression types are not semantically primitive, but can instead be defined as macros. With the exception of {\cf quasiquote}, whose macro definition is complex, the derived expressions are classified as library features. Suitable definitions are given in section~\ref{derivedsection}. \section{Primitive expression types} \label{primitivexps} \subsection{Variable references}\unsection \begin{entry}{% \pproto{\hyper{variable}}{\exprtype}} An expression consisting of a variable\index{variable} (section~\ref{variablesection}) is a variable reference. The value of the variable reference is the value stored in the location to which the variable is bound. It is an error to reference an unbound\index{unbound} variable. \begin{scheme} (define x 28) x \ev 28% \end{scheme} \end{entry} \subsection{Literal expressions}\unsection \label{literalsection} \begin{entry}{% \proto{quote}{ \hyper{datum}}{\exprtype} \pproto{\singlequote\hyper{datum}}{\exprtype} \pproto{\hyper{constant}}{\exprtype}} {\cf (quote \hyper{datum})} evaluates to \hyper{datum}.\mainschindex{'} \hyper{Datum} may be any external representation of a Scheme object (see section~\ref{externalreps}). This notation is used to include literal constants in Scheme code. \begin{scheme}% (quote a) \ev a (quote \sharpsign(a b c)) \ev \#(a b c) (quote (+ 1 2)) \ev (+ 1 2)% \end{scheme} {\cf (quote \hyper{datum})} may be abbreviated as \singlequote\hyper{datum}. The two notations are equivalent in all respects. \begin{scheme} 'a \ev a '\#(a b c) \ev \#(a b c) '() \ev () '(+ 1 2) \ev (+ 1 2) '(quote a) \ev (quote a) ''a \ev (quote a)% \end{scheme} Numerical constants, string constants, character constants, and boolean constants evaluate ``to themselves''; they need not be quoted. \begin{scheme} '"abc" \ev "abc" "abc" \ev "abc" '145932 \ev 145932 145932 \ev 145932 '\schtrue \ev \schtrue \schtrue \ev \schtrue% \end{scheme} As noted in section~\ref{storagemodel}, it is an error to alter a constant (i.e.~the value of a literal expression) using a mutation procedure like {\cf set-car!}\ or {\cf string-set!}. \end{entry} \subsection{Procedure calls}\unsection \begin{entry}{% \pproto{(\hyper{operator} \hyperi{operand} \dotsfoo)}{\exprtype}} A procedure call is written by simply enclosing in parentheses expressions for the procedure to be called and the arguments to be passed to it. The operator and operand expressions are evaluated (in an unspecified order) and the resulting procedure is passed the resulting arguments.\mainindex{call}\mainindex{procedure call} \begin{scheme}% (+ 3 4) \ev 7 ((if \schfalse + *) 3 4) \ev 12% \end{scheme} A number of procedures are available as the values of variables in the initial environment; for example, the addition and multiplication procedures in the above examples are the values of the variables {\cf +} and {\cf *}. New procedures are created by evaluating \lambdaexp{}s (see section~\ref{lambda}). \todo{At Friedman's request, flushed mention of other ways.} % or definitions (see section~\ref{define}). Procedure calls may return any number of values (see \ide{values} in section~\ref{proceduresection}). With the exception of {\cf values} the procedures available in the initial environment return one value or, for procedures such as {\cf apply}, pass on the values returned by a call to one of their arguments. Procedure calls are also called {\em combinations}. \mainindex{combination} \begin{note} In contrast to other dialects of Lisp, the order of evaluation is unspecified, and the operator expression and the operand expressions are always evaluated with the same evaluation rules. \end{note} \begin{note} Although the order of evaluation is otherwise unspecified, the effect of any concurrent evaluation of the operator and operand expressions is constrained to be consistent with some sequential order of evaluation. The order of evaluation may be chosen differently for each procedure call. \end{note} \begin{note} In many dialects of Lisp, the empty combination, {\tt ()}, is a legitimate expression. In Scheme, combinations must have at least one subexpression, so {\tt ()} is not a syntactically valid expression. \todo{Dybvig: ``it should be obvious from the syntax.''} \end{note} \todo{Freeman: I think an explanation as to why evaluation order is not specified should be included. It should not include any reference to parallel evaluation. Does any existing compiler generate better code because the evaluation order is unspecified? Clinger: yes: T3, MacScheme v2, probably MIT Scheme and Chez Scheme. But that's not the main reason for leaving the order unspecified.} \end{entry} \subsection{Procedures}\unsection \label{lamba} \begin{entry}{% \proto{lambda}{ \hyper{formals} \hyper{body}}{\exprtype}} \syntax \hyper{Formals} should be a formal arguments list as described below, and \hyper{body} should be a sequence of one or more expressions. \semantics \vest A \lambdaexp{} evaluates to a procedure. The environment in effect when the \lambdaexp{} was evaluated is remembered as part of the procedure. When the procedure is later called with some actual arguments, the environment in which the \lambdaexp{} was evaluated will be extended by binding the variables in the formal argument list to fresh locations, the corresponding actual argument values will be stored in those locations, and the expressions in the body of the \lambdaexp{} will be evaluated sequentially in the extended environment. The result(s) of the last expression in the body will be returned as the result(s) of the procedure call. \begin{scheme} (lambda (x) (+ x x)) \ev {\em{}a procedure} ((lambda (x) (+ x x)) 4) \ev 8 (define reverse-subtract (lambda (x y) (- y x))) (reverse-subtract 7 10) \ev 3 (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (add4 6) \ev 10% \end{scheme} \hyper{Formals} should have one of the following forms: \begin{itemize} \item {\tt(\hyperi{variable} \dotsfoo)}: The procedure takes a fixed number of arguments; when the procedure is called, the arguments will be stored in the bindings of the corresponding variables. \item \hyper{variable}: The procedure takes any number of arguments; when the procedure is called, the sequence of actual arguments is converted into a newly allocated list, and the list is stored in the binding of the \hyper{variable}. \item {\tt(\hyperi{variable} \dotsfoo{} \hyper{variable$_{n}$}\ {\bf.}\ \hyper{variable$_{n+1}$})}: If a space-delimited period precedes the last variable, then the procedure takes $n$ or more arguments, where $n$ is the number of formal arguments before the period (there must be at least one). The value stored in the binding of the last variable will be a newly allocated list of the actual arguments left over after all the other actual arguments have been matched up against the other formal arguments. \end{itemize} It is an error for a \hyper{variable} to appear more than once in \hyper{formals}. \begin{scheme} ((lambda x x) 3 4 5 6) \ev (3 4 5 6) ((lambda (x y . z) z) 3 4 5 6) \ev (5 6)% \end{scheme} Each procedure created as the result of evaluating a \lambdaexp{} is (conceptually) tagged with a storage location, in order to make \ide{eqv?} and \ide{eq?} work on procedures (see section~\ref{equivalencesection}). \end{entry} \subsection{Conditionals}\unsection \begin{entry}{% \proto{if}{ \hyper{test} \hyper{consequent} \hyper{alternate}}{\exprtype} \rproto{if}{ \hyper{test} \hyper{consequent}}{\exprtype}} %\/ if hyper = italic \syntax \hyper{Test}, \hyper{consequent}, and \hyper{alternate} may be arbitrary expressions. \semantics An {\cf if} expression is evaluated as follows: first, \hyper{test} is evaluated. If it yields a true value\index{true} (see section~\ref{booleansection}), then \hyper{consequent} is evaluated and its value(s) is(are) returned. Otherwise \hyper{alternate} is evaluated and its value(s) is(are) returned. If \hyper{test} yields a false value and no \hyper{alternate} is specified, then the result of the expression is unspecified. \begin{scheme} (if (> 3 2) 'yes 'no) \ev yes (if (> 2 3) 'yes 'no) \ev no (if (> 3 2) (- 3 2) (+ 3 2)) \ev 1% \end{scheme} \end{entry} \subsection{Assignments}\unsection \label{assignment} \begin{entry}{% \proto{set!}{ \hyper{variable} \hyper{expression}}{\exprtype}} \hyper{Expression} is evaluated, and the resulting value is stored in the location to which \hyper{variable} is bound. \hyper{Variable} must be bound either in some region\index{region} enclosing the {\cf set!}\ expression or at top level. The result of the {\cf set!} expression is unspecified. \begin{scheme} (define x 2) (+ x 1) \ev 3 (set! x 4) \ev \unspecified (+ x 1) \ev 5% \end{scheme} \end{entry} \section{Derived expression types} \label{derivedexps} The constructs in this section are hygienic, as discussed in section~\ref{macrosection}. For reference purposes, section~\ref{derivedsection} gives macro definitions that will convert most of the constructs described in this section into the primitive constructs described in the previous section. \todo{Mention that no definition of backquote is provided?} \subsection{Conditionals}\unsection \begin{entry}{% \proto{cond}{ \hyperi{clause} \hyperii{clause} \dotsfoo}{library \exprtype}} \syntax Each \hyper{clause} should be of the form \begin{scheme} (\hyper{test} \hyperi{expression} \dotsfoo)% \end{scheme} where \hyper{test} is any expression. Alternatively, a \hyper{clause} may be of the form \begin{scheme} (\hyper{test} => \hyper{expression})% \end{scheme} The last \hyper{clause} may be an ``else clause,'' which has the form \begin{scheme} (else \hyperi{expression} \hyperii{expression} \dotsfoo)\rm.% \end{scheme} \mainschindex{else} \mainschindex{=>} \semantics A {\cf cond} expression is evaluated by evaluating the \hyper{test} expressions of successive \hyper{clause}s in order until one of them evaluates to a true value\index{true} (see section~\ref{booleansection}). When a \hyper{test} evaluates to a true value, then the remaining \hyper{expression}s in its \hyper{clause} are evaluated in order, and the result(s) of the last \hyper{expression} in the \hyper{clause} is(are) returned as the result(s) of the entire {\cf cond} expression. If the selected \hyper{clause} contains only the \hyper{test} and no \hyper{expression}s, then the value of the \hyper{test} is returned as the result. If the selected \hyper{clause} uses the \ide{=>} alternate form, then the \hyper{expression} is evaluated. Its value must be a procedure that accepts one argument; this procedure is then called on the value of the \hyper{test} and the value(s) returned by this procedure is(are) returned by the {\cf cond} expression. If all \hyper{test}s evaluate to false values, and there is no else clause, then the result of the conditional expression is unspecified; if there is an else clause, then its \hyper{expression}s are evaluated, and the value(s) of the last one is(are) returned. \begin{scheme} (cond ((> 3 2) 'greater) ((< 3 2) 'less)) \ev greater% (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal)) \ev equal% (cond ((assv 'b '((a 1) (b 2))) => cadr) (else \schfalse{})) \ev 2% \end{scheme} \end{entry} \begin{entry}{% \proto{case}{ \hyper{key} \hyperi{clause} \hyperii{clause} \dotsfoo}{library \exprtype}} \syntax \hyper{Key} may be any expression. Each \hyper{clause} should have the form \begin{scheme} ((\hyperi{datum} \dotsfoo) \hyperi{expression} \hyperii{expression} \dotsfoo)\rm,% \end{scheme} where each \hyper{datum} is an external representation of some object. All the \hyper{datum}s must be distinct. The last \hyper{clause} may be an ``else clause,'' which has the form \begin{scheme} (else \hyperi{expression} \hyperii{expression} \dotsfoo)\rm.% \end{scheme} \schindex{else} \semantics A {\cf case} expression is evaluated as follows. \hyper{Key} is evaluated and its result is compared against each \hyper{datum}. If the result of evaluating \hyper{key} is equivalent (in the sense of {\cf eqv?}; see section~\ref{eqv?}) to a \hyper{datum}, then the expressions in the corresponding \hyper{clause} are evaluated from left to right and the result(s) of the last expression in the \hyper{clause} is(are) returned as the result(s) of the {\cf case} expression. If the result of evaluating \hyper{key} is different from every \hyper{datum}, then if there is an else clause its expressions are evaluated and the result(s) of the last is(are) the result(s) of the {\cf case} expression; otherwise the result of the {\cf case} expression is unspecified. \begin{scheme} (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite)) \ev composite (case (car '(c d)) ((a) 'a) ((b) 'b)) \ev \unspecified (case (car '(c d)) ((a e i o u) 'vowel) ((w y) 'semivowel) (else 'consonant)) \ev consonant% \end{scheme} \end{entry} \begin{entry}{% \proto{and}{ \hyperi{test} \dotsfoo}{library \exprtype}} The \hyper{test} expressions are evaluated from left to right, and the value of the first expression that evaluates to a false value (see section~\ref{booleansection}) is returned. Any remaining expressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then \schtrue{} is returned. \begin{scheme} (and (= 2 2) (> 2 1)) \ev \schtrue (and (= 2 2) (< 2 1)) \ev \schfalse (and 1 2 'c '(f g)) \ev (f g) (and) \ev \schtrue% \end{scheme} \end{entry} \begin{entry}{% \proto{or}{ \hyperi{test} \dotsfoo}{library \exprtype}} The \hyper{test} expressions are evaluated from left to right, and the value of the first expression that evaluates to a true value (see section~\ref{booleansection}) is returned. Any remaining expressions are not evaluated. If all expressions evaluate to false values, the value of the last expression is returned. If there are no expressions then \schfalse{} is returned. \begin{scheme} (or (= 2 2) (> 2 1)) \ev \schtrue (or (= 2 2) (< 2 1)) \ev \schtrue (or \schfalse \schfalse \schfalse) \ev \schfalse (or (memq 'b '(a b c)) (/ 3 0)) \ev (b c)% \end{scheme} \end{entry} \subsection{Binding constructs} The three binding constructs {\cf let}, {\cf let*}, and {\cf letrec} give Scheme a block structure, like Algol 60. The syntax of the three constructs is identical, but they differ in the regions\index{region} they establish for their variable bindings. In a {\cf let} expression, the initial values are computed before any of the variables become bound; in a {\cf let*} expression, the bindings and evaluations are performed sequentially; while in a {\cf letrec} expression, all the bindings are in effect while their initial values are being computed, thus allowing mutually recursive definitions. \begin{entry}{% \proto{let}{ \hyper{bindings} \hyper{body}}{library \exprtype}} \syntax \hyper{Bindings} should have the form \begin{scheme} ((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,% \end{scheme} where each \hyper{init} is an expression, and \hyper{body} should be a sequence of one or more expressions. It is an error for a \hyper{variable} to appear more than once in the list of variables being bound. \semantics The \hyper{init}s are evaluated in the current environment (in some unspecified order), the \hyper{variable}s are bound to fresh locations holding the results, the \hyper{body} is evaluated in the extended environment, and the value(s) of the last expression of \hyper{body} is(are) returned. Each binding of a \hyper{variable} has \hyper{body} as its region.\index{region} \begin{scheme} (let ((x 2) (y 3)) (* x y)) \ev 6 (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))) \ev 35% \end{scheme} See also named {\cf let}, section \ref{namedlet}. \end{entry} \begin{entry}{% \proto{let*}{ \hyper{bindings} \hyper{body}}{library \exprtype}}\nobreak \nobreak \syntax \hyper{Bindings} should have the form \begin{scheme} ((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,% \end{scheme} and \hyper{body} should be a sequence of one or more expressions. \semantics {\cf Let*} is similar to {\cf let}, but the bindings are performed sequentially from left to right, and the region\index{region} of a binding indicated by {\cf(\hyper{variable} \hyper{init})} is that part of the {\cf let*} expression to the right of the binding. Thus the second binding is done in an environment in which the first binding is visible, and so on. \begin{scheme} (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))) \ev 70% \end{scheme} \end{entry} \begin{entry}{% \proto{letrec}{ \hyper{bindings} \hyper{body}}{library \exprtype}} \syntax \hyper{Bindings} should have the form \begin{scheme} ((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,% \end{scheme} and \hyper{body} should be a sequence of one or more expressions. It is an error for a \hyper{variable} to appear more than once in the list of variables being bound. \semantics The \hyper{variable}s are bound to fresh locations holding undefined values, the \hyper{init}s are evaluated in the resulting environment (in some unspecified order), each \hyper{variable} is assigned to the result of the corresponding \hyper{init}, the \hyper{body} is evaluated in the resulting environment, and the value(s) of the last expression in \hyper{body} is(are) returned. Each binding of a \hyper{variable} has the entire {\cf letrec} expression as its region\index{region}, making it possible to define mutually recursive procedures. \begin{scheme} %(letrec ((x 2) (y 3)) % (letrec ((foo (lambda (z) (+ x y z))) (x 7)) % (foo 4))) \ev 14 % (letrec ((even? (lambda (n) (if (zero? n) \schtrue (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) \schfalse (even? (- n 1)))))) (even? 88)) \ev \schtrue% \end{scheme} One restriction on {\cf letrec} is very important: it must be possible to evaluate each \hyper{init} without assigning or referring to the value of any \hyper{variable}. If this restriction is violated, then it is an error. The restriction is necessary because Scheme passes arguments by value rather than by name. In the most common uses of {\cf letrec}, all the \hyper{init}s are \lambdaexp{}s and the restriction is satisfied automatically. % \todo{use or uses? --- Jinx.} \end{entry} \subsection{Sequencing}\unsection \begin{entry}{% \proto{begin}{ \hyperi{expression} \hyperii{expression} \dotsfoo}{library \exprtype}} The \hyper{expression}s are evaluated sequentially from left to right, and the value(s) of the last \hyper{expression} is(are) returned. This expression type is used to sequence side effects such as input and output. \begin{scheme} (define x 0) (begin (set! x 5) (+ x 1)) \ev 6 (begin (display "4 plus 1 equals ") (display (+ 4 1))) \ev \unspecified \>{\em and prints} 4 plus 1 equals 5% \end{scheme} \end{entry} \subsection{Iteration}%\unsection \noindent% \pproto{(do ((\hyperi{variable} \hyperi{init} \hyperi{step})}{library \exprtype} \mainschindex{do}{\tt\obeyspaces% \dotsfoo)\\ (\hyper{test} \hyper{expression} \dotsfoo)\\ \hyper{command} \dotsfoo)} {\cf Do} is an iteration construct. It specifies a set of variables to be bound, how they are to be initialized at the start, and how they are to be updated on each iteration. When a termination condition is met, the loop exits after evaluating the \hyper{expression}s. {\cf Do} expressions are evaluated as follows: The \hyper{init} expressions are evaluated (in some unspecified order), the \hyper{variable}s are bound to fresh locations, the results of the \hyper{init} expressions are stored in the bindings of the \hyper{variable}s, and then the iteration phase begins. \vest Each iteration begins by evaluating \hyper{test}; if the result is false (see section~\ref{booleansection}), then the \hyper{command} expressions are evaluated in order for effect, the \hyper{step} expressions are evaluated in some unspecified order, the \hyper{variable}s are bound to fresh locations, the results of the \hyper{step}s are stored in the bindings of the \hyper{variable}s, and the next iteration begins. \vest If \hyper{test} evaluates to a true value, then the \hyper{expression}s are evaluated from left to right and the value(s) of the last \hyper{expression} is(are) returned. If no \hyper{expression}s are present, then the value of the {\cf do} expression is unspecified. \vest The region\index{region} of the binding of a \hyper{variable} consists of the entire {\cf do} expression except for the \hyper{init}s. It is an error for a \hyper{variable} to appear more than once in the list of {\cf do} variables. \vest A \hyper{step} may be omitted, in which case the effect is the same as if {\cf(\hyper{variable} \hyper{init} \hyper{variable})} had been written instead of {\cf(\hyper{variable} \hyper{init})}. \begin{scheme} (do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) \ev \#(0 1 2 3 4) (let ((x '(1 3 5 7 9))) (do ((x x (cdr x)) (sum 0 (+ sum (car x)))) ((null? x) sum))) \ev 25% \end{scheme} %\end{entry} \begin{entry}{% \rproto{let}{ \hyper{variable} \hyper{bindings} \hyper{body}}{library \exprtype}} \label{namedlet} ``Named {\cf let}'' is a variant on the syntax of \ide{let} which provides a more general looping construct than {\cf do} and may also be used to express recursions. It has the same syntax and semantics as ordinary {\cf let} except that \hyper{variable} is bound within \hyper{body} to a procedure whose formal arguments are the bound variables and whose body is \hyper{body}. Thus the execution of \hyper{body} may be repeated by invoking the procedure named by \hyper{variable}. % | <-- right margin \begin{scheme} (let loop ((numbers '(3 -2 1 6 -5)) (nonneg '()) (neg '())) (cond ((null? numbers) (list nonneg neg)) ((>= (car numbers) 0) (loop (cdr numbers) (cons (car numbers) nonneg) neg)) ((< (car numbers) 0) (loop (cdr numbers) nonneg (cons (car numbers) neg))))) % \lev ((6 1 3) (-5 -2))% \end{scheme} \end{entry} \subsection{Delayed evaluation}\unsection \begin{entry}{% \proto{delay}{ \hyper{expression}}{library \exprtype}} \todo{Fix.} The {\cf delay} construct is used together with the procedure \ide{force} to implement \defining{lazy evaluation} or \defining{call by need}. {\tt(delay~\hyper{expression})} returns an object called a \defining{promise} which at some point in the future may be asked (by the {\cf force} procedure) \todo{Bartley's white lie; OK?} to evaluate \hyper{expression}, and deliver the resulting value. The effect of \hyper{expression} returning multiple values is unspecified. See the description of {\cf force} (section~\ref{force}) for a more complete description of {\cf delay}. \end{entry} \subsection{Quasiquotation}\unsection \label{quasiquotesection} \begin{entry}{% \proto{quasiquote}{ \hyper{qq template}}{\exprtype} \nopagebreak \pproto{\backquote\hyper{qq template}}{\exprtype}} ``Backquote'' or ``quasiquote''\index{backquote} expressions are useful for constructing a list or vector structure when most but not all of the desired structure is known in advance. If no commas\index{comma} appear within the \hyper{qq template}, the result of evaluating \backquote\hyper{qq template} is equivalent to the result of evaluating \singlequote\hyper{qq template}. If a comma\mainschindex{,} appears within the \hyper{qq template}, however, the expression following the comma is evaluated (``unquoted'') and its result is inserted into the structure instead of the comma and the expression. If a comma appears followed immediately by an at-sign (\atsign),\mainschindex{,@} then the following expression must evaluate to a list; the opening and closing parentheses of the list are then ``stripped away'' and the elements of the list are inserted in place of the comma at-sign expression sequence. A comma at-sign should only appear within a list or vector \hyper{qq template}. % struck: "(in the sense of {\cf equal?})" after "equivalent" \begin{scheme} `(list ,(+ 1 2) 4) \ev (list 3 4) (let ((name 'a)) `(list ,name ',name)) % \lev (list a (quote a)) `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) % \lev (a 3 4 5 6 b) `(({\cf foo} ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))) % \lev ((foo 7) . cons) `\#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8) % \lev \#(10 5 2 4 3 8)% \end{scheme} Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost backquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation. \begin{scheme} `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) % \lev (a `(b ,(+ 1 2) ,(foo 4 d) e) f) (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)) % \lev (a `(b ,x ,'y d) e)% \end{scheme} The two notations \backquote\hyper{qq template} and {\tt (quasiquote \hyper{qq template})} are identical in all respects. {\cf,\hyper{expression}} is identical to {\cf (unquote \hyper{expression})}, and {\cf,@\hyper{expression}} is identical to {\cf (unquote-splicing \hyper{expression})}. The external syntax generated by \ide{write} for two-element lists whose car is one of these symbols may vary between implementations. \mainschindex{`} \begin{scheme} (quasiquote (list (unquote (+ 1 2)) 4)) % \lev (list 3 4) '(quasiquote (list (unquote (+ 1 2)) 4)) % \lev `(list ,(+ 1 2) 4) {\em{}i.e.,} (quasiquote (list (unquote (+ 1 2)) 4))% \end{scheme} Unpredictable behavior can result if any of the symbols \ide{quasiquote}, \ide{unquote}, or \ide{unquote-splicing} appear in positions within a \hyper{qq template} otherwise than as described above. \end{entry} \section{Macros} \label{macrosection} Scheme programs can define and use new derived expression types, called {\em macros}.\mainindex{macro} Program-defined expression types have the syntax \begin{scheme} (\hyper{keyword} {\hyper{datum}} ...)% \end{scheme}% where \hyper{keyword} is an identifier that uniquely determines the expression type. This identifier is called the {\em syntactic keyword}\index{syntactic keyword}, or simply {\em keyword}\index{keyword}, of the macro\index{macro keyword}. The number of the \hyper{datum}s, and their syntax, depends on the expression type. Each instance of a macro is called a {\em use}\index{macro use} of the macro. The set of rules that specifies how a use of a macro is transcribed into a more primitive expression is called the {\em transformer}\index{macro transformer} of the macro. The macro definition facility consists of two parts: \begin{itemize} \item A set of expressions used to establish that certain identifiers are macro keywords, associate them with macro transformers, and control the scope within which a macro is defined, and \item a pattern language for specifying macro transformers. \end{itemize} The syntactic keyword of a macro may shadow variable bindings, and local variable bindings may shadow keyword bindings. \index{keyword} All macros defined using the pattern language are ``hygienic'' and ``referentially transparent'' and thus preserve Scheme's lexical scoping~\cite{Kohlbecker86, hygienic,Bawden88,macrosthatwork,syntacticabstraction}: \mainindex{hygienic} \mainindex{referentially transparent} \begin{itemize} \item If a macro transformer inserts a binding for an identifier (variable or keyword), the identifier will in effect be renamed throughout its scope to avoid conflicts with other identifiers. Note that a \ide{define} at top level may or may not introduce a binding; see section~\ref{defines}. \item If a macro transformer inserts a free reference to an identifier, the reference refers to the binding that was visible where the transformer was specified, regardless of any local bindings that may surround the use of the macro. \end{itemize} %The low-level facility permits non-hygienic macros to be written, %and may be used to implement the high-level pattern language. % The fourth section describes some features that would make the % low-level macro facility easier to use directly. \subsection{Binding constructs for syntactic keywords} \label{bindsyntax} {\cf Let-syntax} and {\cf letrec-syntax} are analogous to {\cf let} and {\cf letrec}, but they bind syntactic keywords to macro transformers instead of binding variables to locations that contain values. Syntactic keywords may also be bound at top level; see section~\ref{define-syntax}. \begin{entry}{% \proto{let-syntax}{ \hyper{bindings} \hyper{body}}{\exprtype}} \syntax \hyper{Bindings} should have the form \begin{scheme} ((\hyper{keyword} \hyper{transformer spec}) \dotsfoo)% \end{scheme} Each \hyper{keyword} is an identifier, each \hyper{transformer spec} is an instance of {\cf syntax-rules}, and \hyper{body} should be a sequence of one or more expressions. It is an error for a \hyper{keyword} to appear more than once in the list of keywords being bound. \semantics The \hyper{body} is expanded in the syntactic environment obtained by extending the syntactic environment of the {\cf let-syntax} expression with macros whose keywords are the \hyper{keyword}s, bound to the specified transformers. Each binding of a \hyper{keyword} has \hyper{body} as its region. \begin{scheme} (let-syntax ((when (syntax-rules () ((when test stmt1 stmt2 ...) (if test (begin stmt1 stmt2 ...)))))) (let ((if \schtrue)) (when if (set! if 'now)) if)) \ev now (let ((x 'outer)) (let-syntax ((m (syntax-rules () ((m) x)))) (let ((x 'inner)) (m)))) \ev outer% \end{scheme} \end{entry} \begin{entry}{% \proto{letrec-syntax}{ \hyper{bindings} \hyper{body}}{\exprtype}} \syntax Same as for {\cf let-syntax}. \semantics The \hyper{body} is expanded in the syntactic environment obtained by extending the syntactic environment of the {\cf letrec-syntax} expression with macros whose keywords are the \hyper{keyword}s, bound to the specified transformers. Each binding of a \hyper{keyword} has the \hyper{bindings} as well as the \hyper{body} within its region, so the transformers can transcribe expressions into uses of the macros introduced by the {\cf letrec-syntax} expression. \begin{scheme} (letrec-syntax ((my-or (syntax-rules () ((my-or) \schfalse) ((my-or e) e) ((my-or e1 e2 ...) (let ((temp e1)) (if temp temp (my-or e2 ...))))))) (let ((x \schfalse) (y 7) (temp 8) (let odd?) (if even?)) (my-or x (let temp) (if y) y))) \ev 7% \end{scheme} \end{entry} \subsection{Pattern language} \label{patternlanguage} A \hyper{transformer spec} has the following form: \begin{entry}{% \proto{syntax-rules}{ \hyper{literals} \hyper{syntax rule} \dotsfoo}{}} \syntax \hyper{Literals} is a list of identifiers and each \hyper{syntax rule} should be of the form \begin{scheme} (\hyper{pattern} \hyper{template})% \end{scheme} The \hyper{pattern} in a \hyper{syntax rule} is a list \hyper{pattern} that begins with the keyword for the macro. A \hyper{pattern} is either an identifier, a constant, or one of the following \begin{scheme} (\hyper{pattern} \ldots) (\hyper{pattern} \hyper{pattern} \ldots . \hyper{pattern}) (\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis}) \#(\hyper{pattern} \ldots) \#(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis})% \end{scheme} and a template is either an identifier, a constant, or one of the following \begin{scheme} (\hyper{element} \ldots) (\hyper{element} \hyper{element} \ldots . \hyper{template}) \#(\hyper{element} \ldots)% \end{scheme} where an \hyper{element} is a \hyper{template} optionally followed by an \hyper{ellipsis} and an \hyper{ellipsis} is the identifier ``{\cf ...}'' (which cannot be used as an identifier in either a template or a pattern).\schindex{...} \semantics An instance of {\cf syntax-rules} produces a new macro transformer by specifying a sequence of hygienic rewrite rules. A use of a macro whose keyword is associated with a transformer specified by {\cf syntax-rules} is matched against the patterns contained in the \hyper{syntax rule}s, beginning with the leftmost \hyper{syntax rule}. When a match is found, the macro use is transcribed hygienically according to the template. An identifier that appears in the pattern of a \hyper{syntax rule} is a {\em pattern variable}, unless it is the keyword that begins the pattern, is listed in \hyper{literals}, or is the identifier ``{\cf ...}''. Pattern variables match arbitrary input elements and are used to refer to elements of the input in the template. It is an error for the same pattern variable to appear more than once in a \hyper{pattern}. The keyword at the beginning of the pattern in a \hyper{syntax rule} is not involved in the matching and is not considered a pattern variable or literal identifier. \begin{rationale} The scope of the keyword is determined by the expression or syntax definition that binds it to the associated macro transformer. If the keyword were a pattern variable or literal identifier, then the template that follows the pattern would be within its scope regardless of whether the keyword were bound by {\cf let-syntax} or by {\cf letrec-syntax}. \end{rationale} Identifiers that appear in \hyper{literals} are interpreted as literal identifiers to be matched against corresponding subforms of the input. A subform in the input matches a literal identifier if and only if it is an identifier and either both its occurrence in the macro expression and its occurrence in the macro definition have the same lexical binding, or the two identifiers are equal and both have no lexical binding. % [Bill Rozas suggested the term "noise word" for these literal % identifiers, but in their most interesting uses, such as a setf % macro, they aren't noise words at all. -- Will] A subpattern followed by {\cf ...} can match zero or more elements of the input. It is an error for {\cf ...} to appear in \hyper{literals}. Within a pattern the identifier {\cf ...} must follow the last element of a nonempty sequence of subpatterns. More formally, an input form $F$ matches a pattern $P$ if and only if: \begin{itemize} \item $P$ is a non-literal identifier; or \item $P$ is a literal identifier and $F$ is an identifier with the same binding; or \item $P$ is a list {\cf ($P_1$ $\dots$ $P_n$)} and $F$ is a list of $n$ forms that match $P_1$ through $P_n$, respectively; or \item $P$ is an improper list {\cf ($P_1$ $P_2$ $\dots$ $P_n$ . $P_{n+1}$)} and $F$ is a list or improper list of $n$ or more forms that match $P_1$ through $P_n$, respectively, and whose $n$th ``cdr'' matches $P_{n+1}$; or \item $P$ is of the form {\cf ($P_1$ $\dots$ $P_n$ $P_{n+1}$ \meta{ellipsis})} where \meta{ellipsis} is the identifier {\cf ...} and $F$ is a proper list of at least $n$ forms, the first $n$ of which match $P_1$ through $P_n$, respectively, and each remaining element of $F$ matches $P_{n+1}$; or \item $P$ is a vector of the form {\cf \#($P_1$ $\dots$ $P_n$)} and $F$ is a vector of $n$ forms that match $P_1$ through $P_n$; or \item $P$ is of the form {\cf \#($P_1$ $\dots$ $P_n$ $P_{n+1}$ \meta{ellipsis})} where \meta{ellipsis} is the identifier {\cf ...} and $F$ is a vector of $n$ or more forms the first $n$ of which match $P_1$ through $P_n$, respectively, and each remaining element of $F$ matches $P_{n+1}$; or \item $P$ is a datum and $F$ is equal to $P$ in the sense of the {\cf equal?} procedure. \end{itemize} It is an error to use a macro keyword, within the scope of its binding, in an expression that does not match any of the patterns. When a macro use is transcribed according to the template of the matching \hyper{syntax rule}, pattern variables that occur in the template are replaced by the subforms they match in the input. Pattern variables that occur in subpatterns followed by one or more instances of the identifier {\cf ...} are allowed only in subtemplates that are followed by as many instances of {\cf ...}. They are replaced in the output by all of the subforms they match in the input, distributed as indicated. It is an error if the output cannot be built up as specified. %%% This description of output construction is very vague. It should %%% probably be formalized, but that is not easy... Identifiers that appear in the template but are not pattern variables or the identifier {\cf ...} are inserted into the output as literal identifiers. If a literal identifier is inserted as a free identifier then it refers to the binding of that identifier within whose scope the instance of {\cf syntax-rules} appears. If a literal identifier is inserted as a bound identifier then it is in effect renamed to prevent inadvertent captures of free identifiers. As an example, if \ide{let} and \ide{cond} are defined as in section~\ref{derivedsection} then they are hygienic (as required) and the following is not an error. \begin{scheme} (let ((=> \schfalse)) (cond (\schtrue => 'ok))) \ev ok% \end{scheme} The macro transformer for {\cf cond} recognizes {\cf =>} as a local variable, and hence an expression, and not as the top-level identifier {\cf =>}, which the macro transformer treats as a syntactic keyword. Thus the example expands into \begin{scheme} (let ((=> \schfalse)) (if \schtrue (begin => 'ok)))% \end{scheme} instead of \begin{scheme} (let ((=> \schfalse)) (let ((temp \schtrue)) (if temp ('ok temp))))% \end{scheme} which would result in an invalid procedure call. \end{entry} r5rs-doc-20010328.orig/extract.scm0100644001167100001440000000616606473325443015246 0ustar cphusers ; Code to extract the examples from the report. Written for R5RS by ; Richard Kelsey. ; This prints everything in INPUT-FILE that is between a "\begin{scheme}" ; and an "\end{scheme}" to the current output port. (define (find-examples input-file) (call-with-input-file input-file (lambda (in) (extract-text "\\begin{scheme}" "\\end{scheme}" (input-port->source in) (output-port->sink (current-output-port)))))) ; Turning ports into sources (thunks that generate characters) and ; sinks (procedures of one argument that consume characters). (define (input-port->source port) (lambda () (read-char port))) (define (output-port->sink port) (lambda (char) (write-char char port))) ; Read characters from SOURCE, passing to SINK all characters found between ; the strings BEGIN and END. (define (extract-text begin end source sink) (let loop () (if (find-string begin source (lambda (char) (values))) (if (find-string end source sink) (loop))))) ; Transfer characters from SOURCE to SINK until STRING is found. ; ; We first make a circular buffer containing the first (string-length STRING) ; characters from SOURCE. We then compare the buffer with STRING to see if ; a match is found. If not, we pass the first character from the buffer to ; SINK and get the next item from SOURCE. If it's a character we put it in ; the buffer, advance the buffer one character, and continue. When we reach ; the end of SOURCE, the remaining characters in the buffer are passed to SINK. (define (find-string string source sink) (let ((buffer (make-circular-buffer (string-length string) source))) (let loop ((buffer buffer)) (if (buffer-match? string buffer) #t (begin (sink (car buffer)) (let ((next (source))) (if (char? next) (begin (set-car! buffer next) (loop (cdr buffer))) (begin (set-car! buffer #f) (let flush-loop ((buffer (cdr buffer))) (if (car buffer) (begin (sink (car buffer)) (flush-loop (cdr buffer))) #f)))))))))) ; Returns a circular list of COUNT pairs containing the first COUNT ; items from SOURCE. (define (make-circular-buffer count source) (let ((start (list (source)))) (let loop ((last start) (i 1)) (if (= i count) (begin (set-cdr! last start) last) (let ((next (list (source)))) (set-cdr! last next) (loop next (+ i 1))))) start)) ; Returns #T if the contents of the BUFFER, a list of characters, matches ; STRING. This is the same as `(string=? string (list->string buffer))' ; except that it works for circular buffers. (define (buffer-match? string buffer) (let loop ((buffer buffer) (i 0)) (cond ((= i (string-length string)) #t) ((char=? (car buffer) (string-ref string i)) (loop (cdr buffer) (+ i 1))) (else #f)))) ; Return a source that generates the characters from STRING. This is only ; used for testing. (define (string-source string) (let ((i 0)) (lambda () (if (= i (string-length string)) #f (begin (set! i (+ i 1)) (string-ref string (- i 1))))))) r5rs-doc-20010328.orig/intro.tex0100644001167100001440000001660106472641050014732 0ustar cphusers\clearextrapart{Introduction} \label{historysection} Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make additional features appear necessary. Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible enough to support most of the major programming paradigms in use today. %Scheme has influenced the evolution of Lisp. Scheme was one of the first programming languages to incorporate first class procedures as in the lambda calculus, thereby proving the usefulness of static scope rules and block structure in a dynamically typed language. Scheme was the first major dialect of Lisp to distinguish procedures from lambda expressions and symbols, to use a single lexical environment for all variables, and to evaluate the operator position of a procedure call in the same way as an operand position. By relying entirely on procedure calls to express iteration, Scheme emphasized the fact that tail-recursive procedure calls are essentially goto's that pass arguments. Scheme was the first widely used programming language to embrace first class escape procedures, from which all previously known sequential control structures can be synthesized. A subsequent version of Scheme introduced the concept of exact and inexact numbers, an extension of Common Lisp's generic arithmetic. More recently, Scheme became the first programming language to support hygienic macros, which permit the syntax of a block-structured language to be extended in a consistent and reliable manner. % A few %of these innovations have recently been incorporated into Common Lisp, while %others remain to be adopted. \todo{Ramsdell: I would like to make a few comments on presentation. The most important comment is about section organization. Newspaper writers spend most of their time writing the first three paragraphs of any article. This part of the article is often the only part read by readers, and is important in enticing readers to continue. In the same way, The first page is most likely to be the only page read by many SIGPLAN readers. If I had my choice of what I would ask them to read, it would be the material in section 1.1, the Semantics section that notes that scheme is lexically scoped, tail recursive, weakly typed, ... etc. I would expand on the discussion on continuations, as they represent one important difference between Scheme and other languages. The introduction, with its history of scheme, its history of scheme reports and meetings, and acknowledgements giving names of people that the reader will not likely know, is not that one page I would like all to read. I suggest moving the history to the back of the report, and use the first couple of pages to convince the reader that the language documented in this report is worth studying. } \subsection*{Background} \vest The first description of Scheme was written in 1975~\cite{Scheme75}. A revised report~\cite{Scheme78} \todo{italicize or not?} appeared in 1978, which described the evolution of the language as its MIT implementation was upgraded to support an innovative compiler~\cite{Rabbit}. Three distinct projects began in 1981 and 1982 to use variants of Scheme for courses at MIT, Yale, and Indiana University~\cite{Rees82,MITScheme,Scheme311}. An introductory computer science textbook using Scheme was published in 1984~\cite{SICP}. %\vest As might be expected of a language used primarily for education and %research, Scheme has always evolved rapidly. This was no problem when %Scheme was used only within MIT, but \vest As Scheme became more widespread, local dialects began to diverge until students and researchers occasionally found it difficult to understand code written at other sites. Fifteen representatives of the major implementations of Scheme therefore met in October 1984 to work toward a better and more widely accepted standard for Scheme. %Participating in this workshop were Hal Abelson, Norman Adams, David %Bartley, Gary Brooks, William Clinger, Daniel Friedman, Robert Halstead, %Chris Hanson, Christopher Haynes, Eugene Kohlbecker, Don Oxley, Jonathan Rees, %Guillermo Rozas, Gerald Jay Sussman, and Mitchell Wand. Kent Pitman %made valuable contributions to the agenda for the workshop but was %unable to attend the sessions. % %Subsequent electronic mail discussions and committee work completed the %definition of the language. %Gerry Sussman drafted the section on numbers, Chris Hanson drafted the %sections on characters and strings, and Gary Brooks and William Clinger %drafted the sections on input and output. %William Clinger recorded the decisions of the workshop and %compiled the pieces into a coherent document. %The ``Revised revised report on Scheme''~\cite{RRRS} Their report~\cite{RRRS} was published at MIT and Indiana University in the summer of 1985. Further revision took place in the spring of 1986~\cite{R3RS}, %, again accomplished %almost entirely by electronic mail, resulted in the present report. and in the spring of 1988~\cite{R4RS}. The present report reflects further revisions agreed upon in a meeting at Xerox PARC in June 1992. %\vest The number 3 in the title is part of the title, not a reference to %a footnote. The word ``revised'' is raised to the third power because %the report is a revision of a report that was already twice revised. \todo{Write an editors' note?} \medskip We intend this report to belong to the entire Scheme community, and so we grant permission to copy it in whole or in part without fee. In particular, we encourage implementors of Scheme to use this report as a starting point for manuals and other documentation, modifying it as necessary. \subsection*{Acknowledgements} We would like to thank the following people for their help: Alan Bawden, Michael Blair, George Carrette, Andy Cromarty, Pavel Curtis, Jeff Dalton, Olivier Danvy, Ken Dickey, Bruce Duba, Marc Feeley, Andy Freeman, Richard Gabriel, Yekta G\"ursel, Ken Haase, Robert Hieb, Paul Hudak, Morry Katz, Chris Lindblad, Mark Meyer, Jim Miller, Jim Philbin, John Ramsdell, Mike Shaff, Jonathan Shapiro, Julie Sussman, Perry Wagle, Daniel Weise, Henry Wu, and Ozan Yigit. We thank Carol Fessenden, Daniel Friedman, and Christopher Haynes for permission to use text from the Scheme 311 version 4 reference manual. We thank Texas Instruments, Inc.~for permission to use text from the {\em TI Scheme Language Reference Manual}\cite{TImanual85}. We gladly acknowledge the influence of manuals for MIT Scheme\cite{MITScheme}, T\cite{Rees84}, Scheme 84\cite{Scheme84},Common Lisp\cite{CLtL}, and Algol 60\cite{Naur63}. \vest We also thank Betty Dexter for the extreme effort she put into setting this report in \TeX, and Donald Knuth for designing the program that caused her troubles. \vest The Artificial Intelligence Laboratory of the Massachusetts Institute of Technology, the Computer Science Department of Indiana University, the Computer and Information Sciences Department of the University of Oregon, and the NEC Research Institute supported the preparation of this report. Support for the MIT work was provided in part by the Advanced Research Projects Agency of the Department of Defense under Office of Naval Research contract N00014-80-C-0505. Support for the Indiana University work was provided by NSF grants NCS 83-04567 and NCS 83-03325. r5rs-doc-20010328.orig/repository.tex0100644001167100001440000000042106246352111016003 0ustar cphusers\extrapart{Additional material} The Internet Scheme Repository at \begin{center} {\cf http://www.cs.indiana.edu/scheme-repository/} \end{center} contains an extensive Scheme bibliography, as well as papers, programs, implementations, and other material related to Scheme. r5rs-doc-20010328.orig/algol60.cls0100644001167100001440000005701606473332642015036 0ustar cphusers%% %% This is file `algol60.cls', %% NOT generated with the (ludicrous) docstrip utility, but instead hacked %% from a file that was. %% %% Modified from `report.cls' by Richard A. Kelsey. This is an attempt to %% bring Jonathan Rees's ALGOL 60 style into the brave new world of 2e. %% Changes marked with !!. All comments after this initial block are mine. %% %% Portions Copyright 1993 1994 1995 1996 %% The LaTeX3 Project and any individual authors listed elsewhere %% in this file. %% %% For further copyright information, and conditions for modification %% and distribution, see the file legal.txt, and any other copyright %% notices in this file. %% %% This file is NOT part of the LaTeX2e system. %% ---------------------------------------- %% This system is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %% \NeedsTeXFormat{LaTeX2e}[1995/12/01] \ProvidesClass{algol60}[1997/03/13 Algol 60 document class] % !! \newcommand\@ptsize{} \newif\if@restonecol \newif\if@titlepage \@titlepagetrue \newif\if@openright \if@compatibility\else \DeclareOption{a4paper} {\setlength\paperheight {297mm}% \setlength\paperwidth {210mm}} \DeclareOption{a5paper} {\setlength\paperheight {210mm}% \setlength\paperwidth {148mm}} \DeclareOption{b5paper} {\setlength\paperheight {250mm}% \setlength\paperwidth {176mm}} \DeclareOption{letterpaper} {\setlength\paperheight {11in}% \setlength\paperwidth {8.5in}} \DeclareOption{legalpaper} {\setlength\paperheight {14in}% \setlength\paperwidth {8.5in}} \DeclareOption{executivepaper} {\setlength\paperheight {10.5in}% \setlength\paperwidth {7.25in}} \DeclareOption{landscape} {\setlength\@tempdima {\paperheight}% \setlength\paperheight {\paperwidth}% \setlength\paperwidth {\@tempdima}} \fi \if@compatibility \renewcommand\@ptsize{0} \else \DeclareOption{10pt}{\renewcommand\@ptsize{0}} \fi \DeclareOption{11pt}{\renewcommand\@ptsize{1}} \DeclareOption{12pt}{\renewcommand\@ptsize{2}} \if@compatibility\else \DeclareOption{oneside}{\@twosidefalse \@mparswitchfalse} \fi \DeclareOption{twoside}{\@twosidetrue \@mparswitchtrue} \DeclareOption{draft}{\setlength\overfullrule{5pt}} \if@compatibility\else \DeclareOption{final}{\setlength\overfullrule{0pt}} \fi \DeclareOption{titlepage}{\@titlepagetrue} \if@compatibility\else \DeclareOption{notitlepage}{\@titlepagefalse} \fi \if@compatibility \else \DeclareOption{openright}{\@openrighttrue} \DeclareOption{openany}{\@openrightfalse} \fi \if@compatibility\else \DeclareOption{onecolumn}{\@twocolumnfalse} \fi \DeclareOption{twocolumn}{\@twocolumntrue} \DeclareOption{leqno}{\input{leqno.clo}} \DeclareOption{fleqn}{\input{fleqn.clo}} \DeclareOption{openbib}{% \AtEndOfPackage{% \renewcommand\@openbib@code{% \advance\leftmargin\bibindent \itemindent -\bibindent \listparindent \itemindent \parsep \z@ }% \renewcommand\newblock{\par}}% } \ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final,openany} \ProcessOptions \input{size1\@ptsize.clo} \setlength\lineskip{1\p@} \setlength\normallineskip{1\p@} \renewcommand\baselinestretch{} \setlength\parskip{0\p@ \@plus \p@} \@lowpenalty 51 \@medpenalty 151 \@highpenalty 301 \setcounter{topnumber}{2} \renewcommand\topfraction{.7} \setcounter{bottomnumber}{1} \renewcommand\bottomfraction{.3} \setcounter{totalnumber}{3} \renewcommand\textfraction{.2} \renewcommand\floatpagefraction{.5} \setcounter{dbltopnumber}{2} \renewcommand\dbltopfraction{.7} \renewcommand\dblfloatpagefraction{.5} \if@twoside \def\ps@headings{% \let\@oddfoot\@empty\let\@evenfoot\@empty \def\@evenhead{\thepage\quad\headertitle\hfil}% %!! \def\@evenhead{\thepage\hfil\slshape\leftmark}% \def\@oddhead{\hfil\rightmark\quad\thepage}% %!! \def\@oddhead{{\slshape\rightmark}\hfil\thepage}% \let\@mkboth\markboth \def\chaptermark##1{% \markright { %!! \mark { \MakeUppercase{% \ifnum \c@secnumdepth >\m@ne \@chapapp\ \thechapter. \ % \fi %!! ##1}}{}}% ##1}{}}% \def\sectionmark##1{% } %!! \markright {\MakeUppercase{% %!! \ifnum \c@secnumdepth >\z@ %!! \thesection. \ % %!! \fi %!! ##1}}} } \else \def\ps@headings{% \let\@oddfoot\@empty \def\@oddhead{{\slshape\rightmark}\hfil\thepage}% \let\@mkboth\markboth \def\chaptermark##1{% \markright {\MakeUppercase{% \ifnum \c@secnumdepth >\m@ne \@chapapp\ \thechapter. \ % \fi ##1}}}} \fi \def\ps@myheadings{% \let\@oddfoot\@empty\let\@evenfoot\@empty \def\@evenhead{\thepage\hfil\slshape\leftmark}% \def\@oddhead{{\slshape\rightmark}\hfil\thepage}% \let\@mkboth\@gobbletwo \let\chaptermark\@gobble \let\sectionmark\@gobble } \if@titlepage \newcommand\maketitle{\begin{titlepage}% \let\footnotesize\small \let\footnoterule\relax \let \footnote \thanks \null\vfil \vskip 60\p@ \begin{center}% {\LARGE \@title \par}% \vskip 3em% {\large \lineskip .75em% \begin{tabular}[t]{c}% \@author \end{tabular}\par}% \vskip 1.5em% {\large \@date \par}% % Set date in \large size. \end{center}\par \@thanks \vfil\null \end{titlepage}% \setcounter{footnote}{0}% \global\let\thanks\relax \global\let\maketitle\relax \global\let\@thanks\@empty \global\let\@author\@empty \global\let\@date\@empty \global\let\@title\@empty \global\let\title\relax \global\let\author\relax \global\let\date\relax \global\let\and\relax } \else \newcommand\maketitle{\par \begingroup \renewcommand\thefootnote{\@fnsymbol\c@footnote}% \def\@makefnmark{\rlap{\@textsuperscript{\normalfont\@thefnmark}}}% \long\def\@makefntext##1{\parindent 1em\noindent \hb@xt@1.8em{% \hss\@textsuperscript{\normalfont\@thefnmark}}##1}% \if@twocolumn \ifnum \col@number=\@ne \@maketitle \else \twocolumn[\@maketitle]% \fi \else \newpage \global\@topnum\z@ % Prevents figures from going at top of page. \@maketitle \fi \thispagestyle{plain}\@thanks \endgroup \setcounter{footnote}{0}% \global\let\thanks\relax \global\let\maketitle\relax \global\let\@maketitle\relax \global\let\@thanks\@empty \global\let\@author\@empty \global\let\@date\@empty \global\let\@title\@empty \global\let\title\relax \global\let\author\relax \global\let\date\relax \global\let\and\relax } \def\@maketitle{% \newpage \null \vskip 2em% \begin{center}% \let \footnote \thanks {\LARGE \@title \par}% \vskip 1.5em% {\large \lineskip .5em% \begin{tabular}[t]{c}% \@author \end{tabular}\par}% \vskip 1em% {\large \@date}% \end{center}% \par \vskip 1.5em} \fi \newcommand*\chaptermark[1]{} \setcounter{secnumdepth}{2} \newcounter {part} \newcounter {chapter} \newcounter {section}[chapter] \newcounter {subsection}[section] \newcounter {subsubsection}[subsection] \newcounter {paragraph}[subsubsection] \newcounter {subparagraph}[paragraph] \renewcommand\thepart {\@Roman\c@part} \renewcommand\thechapter {\@arabic\c@chapter} \renewcommand\thesection {\thechapter.\@arabic\c@section} \renewcommand\thesubsection {\thesection.\@arabic\c@subsection} \renewcommand\thesubsubsection{\thesubsection .\@arabic\c@subsubsection} \renewcommand\theparagraph {\thesubsubsection.\@arabic\c@paragraph} \renewcommand\thesubparagraph {\theparagraph.\@arabic\c@subparagraph} %!! \newcommand\@chapapp{\chaptername} \newcommand\@chapapp{} \newcommand\part{% \if@openright \cleardoublepage \else \clearpage \fi \thispagestyle{plain}% \if@twocolumn \onecolumn \@tempswatrue \else \@tempswafalse \fi \null\vfil \secdef\@part\@spart} \def\@part[#1]#2{% \ifnum \c@secnumdepth >-2\relax \refstepcounter{part}% \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% \else \addcontentsline{toc}{part}{#1}% \fi \markboth{}{}% {\centering \interlinepenalty \@M \normalfont \ifnum \c@secnumdepth >-2\relax \huge\bfseries \partname~\thepart \par \vskip 20\p@ \fi \Huge \bfseries #2\par}% \@endpart} \def\@spart#1{% {\centering \interlinepenalty \@M \normalfont \Huge \bfseries #1\par}% \@endpart} \def\@endpart{\vfil\newpage \if@twoside \null \thispagestyle{empty}% \newpage \fi \if@tempswa \twocolumn \fi} % Chapters don't cause a pagebreak. \newcommand\chapter{%!! \if@openright\cleardoublepage\else\clearpage\fi %!! \thispagestyle{plain}% \global\@topnum\z@ \@afterindentfalse \secdef\@chapter\@schapter} \def\@chapter[#1]#2{\ifnum \c@secnumdepth >\m@ne \refstepcounter{chapter}% \typeout{\@chapapp\space\thechapter.}% \addcontentsline{toc}{chapter}% {\protect\numberline{\thechapter}#1}% \else \addcontentsline{toc}{chapter}{#1}% \fi \chaptermark{#1}% \addtocontents{lof}{\protect\addvspace{10\p@}}% \addtocontents{lot}{\protect\addvspace{10\p@}}% \if@twocolumn %!! \@topnewpage[\@makechapterhead{#2}]% \@makechapterhead{#2}% \@afterheading \else \@makechapterhead{#2}% \@afterheading \fi} % Change chapter headings \def\@makechapterhead#1{% %!! \vspace*{50\p@}% \vspace{3ex plus 1ex minus 1ex} % Space at top of text page. [NOT *] {%\parindent \z@ \raggedright \normalfont \ifnum \c@secnumdepth >\m@ne \large\bfseries \@chapapp\space \thechapter. \quad %!! \par\nobreak %!! \vskip 20\p@ \fi \interlinepenalty\@M \large \bfseries #1\par\nobreak %!! was Huge %!! \vskip 40\p@ }} \def\@schapter#1{\if@twocolumn %!! \@topnewpage[\@makeschapterhead{#1}]% \@makeschapterhead{#1}% %!! Chapters don't start pages \else \@makeschapterhead{#1}% \@afterheading \fi} \def\@makeschapterhead#1{% %!! \vspace*{50\p@}% \vspace{4ex plus 1ex minus 1ex} % Space at top of text page. [NOT *] {%!! \parindent \z@ \raggedright \normalfont \centerline{\large\bfseries\uppercase{#1}} % Chapter heading %!! \interlinepenalty\@M %!! \large \bfseries #1\par\nobreak \nobreak % ? %!! \vskip 40\p@ }} %!! Put dots after section numbers \renewcommand{\@seccntformat}[1]{{\csname the#1\endcsname}.\hspace{0.5em}} %!! Mutation to the \numberline command, similar to above. %\renewcommand\numberline[1]{\advance\hangindent\@tempdima % \hbox to\@tempdima{#1.\hfil}} %!!! CLOBBER ARABIC COMMAND TO ALLOW FOR CHAPTER, SECTION, ETC. ZERO % I have my doubts about this one. -RK % \def\@arabic#1{\ifnum #1>\m@ne \number #1\fi} \newcommand\section{\@startsection {section}{1}{\z@}% {-3.5ex \@plus -1ex \@minus -.2ex}% {2ex \@plus.2ex}% %!! smaller gap %!! {2.3ex \@plus.2ex}% {\normalfont\large\bfseries}} %!! was Large \newcommand\subsection{\@startsection{subsection}{2}{\z@}% {-3.25ex\@plus -1ex \@minus -.2ex}% {1ex \@plus .2ex}% %!! smaller gap %!! {1.5ex \@plus .2ex}% {\normalfont\normalsize\bfseries}} \newcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-3.25ex\@plus -1ex \@minus -.2ex}% {1ex \@plus .2ex}% %!! smaller gap %!! {1.5ex \@plus .2ex}% {\normalfont\normalsize\bfseries}} \newcommand\paragraph{\@startsection{paragraph}{4}{\z@}% {3.25ex \@plus1ex \@minus.2ex}% {-1em}% {\normalfont\normalsize\bfseries}} \newcommand\subparagraph{\@startsection{subparagraph}{5}{\parindent}% {3.25ex \@plus1ex \@minus .2ex}% {-1em}% {\normalfont\normalsize\bfseries}} \if@twocolumn \setlength\leftmargini {2em} \else \setlength\leftmargini {2.5em} \fi \leftmargin \leftmargini \setlength\leftmarginii {2.2em} \setlength\leftmarginiii {1.87em} \setlength\leftmarginiv {1.7em} \if@twocolumn \setlength\leftmarginv {.5em} \setlength\leftmarginvi {.5em} \else \setlength\leftmarginv {1em} \setlength\leftmarginvi {1em} \fi \setlength \labelsep {.5em} \setlength \labelwidth{\leftmargini} \addtolength\labelwidth{-\labelsep} \@beginparpenalty -\@lowpenalty \@endparpenalty -\@lowpenalty \@itempenalty -\@lowpenalty \renewcommand\theenumi{\@arabic\c@enumi} \renewcommand\theenumii{\@alph\c@enumii} \renewcommand\theenumiii{\@roman\c@enumiii} \renewcommand\theenumiv{\@Alph\c@enumiv} \newcommand\labelenumi{\theenumi.} \newcommand\labelenumii{(\theenumii)} \newcommand\labelenumiii{\theenumiii.} \newcommand\labelenumiv{\theenumiv.} \renewcommand\p@enumii{\theenumi} \renewcommand\p@enumiii{\theenumi(\theenumii)} \renewcommand\p@enumiv{\p@enumiii\theenumiii} \newcommand\labelitemi{$\m@th\bullet$} \newcommand\labelitemii{\normalfont\bfseries --} \newcommand\labelitemiii{$\m@th\ast$} \newcommand\labelitemiv{$\m@th\cdot$} \newenvironment{description} {\list{}{\labelwidth\z@ \itemindent-\leftmargin \let\makelabel\descriptionlabel}} {\endlist} \newcommand*\descriptionlabel[1]{\hspace\labelsep \normalfont\bfseries #1} \if@titlepage \newenvironment{abstract}{% \titlepage \null\vfil \@beginparpenalty\@lowpenalty \begin{center}% \bfseries \abstractname \@endparpenalty\@M \end{center}}% {\par\vfil\null\endtitlepage} \else \newenvironment{abstract}{% \if@twocolumn \section*{\abstractname}% \else \small \begin{center}% {\bfseries \abstractname\vspace{-.5em}\vspace{\z@}}% \end{center}% \quotation \fi} {\if@twocolumn\else\endquotation\fi} \fi \newenvironment{verse} {\let\\\@centercr \list{}{\itemsep \z@ \itemindent -1.5em% \listparindent\itemindent \rightmargin \leftmargin \advance\leftmargin 1.5em}% \item\relax} {\endlist} \newenvironment{quotation} {\list{}{\listparindent 1.5em% \itemindent \listparindent \rightmargin \leftmargin \parsep \z@ \@plus\p@}% \item\relax} {\endlist} \newenvironment{quote} {\list{}{\rightmargin\leftmargin}% \item\relax} {\endlist} \if@compatibility \newenvironment{titlepage} {% \if@twocolumn \@restonecoltrue\onecolumn \else \@restonecolfalse\newpage \fi \thispagestyle{empty}% \setcounter{page}\z@ }% {\if@restonecol\twocolumn \else \newpage \fi } \else \newenvironment{titlepage} {% \if@twocolumn \@restonecoltrue\onecolumn \else \@restonecolfalse\newpage \fi \thispagestyle{empty}% \setcounter{page}\@ne }% {\if@restonecol\twocolumn \else \newpage \fi \if@twoside\else \setcounter{page}\@ne \fi } \fi \newcommand\appendix{\par \setcounter{chapter}{0}% \setcounter{section}{0}% \renewcommand\@chapapp{\appendixname}% \renewcommand\thechapter{\@Alph\c@chapter}} \setlength\arraycolsep{5\p@} \setlength\tabcolsep{6\p@} \setlength\arrayrulewidth{.4\p@} \setlength\doublerulesep{2\p@} \setlength\tabbingsep{\labelsep} \skip\@mpfootins = \skip\footins \setlength\fboxsep{3\p@} \setlength\fboxrule{.4\p@} \@addtoreset{equation}{chapter} \renewcommand\theequation{\thechapter.\@arabic\c@equation} \newcounter{figure}[chapter] \renewcommand\thefigure{\thechapter.\@arabic\c@figure} \def\fps@figure{tbp} \def\ftype@figure{1} \def\ext@figure{lof} \def\fnum@figure{\figurename~\thefigure} \newenvironment{figure} {\@float{figure}} {\end@float} \newenvironment{figure*} {\@dblfloat{figure}} {\end@dblfloat} \newcounter{table}[chapter] \renewcommand\thetable{\thechapter.\@arabic\c@table} \def\fps@table{tbp} \def\ftype@table{2} \def\ext@table{lot} \def\fnum@table{\tablename~\thetable} \newenvironment{table} {\@float{table}} {\end@float} \newenvironment{table*} {\@dblfloat{table}} {\end@dblfloat} \newlength\abovecaptionskip \newlength\belowcaptionskip \setlength\abovecaptionskip{10\p@} \setlength\belowcaptionskip{0\p@} \long\def\@makecaption#1#2{% \vskip\abovecaptionskip \sbox\@tempboxa{#1: #2}% \ifdim \wd\@tempboxa >\hsize #1: #2\par \else \global \@minipagefalse \hb@xt@\hsize{\hfil\box\@tempboxa\hfil}% \fi \vskip\belowcaptionskip} \DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm} \DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf} \DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt} \DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf} \DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit} \DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl} \DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc} \DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal} \DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal} \newcommand\@pnumwidth{1.55em} \newcommand\@tocrmarg{2.55em} \newcommand\@dotsep{4.5} \setcounter{tocdepth}{1} %!! was 2 \newcommand\tableofcontents{% % \if@twocolumn % \@restonecoltrue\twocolumn %!! was \onecolumn % \else % \@restonecolfalse % \fi % \chapter*{\contentsname % \@mkboth{% % \MakeUppercase\contentsname}{\MakeUppercase\contentsname}}% \@starttoc{toc}% % \if@restonecol\twocolumn\fi } \newcommand*\l@part[2]{% \ifnum \c@tocdepth >-2\relax \addpenalty{-\@highpenalty}% \addvspace{2.25em \@plus\p@}% \begingroup \setlength\@tempdima{3em}% \parindent \z@ \rightskip \@pnumwidth \parfillskip -\@pnumwidth {\leavevmode \large \bfseries #1\hfil \hb@xt@\@pnumwidth{\hss #2}}\par \nobreak \global\@nobreaktrue \everypar{\global\@nobreakfalse\everypar{}}% \endgroup \fi} %!! \tocshrink added as the only way I can find that will arbitrarily reduce %!! the baseline spacing in the TOC. \newcommand{\tocshrink}[0]{0em} \newcommand*\l@chapter{\addvspace{\tocshrink}\@dottedtocline{1}{0em}{1.2em}} %!! \newcommand*\l@chapter[2]{% %!! \ifnum \c@tocdepth >\m@ne %!! \addpenalty{-\@highpenalty}% %!! \vskip 1.0em \@plus\p@ %!! \setlength\@tempdima{1.5em}% %!! \begingroup %!! \parindent \z@ \rightskip \@pnumwidth %!! \parfillskip -\@pnumwidth %!! \leavevmode \bfseries %!! \advance\leftskip\@tempdima %!! \hskip -\leftskip %!! #1\nobreak\hfil \nobreak\hb@xt@\@pnumwidth{\hss #2}\par %!! \penalty\@highpenalty %!! \endgroup %!! \fi} \newcommand*\l@section{\addvspace{\tocshrink}\@dottedtocline{1}{1.5em}{2.3em}} \newcommand*\l@subsection{\@dottedtocline{2}{3.8em}{3.2em}} \newcommand*\l@subsubsection{\@dottedtocline{3}{7.0em}{4.1em}} \newcommand*\l@paragraph{\@dottedtocline{4}{10em}{5em}} \newcommand*\l@subparagraph{\@dottedtocline{5}{12em}{6em}} \newcommand\listoffigures{% \if@twocolumn \@restonecoltrue\onecolumn \else \@restonecolfalse \fi \chapter*{\listfigurename \@mkboth{\MakeUppercase\listfigurename}% {\MakeUppercase\listfigurename}}% \@starttoc{lof}% \if@restonecol\twocolumn\fi } \newcommand*\l@figure{\@dottedtocline{1}{1.5em}{2.3em}} \newcommand\listoftables{% \if@twocolumn \@restonecoltrue\onecolumn \else \@restonecolfalse \fi \chapter*{\listtablename \@mkboth{% \MakeUppercase\listtablename}{\MakeUppercase\listtablename}}% \@starttoc{lot}% \if@restonecol\twocolumn\fi } \let\l@table\l@figure \newdimen\bibindent \setlength\bibindent{1.5em} \newenvironment{thebibliography}[1] {\chapter*{\MakeUppercase\bibname \@mkboth{\bibname}{\bibname}}% \addcontentsline{toc}{chapter}{\bibname} \list{\@biblabel{\@arabic\c@enumiv}}% {\settowidth\labelwidth{\@biblabel{#1}}% \leftmargin\labelwidth \advance\leftmargin\labelsep \@openbib@code \usecounter{enumiv}% \let\p@enumiv\@empty \renewcommand\theenumiv{\@arabic\c@enumiv}}% \sloppy\clubpenalty4000\widowpenalty4000% \sfcode`\.\@m} {\def\@noitemerr {\@latex@warning{Empty `thebibliography' environment}}% \endlist} \newcommand\newblock{\hskip .11em\@plus.33em\@minus.07em} \let\@openbib@code\@empty \newenvironment{theindex} {\if@twocolumn \@restonecolfalse \else \@restonecoltrue \fi \columnseprule \z@ %!! \columnsep 35\p@ \twocolumn[\@makeschapterhead{\indexname}]% \@mkboth{\MakeUppercase\indexname}% {\MakeUppercase\indexname}% \thispagestyle{plain}\parindent\z@ \parskip\z@ \@plus .3\p@\relax \let\item\@idxitem} {\if@restonecol\onecolumn\else\clearpage\fi} \newcommand\@idxitem{\par\hangindent 40\p@} \newcommand\subitem{\@idxitem \hspace*{20\p@}} \newcommand\subsubitem{\@idxitem \hspace*{30\p@}} \newcommand\indexspace{\par \vskip 10\p@ \@plus5\p@ \@minus3\p@\relax} \renewcommand\footnoterule{% \kern-3\p@ \hrule\@width.4\columnwidth \kern2.6\p@} \@addtoreset{footnote}{chapter} \newcommand\@makefntext[1]{% \parindent 1em% \noindent \hb@xt@1.8em{\hss\@makefnmark}#1} \newcommand\contentsname{Contents} \newcommand\listfigurename{List of Figures} \newcommand\listtablename{List of Tables} \newcommand\bibname{Bibliography} \newcommand\indexname{Index} \newcommand\figurename{Figure} \newcommand\tablename{Table} \newcommand\partname{Part} \newcommand\chaptername{Chapter} \newcommand\appendixname{Appendix} \newcommand\abstractname{Abstract} \newcommand\today{} \edef\today{\ifcase\month\or January\or February\or March\or April\or May\or June\or July\or August\or September\or October\or November\or December\fi \space\number\day, \number\year} \setlength\columnsep{10\p@} \setlength\columnseprule{0\p@} \pagestyle{plain} \pagenumbering{arabic} \if@twoside \else \raggedbottom \fi \if@twocolumn \twocolumn \sloppy \flushbottom \else \onecolumn \fi \endinput %!! Some size stuff \parskip 5pt plus 2pt minus 2pt %!! 0pt plus 1pt % Extra vertical space between paragraphs. \parindent 0pt %!! 15pt % Width of paragraph indentation. \topsep 0pt plus 2pt %!! 8pt plus 2pt minus 4pt % Extra vertical space, in addition to r5rs-doc-20010328.orig/rrrs2txi.scm0100644001167100001440000014510007260521512015351 0ustar cphusers;"rrrs2txi.scm", A program to convert Scheme Reports to TeXInfo format. ; Copyright (c) 1998, 2001 Aubrey Jaffer ; Time-stamp: "2001-03-28 21:33:49 jaffer" ; ;Permission to copy this software, to redistribute it, and to use it ;for any purpose is granted, subject to the following restrictions and ;understandings. ; ;1. Any copy made of this software must include this copyright notice ;in full. ; ;2. I have made no warrantee or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; ;3. In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. ;; -=-=-=-=-=- ;; This program translates the LaTeX source ".tex" files of the ;; "Revised(3) Report on the Algorithmic Language Scheme", ;; "Revised(4) Report on the Algorithmic Language Scheme", or ;; "Revised(5) Report on the Algorithmic Language Scheme" ;; to TeXInfo format. If "rrrs2txi.scm" is LOADed into Scheme in a ;; directory containing "r3rs.tex", "r4rs.tex", or "r5rs.tex", then ;; calling the Scheme procedure GO with no arguments (go) will ;; translate the report contained in that directory. The resulting ;; ".txi" file is written to the current directory. ;; Otherwise, calling the GO procedure will translate all reports ;; contained in "r3rs", "r4rs", or "r5rs" subdirectories of the ;; current directory to texinfo format. The resulting ".txi" files ;; are written to the current directory. ;; If a Scheme report is successfully converted, GO also tries to ;; compile the new ".txi" file to INFO format. The resulting info ;; files are placed in the directory named by the variable ;; *INFO-VICINITY*, defined here. (define *info-vicinity* (make-vicinity "/usr/local/info/")) ;; Change *INFO-VICINITY*'s value to suit your platform. (require 'common-list-functions) (require 'string-search) (require 'string-port) (require 'string-case) (require 'fluid-let) (require 'line-i/o) (require 'printf) (define *input-vicinity* (user-vicinity)) (define *output-vicinity* (user-vicinity)) (define *input-basename* #f) (define *tex-input-port* #f) (define *txi-output-port* #f) (define *begin-stack* '()) (define *entry-type* #f) (define *brace-depth* 0) (define *paren-depth* 0) (define *previous-char* #f) (define *closer* #f) (define *tab-index* 0) (define *column* 0) (define *html* #f) (define (tex:errwarn class . args) (define cep (current-error-port)) (force-output (current-output-port)) (force-output *txi-output-port*) (if (null? *new-labels*) (if *input-basename* (fprintf cep "%s: \"%s.tex\": %s: " class *input-basename* *name*) (fprintf cep "%s: %s: " class *name*)) (if *input-basename* (fprintf cep "%s: \"%s.tex\": %s: %s: " class *input-basename* *name* (caar *new-labels*)) (fprintf cep "%s: %s: %s: " class *name* (caar *new-labels*)))) (if (not (null? args)) (begin (display (car args) cep) (for-each (lambda (x) (display #\ cep) (write x cep)) (cdr args)))) (newline cep) (force-output cep)) (define (tex:warn . args) (apply tex:errwarn "WARN" args)) (define (tex:error . args) (apply tex:errwarn "ERROR" args) '(print '*closer* *closer* '*brace-depth* *brace-depth* '*previous-char* *previous-char* 'peek-char (pc)) (require 'pretty-print) (pretty-print *begin-stack*) (abort)) (define *name* "?") (define *previous-labels* '()) (define *new-labels* '(("define-syntax" . "Syntax definitions"))) (define (define-label label) ;;(print 'define-label label) (let ((pair (assoc label *new-labels*)) (old-pair (assoc label *previous-labels*))) (cond ((not pair) (set! *new-labels* (cons (cons label *name*) *new-labels*))) ((equal? (cdr pair) *name*)) ((and old-pair (not (equal? (cdr old-pair) *name*))) (set-cdr! pair *name*) (tex:warn label 'changed-from (cdr old-pair) 'to *name*)) (else (tex:warn label 'changed-from (cdr pair) 'to *name*) (set-cdr! pair *name*))))) ;;; \pproto has some weird stuff. Try to extract a label; the only ;;; one seems to be `do' (define (extract-do-label proc) (if (equal? "(do " (substring proc 0 4)) (define-label "do"))) (define (label->name label) (let ((pair (or (assoc label *new-labels*) (assoc label *previous-labels*)))) (cond (pair (cdr pair)) (else (tex:warn 'label-not-found label) label)))) ;;;; space and special character utilities (define (string-whitespace? str) (do ((idx (+ -1 (string-length str)) (+ -1 idx))) ((or (negative? idx) (not (char-whitespace? (string-ref str idx)))) (negative? idx)))) (define (output-text-lines . lines) (for-each (lambda (str) (display str *txi-output-port*) (tex:newline #f #f)) lines)) (define (escape-special chr) (case chr ((#\@ #\{ #\}) (string #\@ chr)) ;;((#\#) "@pounds{}") (else chr))) (define tabs (make-vector 10 0)) (define (bump-column str) (set! *column* (+ (or (substring? "}" str) (and (substring? "{" str) (- (string-length str) (substring? "{" str) 1)) (string-length str)) *column*))) (define (space-to-column col) ;;(print 'space-to-column col '*column* *column*) (cond ((negative? (- col *column*)) (tex:warn 'spacing-backwards? *column* col)) (else (display (make-string (- col *column*) #\ ) *txi-output-port*))) (set! *column* col)) (define (space-to-tab-stop idx) ;;(print 'space-to-tab-stop idx) (space-to-column (vector-ref tabs idx)) (set! *tab-index* (+ idx 1))) (define (set-tabs! . args) (define idx 0) (set! *column* 0) (set! *paren-depth* 0) (for-each (lambda (tbcl) (vector-set! tabs idx tbcl) (set! idx (+ 1 idx))) args)) (define (pc) (peek-char *tex-input-port*)) (define (rc) (let ((chr (read-char *tex-input-port*))) (cond ((eqv? #\newline chr) (set! *tab-index* 0) (set! *column* 0)) (else (set! *column* (+ 1 *column*)))) chr)) (define (rl) ;;(print 'rl *tab-index* *column*) (set! *column* 0) (set! *tab-index* 0) (read-line *tex-input-port*)) (define (close-parens) (cond ((positive? *paren-depth*) (let ((closes (make-string *paren-depth* #\)))) (tex:warn "Closing Scheme expression!") (fprintf *txi-output-port* "\\n%s\\n" closes)))) (set! *paren-depth* 0)) ;;;; Make index entries (define *index-memory* '()) (define *index-entries* '()) (define (make-index-entry name before after) (let ((new-index (sprintf #f "@%s%s%s" before (string-downcase name) after))) (cond ((not (member new-index *index-memory*)) (set! *index-memory* (cons new-index *index-memory*)) (set! *index-entries* (cons new-index *index-entries*)))))) (define (rule:index cmd me before after) (fluid-let ((*tex-rules* (append (rule #\newline " ") *tex-rules*))) (make-index-entry (capture-argument) before after)) #t) (define (tex:newline chr me) (set! *tab-index* 0) (set! *column* 0) ;;(case (pc) ((#\newline #\ ) (read-char *tex-input-port*))) (newline *txi-output-port*) (for-each (lambda (str) (display str *txi-output-port*) (newline *txi-output-port*)) *index-entries*) (set! *index-entries* '()) #t) ;;;; Process files. (define (check-file-end iport) (do ((chr (read-char iport) (read-char iport))) ((or (eof-object? chr) (not (char-whitespace? chr))) (if (not (eof-object? chr)) (tex:warn 'process-rrrs-file (string-append *input-basename* ".tex") 'ended-prematurely chr (read-line iport)))))) (define (process-rrrs-file base-name) (fluid-let ((*input-basename* base-name)) (fprintf (current-error-port) "Translating \"%s.tex\"\\n" base-name) (call-with-input-file (in-vicinity *input-vicinity* (string-append base-name ".tex")) (lambda (iport) (fluid-let ((*tex-input-port* iport)) (process-tex-input #t) (check-file-end iport) #t))))) (define (tex->txi . optargs) (cond ((null? optargs) (set! *txi-output-port* (current-output-port)) (set! *tex-input-port* (current-input-port)) (process-tex-input #t)) (else (newline) (cond ((not (null? (cdr optargs))) (set! *input-vicinity* (car optargs)) (set! optargs (cdr optargs)))) (cond ((not (null? (cdr optargs))) (set! *output-vicinity* (cadr optargs)))) (let* ((basename (car optargs)) (labels (in-vicinity *output-vicinity* (string-append basename "-nod.scm")))) (if (file-exists? labels) (call-with-input-file labels (lambda (lport) (set! *previous-labels* (read lport)) (set! *previous-nodes* (read lport)) (if (eof-object? *previous-nodes*) (set! *previous-nodes* '()))))) (call-with-output-file ;;"/dev/tty" (in-vicinity *output-vicinity* (string-append basename ".txi")) (lambda (oport) (set! *txi-output-port* oport) (process-rrrs-file basename))) (if (and (not (null? *new-labels*)) (not (null? *new-nodes*))) (call-with-output-file labels (lambda (oport) (fprintf oport "(\\n") (for-each (lambda (pair) (fprintf oport " %#a\\n" pair)) *new-labels*) (fprintf oport ")\\n") (fprintf oport "(\\n") (for-each (lambda (lst) (fprintf oport " %#a\\n" lst)) *new-nodes*) (fprintf oport ")\\n")))) (and (equal? *previous-labels* *new-labels*) (equal? *previous-nodes* *new-nodes*)))))) ;;;; Use `system' to convert to info format (define (txi->info vic base . info-vic) (newline) (set! info-vic (if (null? info-vic) *info-vicinity* (car info-vic))) (and (provided? 'system) (zero? (system (sprintf #f "makeinfo %s%s.txi -o %s%s.info" vic base info-vic base))) (zero? (system (sprintf #f "install-info %s%s.info %sdir" info-vic base info-vic))))) ;;;; Rules (define rules append) (define (rule toks . args) (map (lambda (tok) (cons tok args)) (if (pair? toks) toks (list toks)))) (define (process-rule rul) (cond ((procedure? (cadr rul)) (let ((ans (apply (cadr rul) rul))) (set! *previous-char* (car rul)) ans)) ((char? (cadr rul)) (set! *previous-char* (car rul)) (display (cadr rul) *txi-output-port*) #t) ((symbol? (cadr rul)) (cadr rul)) ((string? (cadr rul)) (set! *column* (+ -1 *column* (if (null? (cddr rul)) (string-length (cadr rul)) (if (negative? (caddr rul)) (- 1 *column*) (caddr rul))))) (set! *previous-char* (car rul)) (apply fprintf *txi-output-port* (cdr rul)) #t) (else (set! *previous-char* (car rul)) (tex:error (car rul) '=> 'malformed-rule rul)))) (define (process-one left) (let* ((tok (if (eqv? #t left) (rc) left)) (rul (or (assv tok *tex-rules*)))) ;;(print *brace-depth* (make-string (max 0 *brace-depth*) #\ ) tok '*closer* *closer*) (cond ((eof-object? tok) (cond ((not (zero? *brace-depth*)) (tex:error '*brace-depth* 'not-zero *brace-depth*))) tok) ((not rul) (set! *previous-char* tok) (display tok *txi-output-port*) (if (not (char? tok)) (tex:warn tok 'unknown)) #t) (else (process-rule rul))))) (define (process-tex-input left) (do ((left (process-one left) (process-one left))) ((or (eqv? #f left) (eof-object? left)) left))) ;;;; Arguments to backslash commands (define (process-full-bracketed capture?) (if capture? (case (read-char *tex-input-port*) ((#\[) (call-with-output-string (lambda (oport) (fluid-let ((*closer* #\]) (*txi-output-port* oport) (*tex-rules* (append (rule #\] tex:close) (rule 'tt (lambda (cmd me) (fprintf *txi-output-port* "@t{") (process-tex-input #t) (fprintf *txi-output-port* "}") #f)) *tex-rules*))) (process-tex-input #t))))) (else (tex:error 'missing #\[))) (case (read-char *tex-input-port*) ((#\[) (fluid-let ((*closer* #\]) (*tex-rules* (append (rule #\] tex:close) (rule 'tt (lambda (cmd me) (fprintf *txi-output-port* "@t{") (process-tex-input #t) (fprintf *txi-output-port* "}") #f)) *tex-rules*))) (process-tex-input #t))) (else (tex:error 'missing #\[))))) (define (process-opt-arg cmd) (case cmd ((linebreak) (process-full-bracketed #t) #t) ((documentstyle documentclass) (let* ((optarg (process-full-bracketed #t)) (arg (capture-braced-expression))) (output-text-lines "\\input texinfo @c -*-texinfo-*-" "@c %**start of header") (fprintf *txi-output-port* "@setfilename %s\\n" (string-append *input-basename* ".info")) (fprintf *txi-output-port* "@settitle Revised(%c) Scheme\\n" (string-ref *input-basename* 1)))) ((topnewpage) (cond (*html* (fluid-let ((*tex-rules* (append (rule #\newline "") (rule '(begin-center end-center) "") (rule '(#\& bs-bs) "\\n@author ") (rule 'begin-tabular (lambda (cmd me) (capture-braced-expression) (fluid-let ((*closer* 'end-tabular) (*tex-rules* (append (rule 'end-tabular tex:close "" "") (rule '(#\& bs-bs) "\\n@author ") collapse-spaces *tex-rules*))) (process-tex-input #t) #t))) (rule 'multicolumn (lambda (cmd me . ruls) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (let* ((arg1 (capture-argument)) (arg2 (capture-braced-expression))) (fprintf *txi-output-port* "\\n@author ") (process-braced-expression)))) (rule #\newline "")) *tex-rules*))) (process-full-bracketed #f)) (fluid-let ((*tex-rules* (append (rule 'eject tex:close) *tex-rules*)) (*closer* 'eject)) (process-tex-input #\newline))) (else (fluid-let ((*tex-rules* (append (rule #\newline "") (rule '(begin-center end-center) "") (rule 'begin-tabular (lambda (cmd me) (define numcols (string-length (fluid-let ((*tex-rules* (append (rule #\@ "") (rule 'bs-bs "\\n" -1) *tex-rules*))) (capture-braced-expression)))) (fprintf *txi-output-port* "@c %s\\n" cmd) (fprintf *txi-output-port* "@quotation\\n") (fprintf *txi-output-port* "@multitable @columnfractions") (do ((i (+ -1 numcols) (+ -1 i))) ((negative? i)) (fprintf *txi-output-port* " %.2f" (/ numcols))) (fprintf *txi-output-port* "\\n@item ") (fluid-let ((*closer* 'end-tabular) (*tex-rules* (append (rule 'end-tabular tex:close "" "@end multitable" "@end quotation" "") (rule #\& "@tab ") (rule #\newline "") (rule 'bs-bs "\\n@item " -1) *tex-rules*))) (process-tex-input #t) #t))) *tex-rules*))) (process-full-bracketed #f)) (fluid-let ((*tex-rules* (append (rule 'eject tex:close) *tex-rules*)) (*closer* 'eject)) (process-tex-input #\newline))))) ((item) (fprintf *txi-output-port* "@item ") (process-full-bracketed #f) (cond ((not (eqv? #\newline (pc))) (tex:newline #f #f)))) (else (tex:error cmd 'does-not-take-optional-arguments))) #t) (define (capture-braced-expression) (call-with-output-string (lambda (oport) (fluid-let ((*txi-output-port* oport)) (process-braced-expression))))) (define (process-braced-expression) (case (pc) ((#\{) (read-char *tex-input-port*) (fluid-let ((*tex-rules* (append (rule #\} tex:close) *tex-rules*)) (*brace-depth* (+ 1 *brace-depth*)) (*closer* #\})) (process-tex-input #t) #t)) (else (tex:error 'process-braced-expression 'missing #\{)))) (define (capture-argument) (call-with-output-string (lambda (oport) (fluid-let ((*txi-output-port* oport)) (process-argument))))) (define (check-brace-depth! bd tok) (cond ((eqv? bd *brace-depth*)) (else (tex:warn (if (< *brace-depth* bd) 'brace-over-used-by 'brace-under-used-by) tok *brace-depth* 'not bd)))) ;;; Stub for top-level definition. (define (process-argument) (tex:error 'process-argument "called without setup-argument-processing")) ;;;; Backslash commands ;;; TeX is nasty in its treatment of curly braces: ;;; {\rm text} => (rm text) ;;; \rm{text} => (rm text) ;;; \rm{\var{proc}} => (rm (var proc)) ;;; \rm{\var proc} => (rm (var proc)) ;;; 1 pair: \foo{...} ;;; early-brace: {\foo ...} ;;; 2 pair: {\foo{...} ...} strip outer pair (define (read-bs-token) (define (char-alphabetic*? chr) (or (char-alphabetic? chr) (eqv? #\* chr))) (do ((chr (pc) (pc)) (lst '() (cons chr lst))) ((or (eof-object? chr) (not (char-alphabetic*? chr))) (let ((str (list->string (reverse lst)))) (if (equal? "" str) (tex:error 'null-bs-token) (string->symbol str)))) (read-char *tex-input-port*))) (define (read-bs-command early-brace?) (define bschr (pc)) (define processed-argument? #f) (cond ((char-alphabetic? bschr) (let* ((tok (read-bs-token)) (chr (pc))) (cond ((eqv? #\[ chr) (process-opt-arg tok)) (else (fluid-let ((process-argument (lambda () (set! processed-argument? #t) (let ((chr (pc)) (bd *brace-depth*)) (case chr ((#\{) (read-char *tex-input-port*) (fluid-let ((*brace-depth* (+ 1 bd)) ;(if early-brace? 2 1) (*tex-rules* (append (rule #\} tex:close) *tex-rules*)) (*closer* #\})) (process-tex-input #t) (check-brace-depth! bd tok) #f)) (else (do ((ch (pc) (pc))) ((not (char-whitespace? ch))) (read-char *tex-input-port*)) (if early-brace? (process-tex-input #t) (if (zero? bd) (fluid-let ((*tex-rules* (append (rule #\newline tex:close) *tex-rules*)) (*closer* #\newline)) (process-tex-input (if (eqv? #\newline chr) #\newline #t)) (check-brace-depth! bd tok) (set! processed-argument? #f) #\newline) (process-tex-input #t))))))))) (let ((ans (cond ((and early-brace? (not (eqv? chr #\{))) (fluid-let ((*tex-rules* (append (rule #\} tex:close) *tex-rules*)) (*brace-depth* (+ 1 *brace-depth*)) (*closer* #\})) (process-tex-input tok) #t)) ((and early-brace? (eqv? chr #\{)) (fluid-let ((*tex-rules* (append (rule #\} tex:close) *tex-rules*)) (*brace-depth* (+ 1 *brace-depth*)) (*closer* #\})) (process-tex-input tok) (process-tex-input #t) #t)) (else (process-one tok))))) ;;(print 'processed-argument? processed-argument? 'ans ans) (if processed-argument? (if (or (eqv? chr #\{) early-brace?) (if (eqv? ans #f) #t ans) #f) ans))))))) ((char-numeric? bschr) (tex:error 'bs-digit? bschr)) (else (case bschr ((#\/) (read-char *tex-input-port*) 'italic-space) ((#\=) (read-char *tex-input-port*) (set! *column* (+ -1 *column*)) (vector-set! tabs *tab-index* *column*) ;;(print '= *tab-index* *column*) (set! *tab-index* (+ 1 *tab-index*)) #t) ((#\>) (read-char *tex-input-port*) (set! *column* (+ -1 *column*)) ;;(print '> *tab-index* *column*) (space-to-tab-stop *tab-index*) #t) ((#\\) (read-char *tex-input-port*) (cond ((char-whitespace? (rc)) 'bs-bs) (else (tex:error 'non-whitespace 'after-bs-bs)))) ((#\ #\newline) (case *previous-char* ((#\.) (display "@:" *txi-output-port*))) (display (read-char *tex-input-port*) *txi-output-port*) #t) ((#\#) (read-char *tex-input-port*) (display #\#;;(if (member "scheme" *begin-stack*) #\# "@pounds{}") *txi-output-port*) #t) ((#\{ #\} #\-) (fprintf *txi-output-port* "@%c" (read-char *tex-input-port*)) #t) ((#\_ #\,) (read-char *tex-input-port*) (display #\ *txi-output-port*) #t) ((#\;) (rc) (display " " *txi-output-port*) #t) ((#\:) (rc) (set! *column* (+ 1 *column*)) (display "-->" *txi-output-port*) #t) ((#\` #\| #\' #\" #\$ #\& #\%) (display (read-char *tex-input-port*) *txi-output-port*) #t) (else (tex:warn (string #\\ (pc))) (display (read-char *tex-input-port*) *txi-output-port*) #t))))) (define (tex:input cmd me) (let ((name (capture-argument))) (case (string->symbol name) ((first) (output-text-lines "@c @include{first}" "@titlepage" "" "@c HTML first page" "@title Scheme") (fprintf *txi-output-port* "@subtitle Revised(%c) Report on the Algorithmic Language Scheme\\n" (string-ref *input-basename* 1)) (fluid-let ((vet-node-name #f) (*html* #t) (*tex-rules* (append (rule 'chapter* node 'unnumbered) (rule `huge (lambda (cmd me) (capture-argument) #f)) (rule (string->symbol "Huge") "") (rule 'vskip disappear) (rule '$$ "") *tex-rules*))) (process-rrrs-file name)) (output-text-lines "@end titlepage" "" "@c INFO first page" "@ifinfo" "") (fluid-let ((*tex-rules* (append (rule `huge node 'top collapse-spaces (rule '(bs-bs #\newline #\^ bf) "") (rule 'vskip (lambda (cmd me) (rl) #t))) (rule (string->symbol "Huge") "") (rule 'chapter* node 'majorheading) (rule 'tableofcontents (lambda (cmd me) (define nod (assoc "top" *previous-nodes*)) (output-text-lines "@unnumbered Contents") (and nod (emit-menu! nod)) #t)) *tex-rules*))) (process-rrrs-file name)) (output-text-lines "@end ifinfo" "")) ((commands) (fprintf (current-error-port) "...Skipping \"%s.tex\"\\n" name)) ((sem) (fprintf (current-error-port) "...Skipping \"%s.tex\"\\n" name) (emit-node! 'section "Formal semantics") (define-label "formalsemanticssection") (output-text-lines "" "" "This section provides a formal denotational semantics for the primitive" "expressions of Scheme and selected built-in procedures. The concepts" "and notation used here are described in @sc{[Stoy77]}." "" "@quotation" "@emph{Note:} The formal semantics section was written in La@TeX{} which" "is incompatible with @TeX{}info. See the Formal semantics section: " (sprintf #f "@url{http://swissnet.ai.mit.edu/~jaffer/%s-formal.pdf}" *input-basename*) "@end quotation" "" )) ((index) (output-text-lines "@ifinfo" "@unnumberedsec Concepts" "@end ifinfo" "@printindex cp" "@page" "@ifinfo" "@unnumberedsec Procedures" "@printindex fn" "@end ifinfo")) (else (fprintf *txi-output-port* "@c @include{%s}\\n" name) (process-rrrs-file name)))) #f) ;;;; Texinfo nodes (define *new-nodes* '()) (define *previous-nodes* '()) (define *node-stack* '()) (define (node-rank type) (case (if (symbol? type) type (string->symbol type)) ((top) 1) ((chapter unnumbered appendix) 3) ((majorheading chapheading) 4) ((section unnumberedsec appendixsec) 5) ((heading) 6) ((subsection unnumberedsubsec appendixsubsec) 7) ((subheading) 8) ((subsubsection unnumberedsubsubsec appendixsubsubsec) 9) ((subsubheading) 10) (else (tex:error 'unknown-node-type type)))) (define (find-previous-node name rank stack) (cond ((null? stack) "(dir)") ((= (cadar stack) rank) (if (caddar stack) (tex:error 'previous-already-set (car stack))) (set-car! (cddar stack) name) (caar stack)) ((< (cadar stack) rank) (cond ((equal? "top" (caar stack)) (set-car! (cddar stack) name))) (caar stack)) (else (find-previous-node name rank (cdr stack))))) (define (find-parent-node name rank stack) (cond ((null? stack) "(dir)") ((< (cadar stack) rank) (set-car! (last-pair (car stack)) (append (car (last-pair (car stack))) (list name))) (caar stack)) (else (find-parent-node name rank (cdr stack))))) (define (update-stack rank nod stack) (cond ((null? stack) (if (not (eqv? 1 rank)) (tex:error 'null-stack-with-non-zero-rank? rank nod)) (list nod)) ((< rank (cadar stack)) (update-stack rank nod (cdr stack))) (else (cons nod stack)))) (define (vet-node-name cmd name) (if (not (symbol? cmd)) (tex:error 'vet-node-name 'symbol? cmd)) (cond ((substring? "Appendix: " name) (set! name (substring name (+ (string-length "Appendix: ") (substring? "Appendix: " name)) (string-length name)))) ((substring? "index " name) (set! name "Index")) ((eq? 'top cmd) (newline *txi-output-port*) (set! *column* 0) (set! name "top"))) (cond ((not (assoc name *new-nodes*)) (let ((rank (node-rank cmd))) (if (odd? rank) (let ((nod (list name rank #f (find-previous-node name rank *node-stack*) (find-parent-node name rank *node-stack*) '()))) (set! *new-nodes* (cons nod *new-nodes*)) (set! *node-stack* (update-stack rank nod *node-stack*))))) name) ((eq? 'top cmd) (tex:error 'multiple-top-nodes? cmd name *name*)) ((eqv? #\s (string-ref name (+ -1 (string-length name)))) (vet-node-name cmd (substring name 0 (+ -1 (string-length name))))) (else (vet-node-name cmd (string-append name (if (eqv? #\ (string-ref name (+ -2 (string-length name)))) "I" " I")))))) (define (emit-node! cmd name) (set! *name* (if vet-node-name (vet-node-name cmd name) name)) (fprintf (current-error-port) " %s \"%s\"\\n" cmd *name*) (if vet-node-name (let ((nod (assoc *name* *previous-nodes*))) (cond ((not nod) (fprintf *txi-output-port* "@%s %s\\n" cmd name)) (else (fprintf *txi-output-port* "@node %s, %s, %s, %s\\n" *name* (or (caddr nod) " ") (or (cadddr nod) " ") (list-ref nod 4)) (fprintf *txi-output-port* "@%s %s\\n" cmd name) (cond ((and (not (eqv? 'top cmd)) (not (null? (list-ref nod 5)))) (emit-menu! nod)))))) (fprintf *txi-output-port* "@%s %s\\n" cmd name)) (set! *index-memory* '()) (if (not (eqv? 'top cmd)) (make-index-entry name "cindex @w{" "}"))) (define (emit-menu! nod) (fprintf *txi-output-port* "\\n@menu\\n") (for-each (lambda (menu-line) (fprintf *txi-output-port* "* %-30s\\n" (string-append menu-line ":: "))) (list-ref nod 5)) (fprintf *txi-output-port* "@end menu\\n")) (define (node cmd me alias . ruls) (define ans #f) (let ((name (call-with-output-string (lambda (oport) (fluid-let ((*txi-output-port* oport) (*tex-rules* (append (rule 'tt "") (rule #\, ";") (apply rules ruls) *tex-rules*))) (set! ans (process-argument))))))) (cond ((string-ci=? "Contents" name) ans) (else (emit-node! (or alias cmd) name) ans)))) (define setboxes (make-vector 10 "")) (define (setbox cmd me) (let* ((idx (string->number (string (read-char *tex-input-port*)))) (expn (call-with-output-string (lambda (oport) (fluid-let ((*txi-output-port* oport)) (process-one #t)))))) (vector-set! setboxes idx expn) #t)) (define (copy-box cmd me) (let* ((idx (string->number (string (read-char *tex-input-port*))))) (display (vector-ref setboxes idx) *txi-output-port*) #t)) ;;;; Rule functions (define (unmatched-close chr me) (tex:error 'unmatched chr)) (define (tex:close chr me . lines) (cond ((not (eqv? chr *closer*)) (tex:error 'close-mismatch chr 'should-be *closer*))) (case chr ((#\}) (set! *brace-depth* (+ -1 *brace-depth*)) (set! *column* (+ -1 *column*)))) (if (= 1 (length lines)) (fprintf *txi-output-port* (car lines)) (apply output-text-lines lines)) #f) (define (scheme-mode cmd me closer . ruls) (define post (cond (*entry-type* (fprintf *txi-output-port* "\\n@format\\n@t{") (case (pc) ((#\newline) (read-char *tex-input-port*) (set! *column* 0))) "}\\n@end format\\n") (else (fprintf *txi-output-port* "\\n@example\\n") "\\n@end example\\n"))) (if (member "itemize" *begin-stack*) (set-tabs! 5 35) (set-tabs! 10 40)) (fluid-let ((*closer* closer) (*tex-rules* (append (rule closer tex:close post) (apply rules ruls) *tex-rules*))) (process-tex-input #t)) (close-parens) #t) (define (commentize cmd me . ruls) (fprintf *txi-output-port* "@c \\\\%s%s\\n" cmd (rl)) #t) (define (continue-line chr me) (case (pc) ((#\newline) (rc) (do () ((not (or (eqv? (pc) #\ ) (eqv? (pc) slib:tab)))) (read-char *tex-input-port*))) (else (if (not (= 1 *column*)) (newline *txi-output-port*)) (fprintf *txi-output-port* "@c %s\\n" (rl)))) #t) (define (disappear cmd me . ruls) (rl) #\newline) (define (postfix cmd me suffix) (set! *column* (+ -1 *column*)) (let ((ans (process-argument))) (fprintf *txi-output-port* suffix) (set! *column* (+ *column* (string-length suffix))) ans)) (define (encapsulate from me to . ruls) (set! *column* (+ -1 *column*)) ;for \ already read. (fprintf *txi-output-port* "@%s{" to) (if (null? ruls) (let ((ans (process-argument))) (fprintf *txi-output-port* "}") ans) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (let ((ans (process-argument))) (fprintf *txi-output-port* "}") ans)))) (define (process-argument-with-rules cmd me . ruls) (define post #f) (cond ((and (not (null? ruls)) (not (list? (car ruls)))) (fprintf *txi-output-port* (car ruls)) (set! *column* (+ -1 *column*)) ;for \ already read. (bump-column (car ruls)) (set! ruls (cdr ruls)) (cond ((and (not (null? ruls)) (not (list? (car ruls)))) (set! post (car ruls)) (set! ruls (cdr ruls)))) (let ((ans (if (null? ruls) (process-argument) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (process-argument))))) (cond (post (fprintf *txi-output-port* post) (bump-column post))) ans)) ((null? ruls) (process-argument)) (else (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (process-argument))))) ;;;; The Rules (define collapse-spaces (rule (list slib:tab #\ ) (lambda (chr me) (display #\ *txi-output-port*) (do ((ch (pc) (pc))) ((not (or (eqv? ch #\ ) (eqv? ch slib:tab))) #t) (read-char *tex-input-port*))))) (define compress-top-level-spaces (rule (list slib:tab #\ ) (lambda (chr me) (cond ((zero? *paren-depth*) (display #\ *txi-output-port*) (do ((ch (pc) (pc))) ((not (or (eqv? ch #\ ) (eqv? ch slib:tab)))) (read-char *tex-input-port*))) ((eqv? slib:tab chr) (space-to-column (+ (- 8 (modulo *column* 8)) *column*))) (else (display chr *txi-output-port*))) #t))) (define *tex-rules* (rules (rule #\~ #\ ) (rule #\@ "@@" 1) (rule #\% (lambda (chr me) (let* ((col *column*) (line (rl))) (cond ((string-whitespace? line) (if (eqv? #\space *previous-char*) ;(= 1 col) #t #\newline)) (else (if (not (= 1 col)) (newline *txi-output-port*)) (fprintf *txi-output-port* "@c %s\\n" line) #t))))) (rule #\{ (lambda (chr me . ruls) (case (pc) ((#\}) (read-char *tex-input-port*) (set! *column* (+ -1 *column*)) #t) ((#\\) (read-char *tex-input-port*) (read-bs-command #t)) (else (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*)) (*brace-depth* (+ 1 *brace-depth*)) (*closer* #\})) (process-tex-input #t) #t)))) (rule #\} tex:close)) (rule #\} unmatched-close) (rule #\] unmatched-close) (rule #\\ (lambda (chr me) (read-bs-command #f))) (rule #\$ (lambda (chr me) (case (pc) ((#\$) (read-char *tex-input-port*) '$$) (else '$)))) (rule slib:tab (lambda (chr me) (set! *column* (+ -1 *column*)) (space-to-column (+ (- 8 (modulo *column* 8)) *column*)) #t)) (rule #\newline tex:newline) (rule '($ $$) (lambda (tok me . ruls) (fluid-let ((*tex-rules* (append (rule tok tex:close) (apply rules ruls) *tex-rules*)) (*closer* tok)) (case tok (($$) (fprintf *txi-output-port* "\\n\\n@center ") (process-tex-input #\newline) #\newline) (($) (process-tex-input #t) #t)))) (rule #\newline "") (rule 'sqrt "sqrt") (rule 'sin "sin") (rule 'cos "cos") (rule 'tan "tan") (rule 'log "log") (rule 'pi "pi") (rule 'over "/") (rule 'bf process-argument-with-rules "(" ")")) (rule 'char (lambda (cmd me) (let ((chr (read-char *tex-input-port*))) (display (escape-special (integer->char (case chr ((#\') (let* ((c1 (read-char *tex-input-port*)) (c2 (rc))) (string->number (string c1 c2) 8))) ((#\") (let* ((c1 (read-char *tex-input-port*)) (c2 (rc))) (string->number (string c1 c2) 16))) (else (tex:error 'char-argument-not-understood chr))))) *txi-output-port*) #t))) (rule 'multicolumn (lambda (cmd me . ruls) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (let* ((arg1 (capture-argument)) (arg2 (capture-braced-expression))) (fprintf *txi-output-port* "\\n@center ") (process-braced-expression)))) (rule #\newline "")) (rule 'begin-center (lambda (cmd me . ruls) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*)) (*closer* 'end-center)) (fprintf *txi-output-port* "\\n@center ") (process-tex-input #t) #\newline)) collapse-spaces (rule 'end-center tex:close) (rule #\newline "\\n@center ")) (rule 'extracolsep (lambda (cmd me) (capture-argument) #f)) (rule 'verb (lambda (cmd me) (let ((closer (read-char *tex-input-port*))) (do ((chr (rc) (read-char *tex-input-port*))) ((or (eqv? chr closer) (eof-object? chr)) #t) (display (escape-special chr) *txi-output-port*))))) ;; These commands translate simply. (rule (string->symbol "TeX") "@TeX{}" 3) (rule 'sharpfoo process-argument-with-rules "@t{#" "}") (rule 'cite process-argument-with-rules "[" "]" (rule #\, "], [")) (rule 'schfalse "@t{#f}" 2) (rule 'schtrue "@t{#t}" 2) (rule 'unspecified "@emph{unspecified}" 10) (rule 'scherror "@emph{error}" 5) (rule 'semantics "@emph{Semantics:}" 10) (rule 'syntax "@emph{Syntax:}" 7) (rule 'exprtype "syntax") (rule 'singlequote "@t{'}" 1) (rule 'backquote "@t{`}" 1) (rule 'backwhack "\\\\" 1) (rule 'atsign "@@" 1) (rule 'sharpsign "#") (rule 'prime "^") (rule '(dots dotsfoo) "@dots{}" 3) (rule 'makeindex "") ;;(rule 'ae "@ae{}" 2) (rule 'ae "ae" 2) (rule 'le "<=") (rule 'leq "<=") (rule 'neq "~=") (rule 'langle "<") (rule 'rangle ">") (rule 'cdot ".") (rule 'ldots "@dots{}" 3) (rule 'vdots "@dots{}" 3) ;;(rule 'ev "@result{}") (rule '(goesto evalsto) "@result{}" 3) ;;(rule 'lev "@expansion{}") ;never invoked! (rule 'break "@*") (rule '(hfil hfill vfill par nobreak qquad unsection footnotesize tableofcontents) "") ;; These come with {} after them. (rule (string->symbol "Lambdaexp") "lambda expression") (rule 'lambdaexp "lambda expression") (rule 'nopagebreak "") (rule 'doublequote "\"") (rule 'coerce "->") ;; These begin lines (rule '(newpage eject) "\\n@page\\n" -1) (rule 'medskip "@sp 3") (rule 'bigskip "@sp 6") (rule 'noindent "\\n@noindent\\n" -1) (rule 'item (lambda (cmd me) (case (pc) ((#\ ) (read-char *tex-input-port*) (fprintf *txi-output-port* "@item\\n") (set! *column* 0)) (else (fprintf *txi-output-port* "@item ") (set! *column* 3))) #t)) ;; These occur as {\tt ...} (rule 'tt encapsulate 't) (rule 'rm encapsulate 'r) (rule 'it encapsulate 'i) (rule 'itshape encapsulate 'i) (rule 'italic-space "") ;\/ (rule 'bf encapsulate 'b) (rule 'mathbf 'bf) (rule 'sc encapsulate 'sc) (rule 'authorsc encapsulate 'sc) (rule 'em encapsulate 'emph) (rule 'cf (lambda (cmd me) (define ans #f) (let ((arg (call-with-output-string (lambda (oport) (fluid-let ((*txi-output-port* oport)) (set! ans (process-argument))))))) (fprintf *txi-output-port* "@%s{%s}" (if (substring? "http://" arg) 'url 'samp) arg) ans))) (rule 'hbox (lambda (cmd me) (case (pc) ((#\ ) (do ((ch (pc) (pc))) ((eqv? #\\ ch)) (read-char *tex-input-port*)) (space-to-column (+ 7 *column*)))) (fprintf *txi-output-port* "@w{") (let ((ans (process-argument))) (fprintf *txi-output-port* "}") ans))) (rule 'wd (lambda (cmd me) (read-char *tex-input-port*) (space-to-column (+ 8 *column*)) #t)) ;; These occur as \vr{...} (rule 'vr encapsulate 'var) (rule 'var encapsulate 'var) (rule 'type encapsulate 'i) (rule 'tupe encapsulate 'r) ;;(rule 'meta encapsulate 'r) (rule 'meta process-argument-with-rules "<" ">") (rule 'displaystyle postfix "") (rule 'begin-scheme scheme-mode 'end-scheme ;;compress-top-level-spaces (rule 'sharpfoo process-argument-with-rules "#") (rule 'schtrue "#t") (rule 'schfalse "#f") (rule 'ev (lambda (cmd me) (close-parens) (space-to-tab-stop 1) (fprintf *txi-output-port* "==>") #t)) (rule 'lev (lambda (cmd me) (close-parens) (newline *txi-output-port*) (set! *column* 0) (space-to-tab-stop 0) (fprintf *txi-output-port* "==>") #t)) (rule #\# "#") (rule 'ide "")) (rule 'begin-schemenoindent ;used for example.tex and derive.tex scheme-mode 'end-schemenoindent (rule 'iet " == ") (rule 'schtrue "#t") (rule 'schfalse "#f") (rule 'hyper process-argument-with-rules "<" ">") (rule #\# "#")) (rule 'begin-grammar (lambda (cmd me . ruls) (set-tabs! 3 6) (fluid-let ((*closer* 'end-grammar) (*tex-rules* (append (apply rules ruls) *tex-rules*))) (fprintf *txi-output-port* "\\n@format\\n@t{") (process-tex-input #t)) #t) (rule 'end-grammar tex:close "}" "" "@end format" "") (rule 'sharpfoo process-argument-with-rules "#") (rule 'schtrue "#t") (rule 'schfalse "#f") (rule #\ (lambda (chr me) ;;(print 'space *column*) (set! *column* (+ -1 *column*)) (do ((col (+ 1 *column*)) (ch (pc) (pc))) ((not (or (eqv? ch #\ ) (eqv? ch slib:tab))) (case (pc) ((#\\) (rc) (case (pc) ((#\>) (read-bs-command #f)) (else (space-to-column (+ 1 col)) (read-bs-command #f)))) (else (space-to-column col) #t))) (case (read-char *tex-input-port*) ((#\ ) (set! col (+ 1 col))) (else (tex:warn 'saw-tab) (set! col (+ (- 8 (modulo col 8)) col))))))) (rule #\% continue-line) (rule #\# "#")) (rule '(begin-note begin-rationale) (lambda (cmd me) (fprintf *txi-output-port* "\\n@quotation\\n@emph{%s:}" (let ((str (symbol->string cmd))) (set! str (substring str 6 (string-length str))) (string-set! str 0 (char-upcase (string-ref str 0))) str)) #t)) (rule 'begin-tabbing "\\n@format") (rule 'bs-bs "\\n" -1) (rule 'end-tabbing "@end format\\n") (rule '(end-note end-rationale) "@end quotation\\n" -1) (rule 'begin-entry "") (rule 'end-entry (lambda (tok me) (fprintf *txi-output-port* "@end %s" *entry-type*) (set! *entry-type* #f) #t)) (rule 'unpenalty (lambda (tok me) (fprintf *txi-output-port* "\\n@end %s" *entry-type*) (set! *entry-type* #f) #t)) (rule 'begin-itemize (lambda (cmd me . ruls) (fluid-let ((*closer* 'end-itemize) (*tex-rules* (append (apply rules ruls) *tex-rules*))) (output-text-lines "" "" "@itemize @bullet") (process-tex-input #t) #t)) (rule #\newline (lambda (chr me) (newline *txi-output-port*) (set! *column* 0) (do ((col 0) (ch (pc) (pc))) ((not (or (eqv? ch #\ ) (eqv? ch slib:tab))) (case (pc) ((#\( #\)) (space-to-column col) #t) (else #t))) (case (read-char *tex-input-port*) ((#\ ) (set! col (+ 1 col))) (else (set! col (+ (- 8 (modulo col 8)) col))))))) (rule 'bs-bs "\\n@item " -1) (rule 'end-itemize tex:close "\\n@end itemize\\n")) (rule 'begin-description "\\n@table @t\\n" -1) (rule 'begin-tabular (lambda (cmd me) (define numcols (string-length (fluid-let ((*tex-rules* (append (rule #\@ "") (rule 'bs-bs "\\n" -1) *tex-rules*))) (capture-braced-expression)))) (fprintf *txi-output-port* "@c %s\\n" cmd) (fprintf *txi-output-port* "@quotation\\n@table @asis\\n@item ") (fluid-let ((*closer* 'end-tabular) (*tex-rules* (append (rule 'end-tabular tex:close "" "@end table" "@end quotation" "") (rule #\& "\\n") (rule #\newline "") (rule 'bs-bs "\\n@item " -1) *tex-rules*))) (process-tex-input #t) #t))) (rule 'end-description "@end table\\n" -1) (rule 'end-thebibliography "@end itemize\\n" -1) (rule 'begin-thebibliography (lambda (cmd me) (emit-node! 'unnumbered "Bibliography") (output-text-lines "" "" "@itemize @bullet") (fprintf *txi-output-port* "@c ") (fluid-let ((*tex-rules* (append (rule 'cite encapsulate 'cite) *tex-rules*))) (process-braced-expression) #\newline))) (rule 'begin-theindex (lambda (tok me) (fprintf (current-error-port) "...Indexing\\n") (emit-node! 'unnumbered "Alphabetic index of definitions of concepts, keywords, and procedures") #\newline)) (rule 'end-theindex "@ifinfo\\n@unnumberedsec References\\n@printindex pg\\n@end ifinfo\\n" ) (rule 'end-theindex (lambda (tok me) (output-text-lines "@ifinfo" "@unnumberedsec References" "@printindex pg" "@end ifinfo" "") #\newline)) (rule 'begin-document (lambda (tok me) (output-text-lines ;;"@setchapternewpage on" "@paragraphindent 0" "@c %**end of header" "@iftex" "@syncodeindex fn cp" "@syncodeindex vr cp" "@end iftex" "" "@ifinfo" "@dircategory The Algorithmic Language Scheme" "@direntry") (fprintf *txi-output-port* "* %s: (%s). The Revised(%c) Report on Scheme.\\n" (string-upcase *input-basename*) *input-basename* (string-ref *input-basename* 1)) (output-text-lines "@end direntry" "@end ifinfo") #t)) (rule 'end-document (lambda (tok me) (output-text-lines "@contents" "@bye") (cond ((not (null? *begin-stack*)) (tex:error '*begin-stack* 'not-empty *begin-stack*)) ((not (zero? *brace-depth*)) (tex:error '*brace-depth* 'not-zero *brace-depth*))) #f)) ;; \-commands which take arguments ;; but aren't simple substitutions. (rule 'vest (lambda (cmd me) (case (pc) ((#\ ) (read-char *tex-input-port*))) #t)) (rule 'begin (lambda (cmd me) (let* ((name (capture-argument)) (tok (string->symbol (string-append "begin-" name)))) (set! *begin-stack* (cons name *begin-stack*)) (cond ((assv tok *tex-rules*) tok) (else (tex:warn tok 'not-recognized) #f))))) (rule 'end (lambda (cmd me) (let* ((name (capture-argument)) (tok (string->symbol (string-append "end-" name)))) (cond ((null? *begin-stack*) (tex:error 'end name 'begin-stack-empty)) ((not (equal? name (car *begin-stack*))) (tex:error 'end name 'doesn't-match 'begin (car *begin-stack*))) (else (set! *begin-stack* (cdr *begin-stack*)))) (cond ((assv tok *tex-rules*) tok) (else (tex:warn tok 'not-recognized) #f))))) (rule 'arbno postfix "*") ;was "@r{*}" (rule 'atleastone postfix "+") ;was "@r{+}" (rule 'hyper process-argument-with-rules "@r{<" ">}") (rule '(todo nodomain) (lambda (cmd me . ruls) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (cond ((not (eqv? #\newline *previous-char*)) (tex:newline #f #f))) (fprintf *txi-output-port* "@ignore %s\\n" cmd) (process-argument) (fprintf *txi-output-port* "\\n@end ignore\\n") #t)) (rule #\[ "[") (rule #\] "]") (rule 'begin "\\begin") (rule 'end "\\end") (rule '(subsection subsection*) "")) (rule 'domain (lambda (cmd me) (process-argument) #t)) (rule 'vari process-argument-with-rules "@var{" "1}") (rule 'varii process-argument-with-rules "@var{" "2}") (rule 'variii process-argument-with-rules "@var{" "3}") ;;(rule 'variv process-argument-with-rules "@var{" "4}") (rule 'vri process-argument-with-rules "@var{" "1}") (rule 'vrii process-argument-with-rules "@var{" "2}") (rule 'vriii process-argument-with-rules "@var{" "3}") (rule 'vriv process-argument-with-rules "@var{" "4}") (rule 'hyperi process-argument-with-rules "@r{<" "1>}") (rule 'hyperii process-argument-with-rules "@r{<" "2>}") (rule 'hyperiii process-argument-with-rules "@r{<" "3>}") (rule 'hyperiv process-argument-with-rules "@r{<" "4>}") (rule 'hypern process-argument-with-rules "@r{<" "_n>}") (rule 'index rule:index "cindex @w{" "}") (rule 'mainindex rule:index "cindex @w{" "}") (rule 'mainschindex rule:index "cindex @w{" "}") (rule 'schindex rule:index "vindex " "") (rule 'sharpindex rule:index "vindex #" "") (rule 'ide (lambda (cmd me) (let ((name (capture-argument))) (fprintf *txi-output-port* "@code{%s}" name) (make-index-entry name "vindex @w{" "}")) #f)) (rule 'defining (lambda (cmd me) (let ((name (capture-argument))) (fprintf *txi-output-port* "@dfn{%s}" name) (make-index-entry name "cindex @w{" "}")) #f)) (rule 'bibitem (lambda (cmd me) (let ((name (capture-argument))) (fprintf *txi-output-port* "@item [%s]" name) (make-index-entry name "pindex " "")) #f)) (rule 'foo (lambda (cmd me) (let ((name (capture-argument))) (fprintf *txi-output-port* "@var{%s}, @var{%s1}, @dots{} @var{%sj}, @dots{}" name name name)) #f)) (rule 'clearextrapart node 'unnumbered) (rule 'extrapart node 'unnumbered) (rule 'subsection* node 'unnumberedsec) (rule '(chapter section subsection) node #f) (rule 'label (lambda (cmd me) (define-label (capture-argument)) #f)) (rule #\( (lambda (chr me) (set! *paren-depth* (+ 1 *paren-depth*)) (display chr *txi-output-port*) #t)) (rule #\) (lambda (chr me) (set! *paren-depth* (+ -1 *paren-depth*)) (display chr *txi-output-port*) #t)) (rule 'ref (lambda (cmd me) (let ((name (label->name (capture-argument)))) (cond ((positive? *paren-depth*) (fprintf *txi-output-port* "@pxref{%s}" name)) (else (fprintf *txi-output-port* "@ref{%s}" name))) #f))) (rule '(proto rproto) (lambda (cmd me . ruls) (let* ((proc (capture-argument)) (args (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (capture-braced-expression))) (type (capture-braced-expression))) (fprintf *txi-output-port* "@%s {%s} %s %s" (if *entry-type* "deffnx" "deffn") type proc args) (case cmd ((proto) (define-label proc))) (set! *entry-type* "deffn")) #f) (rule '(vari vri) postfix "1") (rule '(varii vrii) postfix "2") (rule '(variii vriii) postfix "3") (rule 'vriv postfix "4") (rule 'hyperi process-argument-with-rules "<" "1>") (rule 'hyperii process-argument-with-rules "<" "2>") (rule 'hyperiii process-argument-with-rules "<" "3>") (rule 'hyperiv process-argument-with-rules "<" "4>") (rule 'hypern process-argument-with-rules "<" "_n>")) (rule 'vproto (lambda (cmd me) (let* ((var (capture-argument)) (type (capture-braced-expression))) (fprintf *txi-output-port* "@%s {%s} %s" (if *entry-type* "defvrx" "defvr") type var) (define-label var) (set! *entry-type* "defvr")) #f)) (rule 'pproto ; like proto without args (lambda (cmd me . ruls) (fluid-let ((*tex-rules* (append (apply rules ruls) *tex-rules*))) (let* ((proc (capture-argument)) (type (capture-braced-expression))) (if *entry-type* (fprintf *txi-output-port* "\\n@deffnx {%s} %s" type proc) (fprintf *txi-output-port* "@deffn {%s} %s" type proc)) (extract-do-label proc) (set! *entry-type* "deffn") ;;(process-argument) #\newline ))) (rule 'tt "")) (rule 'obeyspaces process-argument-with-rules (rule '(bs-bs #\newline #\%) "") collapse-spaces) (rule 'vspace (lambda (cmd me) (let ((arg (capture-argument))) (set! arg (string->number (substring arg 0 (substring? "ex" arg)))) (fprintf *txi-output-port* "@sp %d" (abs arg)) #f))) (rule 'vskip (lambda (cmd me) (let* ((line (rl)) (linl (string-length line))) (do ((idx 0 (+ 1 idx))) ((or (eqv? idx linl) (not (char-whitespace? (string-ref line idx)))) (cond ((or (eqv? idx linl) (not (or (substring? "ex" line) (substring? "pt" line)))) (tex:error 'vskip-not-understood: line))) (set! line (substring line idx (or (substring? "ex" line) (substring? "pt" line)))))) (set! linl (string->number line)) (cond (linl (fprintf *txi-output-port* "\\n@sp %d\\n" (inexact->exact linl))) (else (tex:error 'vskip-number-not-understood: line)))) #\newline)) (rule 'input tex:input) (rule 'setbox setbox) (rule 'copy copy-box) ;; R5RS additional symbols. (rule 'integerversion "5") (rule 'callcc "@t{call-with-current-continuation}" 30) ;; \-commands{...} which turn into single-line comments. (rule '(newcommand pagestyle thispagestyle clearchapterstar topmargin headsep textheight textwidth columnsep columnseprule parskip parindent topsep oddsidemargin evensidemargin addvspace renewcommand tocshrink def showboxdepth) commentize (rule 'type "\\\\type" 5)) )) (define t (lambda args (apply tex->txi args) (newline))) '(begin (define r restart) (trace-all "rrrs2txi.scm") ;;(trace read-char char-whitespace?) (untrace rule rules read-bs-token string-whitespace? ;;process-tex-input tex:close process-one tex:warn tex:error tex:errwarn check-brace-depth!)) ;;(trace encapsulate process-one process-tex-input tex:close) (define go (let ((me (in-vicinity (program-vicinity) "rrrs2txi"))) (lambda () (do ((r 6 (+ -1 r)) (name "r6rs" (string-append "r" (number->string (+ -1 r)) "rs"))) ((or (< r 3) (file-exists? (string-append name ".tex"))) (cond ((< r 3) (do ((found? #f) (r 6 (+ -1 r)) (base "r6rs" (string-append "r" (number->string (+ -1 r)) "rs"))) ((< r 3) (if (not found?) (slib:error 'could-not-find "r?rs.tex")) #t) (let ((vic (sub-vicinity (user-vicinity) base))) (cond ((file-exists? (in-vicinity vic (string-append base ".tex"))) (set! found? #t) (load me) (cond ((tex->txi vic base) (txi->info (user-vicinity) base)) ((begin (load me) (tex->txi vic base)) (txi->info (user-vicinity) base)))))))) ((begin (load me) (tex->txi name)) (txi->info (user-vicinity) base)) ((begin (load me) (tex->txi name)) (txi->info (user-vicinity) base))))))))