This chapter describes Scheme's (rnrs base (6))library, which exports many of the procedure and syntax bindings that are traditionally associated with Scheme.
Section 11.20 defines the rules that identify tail calls and tail contexts in constructs from the (rnrs base (6)) library.
No object satisfies more than one of the following predicates:
boolean? pair?
symbol? number?
char? string?
vector? procedure?
null?
These predicates define the base types boolean, pair, symbol, number, char (or character), string, vector, and procedure. Moreover, the empty list is a special object of its own type.
Note that, although there is a separate boolean type, any Scheme value can be used as a boolean value for the purpose of a conditional test; see section 5.7.
Definitionsmay appear within a <toplevel body> (section 8.1), at the top of a <library body> (section 7.1), or at the top of a <body> (section 11.3).
A <definition> may be a variable definition (section 11.2.1) or keyword definition (section 11.2.1). Macro uses that expand into definitions or groups of definitions (packaged in a begin, letsyntax, or letrecsyntax form; see section 11.4.7) may also appear wherever other definitions may appear.
The define form described in this section is a <definition>used to create variable bindings and may appear anywhere other definitions may appear.
The first from of define binds <variable> to a new location before assigning the value of <expression> to it.
(define add3(lambda (x) (+ x 3)))
(add3 3) ⇒ 6
(define first car)
(first '(1 2)) ⇒ 1
The continuation of <expression> should not be invoked more than once.
Implementation responsibilities: Implementations should detect that the continuation of <expression> is invoked more than once. If the implementation detects this, it must raise an exception with condition type &assertion.
The second form of define is equivalent to
(define <variable> <unspecified>)where <unspecified> is a sideeffectfree expression returning an unspecified value.
In the third form of define, <formals> must be either a sequence of zero or more variables, or a sequence of one or more variables followed by a dot . and another variable (as in a lambda expression, see section 11.4.2). This form is equivalent to
(define <variable>(lambda (<formals>) <body>)).
In the fourth form of define, <formal> must be a single variable. This form is equivalent to
(define <variable>(lambda <formal> <body>)).
The definesyntax form described in this section is a <definition>used to create keyword bindings and may appear anywhere other definitions may appear.
Binds <keyword> to the value of <expression>, which must evaluate, at macroexpansion time, to a transformer. Macro transformers can be created using the syntaxrules and identifiersyntax forms described in section 11.19. See library section on “Transformers” for a more complete description of transformers.
Keyword bindings established by definesyntax are visible throughout the body in which they appear, except where shadowed by other bindings, and nowhere else, just like variable bindings established by define. All bindings established by a set of definitions, whether keyword or variable definitions, are visible within the definitions themselves.
Implementation responsibilities: The implementation should detect if the value of <expression> cannot possibly be a transformer.
Example:
(let ()
(define even?
(lambda (x)
(or (= x 0) (odd? ( x 1)))))
(definesyntax odd?
(syntaxrules ()
((odd? x) (not (even? x)))))
(even? 10)) ⇒ #t
An implication of the lefttoright processing order (section 10) is that one definition can affect whether a subsequent form is also a definition.
Example:
(let ()
(definesyntax bindtozero
(syntaxrules ()
((bindtozero id) (define id 0))))
(bindtozero x)
x) ⇒ 0
The behavior is unaffected by any binding for bindtozero that might appear outside of the let expression.
The <body> of a lambda, let, let*, letvalues, let*values, letrec, or letrec* expression, or that of a definition with a body consists of zero or more definitions followed by one or more expressions.
<definition> ... <expression_{1}> <expression_{2}> ...
Each identifier defined by a definition is local to the <body>. That is, the identifier is bound, and the region of the binding is the entire <body> (see section 5.2).
Example:
(let ((x 5))(define foo (lambda (y) (bar x y)))
(define bar (lambda (a b) (+ (* a b) a)))
(foo (+ x 3))) ⇒ 45
When begin, letsyntax, or letrecsyntax forms occur in a body prior to the first expression, they are spliced into the body; see section 11.4.7. Some or all of the body, including portions wrapped in begin, letsyntax, or letrecsyntax forms, may be specified by a macro use (see section 9.2).
An expanded <body> (see chapter 10) containing variable definitions can always be converted into an equivalent letrec* expression. For example, the let expression in the above example is equivalent to
(let ((x 5))
(letrec* ((foo (lambda (y) (bar x y)))
(bar (lambda (a b) (+ (* a b) a))))
(foo (+ x 3))))
The entries in this section describe the expressions of the (rnrs base (6)) library, which may occur in the position of the <expression> syntactic variable in addition to the primitive expression types as described in section 9.1.
Syntax: <Datum> should be a syntactic datum.
Semantics: (quote <datum>) evaluates to the datum value represented by <datum> (see section 4.3). This notation is used to include constants.
(quote a) ⇒ a
(quote #(a b c)) ⇒ #(a b c)
(quote (+ 1 2)) ⇒ (+ 1 2)
As noted in section 4.3.5, (quote <datum>) may be abbreviated as '<datum>:
'"abc" ⇒ "abc"
'145932 ⇒ 145932
'a ⇒ a
'#(a b c) ⇒ #(a b c)
'() ⇒ ()
'(+ 1 2) ⇒ (+ 1 2)
'(quote a) ⇒ (quote a)
''a ⇒ (quote a)
As noted in section 5.10, constants are immutable.
Note: Different constants that are the value of a quote expression may share the same locations.
Syntax: <Formals> must be a formal parameter list as described below, and <body> must be as described in section 11.3.
Semantics: A lambda expression evaluates to a procedure. The environment in effect when the lambda expression is evaluated is remembered as part of the procedure. When the procedure is later called with some arguments, the environment in which the lambda expression was evaluated is extended by binding the variables in the parameter list to fresh locations, and the resulting argument values are stored in those locations. Then, the expressions in the body of the lambda expression (which may contain definitions and thus represent a letrec* form, see section 11.3) are evaluated sequentially in the extended environment. The results of the last expression in the body are returned as the results of the procedure call.
(lambda (x) (+ x x)) ⇒ a procedure
((lambda (x) (+ x x)) 4) ⇒ 8
((lambda (x)
(define (p y)
(+ y 1))
(+ (p x) x))
5) ⇒ 11
(define reversesubtract
(lambda (x y) ( y x)))
(reversesubtract 7 10) ⇒ 3
(define add4
(let ((x 4))
(lambda (y) (+ x y))))
(add4 6) ⇒ 10
<Formals> must have one of the following forms:
(<variable_{1}> ...): The procedure takes a fixed number of arguments; when the procedure is called, the arguments are stored in the bindings of the corresponding variables.
<variable>: The procedure takes any number of arguments; when the procedure is called, the sequence of arguments is converted into a newly allocated list, and the list is stored in the binding of the <variable>.
(<variable_{1}> ... <variable_{n}> . <variable_{n+1}>): If a period . precedes the last variable, then the procedure takes n or more arguments, where n is the number of parameters before the period (there must be at least one). The value stored in the binding of the last variable is a newly allocated list of the arguments left over after all the other arguments have been matched up against the other parameters.
((lambda x x) 3 4 5 6) ⇒ (3 4 5 6)
((lambda (x y . z) z)
3 4 5 6) ⇒ (5 6)
Any <variable> must not appear more than once in <formals>.
Syntax: <Test>, <consequent>, and <alternate> must be expressions.
Semantics: An if expression is evaluated as follows: first, <test> is evaluated. If it yields a true value(see section 5.7), then <consequent> is evaluated and its values are returned. Otherwise <alternate> is evaluated and its values are returned. If <test> yields #f and no <alternate> is specified, then the result of the expression is unspecified.
(if (> 3 2) 'yes 'no) ⇒ yes
(if (> 2 3) 'yes 'no) ⇒ no
(if (> 3 2)
( 3 2)
(+ 3 2)) ⇒ 1
(if #f #f) ⇒ unspecified
The <consequent> and <alternate> expressions are in tail context if the if expression itself is; see section 11.20.
<Expression> is evaluated, and the resulting value is stored in the location to which <variable> is bound. <Variable> must be bound either in some regionenclosing the set! expression or at the top level. The result of the set! expression is unspecified.
(let ((x 2))
(+ x 1)
(set! x 4)
(+ x 1)) ⇒ 5
It is a syntax violation if <variable> refers to an immutable binding.
Note: The identifier set! is exported with level 1 as well. See section 11.19.
Syntax: Each <cond clause> must be of the form
(<test> <expression_{1}> ...)where <test> is an expression. Alternatively, a <cond clause> may be of the form
(<test> => <expression>)The last <cond clause> may be an “else clause”, which has the form
(else <expression_{1}> <expression_{2}> ...).
Semantics: A cond expression is evaluated by evaluating the <test> expressions of successive <cond clause>s in order until one of them evaluates to a true value(see section 5.7). When a <test> evaluates to a true value, then the remaining <expression>s in its <cond clause> are evaluated in order, and the results of the last <expression> in the <cond clause> are returned as the results of the entire cond expression. If the selected <cond clause> contains only the <test> and no <expression>s, then the value of the <test> is returned as the result. If the selected <cond clause> uses the => alternate form, then the <expression> is evaluated. Its value must be a procedure. This procedure should accept one argument; it is called on the value of the <test> and the values returned by this procedure are returned by the cond expression. If all <test>s evaluate to #f, and there is no else clause, then the conditional expression returns unspecified values; if there is an else clause, then its <expression>s are evaluated, and the values of the last one are returned.
(cond ((> 3 2) 'greater)
((< 3 2) 'less)) ⇒ greater
(cond ((> 3 3) 'greater)
((< 3 3) 'less)
(else 'equal)) ⇒ equal
(cond ('(1 2 3) => cadr)
(else #f)) ⇒ 2
For a <cond clause> of one of the following forms
(<test> <expression_{1}> ...)(else <expression_{1}> <expression_{2}> ...)
the last <expression> is in tail context if the cond form itself is. For a <cond clause> of the form
(<test> => <expression>)the (implied) call to the procedure that results from the evaluation of <expression> is in a tail context if the cond form itself is. See section 11.20.
A sample definition of cond in terms of simpler forms is in appendix B.
Syntax: <Key> must be an expression. Each <case clause> must have one of the following forms:
((<datum_{1}> ...) <expression_{1}> <expression_{2}> ...)(else <expression_{1}> <expression_{2}> ...)
The second form, which specifies an “else clause”, may only appear as the last <case clause>. Each <datum> is an external representation of some object. The data represented by the <datum>s need not be distinct.
Semantics: A case expression is evaluated as follows. <Key> is evaluated and its result is compared using eqv? (see section 11.5) against the data represented by the <datum>s of each <case clause> in turn, proceeding in order from left to right through the set of clauses. If the result of evaluating <key> is equivalent to a datum of a <case clause>, the corresponding <expression>s are evaluated from left to right and the results of the last expression in the <case clause> are returned as the results of the case expression. Otherwise, the comparison process continues. If the result of evaluating <key> is different from every datum in each set, then if there is an else clause its expressions are evaluated and the results of the last are the results of the case expression; otherwise the case expression returns unspecified values.
(case (* 2 3)
((2 3 5 7) 'prime)
((1 4 6 8 9) 'composite)) ⇒ composite
(case (car '(c d))
((a) 'a)
((b) 'b)) ⇒ unspecified
(case (car '(c d))
((a e i o u) 'vowel)
((w y) 'semivowel)
(else 'consonant)) ⇒ consonant
The last <expression> of a <case clause> is in tail context if the case expression itself is; see section 11.20.
Syntax: The <test>s must be expressions.
Semantics: If there are no <test>s, #t is returned. Otherwise, the <test> expressions are evaluated from left to right until a <test> returns #f or the last <test> is reached. In the former case, the and expression returns #f without evaluating the remaining expressions. In the latter case, the last expression is evaluated and its values are returned.
(and (= 2 2) (> 2 1)) ⇒ #t
(and (= 2 2) (< 2 1)) ⇒ #f
(and 1 2 'c '(f g)) ⇒ (f g)
(and) ⇒ #t
The and keyword could be defined in terms of if using syntaxrules (see section 11.19) as follows:
(definesyntax and
(syntaxrules ()
((and) #t)
((and test) test)
((and test1 test2 ...)
(if test1 (and test2 ...) #f))))
The last <test> expression is in tail context if the and expression itself is; see section 11.20.
Syntax: The <test>s must be expressions.
Semantics: If there are no <test>s, #f is returned. Otherwise, the <test> expressions are evaluated from left to right until a <test> returns a true value val (see section 5.7) or the last <test> is reached. In the former case, the or expression returns val without evaluating the remaining expressions. In the latter case, the last expression is evaluated and its values are returned.
(or (= 2 2) (> 2 1)) ⇒ #t
(or (= 2 2) (< 2 1)) ⇒ #t
(or #f #f #f) ⇒ #f
(or '(b c) (/ 3 0)) ⇒ (b c)
The or keyword could be defined in terms of if using syntaxrules (see section 11.19) as follows:
(definesyntax or
(syntaxrules ()
((or) #f)
((or test) test)
((or test1 test2 ...)
(let ((x test1))
(if x x (or test2 ...))))))
The last <test> expression is in tail context if the or expression itself is; see section 11.20.
The binding constructs described in this section create local bindings for variables that are visible only in a delimited region. The syntax of the constructs let, let*, letrec, and letrec* is identical, but they differ in the regions(see section 5.2) they establish for their variable bindings and in the order in which the values for the bindings are computed. In a let expression, the initial values are computed before any of the variables become bound; in a let* expression, the bindings and evaluations are performed sequentially. In a letrec or letrec* expression, all the bindings are in effect while their initial values are being computed, thus allowing mutually recursive definitions. In a letrec expression, the initial values are computed before being assigned to the variables; in a letrec*, the evaluations and assignments are performed sequentially.
In addition, the binding constructs letvalues and let*values generalize let and let* to allow multiple variables to be bound to the results of expressions that evaluate to multiple values. They are analogous to let and let* in the way they establish regions: in a letvalues expression, the initial values are computed before any of the variables become bound; in a let*values expression, the bindings are performed sequentially.
Sample definitions of all the binding forms of this section in terms of simpler forms are in appendix B.
Syntax: <Bindings> must have the form
((<variable_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3. Any variable must not appear more than once in the <variable>s.
Semantics: The <init>s are evaluated in the current environment (in some unspecified order), the <variable>s are bound to fresh locations holding the results, the <body> is evaluated in the extended environment, and the values of the last expression of <body> are returned. Each binding of a <variable> has <body> as its region.
(let ((x 2) (y 3))
(* x y)) ⇒ 6
(let ((x 2) (y 3))
(let ((x 7)
(z (+ x y)))
(* z x))) ⇒ 35
See also named let, section 11.16.
Syntax: <Bindings> must have the form
((<variable_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3.
Semantics: The let* form is similar to let, but the <init>s are evaluated and bindings created sequentially from left to right, with the regionof each binding including the bindings to its right as well as <body>. Thus the second <init> is evaluated in an environment in which the first binding is visible and initialized, and so on.
(let ((x 2) (y 3))
(let* ((x 7)
(z (+ x y)))
(* z x))) ⇒ 70
Note: While the variables bound by a let expression must be distinct, the variables bound by a let* expression need not be distinct.
Syntax: <Bindings> must have the form
((<variable_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3. Any variable must not appear more than once in the <variable>s.
Semantics: The <variable>s are bound to fresh locations, the <init>s are evaluated in the resulting environment (in some unspecified order), each <variable> is assigned to the result of the corresponding <init>, the <body> is evaluated in the resulting environment, and the values of the last expression in <body> are returned. Each binding of a <variable> has the entire letrec expression as its region, making it possible to define mutually recursive procedures.
(letrec ((even?
(lambda (n)
(if (zero? n)
#t
(odd? ( n 1)))))
(odd?
(lambda (n)
(if (zero? n)
#f
(even? ( n 1))))))
(even? 88))
⇒ #t
It should be possible to evaluate each <init> without assigning or referring to the value of any <variable>. In the most common uses of letrec, all the <init>s are lambda expressions and the restriction is satisfied automatically. Another restriction is that the continuation of each <init> should not be invoked more than once.
Implementation responsibilities: Implementations must detect references to a <variable> during the evaluation of the <init> expressions (using one particular evaluation order and order of evaluating the <init> expressions). If an implementation detects such a violation of the restriction, it must raise an exception with condition type &assertion. Implementations may or may not detect that the continuation of each <init> is invoked more than once. However, if the implementation detects this, it must raise an exception with condition type &assertion.
Syntax: <Bindings> must have the form
((<variable_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3. Any variable must not appear more than once in the <variable>s.
Semantics: The <variable>s are bound to fresh locations, each <variable> is assigned in lefttoright order to the result of evaluating the corresponding <init>, the <body> is evaluated in the resulting environment, and the values of the last expression in <body> are returned. Despite the lefttoright evaluation and assignment order, each binding of a <variable> has the entire letrec* expression as its region, making it possible to define mutually recursive procedures.
(letrec* ((p
(lambda (x)
(+ 1 (q ( x 1)))))
(q
(lambda (y)
(if (zero? y)
0
(+ 1 (p ( y 1))))))
(x (p 5))
(y x))
y)
⇒ 5
It must be possible to evaluate each <init> without assigning or referring to the value of the corresponding <variable> or the <variable> of any of the bindings that follow it in <bindings>. Another restriction is that the continuation of each <init> should not be invoked more than once.
Implementation responsibilities: Implementations must, during the evaluation of an <init> expression, detect references to the value of the corresponding <variable> or the <variable> of any of the bindings that follow it in <bindings>. If an implementation detects such a violation of the restriction, it must raise an exception with condition type &assertion. Implementations may or may not detect that the continuation of each <init> is invoked more than once. However, if the implementation detects this, it must raise an exception with condition type &assertion.
Syntax: <Mvbindings> must have the form
((<formals_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3. Any variable must not appear more than once in the set of <formals>.
Semantics: The <init>s are evaluated in the current environment (in some unspecified order), and the variables occurring in the <formals> are bound to fresh locations containing the values returned by the <init>s, where the <formals> are matched to the return values in the same way that the <formals> in a lambda expression are matched to the arguments in a procedure call. Then, the <body> is evaluated in the extended environment, and the values of the last expression of <body> are returned. Each binding of a variable has <body> as its region.If the <formals> do not match, an exception with condition type &assertion is raised.
(letvalues (((a b) (values 1 2))
((c d) (values 3 4)))
(list a b c d)) ⇒ (1 2 3 4)
(letvalues (((a b . c) (values 1 2 3 4)))
(list a b c)) ⇒ (1 2 (3 4))
(let ((a 'a) (b 'b) (x 'x) (y 'y))
(letvalues (((a b) (values x y))
((x y) (values a b)))
(list a b x y))) ⇒ (x y a b)
Syntax: <Mvbindings> must have the form
((<formals_{1}> <init_{1}>) ...),where each <init> is an expression, and <body> is as described in section 11.3. In each <formals>, any variable must not appear more than once.
Semantics: The let*values form is similar to letvalues, but the <init>s are evaluated and bindings created sequentially from left to right, with the regionof the bindings of each <formals> including the bindings to its right as well as <body>. Thus the second <init> is evaluated in an environment in which the bindings of the first <formals> is visible and initialized, and so on.
(let ((a 'a) (b 'b) (x 'x) (y 'y))
(let*values (((a b) (values x y))
((x y) (values a b)))
(list a b x y))) ⇒ (x y x y)
Note: While all of the variables bound by a letvalues expression must be distinct, the variables bound by different <formals> of a let*values expression need not be distinct.
The <begin> keyword has two different roles, depending on its context:
It may appear as a form in a <body> (see section 11.3), <library body> (see section 7.1), or <toplevel body> (see chapter 8), or directly nested in a begin form that appears in a body. In this case, the begin form must have the shape specified in the first header line. This use of begin acts as a splicing form—the forms inside the <body> are spliced into the surrounding body, as if the begin wrapper were not actually present.
A begin form in a <body> or <library body> must be nonempty if it appears after the first <expression> within the body.
It may appear as an ordinary expression and must have the shape specified in the second header line. In this case, the <expression>s are evaluated sequentially from left to right, and the values of the last <expression> are returned. This expression type is used to sequence side effects such as assignments or input and output.
(define x 0)
(begin (set! x 5)
(+ x 1)) ⇒ 6
(begin (display "4 plus 1 equals ")
(display (+ 4 1))) ⇒ unspecified
and prints 4 plus 1 equals 5
A predicate is a procedure that always returns a boolean value (#t or #f). An 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, eq? is the finest or most discriminating, and equal? is the coarsest. The eqv? predicate is slightly less discriminating than eq?.
The eqv? procedure defines a useful equivalence relation on objects. Briefly, it returns #t if obj_{1} and obj_{2} should normally be regarded as the same object and #f otherwise. This relation is left slightly open to interpretation, but the following partial specification of eqv? must hold for all implementations.
The eqv? procedure returns #t if one of the following holds:
Obj_{1} and obj_{2} are both booleans and are the same according to the boolean=? procedure (section 11.8).
Obj_{1} and obj_{2} are both symbols and are the same according to the symbol=? procedure (section 11.10).
Obj_{1} and obj_{2} are both exactnumber objects and are numerically equal (see =, section 11.7).
Obj_{1} and obj_{2} are both inexactnumber objects, are numerically equal (see =, section 11.7), and yield the same results (in the sense of eqv?) when passed as arguments to any other procedure that can be defined as a finite composition of Scheme's standard arithmetic procedures.
Obj_{1} and obj_{2} are both characters and are the same character according to the char=? procedure (section 11.11).
Both obj_{1} and obj_{2} are the empty list.
Obj_{1} and obj_{2} are objects such as pairs, vectors, bytevectors (library chapter on “Bytevectors”), strings, hashtables, records (library chapter on “Records”), ports (library section on “Port I/O”), or hashtables (library chapter on “Hash tables”) that refer to the same locations in the store (section 5.10).
Obj_{1} and obj_{2} are recordtype descriptors that are specified to be eqv? in library section on “Procedural layer”.
The eqv? procedure returns #f if one of the following holds:
Obj_{1} and obj_{2} are of different types (section 11.1).
Obj_{1} and obj_{2} are booleans for which the boolean=? procedure returns #f.
Obj_{1} and obj_{2} are symbols for which the symbol=? procedure returns #f.
One of obj_{1} and obj_{2} is an exact number object but the other is an inexact number object.
Obj_{1} and obj_{2} are rational number objects for which the = procedure returns #f.
Obj_{1} and obj_{2} yield different results (in the sense of eqv?) when passed as arguments to any other procedure that can be defined as a finite composition of Scheme's standard arithmetic procedures.
Obj_{1} and obj_{2} are characters for which the char=? procedure returns #f.
One of obj_{1} and obj_{2} is the empty list, but the other is not.
Obj_{1} and obj_{2} are objects such as pairs, vectors, bytevectors (library chapter on “Bytevectors”), strings, records (library chapter on “Records”), ports (library section on “Port I/O”), or hashtables (library chapter on “Hashtables”) that refer to distinct locations.
Obj_{1} and obj_{2} are pairs, vectors, strings, or records, or hashtables, where the applying the same accessor (i.e. car, cdr, vectorref, stringref, or record accessors) to both yields results for which eqv? returns #f.
Obj_{1} and obj_{2} are procedures that would behave differently (return different values or have different side effects) for some arguments.
Note: The eqv? procedure returning #t when obj_{1} and obj_{2} are number objects does not imply that = would also return #t when called with obj_{1} and obj_{2} as arguments.
(eqv? 'a 'a) ⇒ #t
(eqv? 'a 'b) ⇒ #f
(eqv? 2 2) ⇒ #t
(eqv? '() '()) ⇒ #t
(eqv? 100000000 100000000) ⇒ #t
(eqv? (cons 1 2) (cons 1 2)) ⇒ #f
(eqv? (lambda () 1)
(lambda () 2)) ⇒ #f
(eqv? #f 'nil) ⇒ #f
The following examples illustrate cases in which the above rules do not fully specify the behavior of eqv?. All that can be said about such cases is that the value returned by eqv? must be a boolean.
(let ((p (lambda (x) x)))
(eqv? p p)) ⇒ unspecified
(eqv? "" "") ⇒ unspecified
(eqv? '#() '#()) ⇒ unspecified
(eqv? (lambda (x) x)
(lambda (x) x)) ⇒ unspecified
(eqv? (lambda (x) x)
(lambda (y) y)) ⇒ unspecified
(eqv? +nan.0 +nan.0) ⇒ unspecified
The next set of examples shows the use of eqv? with procedures that have local state. Calls to gencounter must return a distinct procedure every time, since each procedure has its own internal counter. Calls to genloser return procedures that behave equivalently when called. However, eqv? may not detect this equivalence.
(define gencounter
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) n))))
(let ((g (gencounter)))
(eqv? g g)) ⇒ unspecified
(eqv? (gencounter) (gencounter))
⇒ #f
(define genloser
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) 27))))
(let ((g (genloser)))
(eqv? g g)) ⇒ unspecified
(eqv? (genloser) (genloser))
⇒ unspecified
(letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
(g (lambda () (if (eqv? f g) 'both 'g))))
(eqv? f g)) ⇒ unspecified
(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
(g (lambda () (if (eqv? f g) 'g 'both))))
(eqv? f g)) ⇒ #f
Implementations may share structure between constants where appropriate. Furthermore, a constant may be copied at any time by the implementation so as to exist simultaneously in different sets of locations, as noted in section 11.4.1. Thus the value of eqv? on constants is sometimes implementationdependent.
(eqv? '(a) '(a)) ⇒ unspecified
(eqv? "a" "a") ⇒ unspecified
(eqv? '(b) (cdr '(a b))) ⇒ unspecified
(let ((x '(a)))
(eqv? x x)) ⇒ #t
The eq? predicate is similar to eqv? except that in some cases it is capable of discerning distinctions finer than those detectable by eqv?.
The eq? and eqv? predicates are guaranteed to have the same behavior on symbols, booleans, the empty list, pairs, procedures, nonempty strings, bytevectors, and vectors, and records. The behavior of eq? on number objects and characters is implementationdependent, but it always returns either #t or #f, and returns #t only when eqv? would also return #t. The eq? predicate may also behave differently from eqv? on empty vectors, empty bytevectors, and empty strings.
(eq? 'a 'a) ⇒ #t
(eq? '(a) '(a)) ⇒ unspecified
(eq? (list 'a) (list 'a)) ⇒ #f
(eq? "a" "a") ⇒ unspecified
(eq? "" "") ⇒ unspecified
(eq? '() '()) ⇒ #t
(eq? 2 2) ⇒ unspecified
(eq? #\A #\A) ⇒ unspecified
(eq? car car) ⇒ #t
(let ((n (+ 2 3)))
(eq? n n)) ⇒ unspecified
(let ((x '(a)))
(eq? x x)) ⇒ #t
(let ((x '#()))
(eq? x x)) ⇒ unspecified
(let ((p (lambda (x) x)))
(eq? p p)) ⇒ unspecified
The equal? predicate returns #t if and only if the (possibly infinite) unfoldings of its arguments into regular trees are equal as ordered trees.
The equal? predicate treats pairs and vectors as nodes with outgoing edges, uses string=? to compare strings, uses bytevector=? to compare bytevectors (see library chapter on “Bytevectors”), and uses eqv? to compare other nodes.
(equal? 'a 'a) ⇒ #t
(equal? '(a) '(a)) ⇒ #t
(equal? '(a (b) c)
'(a (b) c)) ⇒ #t
(equal? "abc" "abc") ⇒ #t
(equal? 2 2) ⇒ #t
(equal? (makevector 5 'a)
(makevector 5 'a)) ⇒ #t
(equal? '#vu8(1 2 3 4 5)
(u8list>bytevector
'(1 2 3 4 5)) ⇒ #t
(equal? (lambda (x) x)
(lambda (y) y)) ⇒ unspecified
(let* ((x (list 'a))
(y (list 'a))
(z (list x y)))
(list (equal? z (list y x))
(equal? z (list x x))))
⇒ (#t #t)
Note: The equal? procedure must always terminate, even if its arguments contain cycles.
Returns #t if obj is a procedure, otherwise returns #f.
(procedure? car) ⇒ #t
(procedure? 'car) ⇒ #f
(procedure? (lambda (x) (* x x)))
⇒ #t
(procedure? '(lambda (x) (* x x)))
⇒ #f
The procedures described here implement arithmetic that is generic over the numerical tower described in chapter 3. The generic procedures described in this section accept both exact and inexact number objects as arguments, performing coercions and selecting the appropriate operations as determined by the numeric subtypes of their arguments.
Library chapter on “Arithmetic” describes libraries that define other numerical procedures.
The procedures listed below must return the mathematically correct exact result provided all their arguments are exact:
+  *
max min abs
numerator denominator gcd
lcm floor ceiling
truncate round rationalize
realpart imagpart makerectangular
The procedures listed below must return the correct exact result provided all their arguments are exact, and no divisors are zero:
/
div mod divandmod
div0 mod0 div0andmod0
Moreover, the procedure expt must return the correct exact result provided its first argument is an exact real number object and its second argument is an exact integer object.
The general rule is that the generic operations return the correct exact result when all of their arguments are exact and the result is mathematically welldefined, but return an inexact result when any argument is inexact. Exceptions to this rule include sqrt, exp, log, sin, cos, tan, asin, acos, atan, expt, makepolar, magnitude, and angle, which may (but are not required to) return inexact results even when given exact arguments, as indicated in the specification of these procedures.
One general exception to the rule above is that an implementation may return an exact result despite inexact arguments if that exact result would be the correct result for all possible substitutions of exact arguments for the inexact ones. An example is (* 1.0 0) which may return either 0 (exact) or 0.0 (inexact).
The specification of the numerical operations is written as though infinities and NaNs are representable, and specifies many operations with respect to these number objects in ways that are consistent with the IEEE754 standard for binary floatingpoint arithmetic. An implementation of Scheme may or may not represent infinities and NaNs; however, an implementation must raise a continuable exception with condition type &noinfinities or &nonans (respectively; see library section on “Flonums”) whenever it is unable to represent an infinity or NaN as specified. In this case, the continuation of the exception handler is the continuation that otherwise would have received the infinity or NaN value. This requirement also applies to conversions between number objects and external representations, including the reading of program source code.
Some operations are the semantic basis for several arithmetic procedures. The behavior of these operations is described in this section for later reference.
Scheme's operations for performing integer division rely on mathematical operations div, mod, div_{0}, and mod_{0}, that are defined as follows:
div, mod, div_{0}, and mod_{0} each accept two real numbers x_{1} and x_{2} as operands, where x_{2} must be nonzero.
div returns an integer, and mod returns a real. Their results are specified by
x_{1} 
 x_{2}  =  n_{d}  
x_{1} 
 x_{2}  =  x_{m} 
* where
Examples:
123 
 10  =  12  
123 
 10  =  3  
123 

 =  −12  
123 

 =  3  
−123 
 10  =  −13  
−123 
 10  =  7  
−123 

 =  13  
−123 

 =  7 
* div_{0} and mod_{0} are like div and mod, except the result of mod_{0} lies within a halfopen interval centered on zero. The results are specified by
x_{1} 
 _{0} x_{2}  =  n_{d}  
x_{1} 
 _{0} x_{2}  =  x_{m} 
* where:
Examples:
123 
 _{0} 10  =  12  
123 
 _{0} 10  =  3  
123 
 _{0} 
 =  −12  
123 
 _{0} 
 =  3  
−123 
 _{0} 10  =  −12  
−123 
 _{0} 10  =  −3  
−123 
 _{0} 
 =  12  
−123 
 _{0} 
 =  −3 
*
In general, the transcendental functions log, sin^{−1} (arcsine), cos^{−1} (arccosine), and tan^{−1} are multiply defined. The value of log z is defined to be the one whose imaginary part lies in the range from − (inclusive if −0.0 is distinguished, exclusive otherwise) to (inclusive). log 0 is undefined.
The value of log z for nonreal z is defined in terms of log on real numbers as
where angle z is the angle of z = a · e^{ib} specified as:

with − ≤ angle z≤ and angle z = b + 2 n for some integer n.
With the oneargument version of log defined this way, the values of the twoargumentversion of log, sin^{−1} z, cos^{−1} z, tan^{−1} z, and the twoargument version of tan^{−1} are according to the following formulæ:
log z b  =  ( 
 / 
 )  
sin^{−1} z  =  −i log (i z + (1 − z^{2})^{1/2})  
cos^{−1} z  =  / 2 − sin^{−1} z  
tan^{−1} z  =  (log (1 + i z) − log (1 − i z)) / (2 i)  
tan^{−1} x y  = 
 (x + yi) 
*
The range of tan^{−1} x y is as in the following table. The asterisk (*) indicates that the entry applies to implementations that distinguish minus zero.

These numerical type predicates can be applied to any kind of argument. They return #t if the object is a number object of the named type, and #f otherwise. In general, if a type predicate is true of a number object then all higher type predicates are also true of that number object. Consequently, if a type predicate is false of a number object, then all lower type predicates are also false of that number object.
If z is a complex number object, then (real? z) is true if and only if (zero? (imagpart z)) and (exact? (imagpart z)) are both true.
If x is a real number object, then (rational? x) is true if and only if there exist exact integer objects k_{1} and k_{2} such that (= x (/ k_{1} k_{2})) and (= (numerator x) k_{1}) and (= (denominator x) k_{2}) are all true. Thus infinities and NaNs are not rational number objects.
If q is a rational number objects, then (integer? q) is true if and only if (= (denominator q) 1) is true. If q is not a rational number object, then (integer? q) is #f.
(complex? 3+4i) ⇒ #t
(complex? 3) ⇒ #t
(real? 3) ⇒ #t
(real? 2.5+0.0i) ⇒ #f
(real? 2.5+0i) ⇒ #t
(real? 2.5) ⇒ #t
(real? #e1e10) ⇒ #t
(rational? 6/10) ⇒ #t
(rational? 6/3) ⇒ #t
(rational? 2) ⇒ #t
(integer? 3+0i) ⇒ #t
(integer? 3.0) ⇒ #t
(integer? 8/4) ⇒ #t
(number? +nan.0) ⇒ #t
(complex? +nan.0) ⇒ #t
(real? +nan.0) ⇒ #t
(rational? +nan.0) ⇒ #f
(complex? +inf.0) ⇒ #t
(real? inf.0) ⇒ #t
(rational? inf.0) ⇒ #f
(integer? inf.0) ⇒ #f
Note: Except for number?, the behavior of these type predicates on inexact number objects is unreliable, because any inaccuracy may affect the result.
These numerical type predicates can be applied to any kind of argument. The realvalued? procedure returns #t if the object is a number object and is equal in the sense of = to some real number object, or if the object is a NaN, or a complex number object whose real part is a NaN and whose imaginary part is zero in the sense of zero?. The rationalvalued? and integervalued? procedures return #t if the object is a number object and is equal in the sense of = to some object of the named type, and otherwise they return #f.
(realvalued? +nan.0) ⇒ #t
(realvalued? +nan.0+0i) ⇒ #t
(realvalued? inf.0) ⇒ #t
(realvalued? 3) ⇒ #t
(realvalued? 2.5+0.0i) ⇒ #t
(realvalued? 2.5+0i) ⇒ #t
(realvalued? 2.5) ⇒ #t
(realvalued? #e1e10) ⇒ #t
(rationalvalued? +nan.0) ⇒ #f
(rationalvalued? inf.0) ⇒ #f
(rationalvalued? 6/10) ⇒ #t
(rationalvalued? 6/10+0.0i) ⇒ #t
(rationalvalued? 6/10+0i) ⇒ #t
(rationalvalued? 6/3) ⇒ #t
(integervalued? 3+0i) ⇒ #t
(integervalued? 3+0.0i) ⇒ #t
(integervalued? 3.0) ⇒ #t
(integervalued? 3.0+0.0i) ⇒ #t
(integervalued? 8/4) ⇒ #t
Note: These procedures test whether a given number object can be coerced to the specified type without loss of numerical accuracy. Specifically, the behavior of these predicates differs from the behavior of real?, rational?, and integer? on complex number objects whose imaginary part is inexact zero.
Note: The behavior of these type predicates on inexact number objects is unreliable, because any inaccuracy may affect the result.
These numerical predicates provide tests for the exactness of a quantity. For any number object, precisely one of these predicates is true.
(exact? 5) ⇒ #t
(inexact? +inf.0) ⇒ #t
The inexact procedure returns an inexact representation of z. If inexact number objects of the appropriate type have bounded precision, then the value returned is an inexact number object that is nearest to the argument. If an exact argument has no reasonably close inexact equivalent, an exception with condition type &implementationviolation may be raised.
Note: For a real number object whose magnitude is finite but so large that it has no reasonable finite approximation as an inexact number, a reasonably close inexact equivalent may be +inf.0 or inf.0. Similarly, the inexact representation of a complex number object whose components are finite may have infinite components.
The exact procedure returns an exact representation of z. The value returned is the exact number object that is numerically closest to the argument; in most cases, the result of this procedure should be numerically equal to its argument. If an inexact argument has no reasonably close exact equivalent, an exception with condition type &implementationviolation may be raised.
These procedures implement the natural onetoone correspondence between exact and inexact integer objects throughout an implementationdependent range.
The inexact and exact procedures are idempotent.
These procedures return #t if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing, and #f otherwise.
(= +inf.0 +inf.0) ⇒ #t
(= inf.0 +inf.0) ⇒ #f
(= inf.0 inf.0) ⇒ #t
For any real number object x that is neither infinite nor NaN:
(< inf.0 x +inf.0)) ⇒ #t
(> +inf.0 x inf.0)) ⇒ #t
For any number object z:
(= +nan.0 z) ⇒ #fFor any real number object x:
(< +nan.0 x) ⇒ #f(> +nan.0 x) ⇒ #f
These predicates must be transitive.
Note: The traditional implementations of these predicates in Lisplike languages are not transitive.
Note: While it is possible to compare inexact number objects using these predicates, the results may be unreliable because a small inaccuracy may affect the result; this is especially true of = and zero? (below).When in doubt, consult a numerical analyst.
These numerical predicates test a number object for a particular property, returning #t or #f. The zero? procedure tests if the number object is = to zero, positive? tests whether it is greater than zero, negative? tests whether it is less than zero, odd? tests whether it is odd, even? tests whether it is even, finite? tests whether it is not an infinity and not a NaN, infinite? tests whether it is an infinity, nan? tests whether it is a NaN.
(zero? +0.0) ⇒ #t
(zero? 0.0) ⇒ #t
(zero? +nan.0) ⇒ #f
(positive? +inf.0) ⇒ #t
(negative? inf.0) ⇒ #t
(positive? +nan.0) ⇒ #f
(negative? +nan.0) ⇒ #f
(finite? +inf.0) ⇒ #f
(finite? 5) ⇒ #t
(finite? 5.0) ⇒ #t
(infinite? 5.0) ⇒ #f
(infinite? +inf.0) ⇒ #t
Note: As with the predicates above, the results may be unreliable because a small inaccuracy may affect the result.
These procedures return the maximum or minimum of their arguments.
(max 3 4) ⇒ 4
(max 3.9 4) ⇒ 4.0
For any real number object x:
(max +inf.0 x) ⇒ +inf.0
(min inf.0 x) ⇒ inf.0
Note: If any argument is inexact, then the result is also 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 min or max is used to compare number objects of mixed exactness, and the numerical value of the result cannot be represented as an inexact number object without loss of accuracy, then the procedure may raise an exception with condition type &implementationrestriction.
These procedures return the sum or product of their arguments.
(+ 3 4) ⇒ 7
(+ 3) ⇒ 3
(+) ⇒ 0
(+ +inf.0 +inf.0) ⇒ +inf.0
(+ +inf.0 inf.0) ⇒ +nan.0
(* 4) ⇒ 4
(*) ⇒ 1
(* 5 +inf.0) ⇒ +inf.0
(* 5 +inf.0) ⇒ inf.0
(* +inf.0 +inf.0) ⇒ +inf.0
(* +inf.0 inf.0) ⇒ inf.0
(* 0 +inf.0) ⇒ 0 or +nan.0
(* 0 +nan.0) ⇒ 0 or +nan.0
(* 1.0 0) ⇒ 0 or 0.0
For any real number object x that is neither infinite nor NaN:
(+ +inf.0 x) ⇒ +inf.0
(+ inf.0 x) ⇒ inf.0
For any real number object x:
(+ +nan.0 x) ⇒ +nan.0
For any real number object x that is not an exact 0:
(* +nan.0 x) ⇒ +nan.0
If any of these procedures are applied to mixed nonrational real and nonreal complex arguments, they either raise an exception with condition type &implementationrestriction or return an unspecified number object.
Implementations that distinguish −0.0 should adopt behavior consistent with the following examples:
(+ 0.0 0.0) ⇒ 0.0
(+ 0.0 0.0) ⇒ 0.0
(+ 0.0 0.0) ⇒ 0.0
(+ 0.0 0.0) ⇒ 0.0
With two or more arguments, this procedures returns the difference of its arguments, associating to the left. With one argument, however, it returns the additive inverse of its argument.
( 3 4) ⇒ 1
( 3 4 5) ⇒ 6
( 3) ⇒ 3
( +inf.0 +inf.0) ⇒ +nan.0
If this procedure is applied to mixed nonrational real and nonreal complex arguments, it either raises an exception with condition type &implementationrestriction or returns an unspecified number object.
Implementations that distinguish −0.0 should adopt behavior consistent with the following examples:
( 0.0) ⇒ 0.0
( 0.0) ⇒ 0.0
( 0.0 0.0) ⇒ 0.0
( 0.0 0.0) ⇒ 0.0
( 0.0 0.0) ⇒ 0.0
( 0.0 0.0) ⇒ 0.0
If all of the arguments are exact, then the divisors must all be nonzero. With two or more arguments, this procedure returns the quotient of its arguments, associating to the left. With one argument, however, it returns the multiplicative inverse of its argument.
(/ 3 4 5) ⇒ 3/20
(/ 3) ⇒ 1/3
(/ 0.0) ⇒ +inf.0
(/ 1.0 0) ⇒ +inf.0
(/ 1 0.0) ⇒ inf.0
(/ +inf.0) ⇒ 0.0
(/ 0 0) &assertion exception
(/ 3 0) &assertion exception
(/ 0 3.5) ⇒ 0.0
(/ 0 0.0) ⇒ +nan.0
(/ 0.0 0) ⇒ +nan.0
(/ 0.0 0.0) ⇒ +nan.0
If this procedure is applied to mixed nonrational real and nonreal complex arguments, it either raises an exception with condition type &implementationrestriction or returns an unspecified number object.
Returns the absolute value of its argument.
(abs 7) ⇒ 7
(abs inf.0) ⇒ +inf.0
These procedures implement numbertheoretic integer division and return the results of the corresponding mathematical operations specified in section 11.7.3.1. In each case, x_{1} must be neither infinite nor a NaN, and x_{2} must be nonzero; otherwise, an exception with condition type &assertion is raised.
(div x_{1} x_{2}) ⇒ x_{1} div x_{2}
(mod x_{1} x_{2}) ⇒ x_{1} mod x_{2}
(divandmod x_{1} x_{2}) ⇒ x_{1} div x_{2}, x_{1} mod x_{2}
; two return values
(div0 x_{1} x_{2}) ⇒ x_{1} div_{0} x_{2}
(mod0 x_{1} x_{2}) ⇒ x_{1} mod_{0} x_{2}
(div0andmod0 x_{1} x_{2})
⇒ x_{1} div_{0} x_{2}, x_{1} mod_{0} x_{2}
; two return values
These procedures return the greatest common divisor or least common multiple of their arguments. The result is always nonnegative.
(gcd 32 36) ⇒ 4
(gcd) ⇒ 0
(lcm 32 36) ⇒ 288
(lcm 32.0 36) ⇒ 288.0
(lcm) ⇒ 1
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.
(numerator (/ 6 4)) ⇒ 3
(denominator (/ 6 4)) ⇒ 2
(denominator
(inexact (/ 6 4))) ⇒ 2.0
These procedures return inexact integer objects for inexact arguments that are not infinities or NaNs, and exact integer objects for exact rational arguments. For such arguments, floor returns the largest integer object not larger than x. The ceiling procedure returns the smallest integer object not smaller than x. The truncate procedure returns the integer object closest to x whose absolute value is not larger than the absolute value of x. The round procedure returns the closest integer object to x, rounding to even when x represents a number halfway between two integers.
Note: If the argument to one of these procedures is inexact, then the result is also inexact. If an exact value is needed, the result should be passed to the exact procedure.
Although infinities and NaNs are not integer objects, these procedures return an infinity when given an infinity as an argument, and a NaN when given a NaN.
(floor 4.3) ⇒ 5.0
(ceiling 4.3) ⇒ 4.0
(truncate 4.3) ⇒ 4.0
(round 4.3) ⇒ 4.0
(floor 3.5) ⇒ 3.0
(ceiling 3.5) ⇒ 4.0
(truncate 3.5) ⇒ 3.0
(round 3.5) ⇒ 4.0
(round 7/2) ⇒ 4
(round 7) ⇒ 7
(floor +inf.0) ⇒ +inf.0
(ceiling inf.0) ⇒ inf.0
(round +nan.0) ⇒ +nan.0
The rationalize procedure returns the a number object representing the simplest rational number differing from x_{1} by no more than x_{2}. A rational number r_{1} is simpler 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} ≤ p_{2} and q_{1} ≤ 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.
(rationalize (exact .3) 1/10)(rationalize .3 1/10)
⇒ #i1/3 ; approximately
(rationalize +inf.0 3) ⇒ +inf.0
(rationalize +inf.0 +inf.0) ⇒ +nan.0
(rationalize 3 +inf.0) ⇒ 0.0
The first two examples hold only in implementations whose inexact real number objects have sufficient precision.
These procedures compute the usual transcendental functions. The exp procedure computes the basee exponential of z. The log procedure with a single argument computes the natural logarithm of z (not the baseten logarithm); (log z_{1} z_{2}) computes the basez_{2} logarithm of z_{1}. The asin, acos, and atan procedures compute arcsine, arccosine, and arctangent, respectively. The twoargument variant of atan computes (angle (makerectangular x_{2} x_{1})).
See section 11.7.3.2 for the underlying mathematical operations. These procedures may return inexact results even when given exact arguments.
(exp +inf.0) ⇒ +inf.0
(exp inf.0) ⇒ 0.0
(log +inf.0) ⇒ +inf.0
(log 0.0) ⇒ inf.0
(log 0) &assertion exception
(log inf.0)
⇒ +inf.0+3.141592653589793i
; approximately
(atan inf.0)
⇒ 1.5707963267948965 ; approximately
(atan +inf.0)
⇒ 1.5707963267948965 ; approximately
(log 1.0+0.0i)
⇒ 0.0+3.141592653589793i ; approximately
(log 1.00.0i)
⇒ 0.03.141592653589793i ; approximately
; if 0.0 is distinguished
Returns the principal square root of z. For rational z, the result has either positive real part, or zero real part and nonnegative imaginary part. With log defined as in section 11.7.3.2, the value of (sqrt z) could be expressed as e^{(log z/2)}.
The sqrt procedure may return an inexact result even when given an exact argument.
(sqrt 5)
(sqrt +inf.0) ⇒ +inf.0
(sqrt inf.0) ⇒ +inf.0i
The exactintegersqrt procedure returns two nonnegative exact integer objects s and r where k = s^{2} + r and k < (s + 1)^{2}.
(exactintegersqrt 4) ⇒ 2 0
(exactintegersqrt 5) ⇒ 2 1
; two return values
Returns z_{1} raised to the power z_{2}. For nonzero z_{1}, this is e^{z2 log z1}. 0.0^{z} is 1.0 if z = 0.0, and 0.0 if (realpart z) is positive. For other cases in which the first argument is zero, either an exception is raised with condition type &implementationrestriction, or an unspecified number object is returned.
For an exact real number object z_{1} and an exact integer object z_{2}, (expt z_{1} z_{2}) must return an exact result. For all other values of z_{1} and z_{2}, (expt z_{1} z_{2}) may return an inexact result, even when both z_{1} and z_{2} are exact.
(expt 5 3) ⇒ 125
(expt 5 3) ⇒ 1/125
(expt 5 0) ⇒ 1
(expt 0 5) ⇒ 0
(expt 0 5+.0000312i) ⇒ 0
(expt 0 5) ⇒ unspecified
(expt 0 5+.0000312i) ⇒ unspecified
(expt 0 0) ⇒ 1
(expt 0.0 0.0) ⇒ 1.0
Suppose a_{1}, a_{2}, a_{3}, and a_{4} are real numbers, and c is a complex number such that the following holds:
Then, if x_{1}, x_{2}, x_{3}, and x_{4} are number objects representing a_{1}, a_{2}, a_{3}, and a_{4}, respectively, (makerectangular x_{1} x_{2}) returns c, and (makepolar x_{3} x_{4}) returns c.
(makerectangular 1.1 2.2)(makepolar 1.1 2.2)
⇒ 1.1@2.2 ; approximately
Conversely, if − ≤ a_{4} ≤ , and if z is a number object representing c, then (realpart z) returns a_{1} (imagpart z) returns a_{2}, (magnitude z) returns a_{3}, and (angle z) returns a_{4}.
(realpart 1.1+2.2i) ⇒ 1.1 ; approximately
(imagpart 1.1+2.2i) ⇒ 2.2i ; approximately
(magnitude 1.1@2.2) ⇒ 1.1 ; approximately
(angle 1.1@2.2) ⇒ 2.2 ; approximately
(angle 1.0)
⇒ 3.141592653589793 ; approximately
(angle 1.0+0.0i)
⇒ 3.141592653589793 ; approximately
(angle 1.00.0i)
⇒ 3.141592653589793 ; approximately
; if 0.0 is distinguished
(angle +inf.0) ⇒ 0.0
(angle inf.0)
⇒ 3.141592653589793 ; approximately
Moreover, suppose x_{1}, x_{2} are such that either x_{1} or x_{2} is an infinity, then
(makerectangular x_{1} x_{2}) ⇒ z(magnitude z) ⇒ +inf.0
The makepolar, magnitude, and angle procedures may return inexact results even when given exact arguments.
(angle 1)
Radix must be an exact integer object, either 2, 8, 10, or 16. If omitted, radix defaults to 10. If a precision is specified, then z must be an inexact complex number object, precision must be an exact positive integer object, and radix must be 10. The number>string procedure takes a number object and a radix and returns as a string an external representation of the given number object in the given radix such that
(let ((number z) (radix radix))(eqv? (string>number
(number>string number radix)
radix)
number))
is true. If no possible result makes this expression true, an exception with condition type &implementationrestriction is raised.
Note: The error case can occur only when z is not a complex number object or is a complex number object with a nonrational real or imaginary part.
If a precision is specified, then the representations of the inexact real components of the result, unless they are infinite or NaN, specify an explicit <mantissa width> p, and p is the least p ≥ precision for which the above expression is true.
If z is inexact, the radix is 10, and the above expression and condition 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, trailing zeroes, and mantissa width) needed to make the above expression and condition true [4, 7]; otherwise the format of the result is unspecified.
The result returned by number>string never contains an explicit radix prefix.
Returns a number object with maximally precise representation expressed by the given string. Radix must be an exact integer object, either 2, 8, 10, or 16. If supplied, radix is a default radix that may be overridden by an explicit radix prefix in string (e.g., "#o177"). If radix is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number object or a notation for a rational number object with a zero denominator, then string>number returns #f.
(string>number "100") ⇒ 100(string>number "100" 16) ⇒ 256
(string>number "1e2") ⇒ 100.0
(string>number "0/0") ⇒ #f
(string>number "+inf.0") ⇒ +inf.0
(string>number "inf.0") ⇒ inf.0
(string>number "+nan.0") ⇒ +nan.0
Note: The string>number procedure always returns a number object or #f; it never raises an exception.
The standard boolean objects for true and false have external representations #t and #f.However, of all objects, only #f counts as false in conditional expressions. See section 5.7.
Note: Programmers accustomed to other dialects of Lisp should be aware that Scheme distinguishes both #f and the empty list from each other and from the symbol nil.
Returns #t if obj is #f, and returns #f otherwise.
(not #t) ⇒ #f
(not 3) ⇒ #f
(not (list 3)) ⇒ #f
(not #f) ⇒ #t
(not '()) ⇒ #f
(not (list)) ⇒ #f
(not 'nil) ⇒ #f
Returns #t if obj is either #t or #f and returns #f otherwise.
(boolean? #f) ⇒ #t
(boolean? 0) ⇒ #f
(boolean? '()) ⇒ #f
Returns #t if the booleans are the same.
A pair is a compound structure with two fields called the car and cdr fields (for historical reasons). Pairs are created by the procedure cons. The car and cdr fields are accessed by the procedures car and cdr.
Pairs are used primarily to represent lists. A list can be defined recursively as either the empty listor a pair whose cdr is a list. More precisely, the set of lists is defined as the smallest set X such that
The empty list is in X.
If list is in X, then any pair whose cdr field contains list is also in X.
The objects in the car fields of successive pairs of a list are the elements of the list. For example, a twoelement 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 listis a special object of its own type. It is not a pair. It has no elements and its length is zero.
Note: The above definitions imply that all lists have finite length and are terminated by the empty list.
A chain of pairs not ending in the empty list is called an improper list. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists:
(a b c . d)
is equivalent to
(a . (b . (c . d)))
Whether a given pair is a list depends upon what is stored in the cdr field.
Returns #t if obj is a pair, and otherwise returns #f.
(pair? '(a . b)) ⇒ #t
(pair? '(a b c)) ⇒ #t
(pair? '()) ⇒ #f
(pair? '#(a b)) ⇒ #f
Returns a newly allocated pair whose car is obj_{1} and whose cdr is obj_{2}. The pair is guaranteed to be different (in the sense of eqv?) from every existing object.
(cons 'a '()) ⇒ (a)
(cons '(a) '(b c d)) ⇒ ((a) b c d)
(cons "a" '(b c)) ⇒ ("a" b c)
(cons 'a 3) ⇒ (a . 3)
(cons '(a b) 'c) ⇒ ((a b) . c)
Returns the contents of the car field of pair.
(car '(a b c)) ⇒ a
(car '((a) b c d)) ⇒ (a)
(car '(1 . 2)) ⇒ 1
(car '()) &assertion exception
Returns the contents of the cdr field of pair.
(cdr '((a) b c d)) ⇒ (b c d)
(cdr '(1 . 2)) ⇒ 2
(cdr '()) &assertion exception
These procedures are compositions of car and cdr, where for example caddr could be defined by
(define caddr (lambda (x) (car (cdr (cdr x))))).
Arbitrary compositions, up to four deep, are provided. There are twentyeight of these procedures in all.
Returns #t if obj is the empty list, #fotherwise.
Returns #t if obj is a list, #f otherwise. By definition, all lists are chains of pairs that have finite length and are terminated by the empty list.
(list? '(a b c)) ⇒ #t
(list? '()) ⇒ #t
(list? '(a . b)) ⇒ #f
Returns a newly allocated list of its arguments.
(list 'a (+ 3 4) 'c) ⇒ (a 7 c)
(list) ⇒ ()
Returns the length of list.
(length '(a b c)) ⇒ 3
(length '(a (b) (c d e))) ⇒ 3
(length '()) ⇒ 0
Returns a possibly improper list consisting of the elements of the first list followed by the elements of the other lists, with obj as the cdr of the final pair. An improper list results if obj is not a list.
(append '(x) '(y)) ⇒ (x y)
(append '(a) '(b c d)) ⇒ (a b c d)
(append '(a (b)) '((c))) ⇒ (a (b) (c))
(append '(a b) '(c . d)) ⇒ (a b c . d)
(append '() 'a) ⇒ a
If append constructs a nonempty chain of pairs, it is always newly allocated. If no pairs are allocated, obj is returned.
Returns a newly allocated list consisting of the elements of list in reverse order.
(reverse '(a b c)) ⇒ (c b a)
(reverse '(a (b c) d (e (f))))
⇒ ((e (f)) d (b c) a)
List should be a list of size at least k. The listtail procedure returns the subchain of pairs of list obtained by omitting the first k elements.
(listtail '(a b c d) 2) ⇒ (c d)
Implementation responsibilities: The implementation must check that list is a chain of pairs whose length is at least k. It should not check that it is a chain of pairs beyond this length.
List must be a list whose length is at least k + 1. The listtail procedure returns the kth element of list.
(listref '(a b c d) 2) ⇒ c
Implementation responsibilities: The implementation must check that list is a chain of pairs whose length is at least k + 1. It should not check that it is a list of pairs beyond this length.
The lists should all have the same length. Proc should accept as many arguments as there are lists and return a single value. Proc should not mutate any of the lists.
The map procedure applies proc elementwise to the elements of the lists and returns a list of the results, in order. Proc is always called in the same dynamic environment as map itself. The order in which proc is applied to the elements of the lists is unspecified. If multiple returns occur from map, the values returned by earlier returns are not mutated.
(map cadr '((a b) (d e) (g h)))
(map (lambda (n) (expt n n))
'(1 2 3 4 5))
⇒ (1 4 27 256 3125)
(map + '(1 2 3) '(4 5 6)) ⇒ (5 7 9)
(let ((count 0))
(map (lambda (ignored)
(set! count (+ count 1))
count)
'(a b))) ⇒ (1 2) or (2 1)
Implementation responsibilities: The implementation should check that the lists all have the same length. The implementation must check the restrictions on proc to the extent performed by applying it as described. An implementation may check whether proc is an appropriate argument before applying it.
The lists should all have the same length. Proc should accept as many arguments as there are lists. Proc should not mutate any of the lists.
The foreach procedure applies proc elementwise to the elements of the lists for its side effects, in order from the first elements to the last. Proc is always called in the same dynamic environment as foreach itself. The return values of foreach are unspecified.
(let ((v (makevector 5)))
(foreach (lambda (i)
(vectorset! v i (* i i)))
'(0 1 2 3 4))
v) ⇒ #(0 1 4 9 16)
(foreach (lambda (x) x) '(1 2 3 4))
⇒ unspecified
(foreach even? '()) ⇒ unspecified
Implementation responsibilities: The implementation should check that the lists all have the same length. The implementation must check the restrictions on proc to the extent performed by applying it as described. An implementation may check whether proc is an appropriate argument before applying it.
Note: Implementations of foreach may or may not tailcall proc on the last elements.
Symbols are objects whose usefulness rests on the fact that two symbols are identical (in the sense of eq?, eqv? and equal?) if and only if their names are spelled the same way. A symbol literal is formed using quote.
Returns #t if obj is a symbol, otherwise returns #f.
(symbol? 'foo) ⇒ #t
(symbol? (car '(a b))) ⇒ #t
(symbol? "bar") ⇒ #f
(symbol? 'nil) ⇒ #t
(symbol? '()) ⇒ #f
(symbol? #f) ⇒ #f
Returns the name of symbol as an immutable string.
(symbol>string 'flyingfish)
⇒ "flyingfish"
(symbol>string 'Martin) ⇒ "Martin"
(symbol>string
(string>symbol "Malvina"))
⇒ "Malvina"
Returns #t if the symbols are the same, i.e., if their names are spelled the same.
Returns the symbol whose name is string.
(eq? 'mISSISSIppi 'mississippi)
(string>symbol "mISSISSIppi")
⇒the symbol with name "mISSISSIppi"
(eq? 'bitBlt (string>symbol "bitBlt"))
⇒ #t
(eq? 'JollyWog
(string>symbol
(symbol>string 'JollyWog)))
⇒ #t
(string=? "K. Harper, M.D."
(symbol>string
(string>symbol "K. Harper, M.D.")))
⇒ #t
Characters are objects that represent Unicode scalar values [27].
Note: Unicode defines a standard mapping between sequences of Unicode scalar values(integers in the range 0 to #x10FFFF, excluding the range #xD800 to #xDFFF) in the latest version of the standard and humanreadable “characters”. More precisely, Unicode distinguishes between glyphs, which are printed for humans to read, and characters, which are abstract entities that map to glyphs (sometimes in a way that's sensitive to surrounding characters). Furthermore, different sequences of scalar values sometimes correspond to the same character. The relationships among scalar, characters, and glyphs are subtle and complex.Despite this complexity, most things that a literate human would call a “character” can be represented by a single Unicode scalar value (although several sequences of Unicode scalar values may represent that same character). For example, Roman letters, Cyrillic letters, Hebrew consonants, and most Chinese characters fall into this category.
Unicode scalar values exclude the range #xD800 to #xDFFF, which are part of the range of Unicode code points. However, the Unicode code points in this range, the socalled surrogates, are an artifact of the UTF16 encoding, and can only appear in specific Unicode encodings, and even then only in pairs that encode scalar values. Consequently, all characters represent code points, but the surrogate code points do not have representations as characters.
Returns #t if obj is a character, otherwise returns #f.
Sv must be a Unicode scalar value, i.e., a nonnegative exact integer object in [0, #xD7FF] ∪ [#xE000, #x10FFFF].
Given a character, char>integer returns its Unicode scalar value as an exact integer object. For a Unicode scalar value sv, integer>char returns its associated character.
(integer>char 32) ⇒ #\space
(char>integer (integer>char 5000))
⇒ 5000
(integer>char #\xD800) &assertion exception
These procedures impose a total ordering on the set of characters according to their Unicode scalar values.
(char<? #\z #\ß) ⇒ #t
(char<? #\z #\Z) ⇒ #f
Strings are sequences of characters.
The length of a string is the number of characters that it contains. This number is fixed when the string is created. The valid indices of a string are the 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.
Returns #t if obj is a string, otherwise returns #f.
Returns a newly allocated string of length k. If char is given, then all elements of the string are initialized to char, otherwise the contents of the string are unspecified.
Returns a newly allocated string composed of the arguments.
Returns the number of characters in the given string as an exact integer object.
K must be a valid index of string. The stringref procedure returns character
k of string using zeroorigin indexing.
Note: Implementors should make stringref run in constant time.
Returns #t if the strings are the same length and contain the same characters in the same positions. Otherwise, the string=? procedure returns #f.
(string=? "Straße" "Strasse")
These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, string<? is the lexicographic ordering on strings induced by the ordering char<? on characters. If two strings differ in length but are the same up to the length of the shorter string, the shorter string is considered to be lexicographically less than the longer string.
(string<? "z" "ß") ⇒ #t
(string<? "z" "zz") ⇒ #t
(string<? "z" "Z") ⇒ #f
String must be a string, and start and end must be exact integer objects satisfying

The substring procedure returns a newly allocated string formed from the characters of string beginning with index start (inclusive) and ending with index end (exclusive).
Returns a newly allocated string whose characters form the concatenation of the given strings.
List must be a list of characters. The string>list procedure returns a newly allocated list of the characters that make up the given string. The list>string procedure returns a newly allocated string formed from the characters in list. The string>list and list>string procedures are inverses so far as equal? is concerned.
The strings must all have the same length. Proc should accept as many arguments as there are strings. The stringforeach procedure applies proc elementwise to the characters of the strings for its side effects, in order from the first characters to the last. Proc is always called in the same dynamic environment as stringforeach itself. The return values of stringforeach are unspecified.
Analogous to foreach.
Implementation responsibilities: The implementation must check the restrictions on proc to the extent performed by applying it as described. An implementation may check whether proc is an appropriate argument before applying it.
Returns a newly allocated copy of the given string.
Vectors are heterogeneous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time needed to access a randomly chosen element is typically less for the vector than for the list.
The length of a vector is the number of elements that it contains. This number is a nonnegative integer that is fixed when the vector is created. The valid indicesof a vector are the exact nonnegative integer objects 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.
Like list constants, vector constants must be quoted:
'#(0 (2 2 2 2) "Anna")
Returns #t if obj is a vector. Otherwise the procedure returns #f.
Returns a newly allocated vector of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.
Returns a newly allocated vector whose elements contain the given arguments. Analogous to list.
(vector 'a 'b 'c) ⇒ #(a b c)
Returns the number of elements in vector as an exact integer object.
K must be a valid index of vector. The vectorref procedure returns the contents of element
k of vector.
(vectorref '#(1 1 2 3 5 8 13 21) 5)
K must be a valid index of vector. The vectorset! procedure stores obj in element
k of vector, and returns unspecified values.
Passing an immutable vector to vectorset! should cause an exception with condition type &assertion to be raised.
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
(vectorset! vec 1 '("Sue" "Sue"))
vec)
⇒ #(0 ("Sue" "Sue") "Anna")
(vectorset! '#(0 1 2) 1 "doe")
⇒ unspecified
; constant vector
; should raise &assertion exception
The vector>list procedure returns a newly allocated list of the objects contained in the elements of vector. The list>vector procedure returns a newly created vector initialized to the elements of the list list.
(vector>list '#(dah dah didah))
(list>vector '(dididit dah))
⇒ #(dididit dah)
Stores fill in every element of vector and returns unspecified values.
The vectors must all have the same length. Proc should accept as many arguments as there are vectors and return a single value.
The vectormap procedure applies proc elementwise to the elements of the vectors and returns a vector of the results, in order. Proc is always called in the same dynamic environment as vectormap itself. The order in which proc is applied to the elements of the vectors is unspecified. If multiple returns occur from vectormap, the return values returned by earlier returns are not mutated.
Analogous to map.
Implementation responsibilities: The implementation must check the restrictions on proc to the extent performed by applying it as described. An implementation may check whether proc is an appropriate argument before applying it.
The vectors must all have the same length. Proc should accept as many arguments as there are vectors. The vectorforeach procedure applies proc elementwise to the elements of the vectors for its side effects, in order from the first elements to the last. Proc is always called in the same dynamic environment as vectorforeach itself. The return values of vectorforeach are unspecified.
Analogous to foreach.
Implementation responsibilities: The implementation must check the restrictions on proc to the extent performed by applying it as described. An implementation may check whether proc is an appropriate argument before applying it.
Who must be a string or a symbol or #f. Message must be a string. The irritants are arbitrary objects.
These procedures raise an exception. The error procedure should be called when an error has occurred, typically caused by something that has gone wrong in the interaction of the program with the external world or the user. The assertionviolation procedure should be called when an invalid call to a procedure was made, either passing an invalid number of arguments, or passing an argument that it is not specified to handle.
The who argument should describe the procedure or operation that detected the exception. The message argument should describe the exceptional situation. The irritants should be the arguments to the operation that detected the operation.
The condition object provided with the exception (see library chapter on “Exceptions and conditions”) has the following condition types:
If who is not #f, the condition has condition type &who, with who as the value of its field. In that case, who should be the name of the procedure or entity that detected the exception. If it is #f, the condition does not have condition type &who.
The condition has condition type &message, with message as the value of its field.
The condition has condition type &irritants, and its field has as its value a list of the irritants.
Moreover, the condition created by error has condition type &error, and the condition created by assertionviolation has condition type &assertion.
(define (fac n)
(if (not (integervalued? n))
(assertionviolation
'fac "nonintegral argument" n))
(if (negative? n)
(assertionviolation
'fac "negative argument" n))
(letrec
((loop (lambda (n r)
(if (zero? n)
r
(loop ( n 1) (* r n))))))
(loop n 1)))
(fac 5) ⇒ 120
(fac 4.5) &assertion exception
(fac 3) &assertion exception
An assert form is evaluated by evaluating <expression>. If <expression> returns a true value, that value is returned from the assert expression. If <expression> returns #f, an exception with condition types &assertion and &message is raised. The message provided in the condition object is implementationdependent.
Note: Implementations should exploit the fact that assert is syntax to provide as much information as possible about the location of the assertion failure.
This chapter describes various primitive procedures which control the flow of program execution in special ways.
Restargs must be a list. Proc should accept n arguments, where n is number of args plus the length of restargs. The apply procedure calls proc with the elements of the list (append (list arg_{1} ...) restargs) as the actual arguments.
If a call to apply occurs in a tail context, the call to proc is also in a tail context.
(apply + (list 3 4)) ⇒ 7
(define compose
(lambda (f g)
(lambda args
(f (apply g args)))))
((compose sqrt *) 12 75) ⇒ 30
Proc should accept one argument. The procedure callwithcurrentcontinuation (which is the same as the procedure call/cc) packages the current continuation as an “escape procedure”and passes it as an argument to 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 reinstate the continuation that was in effect when the escape procedure was created. Calling the escape procedure may cause the invocation of before and after procedures installed using dynamicwind.
The escape procedure accepts the same number of arguments as the continuation of the original call to callwithcurrentcontinuation.
The escape procedure that is passed to 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.
If a call to callwithcurrentcontinuation occurs in a tail context, the call to proc is also in a tail context.
The following examples show only some ways in which callwithcurrentcontinuation is used. If all real uses were as simple as these examples, there would be no need for a procedure with the power of callwithcurrentcontinuation.
(callwithcurrentcontinuation
(lambda (exit)
(foreach (lambda (x)
(if (negative? x)
(exit x)))
'(54 0 37 3 245 19))
#t)) ⇒ 3
(define listlength
(lambda (obj)
(callwithcurrentcontinuation
(lambda (return)
(letrec ((r
(lambda (obj)
(cond ((null? obj) 0)
((pair? obj)
(+ (r (cdr obj)) 1))
(else (return #f))))))
(r obj))))))
(listlength '(1 2 3 4)) ⇒ 4
(listlength '(a b . c)) ⇒ #f
(callwithcurrentcontinuation procedure?)
⇒ #t
Note: Calling an escape procedure reenters the dynamic extent of the call to callwithcurrentcontinuation, and thus restores its dynamic environment; see section 5.12.
Delivers all of its arguments to its continuation. The values procedure might be defined as follows:
(define (values . things)(callwithcurrentcontinuation
(lambda (cont) (apply cont things))))
The continuations of all nonfinal expressions within a sequence of expressions, such as in lambda, begin, let, let*, letrec, letrec*, letvalues, let*values, case, and cond forms, usually take an arbitrary number of values.
Except for these and the continuations created by callwithvalues, letvalues, and let*values, continuations implicitly accepting a single value, such as the continuations of <operator> and <operand>s of procedure calls or the <test> expressions in conditionals, take exactly one value. The effect of passing an inappropriate number of values to such a continuation is undefined.
Producer must be a procedure and should accept zero arguments. Consumer must be a procedure and should accept as many values as producer returns. The callwithvalues procedure calls producer with no arguments and a continuation that, when passed some values, calls the consumer procedure with those values as arguments. The continuation for the call to consumer is the continuation of the call to callwithvalues.
(callwithvalues (lambda () (values 4 5))
(lambda (a b) b))
⇒ 5
(callwithvalues * ) ⇒ 1
If a call to callwithvalues occurs in a tail context, the call to consumer is also in a tail context.
Implementation responsibilities: After producer returns, the implementation must check that consumer accepts as many values as consumer has returned.
Before, thunk, and after must be procedures, and each should accept zero arguments. These procedures may return any number of values. The dynamicwind procedure calls thunk without arguments, returning the results of this call. Moreover, dynamicwind calls before without arguments whenever the dynamic extent of the call to thunk is entered, and after without arguments whenever the dynamic extent of the call to thunk is exited. Thus, in the absence of calls to escape procedures created by callwithcurrentcontinuation, dynamicwind calls before, thunk, and after, in that order.
While the calls to before and after are not considered to be within the dynamic extent of the call to thunk, calls to the before and after procedures of any other calls to dynamicwind that occur within the dynamic extent of the call to thunk are considered to be within the dynamic extent of the call to thunk.
More precisely, an escape procedure transfers control out of the dynamic extent of a set of zero or more active dynamicwind calls x ... and transfer control into the dynamic extent of a set of zero or more active dynamicwind calls y .... It leaves the dynamic extent of the most recent x and calls without arguments the corresponding after procedure. If the after procedure returns, the escape procedure proceeds to the next most recent x, and so on. Once each x has been handled in this manner, the escape procedure calls without arguments the before procedure corresponding to the least recent y. If the before procedure returns, the escape procedure reenters the dynamic extent of the least recent y and proceeds with the next least recent y, and so on. Once each y has been handled in this manner, control is transferred to the continuation packaged in the escape procedure.
Implementation responsibilities: The implementation must check the restrictions on thunk and after only if they are actually called.
(let ((path '())
(c #f))
(let ((add (lambda (s)
(set! path (cons s path)))))
(dynamicwind
(lambda () (add 'connect))
(lambda ()
(add (callwithcurrentcontinuation
(lambda (c0)
(set! c c0)
'talk1))))
(lambda () (add 'disconnect)))
(if (< (length path) 4)
(c 'talk2)
(reverse path))))
⇒ (connect talk1 disconnect
connect talk2 disconnect)
(let ((n 0))
(callwithcurrentcontinuation
(lambda (k)
(dynamicwind
(lambda ()
(set! n (+ n 1))
(k))
(lambda ()
(set! n (+ n 2)))
(lambda ()
(set! n (+ n 4))))))
n) ⇒ 1
(let ((n 0))
(callwithcurrentcontinuation
(lambda (k)
(dynamicwind
values
(lambda ()
(dynamicwind
values
(lambda ()
(set! n (+ n 1))
(k))
(lambda ()
(set! n (+ n 2))
(k))))
(lambda ()
(set! n (+ n 4))))))
n) ⇒ 7
Note: Entering a dynamic extent restores its dynamic environment; see section 5.12.
“Named let” is a variant on the syntax of let that provides a general looping construct and may also be used to express recursion. It has the same syntax and semantics as ordinary let except that <variable> is bound within <body> to a procedure whose parameters are the bound variables and whose body is <body>. Thus the execution of <body> may be repeated by invoking the procedure named by <variable>.
(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)))))
⇒ ((6 1 3) (5 2))
“Backquote” or “quasiquote”expressions are useful for constructing a list or vector structure when some but not all of the desired structure is known in advance.
Syntax: <Qq template> should be as specified by the grammar at the end of this entry.
Semantics: If no unquote or unquotesplicing forms appear within the <qq template>, the result of evaluating (quasiquote <qq template>) is equivalent to the result of evaluating (quote <qq template>).
If an (unquote <expression> ...) form appears inside a <qq template>, however, the <expression>s are evaluated (“unquoted”) and their results are inserted into the structure instead of the unquote form.
If an (unquotesplicing <expression> ...) form appears inside a <qq template>, then the <expression>s must evaluate to lists; the opening and closing parentheses of the lists are then “stripped away” and the elements of the lists are inserted in place of the unquotesplicing form.
Any unquotesplicing or multioperand unquote form must appear only within a list or vector <qq template>.
As noted in section 4.3.5, (quasiquote <qq template>) may be abbreviated `<qq template>, (unquote <expression>) may be abbreviated ,<expression>, and (unquotesplicing <expression>) may be abbreviated ,@<expression>.
`(list ,(+ 1 2) 4) ⇒ (list 3 4)
(let ((name 'a)) `(list ,name ',name))
⇒ (list a (quote a))
`(a ,(+ 1 2) ,@(map abs '(4 5 6)) b)
⇒ (a 3 4 5 6 b)
`(( foo ,( 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
⇒ ((foo 7) . cons)
`#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
⇒ #(10 5 2 4 3 8)
(let ((name 'foo))
`((unquote name name name)))
⇒ (foo foo foo)
(let ((name '(foo)))
`((unquotesplicing name name name)))
⇒ (foo foo foo)
(let ((q '((append x y) (sqrt 9))))
``(foo ,,@q))
⇒ `(foo
(unquote (append x y) (sqrt 9)))
(let ((x '(2 3))
(y '(4 5)))
`(foo (unquote (append x y) (sqrt 9))))
⇒ (foo (2 3 4 5) 3)
Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost quasiquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation.
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
(let ((name1 'x)
(name2 'y))
`(a `(b ,,name1 ,',name2 d) e))
⇒ (a `(b ,x ,'y d) e)
A quasiquote expression may return either fresh, mutable objects or literal structure for any structure that is constructed at run time during the evaluation of the expression. Portions that do not need to be rebuilt are always literal. Thus,
(let ((a 3)) `((1 2) ,a ,4 ,'five 6))may be equivalent to either of the following expressions:
'((1 2) 3 4 five 6)(let ((a 3))
(cons '(1 2)
(cons a (cons 4 (cons 'five '(6))))))
However, it is not equivalent to this expression:
(let ((a 3)) (list (list 1 2) a 4 'five 6))It is a syntax violation if any of the identifiers quasiquote, unquote, or unquotesplicing appear in positions within a <qq template> otherwise than as described above.
The following grammar for quasiquote expressions is not contextfree. 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, .... D keeps track of the nesting depth.
<qq template> → <qq template 1>
<qq template 0> → <expression>
<quasiquotation D> → (quasiquote <qq template D>)
<qq template D> → <lexeme datum>
∣ <list qq template D>
∣ <vector qq template D>
∣ <unquotation D>
<list qq template D> → (<qq template or splice D>*)
∣ (<qq template or splice D>^{+} . <qq template D>)
∣ <quasiquotation D + 1>
<vector qq template D> → #(<qq template or splice D>*)
<unquotation D> → (unquote <qq template D−1>)
<qq template or splice D> → <qq template D>
∣ <splicing unquotation D>
<splicing unquotation D> →
(unquotesplicing <qq template D−1>*)
∣ (unquote <qq template D−1>*)
In <quasiquotation>s, a <list qq template D> can sometimes be confused with either an <unquotation D> or a <splicing unquotation D>. The interpretation as an <unquotation> or <splicing unquotation D> takes precedence.
The letsyntax and letrecsyntax forms bind keywords. Like a begin form, a letsyntax or letrecsyntax form may appear in a definition context, in which case it is treated as a definition, and the forms in the body must also be definitions. A letsyntax or letrecsyntax form may also appear in an expression context, in which case the forms within their bodies must be expressions.
Syntax: <Bindings> must have the form
((<keyword> <expression>) ...)Each <keyword> is an identifier, and each <expression> is an expression that evaluates, at macroexpansion time, to a transformer. Transformers may be created by syntaxrules or identifiersyntax (see section 11.19) or by one of the other mechanisms described in library chapter on “syntaxcase”. It is a syntax violation for <keyword> to appear more than once in the list of keywords being bound.
Semantics: The <form>s are expanded in the syntactic environment obtained by extending the syntactic environment of the letsyntax form with macros whose keywords are the <keyword>s, bound to the specified transformers. Each binding of a <keyword> has the <form>s as its region.
The <form>s of a letsyntax form are treated, whether in definition or expression context, as if wrapped in an implicit begin; see section 11.4.7. Thus definitions in the result of expanding the <form>s have the same region as any definition appearing in place of the letsyntax form would have.
Implementation responsibilities: The implementation should detect if the value of <expression> cannot possibly be a transformer.
(letsyntax ((when (syntaxrules ()
((when test stmt1 stmt2 ...)
(if test
(begin stmt1
stmt2 ...))))))
(let ((if #t))
(when if (set! if 'now))
if)) ⇒ now
(let ((x 'outer))
(letsyntax ((m (syntaxrules () ((m) x))))
(let ((x 'inner))
(m)))) ⇒ outer
(let ()
(letsyntax
((def (syntaxrules ()
((def stuff ...) (define stuff ...)))))
(def foo 42))
foo) ⇒ 42
(let ()
(letsyntax ())
5) ⇒ 5
Syntax: Same as for letsyntax.
Semantics: The <form>s are expanded in the syntactic environment obtained by extending the syntactic environment of the letrecsyntax form with macros whose keywords are the <keyword>s, bound to the specified transformers. Each binding of a <keyword> has the <bindings> as well as the <form>s within its region, so the transformers can transcribe forms into uses of the macros introduced by the letrecsyntax form.
The <form>s of a letrecsyntax form are treated, whether in definition or expression context, as if wrapped in an implicit begin; see section 11.4.7. Thus definitions in the result of expanding the <form>s have the same region as any definition appearing in place of the letrecsyntax form would have.
Implementation responsibilities: The implementation should detect if the value of <expression> cannot possibly be a transformer.
(letrecsyntax
((myor (syntaxrules ()
((myor) #f)
((myor e) e)
((myor e1 e2 ...)
(let ((temp e1))
(if temp
temp
(myor e2 ...)))))))
(let ((x #f)
(y 7)
(temp 8)
(let odd?)
(if even?))
(myor x
(let temp)
(if y)
y))) ⇒ 7
The following example highlights how letsyntax and letrecsyntax differ.
(let ((f (lambda (x) (+ x 1))))
(letsyntax ((f (syntaxrules ()
((f x) x)))
(g (syntaxrules ()
((g x) (f x)))))
(list (f 1) (g 1))))
⇒ (1 2)
(let ((f (lambda (x) (+ x 1))))
(letrecsyntax ((f (syntaxrules ()
((f x) x)))
(g (syntaxrules ()
((g x) (f x)))))
(list (f 1) (g 1))))
⇒ (1 1)
The two expressions are identical except that the letsyntax form in the first expression is a letrecsyntax form in the second. In the first expression, the f occurring in g refers to the letbound variable f, whereas in the second it refers to the keyword f whose binding is established by the letrecsyntax form.
Syntax: Each <literal> must be an identifier. Each <syntax rule> must have the following form:
(<srpattern> <template>)
An <srpattern> is a restricted form of <pattern>, namely, a nonempty <pattern> in one of four parenthesized forms below whose first subform is an identifier or an underscore _. A <pattern> is an identifier, constant, or one of the following.
(<pattern> ...)
(<pattern> <pattern> ... . <pattern>)
(<pattern> ... <pattern> <ellipsis> <pattern> ...)
(<pattern> ... <pattern> <ellipsis> <pattern> ... . <pattern>)
#(<pattern> ...)
#(<pattern> ... <pattern> <ellipsis> <pattern> ...)
An <ellipsis> is the identifier “...” (three periods).
A <template> is a pattern variable, an identifier that is not a pattern variable, a pattern datum, or one of the following.
(<subtemplate> ...)
(<subtemplate> ... . <template>)
#(<subtemplate> ...)
A <subtemplate> is a <template> followed by zero or more ellipses.
Semantics: An instance of syntaxrules evaluates, at macroexpansion time, to 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 syntaxrules is matched against the patterns contained in the <syntax rule>s, beginning with the leftmost <syntax rule>. When a match is found, the macro use is transcribed hygienically according to the template. It is a syntax violation when no match is found.
An identifier appearing within a <pattern> may be an underscore ( _ ), a literal identifier listed in the list of literals (<literal> ...), or an ellipsis ( ... ). All other identifiers appearing within a <pattern> are pattern variables. It is a syntax violation if an ellipsis or underscore appears in (<literal> ...).
While the first subform of <srpattern> may be an identifier, the identifier is not involved in the matching and is not considered a pattern variable or literal identifier.
Pattern variables match arbitrary input subforms and are used to refer to elements of the input. It is a syntax violation if the same pattern variable appears more than once in a <pattern>.
Underscores also match arbitrary input subforms but are not pattern variables and so cannot be used to refer to those elements. Multiple underscores may appear in a <pattern>.
A literal identifier matches an input subform if and only if the input subform is an identifier and either both its occurrence in the input expression and its occurrence in the list of literals have the same lexical binding, or the two identifiers have the same name and both have no lexical binding.
A subpattern followed by an ellipsis can match zero or more elements of the input.
More formally, an input form F matches a pattern P if and only if one of the following holds:
P is an underscore ( _ ).
P is a pattern variable.
P is a literal identifier and F is an identifier such that both P and F would refer to the same binding if both were to appear in the output of the macro outside of any bindings inserted into the output of the macro. (If neither of two likenamed identifiers refers to any binding, i.e., both are undefined, they are considered to refer to the same binding.)
P is of the form (P_{1} ... P_{n}) and F is a list of n elements that match P_{1} through P_{n}.
P is of the form (P_{1} ... P_{n} . P_{x}) and F is a list or improper list of n or more elements whose first n elements match P_{1} through P_{n} and whose nth cdr matches P_{x}.
P is of the form (P_{1} ... P_{k} P_{e} <ellipsis> P_{m+1} ... P_{n}), where <ellipsis> is the identifier ... and F is a list of n elements whose first k elements match P_{1} through P_{k}, whose next m−k elements each match P_{e}, and whose remaining n−m elements match P_{m+1} through P_{n}.
P is of the form (P_{1} ... P_{k} P_{e} <ellipsis> P_{m+1} ... P_{n} . P_{x}), where <ellipsis> is the identifier ... and F is a list or improper list of n elements whose first k elements match P_{1} through P_{k}, whose next m−k elements each match P_{e}, whose next n−m elements match P_{m+1} through P_{n}, and whose nth and final cdr matches P_{x}.
P is of the form #(P_{1} ... P_{n}) and F is a vector of n elements that match P_{1} through P_{n}.
P is of the form #(P_{1} ... P_{k} P_{e} <ellipsis> P_{m+1} ... P_{n}), where <ellipsis> is the identifier ... and F is a vector of n or more elements whose first k elements match P_{1} through P_{k}, whose next m−k elements each match P_{e}, and whose remaining n−m elements match P_{m+1} through P_{n}.
P is a pattern datum (any nonlist, nonvector, nonsymbol datum) and F is equal to P in the sense of the equal? procedure.
When a macro use is transcribed according to the template of the matching <syntax rule>, pattern variables that occur in the template are replaced by the subforms they match in the input.
Pattern data and identifiers that are not pattern variables or ellipses are copied into the output. A subtemplate followed by an ellipsis expands into zero or more occurrences of the subtemplate. Pattern variables that occur in subpatterns followed by one or more ellipses may occur only in subtemplates that are followed by (at least) as many ellipses. These pattern variables are replaced in the output by the input subforms to which they are bound, distributed as specified. If a pattern variable is followed by more ellipses in the subtemplate than in the associated subpattern, the input form is replicated as necessary. The subtemplate must contain at least one pattern variable from a subpattern followed by an ellipsis, and for at least one such pattern variable, the subtemplate must be followed by exactly as many ellipses as the subpattern in which the pattern variable appears. (Otherwise, the expander would not be able to determine how many times the subform should be repeated in the output.) It is a syntax violation if the constraints of this paragraph are not met.
A template of the form (<ellipsis> <template>) is identical to <template>, except that ellipses within the template have no special meaning. That is, any ellipses contained within <template> are treated as ordinary identifiers. In particular, the template (... ...) produces a single ellipsis, .... This allows syntactic abstractions to expand into forms containing ellipses.
(definesyntax belikebegin
(syntaxrules ()
((belikebegin name)
(definesyntax name
(syntaxrules ()
((name expr (... ...))
(begin expr (... ...))))))))
(belikebegin sequence)
(sequence 1 2 3 4) ⇒ 4
As an example for hygienic use of auxiliary identifier, if let and cond are defined as in section 11.16 and appendix B then they are hygienic (as required) and the following is not an error.
(let ((=> #f))
(cond (#t => 'ok))) ⇒ ok
The macro transformer for cond recognizes => as a local variable, and hence an expression, and not as the identifier =>, which the macro transformer treats as a syntactic keyword. Thus the example expands into
(let ((=> #f))
(if #t (begin => 'ok)))
instead of
(let ((=> #f))
(let ((temp #t))
(if temp ('ok temp))))
which would result in an assertion violation.
Syntax: The <id>s must be identifiers. The <template>s must be as for syntaxrules.
Semantics: When a keyword is bound to a transformer produced by the first form of identifiersyntax, references to the keyword within the scope of the binding are replaced by <template>.
(define p (cons 4 5))
(definesyntax p.car (identifiersyntax (car p)))
p.car ⇒ 4
(set! p.car 15) ⇒ &syntax exception
The second, more general, form of identifiersyntax permits the transformer to determine what happens when set! is used. In this case, uses of the identifier by itself are replaced by <template_{1}>, and uses of set! with the identifier are replaced by <template_{2}>.
(define p (cons 4 5))
(definesyntax p.car
(identifiersyntax
(_ (car p))
((set! _ e) (setcar! p e))))
(set! p.car 15)
p.car ⇒ 15
p ⇒ (15 5)
A tail callis a procedure call that occurs in a tail context. Tail contexts are defined inductively. Note that a tail context is always determined with respect to a particular lambda expression.
The last expression within the body of a lambda expression, shown as <tail expression> below, occurs in a tail context.
(lāmbda <formals><definition>*
<expression>* <tail expression>)
If one of the following expressions is in a tail context, then the subexpressions shown as <tail expression> are in a tail context. These were derived from specifications of the syntax of the forms described in this chapter by replacing some occurrences of <expression> with <tail expression>. Only those rules that contain tail contexts are shown here.
(if <expression> <tail expression> <tail expression>)(if <expression> <tail expression>)
(cond <cond clause>^{+})
(cond <cond clause>* (else <tail sequence>))
(cāse <expression>
<case clause>^{+})
(cāse <expression>
<case clause>*
(else <tail sequence>))
(and <expression>* <tail expression>)
(or <expression>* <tail expression>)
(let <bindings> <tail body>)
(let <variable> <bindings> <tail body>)
(let* <bindings> <tail body>)
(letrec* <bindings> <tail body>)
(letrec <bindings> <tail body>)
(letvalues <mvbindings> <tail body>)
(let*values <mvbindings> <tail body>)
(letsyntax <bindings> <tail body>)
(letrecsyntax <bindings> <tail body>)
(begin <tail sequence>)
A <cond clause> is
(<test> <tail sequence>),a <case clause> is
((<datum>*) <tail sequence>),a <tail body> is
<definition>* <tail sequence>,and a <tail sequence> is
<expression>* <tail expression>.
If a cond expression is in a tail context, and has a clause of the form (<expression_{1}> => <expression_{2}>) then the (implied) call to the procedure that results from the evaluation of <expression_{2}> is in a tail context. <Expression_{2}> itself is not in a tail context.
Certain builtin procedures must also perform tail calls. The first argument passed to apply and to callwithcurrentcontinuation, and the second argument passed to callwithvalues, must be called via a tail call.
In the following example the only tail call is the call to f. None of the calls to g or h are tail calls. The reference to x is in a tail context, but it is not a call and thus is not a tail call.
(lambda ()(if (g)
(let ((x (h)))
x)
(and (g) (f))))
Note: Implementations may recognize that some nontail calls, such as the call to h above, can be evaluated as though they were tail calls. In the example above, the let expression could be compiled as a tail call to h. (The possibility of h returning an unexpected number of values can be ignored, because in that case the effect of the let is explicitly unspecified and implementationdependent.)