source: project/wiki/man/4/The R5RS standard @ 30951

Last change on this file since 30951 was 30951, checked in by sjamaan, 7 years ago

Update the online User's Manual for CHICKEN 4.9.0

File size: 123.8 KB
1This document describes Chicken's R5RS support, with a heavy emphasis
2on syntax and procedures.  It is based directly on the
3''Revised^5 Report on the Algorithmic Language Scheme''.
6== Expressions
8Expression types are categorized as primitive or derived. Primitive
9expression types include variables and procedure calls. Derived
10expression types are not semantically primitive, but can instead be
11defined as macros. With the exception of quasiquote, whose macro
12definition is complex, the derived expressions are classified as
13library features.  The distinction which R5RS makes between primitive
14and derived is unimportant and does not necessarily reflect how it's
15implemented in CHICKEN itself.
17=== Primitive expression types
19==== Variable references
23An expression consisting of a variable is a variable reference. The
24value of the variable reference is the value stored in the location to
25which the variable is bound. It is an error to reference an unbound
28 (define x 28)
29 x           ===>  28
31==== Literal expressions
33<macro>(quote <datum>)</macro><br>
37(quote <datum>) evaluates to <datum>. <Datum> may be any external
38representation of a Scheme object. This notation is used to include
39literal constants in Scheme code.
41 (quote a)                    ===>  a
42 (quote #(a b c))             ===>  #(a b c)
43 (quote (+ 1 2))              ===>  (+ 1 2)
45(quote <datum>) may be abbreviated as '<datum>. The two notations are
46equivalent in all respects.
48 'a                           ===>  a
49 '#(a b c)                    ===>  #(a b c)
50 '()                          ===>  ()
51 '(+ 1 2)                     ===>  (+ 1 2)
52 '(quote a)                   ===>  (quote a)
53 ''a                          ===>  (quote a)
55Numerical constants, string constants, character constants, and boolean
56constants evaluate "to themselves"; they need not be quoted.
58 '"abc"             ===>  "abc"
59 "abc"              ===>  "abc"
60 '145932            ===>  145932
61 145932             ===>  145932
62 '#t                ===>  #t
63 #t                 ===>  #t
65It is an error to alter a constant (i.e. the value of a literal
66expression) using a mutation procedure like set-car! or string-set!.
67In the current implementation of CHICKEN, identical constants don't
68share memory and it is possible to mutate them, but this may change in
69the future.
71==== Procedure calls
73<macro>(<operator> <operand[1]> ...)</macro><br>
75A procedure call is written by simply enclosing in parentheses
76expressions for the procedure to be called and the arguments to be
77passed to it. The operator and operand expressions are evaluated (in an
78unspecified order) and the resulting procedure is passed the resulting
81 (+ 3 4)                           ===>  7
82 ((if #f + *) 3 4)                 ===>  12
84A number of procedures are available as the values of variables in the
85initial environment; for example, the addition and multiplication
86procedures in the above examples are the values of the variables + and
87*.  New procedures are created by evaluating lambda
88expressions. Procedure calls may return any number of values (see the
89{{values}} procedure [[#control-features|below]]).
91Procedure calls are also called combinations.
93Note:   In contrast to other dialects of Lisp, the order of
94evaluation is unspecified, and the operator expression and the
95operand expressions are always evaluated with the same evaluation
98Note:   Although the order of evaluation is otherwise unspecified,
99the effect of any concurrent evaluation of the operator and operand
100expressions is constrained to be consistent with some sequential
101order of evaluation. The order of evaluation may be chosen
102differently for each procedure call.
104Note:   In many dialects of Lisp, the empty combination, (), is a
105legitimate expression. In Scheme, combinations must have at least
106one subexpression, so () is not a syntactically valid expression.
108==== Procedures
110<macro>(lambda <formals> <body>)</macro><br>
112Syntax: <Formals> should be a formal arguments list as described below,
113and <body> should be a sequence of one or more expressions.
115Semantics: A lambda expression evaluates to a procedure. The
116environment in effect when the lambda expression was evaluated is
117remembered as part of the procedure. When the procedure is later called
118with some actual arguments, the environment in which the lambda
119expression was evaluated will be extended by binding the variables in
120the formal argument list to fresh locations, the corresponding actual
121argument values will be stored in those locations, and the expressions
122in the body of the lambda expression will be evaluated sequentially in
123the extended environment. The result(s) of the last expression in the
124body will be returned as the result(s) of the procedure call.
126 (lambda (x) (+ x x))              ===>  a procedure
127 ((lambda (x) (+ x x)) 4)          ===>  8
129 (define reverse-subtract
130   (lambda (x y) (- y x)))
131 (reverse-subtract 7 10)           ===>  3
133 (define add4
134   (let ((x 4))
135     (lambda (y) (+ x y))))
136 (add4 6)                          ===>  10
138<Formals> should have one of the following forms:
140*   (<variable[1]> ...): The procedure takes a fixed number of
141    arguments; when the procedure is called, the arguments will be
142    stored in the bindings of the corresponding variables.
144*   <variable>: The procedure takes any number of arguments; when the
145    procedure is called, the sequence of actual arguments is converted
146    into a newly allocated list, and the list is stored in the binding
147    of the <variable>.
149*   (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
150    space-delimited period precedes the last variable, then the
151    procedure takes n or more arguments, where n is the number of
152    formal arguments before the period (there must be at least one).
153    The value stored in the binding of the last variable will be a
154    newly allocated list of the actual arguments left over after all
155    the other actual arguments have been matched up against the other
156    formal arguments.
158It is an error for a <variable> to appear more than once in <formals>.
160 ((lambda x x) 3 4 5 6)                  ===>  (3 4 5 6)
161 ((lambda (x y . z) z)
162  3 4 5 6)                               ===>  (5 6)
164Each procedure created as the result of evaluating a lambda expression
165is (conceptually) tagged with a storage location, in order to make eqv?
166and eq? work on procedures.
168==== Conditionals
170<macro>(if <test> <consequent> <alternate>)</macro><br>
171<macro>(if <test> <consequent>)</macro><br>
173Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
176Semantics: An if expression is evaluated as follows: first, <test> is
177evaluated. If it yields a true value (see [[#booleans|the section
178about booleans]] below), then <consequent> is evaluated and its
179value(s) is(are) returned. Otherwise <alternate> is evaluated and its
180value(s) is(are) returned. If <test> yields a false value and no
181<alternate> is specified, then the result of the expression is
184 (if (> 3 2) 'yes 'no)                   ===>  yes
185 (if (> 2 3) 'yes 'no)                   ===>  no
186 (if (> 3 2)
187     (- 3 2)
188     (+ 3 2))                            ===>  1
190==== Assignments
192<macro>(set! <variable> <expression>)</macro><br>
194<Expression> is evaluated, and the resulting value is stored in the
195location to which <variable> is bound. <Variable> must be bound either
196in some region enclosing the set! expression or at top level. The
197result of the set! expression is unspecified.
199 (define x 2)
200 (+ x 1)                         ===>  3
201 (set! x 4)                      ===>  unspecified
202 (+ x 1)                         ===>  5
204=== Derived expression types
206The constructs in this section are hygienic.  For reference purposes,
207these macro definitions will convert most of the constructs described
208in this section into the primitive constructs described in the
209previous section.  This does not necessarily mean that's exactly how
210it's implemented in CHICKEN.
212==== Conditionals
214<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
216Syntax: Each <clause> should be of the form
218 (<test> <expression[1]> ...)
220where <test> is any expression. Alternatively, a <clause> may be of the
223 (<test> => <expression>)
225The last <clause> may be an "else clause," which has the form
227 (else <expression[1]> <expression[2]> ...).
229Semantics: A cond expression is evaluated by evaluating the <test>
230expressions of successive <clause>s in order until one of them
231evaluates to a true value (see [[#booleans|the section about
232booleans]] below). When a <test> evaluates to a true value, then the
233remaining <expression>s in its <clause> are evaluated in order, and
234the result(s) of the last <expression> in the <clause> is(are)
235returned as the result(s) of the entire cond expression. If the
236selected <clause> contains only the <test> and no <expression>s, then
237the value of the <test> is returned as the result.  If the selected
238<clause> uses the => alternate form, then the <expression> is
239evaluated. Its value must be a procedure that accepts one argument;
240this procedure is then called on the value of the <test> and the
241value(s) returned by this procedure is(are) returned by the cond
242expression. If all <test>s evaluate to false values, and there is no
243else clause, then the result of the conditional expression is
244unspecified; if there is an else clause, then its <expression>s are
245evaluated, and the value(s) of the last one is(are) returned.
247 (cond ((> 3 2) 'greater)
248       ((< 3 2) 'less))           ===>  greater
249 (cond ((> 3 3) 'greater)
250       ((< 3 3) 'less)
251       (else 'equal))             ===>  equal
252 (cond ((assv 'b '((a 1) (b 2))) => cadr)
253       (else #f))                 ===>  2
255<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
257Syntax: <Key> may be any expression. Each <clause> should have the form
259 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
261where each <datum> is an external representation of some object.
262Alternatively, as per R7RS, a <clause> may be of the form
264 ((<datum[1]> ...) => <expression>).
266All the <datum>s must be distinct. The last <clause> may be an
267"else clause," which has one of the following two forms:
269 (else <expression[1]> <expression[2]> ...)
270 (else => <expression>).      ; R7RS extension
272Semantics: A case expression is evaluated as follows. <Key> is
273evaluated and its result is compared against each <datum>. If the
274result of evaluating <key> is equivalent (in the sense of {{eqv?}};
275see [[#equivalence-predicates|below]]) to a <datum>, then the
276expressions in the corresponding <clause> are evaluated from left to
277right and the result(s) of the last expression in the <clause> is(are)
278returned as the result(s) of the case expression. If the selected
279<clause> uses the => alternate form (an R7RS extension), then the
280<expression> is evaluated. Its value must be a procedure that accepts
281one argument; this procedure is then called on the value of the <key>
282and the value(s) returned by this procedure is(are) returned by the
283case expression.  If the result of evaluating <key> is different from
284every <datum>, then if there is an else clause its expressions are
285evaluated and the result(s) of the last is(are) the result(s) of the
286case expression; otherwise the result of the case expression is
289 (case (* 2 3)
290   ((2 3 5 7) 'prime)
291   ((1 4 6 8 9) 'composite))             ===>  composite
292 (case (car '(c d))
293   ((a) 'a)
294   ((b) 'b))                             ===>  unspecified
295 (case (car '(c d))
296   ((a e i o u) 'vowel)
297   ((w y) 'semivowel)
298   (else 'consonant))                    ===>  consonant
300<macro>(and <test[1]> ...)</macro><br>
302The <test> expressions are evaluated from left to right, and the value
303of the first expression that evaluates to a false value (see
304[[#booleans|the section about booleans]]) is returned. Any remaining
305expressions are not evaluated. If all the expressions evaluate to true
306values, the value of the last expression is returned. If there are no
307expressions then #t is returned.
309 (and (= 2 2) (> 2 1))                   ===>  #t
310 (and (= 2 2) (< 2 1))                   ===>  #f
311 (and 1 2 'c '(f g))                     ===>  (f g)
312 (and)                                   ===>  #t
314<macro>(or <test[1]> ...)</macro><br>
316The <test> expressions are evaluated from left to right, and the value
317of the first expression that evaluates to a true value (see
318[[#booleans|the section about booleans]]) is returned. Any remaining
319expressions are not evaluated. If all expressions evaluate to false
320values, the value of the last expression is returned. If there are no
321expressions then #f is returned.
323 (or (= 2 2) (> 2 1))                    ===>  #t
324 (or (= 2 2) (< 2 1))                    ===>  #t
325 (or #f #f #f)         ===>  #f
326 (or (memq 'b '(a b c))
327     (/ 3 0))                            ===>  (b c)
329==== Binding constructs
331The three binding constructs let, let*, and letrec give Scheme a block
332structure, like Algol 60. The syntax of the three constructs is
333identical, but they differ in the regions they establish for their
334variable bindings. In a let expression, the initial values are computed
335before any of the variables become bound; in a let* expression, the
336bindings and evaluations are performed sequentially; while in a letrec
337expression, all the bindings are in effect while their initial values
338are being computed, thus allowing mutually recursive definitions.
340<macro>(let <bindings> <body>)</macro><br>
342Syntax: <Bindings> should have the form
344 ((<variable[1]> <init[1]>) ...),
346where each <init> is an expression, and <body> should be a sequence of
347one or more expressions. It is an error for a <variable> to appear more
348than once in the list of variables being bound.
350Semantics: The <init>s are evaluated in the current environment (in
351some unspecified order), the <variable>s are bound to fresh locations
352holding the results, the <body> is evaluated in the extended
353environment, and the value(s) of the last expression of <body> is(are)
354returned. Each binding of a <variable> has <body> as its region.
356 (let ((x 2) (y 3))
357   (* x y))                              ===>  6
359 (let ((x 2) (y 3))
360   (let ((x 7)
361         (z (+ x y)))
362     (* z x)))                           ===>  35
364See also "named let", [[#iteration|below]].
366<macro>(let* <bindings> <body>)</macro><br>
368Syntax: <Bindings> should have the form
370 ((<variable[1]> <init[1]>) ...),
372and <body> should be a sequence of one or more expressions.
374Semantics: Let* is similar to let, but the bindings are performed
375sequentially from left to right, and the region of a binding indicated
376by (<variable> <init>) is that part of the let* expression to the right
377of the binding. Thus the second binding is done in an environment in
378which the first binding is visible, and so on.
380 (let ((x 2) (y 3))
381   (let* ((x 7)
382          (z (+ x y)))
383     (* z x)))                     ===>  70
385<macro>(letrec <bindings> <body>)</macro><br>
387Syntax: <Bindings> should have the form
389 ((<variable[1]> <init[1]>) ...),
391and <body> should be a sequence of one or more expressions. It is an
392error for a <variable> to appear more than once in the list of
393variables being bound.
395Semantics: The <variable>s are bound to fresh locations holding
396undefined values, the <init>s are evaluated in the resulting
397environment (in some unspecified order), each <variable> is assigned to
398the result of the corresponding <init>, the <body> is evaluated in the
399resulting environment, and the value(s) of the last expression in
400<body> is(are) returned. Each binding of a <variable> has the entire
401letrec expression as its region, making it possible to define mutually
402recursive procedures.
404 (letrec ((even?
405           (lambda (n)
406             (if (zero? n)
407                 #t
408                 (odd? (- n 1)))))
409          (odd?
410           (lambda (n)
411             (if (zero? n)
412                 #f
413                 (even? (- n 1))))))
414   (even? 88))
415                         ===>  #t
417One restriction on letrec is very important: it must be possible to
418evaluate each <init> without assigning or referring to the value of any
419<variable>. If this restriction is violated, then it is an error. The
420restriction is necessary because Scheme passes arguments by value
421rather than by name. In the most common uses of letrec, all the <init>s
422are lambda expressions and the restriction is satisfied automatically.
424==== Sequencing
426<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
428The <expression>s are evaluated sequentially from left to right, and
429the value(s) of the last <expression> is(are) returned. This expression
430type is used to sequence side effects such as input and output.
432 (define x 0)
434 (begin (set! x 5)
435        (+ x 1))                          ===>  6
437 (begin (display "4 plus 1 equals ")
438        (display (+ 4 1)))                ===>  unspecified
439   and prints  4 plus 1 equals 5
441==== Iteration
443<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
445Do is an iteration construct. It specifies a set of variables to be
446bound, how they are to be initialized at the start, and how they are to
447be updated on each iteration. When a termination condition is met, the
448loop exits after evaluating the <expression>s.
450Do expressions are evaluated as follows: The <init> expressions are
451evaluated (in some unspecified order), the <variable>s are bound to
452fresh locations, the results of the <init> expressions are stored in
453the bindings of the <variable>s, and then the iteration phase begins.
455Each iteration begins by evaluating <test>; if the result is false
456(see [[#booleans|the section about booleans]]), then the <command>
457expressions are evaluated in order for effect, the <step> expressions
458are evaluated in some unspecified order, the <variable>s are bound to
459fresh locations, the results of the <step>s are stored in the bindings
460of the <variable>s, and the next iteration begins.
462If <test> evaluates to a true value, then the <expression>s are
463evaluated from left to right and the value(s) of the last <expression>
464is(are) returned. If no <expression>s are present, then the value of
465the do expression is unspecified.
467The region of the binding of a <variable> consists of the entire do
468expression except for the <init>s. It is an error for a <variable> to
469appear more than once in the list of do variables.
471A <step> may be omitted, in which case the effect is the same as if
472(<variable> <init> <variable>) had been written instead of (<variable>
475 (do ((vec (make-vector 5))
476      (i 0 (+ i 1)))
477     ((= i 5) vec)
478   (vector-set! vec i i))                    ===>  #(0 1 2 3 4)
480 (let ((x '(1 3 5 7 9)))
481   (do ((x x (cdr x))
482        (sum 0 (+ sum (car x))))
483       ((null? x) sum)))                     ===>  25
485<macro>(let <variable> <bindings> <body>)</macro><br>
487"Named let" is a variant on the syntax of let which provides a more
488general looping construct than do and may also be used to express
489recursions. It has the same syntax and semantics as ordinary let except
490that <variable> is bound within <body> to a procedure whose formal
491arguments are the bound variables and whose body is <body>. Thus the
492execution of <body> may be repeated by invoking the procedure named by
495 (let loop ((numbers '(3 -2 1 6 -5))
496            (nonneg '())
497            (neg '()))
498   (cond ((null? numbers) (list nonneg neg))
499         ((>= (car numbers) 0)
500          (loop (cdr numbers)
501                (cons (car numbers) nonneg)
502                neg))
503         ((< (car numbers) 0)
504          (loop (cdr numbers)
505                nonneg
506                (cons (car numbers) neg)))))
507                 ===>  ((6 1 3) (-5 -2))
509==== Delayed evaluation
511<macro>(delay <expression>)</macro><br>
513The delay construct is used together with the procedure force to
514implement lazy evaluation or call by need. {{(delay <expression>)}}
515returns an object called a promise which at some point in the future
516may be asked (by the force procedure) to evaluate {{<expression>}},
517and deliver the resulting value. The {{<expression>}} may return
518multiple values, which will be correctly memoized and returned by
519subsequent calls to {{force}}.  This is a CHICKEN extension to R5RS.
521See the description of {{force}} (under [[#control-features|Control
522features]], below) for a more complete description of {{delay}}.
524<macro>(delay-force <expression>)</macro><br>
526The expression {{(delay-force expression)}} is conceptually similar to
527{{(delay (force expression))}}, with the difference that forcing the
528result of {{delay-force}} will in effect result in a tail call to
529{{(force expression)}}, while forcing the result of
530{{(delay (force expression))}} might not.
532Thus iterative lazy algorithms that might result in a long series of
533chains of delay and force can be rewritten using delay-force to
534prevent consuming unbounded space during evaluation.
536The {{delay-force}} macro is a CHICKEN extension to R5RS, taken from
539See the description of force (under [[#control-features|Control
540features]], below) for a more complete description of delayed
543<procedure>(make-promise obj)</procedure>
545The make-promise procedure returns a promise which, when forced, will
546return {{obj}} . It is similar to {{delay}}, but does not delay its
547argument: it is a procedure rather than syntax. If {{obj}} is already
548a promise, it is returned.
550This procedure is a CHICKEN extension to R5RS, taken from R7RS.
552==== Quasiquotation
554<macro>(quasiquote <qq template>)</macro><br>
555<macro>`<qq template></macro><br>
557"Backquote" or "quasiquote" expressions are useful for constructing
558a list or vector structure when most but not all of the desired
559structure is known in advance. If no commas appear within the <qq
560template>, the result of evaluating `<qq template> is equivalent to the
561result of evaluating '<qq template>. If a comma appears within the <qq
562template>, however, the expression following the comma is evaluated
563("unquoted") and its result is inserted into the structure instead of
564the comma and the expression. If a comma appears followed immediately
565by an at-sign (@), then the following expression must evaluate to a
566list; the opening and closing parentheses of the list are then
567"stripped away" and the elements of the list are inserted in place of
568the comma at-sign expression sequence. A comma at-sign should only
569appear within a list or vector <qq template>.
571 `(list ,(+ 1 2) 4)          ===>  (list 3 4)
572 (let ((name 'a)) `(list ,name ',name))           
573                 ===>  (list a (quote a))
574 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)           
575                 ===>  (a 3 4 5 6 b)
576 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))           
577                 ===>  ((foo 7) . cons)
578 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)           
579                 ===>  #(10 5 2 4 3 8)
581Quasiquote forms may be nested. Substitutions are made only for
582unquoted components appearing at the same nesting level as the
583outermost backquote. The nesting level increases by one inside each
584successive quasiquotation, and decreases by one inside each
587 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)           
588                 ===>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
589 (let ((name1 'x)
590       (name2 'y))
591   `(a `(b ,,name1 ,',name2 d) e))           
592                 ===>  (a `(b ,x ,'y d) e)
594The two notations `<qq template> and (quasiquote <qq template>) are
595identical in all respects. ,<expression> is identical to (unquote
596<expression>), and ,@<expression> is identical to (unquote-splicing
597<expression>). The external syntax generated by write for two-element
598lists whose car is one of these symbols may vary between
601 (quasiquote (list (unquote (+ 1 2)) 4))           
602                 ===>  (list 3 4)
603 '(quasiquote (list (unquote (+ 1 2)) 4))           
604                 ===>  `(list ,(+ 1 2) 4)
605      i.e., (quasiquote (list (unquote (+ 1 2)) 4))
607Unpredictable behavior can result if any of the symbols quasiquote,
608unquote, or unquote-splicing appear in positions within a <qq template>
609otherwise than as described above.
611=== Macros
613Scheme programs can define and use new derived expression types, called
614macros. Program-defined expression types have the syntax
616 (<keyword> <datum> ...)
618where <keyword> is an identifier that uniquely determines the
619expression type. This identifier is called the syntactic keyword, or
620simply keyword, of the macro. The number of the <datum>s, and their
621syntax, depends on the expression type.
623Each instance of a macro is called a use of the macro. The set of rules
624that specifies how a use of a macro is transcribed into a more
625primitive expression is called the transformer of the macro.
627The macro definition facility consists of two parts:
629*   A set of expressions used to establish that certain identifiers are
630    macro keywords, associate them with macro transformers, and control
631    the scope within which a macro is defined, and
633*   a pattern language for specifying macro transformers.
635The syntactic keyword of a macro may shadow variable bindings, and
636local variable bindings may shadow keyword bindings. All macros defined
637using the pattern language are "hygienic" and "referentially
638transparent" and thus preserve Scheme's lexical scoping:
640*   If a macro transformer inserts a binding for an identifier
641    (variable or keyword), the identifier will in effect be renamed
642    throughout its scope to avoid conflicts with other identifiers.
643    Note that a define at top level may or may not introduce a binding;
644    this depends on whether the binding already existed before (in which
645    case its value will be overridden).
647*   If a macro transformer inserts a free reference to an identifier,
648    the reference refers to the binding that was visible where the
649    transformer was specified, regardless of any local bindings that
650    may surround the use of the macro.
652==== Binding constructs for syntactic keywords
654Let-syntax and letrec-syntax are analogous to let and letrec, but they
655bind syntactic keywords to macro transformers instead of binding
656variables to locations that contain values. Syntactic keywords may also
657be bound at top level.
659<macro>(let-syntax <bindings> <body>)</macro><br>
661Syntax: <Bindings> should have the form
663 ((<keyword> <transformer spec>) ...)
665Each <keyword> is an identifier, each <transformer spec> is an instance
666of syntax-rules, and <body> should be a sequence of one or more
667expressions. It is an error for a <keyword> to appear more than once in
668the list of keywords being bound.
670Semantics: The <body> is expanded in the syntactic environment obtained
671by extending the syntactic environment of the let-syntax expression
672with macros whose keywords are the <keyword>s, bound to the specified
673transformers. Each binding of a <keyword> has <body> as its region.
675 (let-syntax ((when (syntax-rules ()
676                      ((when test stmt1 stmt2 ...)
677                       (if test
678                           (begin stmt1
679                                  stmt2 ...))))))
680   (let ((if #t))
681     (when if (set! if 'now))
682     if))                                   ===>  now
684 (let ((x 'outer))
685   (let-syntax ((m (syntax-rules () ((m) x))))
686     (let ((x 'inner))
687       (m))))                               ===>  outer
689<macro>(letrec-syntax <bindings> <body>)</macro><br>
691Syntax: Same as for let-syntax.
693Semantics: The <body> is expanded in the syntactic environment obtained
694by extending the syntactic environment of the letrec-syntax expression
695with macros whose keywords are the <keyword>s, bound to the specified
696transformers. Each binding of a <keyword> has the <bindings> as well as
697the <body> within its region, so the transformers can transcribe
698expressions into uses of the macros introduced by the letrec-syntax
701 (letrec-syntax
702   ((my-or (syntax-rules ()
703             ((my-or) #f)
704             ((my-or e) e)
705             ((my-or e1 e2 ...)
706              (let ((temp e1))
707                (if temp
708                    temp
709                    (my-or e2 ...)))))))
710   (let ((x #f)
711         (y 7)
712         (temp 8)
713         (let odd?)
714         (if even?))
715     (my-or x
716            (let temp)
717            (if y)
718            y)))                ===>  7
720==== Pattern language
722A <transformer spec> has the following form:
724 (syntax-rules <literals> <syntax rule> ...)
726Syntax: <Literals> is a list of identifiers and each <syntax rule>
727should be of the form
729 (<pattern> <template>)
731The <pattern> in a <syntax rule> is a list <pattern> that begins with
732the keyword for the macro.
734A <pattern> is either an identifier, a constant, or one of the
737 (<pattern> ...)
738 (<pattern> <pattern> ... . <pattern>)
739 (<pattern> ... <pattern> <ellipsis>)
740 #(<pattern> ...)
741 #(<pattern> ... <pattern> <ellipsis>)
743and a template is either an identifier, a constant, or one of the
746 (<element> ...)
747 (<element> <element> ... . <template>)
748 #(<element> ...)
750where an <element> is a <template> optionally followed by an <ellipsis>
751and an <ellipsis> is the identifier "..." (which cannot be used as an
752identifier in either a template or a pattern).
754Semantics: An instance of syntax-rules produces a new macro transformer
755by specifying a sequence of hygienic rewrite rules. A use of a macro
756whose keyword is associated with a transformer specified by
757syntax-rules is matched against the patterns contained in the <syntax
758rule>s, beginning with the leftmost <syntax rule>. When a match is
759found, the macro use is transcribed hygienically according to the
762An identifier that appears in the pattern of a <syntax rule> is a
763pattern variable, unless it is the keyword that begins the pattern, is
764listed in <literals>, or is the identifier "...". Pattern variables
765match arbitrary input elements and are used to refer to elements of the
766input in the template. It is an error for the same pattern variable to
767appear more than once in a <pattern>.
769The keyword at the beginning of the pattern in a <syntax rule> is not
770involved in the matching and is not considered a pattern variable or
771literal identifier.
773Rationale:   The scope of the keyword is determined by the
774expression or syntax definition that binds it to the associated
775macro transformer. If the keyword were a pattern variable or
776literal identifier, then the template that follows the pattern
777would be within its scope regardless of whether the keyword were
778bound by let-syntax or by letrec-syntax.
780Identifiers that appear in <literals> are interpreted as literal
781identifiers to be matched against corresponding subforms of the input.
782A subform in the input matches a literal identifier if and only if it
783is an identifier and either both its occurrence in the macro expression
784and its occurrence in the macro definition have the same lexical
785binding, or the two identifiers are equal and both have no lexical
788A subpattern followed by ... can match zero or more elements of the
789input. It is an error for ... to appear in <literals>. Within a pattern
790the identifier ... must follow the last element of a nonempty sequence
791of subpatterns.
793More formally, an input form F matches a pattern P if and only if:
795*   P is a non-literal identifier; or
797*   P is a literal identifier and F is an identifier with the same
798    binding; or
800*   P is a list (P[1] ... P[n]) and F is a list of n forms that match P
801    [1] through P[n], respectively; or
803*   P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
804    or improper list of n or more forms that match P[1] through P[n],
805    respectively, and whose nth "cdr" matches P[n+1]; or
807*   P is of the form (P[1] ... P[n] P[n+1] <ellipsis>) where <ellipsis>
808    is the identifier ... and F is a proper list of at least n forms,
809    the first n of which match P[1] through P[n], respectively, and
810    each remaining element of F matches P[n+1]; or
812*   P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
813    forms that match P[1] through P[n]; or
815*   P is of the form #(P[1] ... P[n] P[n+1] <ellipsis>) where
816    <ellipsis> is the identifier ... and F is a vector of n or more
817    forms the first n of which match P[1] through P[n], respectively,
818    and each remaining element of F matches P[n+1]; or
820*   P is a datum and F is equal to P in the sense of the equal?
821    procedure.
823It is an error to use a macro keyword, within the scope of its binding,
824in an expression that does not match any of the patterns.
826When a macro use is transcribed according to the template of the
827matching <syntax rule>, pattern variables that occur in the template
828are replaced by the subforms they match in the input. Pattern variables
829that occur in subpatterns followed by one or more instances of the
830identifier ... are allowed only in subtemplates that are followed by as
831many instances of .... They are replaced in the output by all of the
832subforms they match in the input, distributed as indicated. It is an
833error if the output cannot be built up as specified.
835Identifiers that appear in the template but are not pattern variables
836or the identifier ... are inserted into the output as literal
837identifiers. If a literal identifier is inserted as a free identifier
838then it refers to the binding of that identifier within whose scope the
839instance of syntax-rules appears. If a literal identifier is inserted
840as a bound identifier then it is in effect renamed to prevent
841inadvertent captures of free identifiers.
843As an example, if let and cond are defined as usual, then they are
844hygienic (as required) and the following is not an error.
846 (let ((=> #f))
847   (cond (#t => 'ok)))                   ===> ok
849The macro transformer for cond recognizes => as a local variable, and
850hence an expression, and not as the top-level identifier =>, which the
851macro transformer treats as a syntactic keyword. Thus the example
852expands into
854 (let ((=> #f))
855   (if #t (begin => 'ok)))
857instead of
859 (let ((=> #f))
860   (let ((temp #t))
861     (if temp ('ok temp))))
863which would result in an invalid procedure call.
865== Program structure
867== Standard procedures
869This chapter describes Scheme's built-in procedures. The initial (or
870"top level") Scheme environment starts out with a number of variables
871bound to locations containing useful values, most of which are
872primitive procedures that manipulate data. For example, the variable
873abs is bound to (a location initially containing) a procedure of one
874argument that computes the absolute value of a number, and the variable
875+ is bound to a procedure that computes sums. Built-in procedures that
876can easily be written in terms of other built-in procedures are
877identified as "library procedures".
879A program may use a top-level definition to bind any variable. It may
880subsequently alter any such binding by an assignment (see
881[[#assignments|assignments]], above). These operations do
882not modify the behavior of Scheme's built-in procedures. Altering any
883top-level binding that has not been introduced by a definition has an
884unspecified effect on the behavior of the built-in procedures.
886=== Equivalence predicates
888A predicate is a procedure that always returns a boolean value (#t or #f).
889An equivalence predicate is the computational analogue of a
890mathematical equivalence relation (it is symmetric, reflexive, and
891transitive). Of the equivalence predicates described in this section,
892eq? is the finest or most discriminating, and equal? is the coarsest.
893eqv? is slightly less discriminating than eq?.
895<procedure>(eqv? obj[1] obj[2])</procedure><br>
897The eqv? procedure defines a useful equivalence relation on objects.
898Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
899as the same object. This relation is left slightly open to
900interpretation, but the following partial specification of eqv? holds
901for all implementations of Scheme.
903The eqv? procedure returns #t if:
905*   obj[1] and obj[2] are both #t or both #f.
907*   obj[1] and obj[2] are both symbols and
909    (string=? (symbol->string obj1)
910              (symbol->string obj2))
911                ===>  #t
913Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
914symbol" as alluded to in the section on [[#symbols|symbols]]. This
915report does not presume to specify the behavior of eqv? on
916implementation-dependent extensions.
918*   obj[1] and obj[2] are both numbers, are numerically equal (see =,
919    under [[#numerical-operations|numerical operations]]), and are
920    either both exact or both inexact.
922*   obj[1] and obj[2] are both characters and are the same character
923    according to the char=? procedure (see "[[#characters|characters]]").
925*   both obj[1] and obj[2] are the empty list.
927*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
928    same locations in the store.
930*   obj[1] and obj[2] are procedures whose location tags are equal
931    (see "[[#procedures|procedures]]").
933The eqv? procedure returns #f if:
935*   obj[1] and obj[2] are of different types.
937*   one of obj[1] and obj[2] is #t but the other is #f.
939*   obj[1] and obj[2] are symbols but
941    (string=? (symbol->string obj[1])
942              (symbol->string obj[2]))
943                ===>  #f
945*   one of obj[1] and obj[2] is an exact number but the other is an
946    inexact number.
948*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
950*   obj[1] and obj[2] are characters for which the char=? procedure
951    returns #f.
953*   one of obj[1] and obj[2] is the empty list but the other is not.
955*   obj[1] and obj[2] are pairs, vectors, or strings that denote
956    distinct locations.
958*   obj[1] and obj[2] are procedures that would behave differently
959    (return different value(s) or have different side effects) for some
960    arguments.
962 (eqv? 'a 'a)                             ===>  #t
963 (eqv? 'a 'b)                             ===>  #f
964 (eqv? 2 2)                               ===>  #t
965 (eqv? '() '())                           ===>  #t
966 (eqv? 100000000 100000000)               ===>  #t
967 (eqv? (cons 1 2) (cons 1 2))             ===>  #f
968 (eqv? (lambda () 1)
969       (lambda () 2))                     ===>  #f
970 (eqv? #f 'nil)                           ===>  #f
971 (let ((p (lambda (x) x)))
972   (eqv? p p))                            ===>  #t
974The following examples illustrate cases in which the above rules do not
975fully specify the behavior of eqv?. All that can be said about such
976cases is that the value returned by eqv? must be a boolean.
978 (eqv? "" "")                     ===>  unspecified
979 (eqv? '#() '#())                 ===>  unspecified
980 (eqv? (lambda (x) x)
981       (lambda (x) x))            ===>  unspecified
982 (eqv? (lambda (x) x)
983       (lambda (y) y))            ===>  unspecified
985The next set of examples shows the use of eqv? with procedures that
986have local state. Gen-counter must return a distinct procedure every
987time, since each procedure has its own internal counter. Gen-loser,
988however, returns equivalent procedures each time, since the local state
989does not affect the value or side effects of the procedures.
991 (define gen-counter
992   (lambda ()
993     (let ((n 0))
994       (lambda () (set! n (+ n 1)) n))))
995 (let ((g (gen-counter)))
996   (eqv? g g))                   ===>  #t
997 (eqv? (gen-counter) (gen-counter))
998                                 ===>  #f
999 (define gen-loser
1000   (lambda ()
1001     (let ((n 0))
1002       (lambda () (set! n (+ n 1)) 27))))
1003 (let ((g (gen-loser)))
1004   (eqv? g g))                   ===>  #t
1005 (eqv? (gen-loser) (gen-loser))
1006                                 ===>  unspecified
1008 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1009          (g (lambda () (if (eqv? f g) 'both 'g))))
1010   (eqv? f g))
1011                                 ===>  unspecified
1013 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1014          (g (lambda () (if (eqv? f g) 'g 'both))))
1015   (eqv? f g))
1016                                 ===>  #f
1018Since it is an error to modify constant objects (those returned by
1019literal expressions), implementations are permitted, though not
1020required, to share structure between constants where appropriate. Thus
1021the value of eqv? on constants is sometimes implementation-dependent.
1023 (eqv? '(a) '(a))                         ===>  unspecified
1024 (eqv? "a" "a")                           ===>  unspecified
1025 (eqv? '(b) (cdr '(a b)))                 ===>  unspecified
1026 (let ((x '(a)))
1027   (eqv? x x))                            ===>  #t
1029Rationale:   The above definition of eqv? allows implementations
1030latitude in their treatment of procedures and literals:
1031implementations are free either to detect or to fail to detect that
1032two procedures or two literals are equivalent to each other, and
1033can decide whether or not to merge representations of equivalent
1034objects by using the same pointer or bit pattern to represent both.
1036<procedure>(eq? obj[1] obj[2])</procedure><br>
1038Eq? is similar to eqv? except that in some cases it is capable of
1039discerning distinctions finer than those detectable by eqv?.
1041Eq? and eqv? are guaranteed to have the same behavior on symbols,
1042booleans, the empty list, pairs, procedures, and non-empty strings and
1043vectors. Eq?'s behavior on numbers and characters is
1044implementation-dependent, but it will always return either true or
1045false, and will return true only when eqv? would also return true. Eq?
1046may also behave differently from eqv? on empty vectors and empty
1049 (eq? 'a 'a)                             ===>  #t
1050 (eq? '(a) '(a))                         ===>  unspecified
1051 (eq? (list 'a) (list 'a))               ===>  #f
1052 (eq? "a" "a")                           ===>  unspecified
1053 (eq? "" "")                             ===>  unspecified
1054 (eq? '() '())                           ===>  #t
1055 (eq? 2 2)                               ===>  unspecified
1056 (eq? #\A #\A)                           ===>  unspecified
1057 (eq? car car)                           ===>  #t
1058 (let ((n (+ 2 3)))
1059   (eq? n n))              ===>  unspecified
1060 (let ((x '(a)))
1061   (eq? x x))              ===>  #t
1062 (let ((x '#()))
1063   (eq? x x))              ===>  #t
1064 (let ((p (lambda (x) x)))
1065   (eq? p p))              ===>  #t
1067Rationale:   It will usually be possible to implement eq? much more
1068efficiently than eqv?, for example, as a simple pointer comparison
1069instead of as some more complicated operation. One reason is that
1070it may not be possible to compute eqv? of two numbers in constant
1071time, whereas eq? implemented as pointer comparison will always
1072finish in constant time. Eq? may be used like eqv? in applications
1073using procedures to implement objects with state since it obeys the
1074same constraints as eqv?.
1076<procedure>(equal? obj[1] obj[2])</procedure><br>
1078Equal? recursively compares the contents of pairs, vectors, and
1079strings, applying eqv? on other objects such as numbers and symbols. A
1080rule of thumb is that objects are generally equal? if they print the
1081same. Equal? may fail to terminate if its arguments are circular data
1084 (equal? 'a 'a)                          ===>  #t
1085 (equal? '(a) '(a))                      ===>  #t
1086 (equal? '(a (b) c)
1087         '(a (b) c))                     ===>  #t
1088 (equal? "abc" "abc")                    ===>  #t
1089 (equal? 2 2)                            ===>  #t
1090 (equal? (make-vector 5 'a)
1091         (make-vector 5 'a))             ===>  #t
1092 (equal? (lambda (x) x)
1093         (lambda (y) y))          ===>  unspecified
1095=== Numbers
1097Numerical computation has traditionally been neglected by the Lisp
1098community. Until Common Lisp there was no carefully thought out
1099strategy for organizing numerical computation, and with the exception
1100of the MacLisp system [20] little effort was made to execute numerical
1101code efficiently. This report recognizes the excellent work of the
1102Common Lisp committee and accepts many of their recommendations. In
1103some ways this report simplifies and generalizes their proposals in a
1104manner consistent with the purposes of Scheme.
1106It is important to distinguish between the mathematical numbers, the
1107Scheme numbers that attempt to model them, the machine representations
1108used to implement the Scheme numbers, and notations used to write
1109numbers. This report uses the types number, complex, real, rational,
1110and integer to refer to both mathematical numbers and Scheme numbers.
1111Machine representations such as fixed point and floating point are
1112referred to by names such as fixnum and flonum.
1114==== Numerical types
1116Mathematically, numbers may be arranged into a tower of subtypes in
1117which each level is a subset of the level above it:
1119    number
1120    complex
1121    real
1122    rational
1123    integer
1125For example, 3 is an integer. Therefore 3 is also a rational, a real,
1126and a complex. The same is true of the Scheme numbers that model 3. For
1127Scheme numbers, these types are defined by the predicates number?,
1128complex?, real?, rational?, and integer?.
1130There is no simple relationship between a number's type and its
1131representation inside a computer. Although most implementations of
1132Scheme will offer at least two different representations of 3, these
1133different representations denote the same integer.
1135Scheme's numerical operations treat numbers as abstract data, as
1136independent of their representation as possible. Although an
1137implementation of Scheme may use fixnum, flonum, and perhaps other
1138representations for numbers, this should not be apparent to a casual
1139programmer writing simple programs.
1141It is necessary, however, to distinguish between numbers that are
1142represented exactly and those that may not be. For example, indexes
1143into data structures must be known exactly, as must some polynomial
1144coefficients in a symbolic algebra system. On the other hand, the
1145results of measurements are inherently inexact, and irrational numbers
1146may be approximated by rational and therefore inexact approximations.
1147In order to catch uses of inexact numbers where exact numbers are
1148required, Scheme explicitly distinguishes exact from inexact numbers.
1149This distinction is orthogonal to the dimension of type.
1151==== Exactness
1153Scheme numbers are either exact or inexact. A number is exact if it was
1154written as an exact constant or was derived from exact numbers using
1155only exact operations. A number is inexact if it was written as an
1156inexact constant, if it was derived using inexact ingredients, or if it
1157was derived using inexact operations. Thus inexactness is a contagious
1158property of a number. If two implementations produce exact results for
1159a computation that did not involve inexact intermediate results, the
1160two ultimate results will be mathematically equivalent. This is
1161generally not true of computations involving inexact numbers since
1162approximate methods such as floating point arithmetic may be used, but
1163it is the duty of each implementation to make the result as close as
1164practical to the mathematically ideal result.
1166Rational operations such as + should always produce exact results when
1167given exact arguments. If the operation is unable to produce an exact
1168result, then it may either report the violation of an implementation
1169restriction or it may silently coerce its result to an inexact value.
1170See [[#implementation-restrictions|the next section]].
1172With the exception of inexact->exact, the operations described in this
1173section must generally return inexact results when given any inexact
1174arguments. An operation may, however, return an exact result if it can
1175prove that the value of the result is unaffected by the inexactness of
1176its arguments. For example, multiplication of any number by an exact
1177zero may produce an exact zero result, even if the other argument is
1180==== Implementation restrictions
1182Implementations of Scheme are not required to implement the whole
1183tower of subtypes given under "[[#numerical-types|Numerical types]]",
1184but they must implement a coherent subset consistent with both the
1185purposes of the implementation and the spirit of the Scheme
1186language. For example, an implementation in which all numbers are real
1187may still be quite useful.
1189Implementations may also support only a limited range of numbers of any
1190type, subject to the requirements of this section. The supported range
1191for exact numbers of any type may be different from the supported range
1192for inexact numbers of that type. For example, an implementation that
1193uses flonums to represent all its inexact real numbers may support a
1194practically unbounded range of exact integers and rationals while
1195limiting the range of inexact reals (and therefore the range of inexact
1196integers and rationals) to the dynamic range of the flonum format.
1197Furthermore the gaps between the representable inexact integers and
1198rationals are likely to be very large in such an implementation as the
1199limits of this range are approached.
1201An implementation of Scheme must support exact integers throughout the
1202range of numbers that may be used for indexes of lists, vectors, and
1203strings or that may result from computing the length of a list, vector,
1204or string. The length, vector-length, and string-length procedures must
1205return an exact integer, and it is an error to use anything but an
1206exact integer as an index. Furthermore any integer constant within the
1207index range, if expressed by an exact integer syntax, will indeed be
1208read as an exact integer, regardless of any implementation restrictions
1209that may apply outside this range. Finally, the procedures listed below
1210will always return an exact integer result provided all their arguments
1211are exact integers and the mathematically expected result is
1212representable as an exact integer within the implementation:
1214 +            -             *
1215 quotient     remainder     modulo
1216 max          min           abs
1217 numerator    denominator   gcd
1218 lcm          floor         ceiling
1219 truncate     round         rationalize
1220 expt
1222Implementations are encouraged, but not required, to support exact
1223integers and exact rationals of practically unlimited size and
1224precision, and to implement the above procedures and the / procedure in
1225such a way that they always return exact results when given exact
1226arguments. If one of these procedures is unable to deliver an exact
1227result when given exact arguments, then it may either report a
1228violation of an implementation restriction or it may silently coerce
1229its result to an inexact number. Such a coercion may cause an error
1232An implementation may use floating point and other approximate
1233representation strategies for inexact numbers. This report recommends,
1234but does not require, that the IEEE 32-bit and 64-bit floating point
1235standards be followed by implementations that use flonum
1236representations, and that implementations using other representations
1237should match or exceed the precision achievable using these floating
1238point standards [12].
1240In particular, implementations that use flonum representations must
1241follow these rules: A flonum result must be represented with at least
1242as much precision as is used to express any of the inexact arguments to
1243that operation. It is desirable (but not required) for potentially
1244inexact operations such as sqrt, when applied to exact arguments, to
1245produce exact answers whenever possible (for example the square root of
1246an exact 4 ought to be an exact 2). If, however, an exact number is
1247operated upon so as to produce an inexact result (as by sqrt), and if
1248the result is represented as a flonum, then the most precise flonum
1249format available must be used; but if the result is represented in some
1250other way then the representation must have at least as much precision
1251as the most precise flonum format available.
1253Although Scheme allows a variety of written notations for numbers, any
1254particular implementation may support only some of them. For example,
1255an implementation in which all numbers are real need not support the
1256rectangular and polar notations for complex numbers. If an
1257implementation encounters an exact numerical constant that it cannot
1258represent as an exact number, then it may either report a violation of
1259an implementation restriction or it may silently represent the constant
1260by an inexact number.
1262==== Syntax of numerical constants
1264For a complete formal description of the syntax of the written
1265representations for numbers, see the R5RS report. Note that case is
1266not significant in numerical constants.
1268A number may be written in binary, octal, decimal, or hexadecimal by
1269the use of a radix prefix. The radix prefixes are #b (binary), #o
1270(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
1271number is assumed to be expressed in decimal.
1273A numerical constant may be specified to be either exact or inexact by
1274a prefix. The prefixes are #e for exact, and #i for inexact. An
1275exactness prefix may appear before or after any radix prefix that is
1276used. If the written representation of a number has no exactness
1277prefix, the constant may be either inexact or exact. It is inexact if
1278it contains a decimal point, an exponent, or a "#" character in the
1279place of a digit, otherwise it is exact. In systems with inexact
1280numbers of varying precisions it may be useful to specify the precision
1281of a constant. For this purpose, numerical constants may be written
1282with an exponent marker that indicates the desired precision of the
1283inexact representation. The letters s, f, d, and l specify the use of
1284short, single, double, and long precision, respectively. (When fewer
1285than four internal inexact representations exist, the four size
1286specifications are mapped onto those available. For example, an
1287implementation with two internal representations may map short and
1288single together and long and double together.) In addition, the
1289exponent marker e specifies the default precision for the
1290implementation. The default precision has at least as much precision as
1291double, but implementations may wish to allow this default to be set by
1292the user.
1294 3.14159265358979F0
1295         Round to single --- 3.141593
1296 0.6L0
1297         Extend to long --- .600000000000000
1299==== Numerical operations
1301The numerical routines described below have argument restrictions,
1302which are encoded in the naming conventions of the arguments as
1303given in the procedure's signature.  The conventions are as follows:
1305; {{obj}} : any object
1306; {{list, list1, ... listj, ... list : (see "[[#pairs-and-lists|Pairs and lists]]" below)
1307; {{z, z1, ... zj, ...}} : complex number (currently not supported by CHICKEN core, see the "[[/egg/numbers|numbers]]" egg)
1308; {{x, x1, ... xj, ...}} : real number
1309; {{y, y1, ... yj, ...}} : real number
1310; {{q, q1, ... qj, ...}} : rational number (NOTE: fractional numbers are not supported by CHICKEN core, see the "[[/egg/numbers|numbers]]" egg)
1311; {{n, n1, ... nj, ...}} : integer
1312; {{k, k1, ... kj, ...}} : exact non-negative integer
1314The examples used in this section assume that any
1315numerical constant written using an exact notation is indeed
1316represented as an exact number. Some examples also assume that certain
1317numerical constants written using an inexact notation can be
1318represented without loss of accuracy; the inexact constants were chosen
1319so that this is likely to be true in implementations that use flonums
1320to represent inexact numbers.
1322<procedure>(number? obj)</procedure><br>
1323<procedure>(complex? obj)</procedure><br>
1324<procedure>(real? obj)</procedure><br>
1325<procedure>(rational? obj)</procedure><br>
1326<procedure>(integer? obj)</procedure><br>
1328These numerical type predicates can be applied to any kind of argument,
1329including non-numbers. They return #t if the object is of the named
1330type, and otherwise they return #f. In general, if a type predicate is
1331true of a number then all higher type predicates are also true of that
1332number. Consequently, if a type predicate is false of a number, then
1333all lower type predicates are also false of that number. If z is an
1334inexact complex number, then (real? z) is true if and only if (zero?
1335(imag-part z)) is true. If x is an inexact real number, then (integer?
1336x) is true if and only if (= x (round x)).
1338 (complex? 3+4i)                 ===>  #t
1339 (complex? 3)                    ===>  #t
1340 (real? 3)                       ===>  #t
1341 (real? -2.5+0.0i)               ===>  #t
1342 (real? #e1e10)                  ===>  #t
1343 (rational? 6/10)                ===>  #t
1344 (rational? 6/3)                 ===>  #t
1345 (integer? 3+0i)                 ===>  #t
1346 (integer? 3.0)                  ===>  #t
1347 (integer? 8/4)                  ===>  #t
1349Note:   The behavior of these type predicates on inexact numbers is
1350unreliable, since any inaccuracy may affect the result.
1352Note:   In many implementations the rational? procedure will be the
1353same as real?, and the complex? procedure will be the same as
1354number?, but unusual implementations may be able to represent some
1355irrational numbers exactly or may extend the number system to
1356support some kind of non-complex numbers.
1358<procedure>(exact? z)</procedure><br>
1359<procedure>(inexact? z)</procedure><br>
1361These numerical predicates provide tests for the exactness of a
1362quantity. For any Scheme number, precisely one of these predicates is
1365<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
1366<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
1367<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
1368<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
1369<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
1371These procedures return #t if their arguments are (respectively):
1372equal, monotonically increasing, monotonically decreasing,
1373monotonically nondecreasing, or monotonically nonincreasing.
1375These predicates are required to be transitive.
1377Note:   The traditional implementations of these predicates in
1378Lisp-like languages are not transitive.
1380Note:   While it is not an error to compare inexact numbers using
1381these predicates, the results may be unreliable because a small
1382inaccuracy may affect the result; this is especially true of = and
1383zero?. When in doubt, consult a numerical analyst.
1385<procedure>(zero? z)</procedure><br>
1386<procedure>(positive? x)</procedure><br>
1387<procedure>(negative? x)</procedure><br>
1388<procedure>(odd? n)</procedure><br>
1389<procedure>(even? n)</procedure><br>
1391These numerical predicates test a number for a particular property,
1392returning #t or #f. See note above.
1394<procedure>(max x[1] x[2] ...)</procedure><br>
1395<procedure>(min x[1] x[2] ...)</procedure><br>
1397These procedures return the maximum or minimum of their arguments.
1399 (max 3 4)                      ===>  4    ; exact
1400 (max 3.9 4)                    ===>  4.0  ; inexact
1402Note:   If any argument is inexact, then the result will also be
1403inexact (unless the procedure can prove that the inaccuracy is not
1404large enough to affect the result, which is possible only in
1405unusual implementations). If min or max is used to compare numbers
1406of mixed exactness, and the numerical value of the result cannot be
1407represented as an inexact number without loss of accuracy, then the
1408procedure may report a violation of an implementation restriction.
1410<procedure>(+ z[1] ...)</procedure><br>
1411<procedure>(* z[1] ...)</procedure><br>
1413These procedures return the sum or product of their arguments.
1415 (+ 3 4)                         ===>  7
1416 (+ 3)                           ===>  3
1417 (+)                             ===>  0
1418 (* 4)                           ===>  4
1419 (*)                             ===>  1
1421<procedure>(- z[1] z[2])</procedure><br>
1422<procedure>(- z)</procedure><br>
1423<procedure>(- z[1] z[2] ...)</procedure><br>
1424<procedure>(/ z[1] z[2])</procedure><br>
1425<procedure>(/ z)</procedure><br>
1426<procedure>(/ z[1] z[2] ...)</procedure><br>
1428With two or more arguments, these procedures return the difference or
1429quotient of their arguments, associating to the left. With one
1430argument, however, they return the additive or multiplicative inverse
1431of their argument.
1433 (- 3 4)                         ===>  -1
1434 (- 3 4 5)                       ===>  -6
1435 (- 3)                           ===>  -3
1436 (/ 3 4 5)                       ===>  3/20
1437 (/ 3)                           ===>  1/3
1439<procedure>(abs x)</procedure><br>
1441Abs returns the absolute value of its argument.
1443 (abs -7)                        ===>  7
1445<procedure>(quotient n[1] n[2])</procedure><br>
1446<procedure>(remainder n[1] n[2])</procedure><br>
1447<procedure>(modulo n[1] n[2])</procedure><br>
1449These procedures implement number-theoretic (integer) division. n[2]
1450should be non-zero. All three procedures return integers. If n[1]/n[2]
1451is an integer:
1453    (quotient n[1] n[2])           ===> n[1]/n[2]
1454    (remainder n[1] n[2])          ===> 0
1455    (modulo n[1] n[2])             ===> 0
1457If n[1]/n[2] is not an integer:
1459    (quotient n[1] n[2])           ===> n[q]
1460    (remainder n[1] n[2])          ===> n[r]
1461    (modulo n[1] n[2])             ===> n[m]
1463where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
1464|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
1465n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
1467From this we can conclude that for integers n[1] and n[2] with n[2] not
1468equal to 0,
1470     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
1471           (remainder n[1] n[2])))
1472                                         ===>  #t
1474provided all numbers involved in that computation are exact.
1476 (modulo 13 4)                   ===>  1
1477 (remainder 13 4)                ===>  1
1479 (modulo -13 4)                  ===>  3
1480 (remainder -13 4)               ===>  -1
1482 (modulo 13 -4)                  ===>  -3
1483 (remainder 13 -4)               ===>  1
1485 (modulo -13 -4)                 ===>  -1
1486 (remainder -13 -4)              ===>  -1
1488 (remainder -13 -4.0)            ===>  -1.0  ; inexact
1490<procedure>(gcd n[1] ...)</procedure><br>
1491<procedure>(lcm n[1] ...)</procedure><br>
1493These procedures return the greatest common divisor or least common
1494multiple of their arguments. The result is always non-negative.
1496 (gcd 32 -36)                    ===>  4
1497 (gcd)                           ===>  0
1498 (lcm 32 -36)                    ===>  288
1499 (lcm 32.0 -36)                  ===>  288.0  ; inexact
1500 (lcm)                           ===>  1
1502<procedure>(numerator q)</procedure><br>
1503<procedure>(denominator q)</procedure><br>
1505These procedures return the numerator or denominator of their argument;
1506the result is computed as if the argument was represented as a fraction
1507in lowest terms. The denominator is always positive. The denominator of
15080 is defined to be 1.
1510 (numerator (/ 6 4))            ===>  3
1511 (denominator (/ 6 4))          ===>  2
1512 (denominator
1513   (exact->inexact (/ 6 4)))    ===> 2.0
1515<procedure>(floor x)</procedure><br>
1516<procedure>(ceiling x)</procedure><br>
1517<procedure>(truncate x)</procedure><br>
1518<procedure>(round x)</procedure><br>
1520These procedures return integers. Floor returns the largest integer not
1521larger than x. Ceiling returns the smallest integer not smaller than x.
1522Truncate returns the integer closest to x whose absolute value is not
1523larger than the absolute value of x. Round returns the closest integer
1524to x, rounding to even when x is halfway between two integers.
1526Rationale:   Round rounds to even for consistency with the default
1527rounding mode specified by the IEEE floating point standard.
1529Note:   If the argument to one of these procedures is inexact, then
1530the result will also be inexact. If an exact value is needed, the
1531result should be passed to the inexact->exact procedure.
1533 (floor -4.3)                  ===>  -5.0
1534 (ceiling -4.3)                ===>  -4.0
1535 (truncate -4.3)               ===>  -4.0
1536 (round -4.3)                  ===>  -4.0
1538 (floor 3.5)                   ===>  3.0
1539 (ceiling 3.5)                 ===>  4.0
1540 (truncate 3.5)                ===>  3.0
1541 (round 3.5)                   ===>  4.0  ; inexact
1543 (round 7/2)                   ===>  4    ; exact
1544 (round 7)                     ===>  7
1546<procedure>(rationalize x y)</procedure><br>
1548Rationalize returns the simplest rational number differing from x by no
1549more than y. A rational number r[1] is simpler than another rational
1550number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
1551and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
1552Although not all rationals are comparable in this ordering (consider 2/
15537 and 3/5) any interval contains a rational number that is simpler than
1554every other rational number in that interval (the simpler 2/5 lies
1555between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
1558 (rationalize
1559   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
1560 (rationalize .3 1/10)                ===> #i1/3  ; inexact
1562<procedure>(exp z)</procedure><br>
1563<procedure>(log z)</procedure><br>
1564<procedure>(sin z)</procedure><br>
1565<procedure>(cos z)</procedure><br>
1566<procedure>(tan z)</procedure><br>
1567<procedure>(asin z)</procedure><br>
1568<procedure>(acos z)</procedure><br>
1569<procedure>(atan z)</procedure><br>
1570<procedure>(atan y x)</procedure><br>
1572These procedures are part of every implementation that supports general
1573real numbers; they compute the usual transcendental functions. Log
1574computes the natural logarithm of z (not the base ten logarithm). Asin,
1575acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and
1576arctangent (tan^-1), respectively. The two-argument variant of atan
1577computes (angle (make-rectangular x y)) (see below), even in
1578implementations that don't support general complex numbers.
1580In general, the mathematical functions log, arcsine, arccosine, and
1581arctangent are multiply defined. The value of log z is defined to be
1582the one whose imaginary part lies in the range from -pi
1583(exclusive) to pi (inclusive). log 0 is undefined. With log
1584defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are
1585according to the following formulae:
1587 sin^-1 z = - i log (i z + (1 - z^2)^1/2)
1589 cos^-1 z = pi / 2 - sin^-1 z
1591 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
1593The above specification follows [27], which in turn cites [19]; refer
1594to these sources for more detailed discussion of branch cuts, boundary
1595conditions, and implementation of these functions. When it is possible
1596these procedures produce a real result from a real argument.
1598<procedure>(sqrt z)</procedure><br>
1600Returns the principal square root of z. The result will have either
1601positive real part, or zero real part and non-negative imaginary part.
1603<procedure>(expt z[1] z[2])</procedure><br>
1605Returns z[1] raised to the power z[2]. For z[1] != 0
1607 z[1]^z[2] = e^z[2] log z[1]
16090^z is 1 if z = 0 and 0 otherwise.
1611<procedure>(make-rectangular x[1] x[2])</procedure><br>
1612<procedure>(make-polar x[3] x[4])</procedure><br>
1613<procedure>(real-part z)</procedure><br>
1614<procedure>(imag-part z)</procedure><br>
1615<procedure>(magnitude z)</procedure><br>
1616<procedure>(angle z)</procedure><br>
1618These procedures are part of every implementation that supports general
1619complex numbers. Suppose x[1], x[2], x[3], and x[4] are real numbers
1620and z is a complex number such that
1622 z = x[1] + x[2]i = x[3] . e^i x[4]
1626 (make-rectangular x[1] x[2])         ===> z
1627 (make-polar x[3] x[4])             ===> z
1628 (real-part z)                          ===> x[1]
1629 (imag-part z)                          ===> x[2]
1630 (magnitude z)                          ===> |x[3]|
1631 (angle z)                              ===> x[angle]
1633where - pi < x[angle] < pi with x[angle] = x[4] + 2 pi n
1634for some integer n.
1636Rationale:   Magnitude is the same as abs for a real argument, but
1637abs must be present in all implementations, whereas magnitude need
1638only be present in implementations that support general complex
1641<procedure>(exact->inexact z)</procedure><br>
1642<procedure>(inexact->exact z)</procedure><br>
1644Exact->inexact returns an inexact representation of z. The value
1645returned is the inexact number that is numerically closest to the
1646argument. If an exact argument has no reasonably close inexact
1647equivalent, then a violation of an implementation restriction may be
1650Inexact->exact returns an exact representation of z. The value returned
1651is the exact number that is numerically closest to the argument. If an
1652inexact argument has no reasonably close exact equivalent, then a
1653violation of an implementation restriction may be reported.
1655These procedures implement the natural one-to-one correspondence
1656between exact and inexact integers throughout an
1657implementation-dependent range.
1658See "[[#implementation-restrictions|Implementation restrictions]]".
1660==== Numerical input and output
1662<procedure>(number->string z)</procedure><br>
1663<procedure>(number->string z radix)</procedure><br>
1665Radix must be an exact integer, either 2, 8, 10, or 16. If omitted, radix
1666defaults to 10. The procedure number->string takes a number and a
1667radix and returns as a string an external representation of the given
1668number in the given radix such that
1670 (let ((number number)
1671       (radix radix))
1672   (eqv? number
1673         (string->number (number->string number
1674                                         radix)
1675                         radix)))
1677is true. It is an error if no possible result makes this expression
1680If z is inexact, the radix is 10, and the above expression can be
1681satisfied by a result that contains a decimal point, then the result
1682contains a decimal point and is expressed using the minimum number of
1683digits (exclusive of exponent and trailing zeroes) needed to make the
1684above expression true [3, 5]; otherwise the format of the result is
1687The result returned by number->string never contains an explicit radix
1690Note:   The error case can occur only when z is not a complex
1691number or is a complex number with a non-rational real or imaginary
1694Rationale:   If z is an inexact number represented using flonums,
1695and the radix is 10, then the above expression is normally
1696satisfied by a result containing a decimal point. The unspecified
1697case allows for infinities, NaNs, and non-flonum representations.
1699<procedure>(string->number string)</procedure><br>
1700<procedure>(string->number string radix)</procedure><br>
1702Returns a number of the maximally precise representation expressed by
1703the given string. Radix must be an exact integer, either 2, 8, 10, or
170416. If supplied, radix is a default radix that may be overridden by an
1705explicit radix prefix in string (e.g. "#o177"). If radix is not
1706supplied, then the default radix is 10. If string is not a
1707syntactically valid notation for a number, then string->number
1708returns #f.
1710 (string->number "100")                ===>  100
1711 (string->number "100" 16)             ===>  256
1712 (string->number "1e2")                ===>  100.0
1713 (string->number "15##")               ===>  1500.0
1715Note:   The domain of string->number may be restricted by
1716implementations in the following ways. String->number is permitted
1717to return #f whenever string contains an explicit radix prefix. If
1718all numbers supported by an implementation are real, then string->
1719number is permitted to return #f whenever string uses the polar or
1720rectangular notations for complex numbers. If all numbers are
1721integers, then string->number may return #f whenever the fractional
1722notation is used. If all numbers are exact, then string->number may
1723return #f whenever an exponent marker or explicit exactness prefix
1724is used, or if a # appears in place of a digit. If all inexact
1725numbers are integers, then string->number may return #f whenever a
1726decimal point is used.
1728=== Other data types
1730This section describes operations on some of Scheme's non-numeric data
1731types: booleans, pairs, lists, symbols, characters, strings and
1734==== Booleans
1736The standard boolean objects for true and false are written as #t and #f.
1737What really matters, though, are the objects that the Scheme
1738conditional expressions (if, cond, and, or, do) treat as true or false.
1739The phrase "a true value" (or sometimes just "true") means any
1740object treated as true by the conditional expressions, and the phrase
1741"a false value" (or "false") means any object treated as false by
1742the conditional expressions.
1744Of all the standard Scheme values, only #f counts as false in
1745conditional expressions. Except for #f, all standard Scheme values,
1746including #t, pairs, the empty list, symbols, numbers, strings,
1747vectors, and procedures, count as true.
1749Note:   Programmers accustomed to other dialects of Lisp should be
1750aware that Scheme distinguishes both #f and the empty list from the
1751symbol nil.
1753Boolean constants evaluate to themselves, so they do not need to be
1754quoted in programs.
1756 #t                ===>  #t
1757 #f                ===>  #f
1758 '#f               ===>  #f
1760<procedure>(not obj)</procedure><br>
1762Not returns #t if obj is false, and returns #f otherwise.
1764 (not #t)           ===>  #f
1765 (not 3)            ===>  #f
1766 (not (list 3))     ===>  #f
1767 (not #f)           ===>  #t
1768 (not '())          ===>  #f
1769 (not (list))       ===>  #f
1770 (not 'nil)         ===>  #f
1772<procedure>(boolean? obj)</procedure><br>
1774Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
1776 (boolean? #f)                 ===>  #t
1777 (boolean? 0)                  ===>  #f
1778 (boolean? '())                ===>  #f
1780==== Pairs and lists
1782A pair (sometimes called a dotted pair) is a record structure with two
1783fields called the car and cdr fields (for historical reasons). Pairs
1784are created by the procedure cons. The car and cdr fields are accessed
1785by the procedures car and cdr. The car and cdr fields are assigned by
1786the procedures set-car! and set-cdr!.
1788Pairs are used primarily to represent lists. A list can be defined
1789recursively as either the empty list or a pair whose cdr is a list.
1790More precisely, the set of lists is defined as the smallest set X such
1793*   The empty list is in X.
1794*   If list is in X, then any pair whose cdr field contains list is
1795    also in X.
1797The objects in the car fields of successive pairs of a list are the
1798elements of the list. For example, a two-element list is a pair whose
1799car is the first element and whose cdr is a pair whose car is the
1800second element and whose cdr is the empty list. The length of a list is
1801the number of elements, which is the same as the number of pairs.
1803The empty list is a special object of its own type (it is not a pair);
1804it has no elements and its length is zero.
1806Note:   The above definitions imply that all lists have finite
1807length and are terminated by the empty list.
1809The most general notation (external representation) for Scheme pairs is
1810the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
1811car field and c[2] is the value of the cdr field. For example (4 . 5)
1812is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
1813external representation of a pair, not an expression that evaluates to
1814a pair.
1816A more streamlined notation can be used for lists: the elements of the
1817list are simply enclosed in parentheses and separated by spaces. The
1818empty list is written () . For example,
1820 (a b c d e)
1824 (a . (b . (c . (d . (e . ())))))
1826are equivalent notations for a list of symbols.
1828A chain of pairs not ending in the empty list is called an improper
1829list. Note that an improper list is not a list. The list and dotted
1830notations can be combined to represent improper lists:
1832 (a b c . d)
1834is equivalent to
1836 (a . (b . (c . d)))
1838Whether a given pair is a list depends upon what is stored in the cdr
1839field. When the set-cdr! procedure is used, an object can be a list one
1840moment and not the next:
1842 (define x (list 'a 'b 'c))
1843 (define y x)
1844 y                               ===>  (a b c)
1845 (list? y)                       ===>  #t
1846 (set-cdr! x 4)                  ===>  unspecified
1847 x                               ===>  (a . 4)
1848 (eqv? x y)                      ===>  #t
1849 y                               ===>  (a . 4)
1850 (list? y)                       ===>  #f
1851 (set-cdr! x x)                  ===>  unspecified
1852 (list? x)                       ===>  #f
1854Within literal expressions and representations of objects read by the
1855read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
1856denote two-element lists whose first elements are the symbols quote,
1857quasiquote, unquote, and unquote-splicing, respectively. The second
1858element in each case is <datum>. This convention is supported so that
1859arbitrary Scheme programs may be represented as lists. That is,
1860according to Scheme's grammar, every <expression> is also a <datum>.
1861Among other things, this permits the use of the read procedure to
1862parse Scheme programs.
1864<procedure>(pair? obj)</procedure><br>
1866Pair? returns #t if obj is a pair, and otherwise returns #f.
1868 (pair? '(a . b))                ===>  #t
1869 (pair? '(a b c))                ===>  #t
1870 (pair? '())                     ===>  #f
1871 (pair? '#(a b))                 ===>  #f
1873<procedure>(cons obj[1] obj[2])</procedure><br>
1875Returns a newly allocated pair whose car is obj[1] and whose cdr is
1876obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
1877from every existing object.
1879 (cons 'a '())                   ===>  (a)
1880 (cons '(a) '(b c d))            ===>  ((a) b c d)
1881 (cons "a" '(b c))               ===>  ("a" b c)
1882 (cons 'a 3)                     ===>  (a . 3)
1883 (cons '(a b) 'c)                ===>  ((a b) . c)
1885<procedure>(car pair)</procedure><br>
1887Returns the contents of the car field of pair. Note that it is an error
1888to take the car of the empty list.
1890 (car '(a b c))                  ===>  a
1891 (car '((a) b c d))              ===>  (a)
1892 (car '(1 . 2))                  ===>  1
1893 (car '())                       ===>  error
1895<procedure>(cdr pair)</procedure><br>
1897Returns the contents of the cdr field of pair. Note that it is an error
1898to take the cdr of the empty list.
1900 (cdr '((a) b c d))              ===>  (b c d)
1901 (cdr '(1 . 2))                  ===>  2
1902 (cdr '())                       ===>  error
1904<procedure>(set-car! pair obj)</procedure><br>
1906Stores obj in the car field of pair. The value returned by set-car! is
1909 (define (f) (list 'not-a-constant-list))
1910 (define (g) '(constant-list))
1911 (set-car! (f) 3)                     ===>  unspecified
1912 (set-car! (g) 3)                     ===>  error
1914<procedure>(set-cdr! pair obj)</procedure><br>
1916Stores obj in the cdr field of pair. The value returned by set-cdr! is
1919<procedure>(caar pair)</procedure><br>
1920<procedure>(cadr pair)</procedure><br>
1921<procedure>(cdar pair)</procedure><br>
1922<procedure>(cddr pair)</procedure><br>
1923<procedure>(caaar pair)</procedure><br>
1924<procedure>(caadr pair)</procedure><br>
1925<procedure>(cadar pair)</procedure><br>
1926<procedure>(caddr pair)</procedure><br>
1927<procedure>(cdaar pair)</procedure><br>
1928<procedure>(cdadr pair)</procedure><br>
1929<procedure>(cddar pair)</procedure><br>
1930<procedure>(cdddr pair)</procedure><br>
1931<procedure>(caaaar pair)</procedure><br>
1932<procedure>(caaadr pair)</procedure><br>
1933<procedure>(caadar pair)</procedure><br>
1934<procedure>(caaddr pair)</procedure><br>
1935<procedure>(cadaar pair)</procedure><br>
1936<procedure>(cadadr pair)</procedure><br>
1937<procedure>(caddar pair)</procedure><br>
1938<procedure>(cadddr pair)</procedure><br>
1939<procedure>(cdaaar pair)</procedure><br>
1940<procedure>(cdaadr pair)</procedure><br>
1941<procedure>(cdadar pair)</procedure><br>
1942<procedure>(cdaddr pair)</procedure><br>
1943<procedure>(cddaar pair)</procedure><br>
1944<procedure>(cddadr pair)</procedure><br>
1945<procedure>(cdddar pair)</procedure><br>
1946<procedure>(cddddr pair)</procedure><br>
1948These procedures are compositions of car and cdr, where for example
1949caddr could be defined by
1951 (define caddr (lambda (x) (car (cdr (cdr x))))).
1953<procedure>(null? obj)</procedure><br>
1955Returns #t if obj is the empty list, otherwise returns #f.
1957<procedure>(list? obj)</procedure><br>
1959Returns #t if obj is a list, otherwise returns #f. By definition, all
1960lists have finite length and are terminated by the empty list.
1962 (list? '(a b c))             ===>  #t
1963 (list? '())                  ===>  #t
1964 (list? '(a . b))             ===>  #f
1965 (let ((x (list 'a)))
1966   (set-cdr! x x)
1967   (list? x))                 ===>  #f
1969<procedure>(list obj ...)</procedure><br>
1971Returns a newly allocated list of its arguments.
1973 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
1974 (list)                                  ===>  ()
1976<procedure>(length list)</procedure><br>
1978Returns the length of list.
1980 (length '(a b c))                       ===>  3
1981 (length '(a (b) (c d e)))               ===>  3
1982 (length '())                            ===>  0
1984<procedure>(append list ...)</procedure><br>
1986Returns a list consisting of the elements of the first list followed by
1987the elements of the other lists.
1989 (append '(x) '(y))                      ===>  (x y)
1990 (append '(a) '(b c d))                  ===>  (a b c d)
1991 (append '(a (b)) '((c)))                ===>  (a (b) (c))
1993The resulting list is always newly allocated, except that it shares
1994structure with the last list argument. The last argument may actually
1995be any object; an improper list results if the last argument is not a
1996proper list.
1998 (append '(a b) '(c . d))                ===>  (a b c . d)
1999 (append '() 'a)                         ===>  a
2001<procedure>(reverse list)</procedure><br>
2003Returns a newly allocated list consisting of the elements of list in
2004reverse order.
2006 (reverse '(a b c))                      ===>  (c b a)
2007 (reverse '(a (b c) d (e (f))))
2008                 ===>  ((e (f)) d (b c) a)
2010<procedure>(list-tail list k)</procedure><br>
2012Returns the sublist of list obtained by omitting the first k elements.
2013It is an error if list has fewer than k elements. List-tail could be
2014defined by
2016 (define list-tail
2017   (lambda (x k)
2018     (if (zero? k)
2019         x
2020         (list-tail (cdr x) (- k 1)))))
2022<procedure>(list-ref list k)</procedure><br>
2024Returns the kth element of list. (This is the same as the car of
2025(list-tail list k).) It is an error if list has fewer than k elements.
2027 (list-ref '(a b c d) 2)                ===>  c
2028 (list-ref '(a b c d)
2029           (inexact->exact (round 1.8)))
2030                 ===>  c
2032<procedure>(memq obj list)</procedure><br>
2033<procedure>(memv obj list)</procedure><br>
2034<procedure>(member obj list)</procedure><br>
2036These procedures return the first sublist of list whose car is obj,
2037where the sublists of list are the non-empty lists returned by
2038(list-tail list k) for k less than the length of list. If obj does not
2039occur in list, then #f (not the empty list) is returned. Memq uses eq?
2040to compare obj with the elements of list, while memv uses eqv? and
2041member uses equal?.
2043 (memq 'a '(a b c))                      ===>  (a b c)
2044 (memq 'b '(a b c))                      ===>  (b c)
2045 (memq 'a '(b c d))                      ===>  #f
2046 (memq (list 'a) '(b (a) c))             ===>  #f
2047 (member (list 'a)
2048         '(b (a) c))                     ===>  ((a) c)
2049 (memq 101 '(100 101 102))               ===>  unspecified
2050 (memv 101 '(100 101 102))               ===>  (101 102)
2052<procedure>(assq obj alist)</procedure><br>
2053<procedure>(assv obj alist)</procedure><br>
2054<procedure>(assoc obj alist)</procedure><br>
2056Alist (for "association list") must be a list of pairs. These
2057procedures find the first pair in alist whose car field is obj, and
2058returns that pair. If no pair in alist has obj as its car, then #f (not
2059the empty list) is returned. Assq uses eq? to compare obj with the car
2060fields of the pairs in alist, while assv uses eqv? and assoc uses
2063 (define e '((a 1) (b 2) (c 3)))
2064 (assq 'a e)             ===>  (a 1)
2065 (assq 'b e)             ===>  (b 2)
2066 (assq 'd e)             ===>  #f
2067 (assq (list 'a) '(((a)) ((b)) ((c))))
2068                         ===>  #f
2069 (assoc (list 'a) '(((a)) ((b)) ((c))))   
2070                                    ===>  ((a))
2071 (assq 5 '((2 3) (5 7) (11 13)))   
2072                                    ===>  unspecified
2073 (assv 5 '((2 3) (5 7) (11 13)))   
2074                                    ===>  (5 7)
2076Rationale:   Although they are ordinarily used as predicates, memq,
2077memv, member, assq, assv, and assoc do not have question marks in
2078their names because they return useful values rather than just #t
2079or #f.
2081==== Symbols
2083Symbols are objects whose usefulness rests on the fact that two symbols
2084are identical (in the sense of eqv?) if and only if their names are
2085spelled the same way. This is exactly the property needed to represent
2086identifiers in programs, and so most implementations of Scheme use them
2087internally for that purpose. Symbols are useful for many other
2088applications; for instance, they may be used the way enumerated values
2089are used in Pascal.
2091The rules for writing a symbol are exactly the same as the rules for
2092writing an identifier.
2094It is guaranteed that any symbol that has been returned as part of a
2095literal expression, or read using the read procedure, and subsequently
2096written out using the write procedure, will read back in as the
2097identical symbol (in the sense of eqv?). The string->symbol procedure,
2098however, can create symbols for which this write/read invariance may
2099not hold because their names contain special characters or letters in
2100the non-standard case.
2102Note:   Some implementations of Scheme have a feature known as
2103"slashification" in order to guarantee write/read invariance for
2104all symbols, but historically the most important use of this
2105feature has been to compensate for the lack of a string data type.
2107Some implementations also have "uninterned symbols", which defeat
2108write/read invariance even in implementations with slashification,
2109and also generate exceptions to the rule that two symbols are the
2110same if and only if their names are spelled the same.
2112<procedure>(symbol? obj)</procedure><br>
2114Returns #t if obj is a symbol, otherwise returns #f.
2116 (symbol? 'foo)                  ===>  #t
2117 (symbol? (car '(a b)))          ===>  #t
2118 (symbol? "bar")                 ===>  #f
2119 (symbol? 'nil)                  ===>  #t
2120 (symbol? '())                   ===>  #f
2121 (symbol? #f)                    ===>  #f
2123<procedure>(symbol->string symbol)</procedure><br>
2125Returns the name of symbol as a string. If the symbol was part of an
2126object returned as the value of a literal expression (see
2127"[[#literal-expressions|literal expressions]]") or by a call to the
2128read procedure, and its name contains alphabetic characters, then the
2129string returned will contain characters in the implementation's
2130preferred standard case -- some implementations will prefer upper
2131case, others lower case. If the symbol was returned by string->symbol,
2132the case of characters in the string returned will be the same as the
2133case in the string that was passed to string->symbol.  It is an error
2134to apply mutation procedures like string-set! to strings returned by
2135this procedure.
2137The following examples assume that the implementation's standard case
2138is lower case:
2140 (symbol->string 'flying-fish)     
2141                                           ===>  "flying-fish"
2142 (symbol->string 'Martin)                  ===>  "martin"
2143 (symbol->string
2144    (string->symbol "Malvina"))     
2145                                           ===>  "Malvina"
2147<procedure>(string->symbol string)</procedure><br>
2149Returns the symbol whose name is string. This procedure can create
2150symbols with names containing special characters or letters in the
2151non-standard case, but it is usually a bad idea to create such symbols
2152because in some implementations of Scheme they cannot be read as
2153themselves. See symbol->string.
2155The following examples assume that the implementation's standard case
2156is lower case:
2158 (eq? 'mISSISSIppi 'mississippi) 
2159                 ===>  #t
2160 (string->symbol "mISSISSIppi") 
2161                 ===>  the symbol with name "mISSISSIppi"
2162 (eq? 'bitBlt (string->symbol "bitBlt"))     
2163                 ===>  #f
2164 (eq? 'JollyWog
2165      (string->symbol
2166        (symbol->string 'JollyWog))) 
2167                 ===>  #t
2168 (string=? "K. Harper, M.D."
2169           (symbol->string
2170             (string->symbol "K. Harper, M.D."))) 
2171                 ===>  #t
2173==== Characters
2175Characters are objects that represent printed characters such as
2176letters and digits. Characters are written using the notation #\
2177<character> or #\<character name>. For example:
2179 #\a       ; lower case letter
2180 #\A       ; upper case letter
2181 #\(       ; left parenthesis
2182 #\        ; the space character
2183 #\space   ; the preferred way to write a space
2184 #\newline ; the newline character
2186Case is significant in #\<character>, but not in #\<character name>. If
2187<character> in #\<character> is alphabetic, then the character
2188following <character> must be a delimiter character such as a space or
2189parenthesis. This rule resolves the ambiguous case where, for example,
2190the sequence of characters "#\space" could be taken to be either a
2191representation of the space character or a representation of the
2192character "#\s" followed by a representation of the symbol "pace."
2194Characters written in the #\ notation are self-evaluating. That is,
2195they do not have to be quoted in programs. Some of the procedures that
2196operate on characters ignore the difference between upper case and
2197lower case. The procedures that ignore case have "-ci" (for "case
2198insensitive") embedded in their names.
2200<procedure>(char? obj)</procedure><br>
2202Returns #t if obj is a character, otherwise returns #f.
2204<procedure>(char=? char[1] char[2])</procedure><br>
2205<procedure>(char<? char[1] char[2])</procedure><br>
2206<procedure>(char>? char[1] char[2])</procedure><br>
2207<procedure>(char<=? char[1] char[2])</procedure><br>
2208<procedure>(char>=? char[1] char[2])</procedure><br>
2210These procedures impose a total ordering on the set of characters. It
2211is guaranteed that under this ordering:
2213*   The upper case characters are in order. For example, (char<? #\A #\
2214    B) returns #t.
2215*   The lower case characters are in order. For example, (char<? #\a #\
2216    b) returns #t.
2217*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
2218*   Either all the digits precede all the upper case letters, or vice
2219    versa.
2220*   Either all the digits precede all the lower case letters, or vice
2221    versa.
2223Some implementations may generalize these procedures to take more than
2224two arguments, as with the corresponding numerical predicates.
2226<procedure>(char-ci=? char[1] char[2])</procedure><br>
2227<procedure>(char-ci<? char[1] char[2])</procedure><br>
2228<procedure>(char-ci>? char[1] char[2])</procedure><br>
2229<procedure>(char-ci<=? char[1] char[2])</procedure><br>
2230<procedure>(char-ci>=? char[1] char[2])</procedure><br>
2232These procedures are similar to char=? et cetera, but they treat upper
2233case and lower case letters as the same. For example, (char-ci=? #\A #\
2234a) returns #t. Some implementations may generalize these procedures to
2235take more than two arguments, as with the corresponding numerical
2238<procedure>(char-alphabetic? char)</procedure><br>
2239<procedure>(char-numeric? char)</procedure><br>
2240<procedure>(char-whitespace? char)</procedure><br>
2241<procedure>(char-upper-case? letter)</procedure><br>
2242<procedure>(char-lower-case? letter)</procedure><br>
2244These procedures return #t if their arguments are alphabetic, numeric,
2245whitespace, upper case, or lower case characters, respectively,
2246otherwise they return #f. The following remarks, which are specific to
2247the ASCII character set, are intended only as a guide: The alphabetic
2248characters are the 52 upper and lower case letters. The numeric
2249characters are the ten decimal digits. The whitespace characters are
2250space, tab, line feed, form feed, and carriage return.
2252<procedure>(char->integer char)</procedure><br>
2253<procedure>(integer->char n)</procedure><br>
2255Given a character, char->integer returns an exact integer
2256representation of the character. Given an exact integer that is the
2257image of a character under char->integer, integer->char returns that
2258character. These procedures implement order-preserving isomorphisms
2259between the set of characters under the char<=? ordering and some
2260subset of the integers under the <= ordering. That is, if
2262 (char<=? a b) ===> #t  and  (<= x y) ===> #t
2264and x and y are in the domain of integer->char, then
2266 (<= (char->integer a)
2267     (char->integer b))                  ===>  #t
2269 (char<=? (integer->char x)
2270          (integer->char y))             ===>  #t
2272Note that {{integer->char}} does currently not detect
2273a negative argument and will quietly convert {{-1}} to
2274{{#x1ffff}} in CHICKEN.
2276<procedure>(char-upcase char)</procedure><br>
2277<procedure>(char-downcase char)</procedure><br>
2279These procedures return a character char[2] such that (char-ci=? char
2280char[2]). In addition, if char is alphabetic, then the result of
2281char-upcase is upper case and the result of char-downcase is lower
2284==== Strings
2286Strings are sequences of characters. Strings are written as sequences
2287of characters enclosed within doublequotes ("). A doublequote can be
2288written inside a string only by escaping it with a backslash (\), as in
2290"The word \"recursion\" has many meanings."
2292A backslash can be written inside a string only by escaping it with
2293another backslash. Scheme does not specify the effect of a backslash
2294within a string that is not followed by a doublequote or backslash.
2296A string constant may continue from one line to the next, but the exact
2297contents of such a string are unspecified. The length of a string is
2298the number of characters that it contains. This number is an exact,
2299non-negative integer that is fixed when the string is created. The
2300valid indexes of a string are the exact non-negative integers less than
2301the length of the string. The first character of a string has index 0,
2302the second has index 1, and so on.
2304In phrases such as "the characters of string beginning with index
2305start and ending with index end," it is understood that the index
2306start is inclusive and the index end is exclusive. Thus if start and
2307end are the same index, a null substring is referred to, and if start
2308is zero and end is the length of string, then the entire string is
2309referred to.
2311Some of the procedures that operate on strings ignore the difference
2312between upper and lower case. The versions that ignore case have
2313"-ci" (for "case insensitive") embedded in their names.
2315<procedure>(string? obj)</procedure><br>
2317Returns #t if obj is a string, otherwise returns #f.
2319<procedure>(make-string k)</procedure><br>
2320<procedure>(make-string k char)</procedure><br>
2322Make-string returns a newly allocated string of length k. If char is
2323given, then all elements of the string are initialized to char,
2324otherwise the contents of the string are unspecified.
2326<procedure>(string char ...)</procedure><br>
2328Returns a newly allocated string composed of the arguments.
2330<procedure>(string-length string)</procedure><br>
2332Returns the number of characters in the given string.
2334<procedure>(string-ref string k)</procedure><br>
2336k must be a valid index of string. String-ref returns character k of
2337string using zero-origin indexing.
2339<procedure>(string-set! string k char)</procedure><br>
2341k must be a valid index of string. String-set! stores char in element k
2342of string and returns an unspecified value.
2344 (define (f) (make-string 3 #\*))
2345 (define (g) "***")
2346 (string-set! (f) 0 #\?)          ===>  unspecified
2347 (string-set! (g) 0 #\?)          ===>  error
2348 (string-set! (symbol->string 'immutable)
2349              0
2350              #\?)          ===>  error
2352<procedure>(string=? string[1] string[2])</procedure><br>
2353<procedure>(string-ci=? string[1] string[2])</procedure><br>
2355Returns #t if the two strings are the same length and contain the same
2356characters in the same positions, otherwise returns #f. String-ci=?
2357treats upper and lower case letters as though they were the same
2358character, but string=? treats upper and lower case as distinct
2361<procedure>(string<? string[1] string[2])</procedure><br>
2362<procedure>(string>? string[1] string[2])</procedure><br>
2363<procedure>(string<=? string[1] string[2])</procedure><br>
2364<procedure>(string>=? string[1] string[2])</procedure><br>
2365<procedure>(string-ci<? string[1] string[2])</procedure><br>
2366<procedure>(string-ci>? string[1] string[2])</procedure><br>
2367<procedure>(string-ci<=? string[1] string[2])</procedure><br>
2368<procedure>(string-ci>=? string[1] string[2])</procedure><br>
2370These procedures are the lexicographic extensions to strings of the
2371corresponding orderings on characters. For example, string<? is the
2372lexicographic ordering on strings induced by the ordering char<? on
2373characters. If two strings differ in length but are the same up to the
2374length of the shorter string, the shorter string is considered to be
2375lexicographically less than the longer string.
2377Implementations may generalize these and the string=? and string-ci=?
2378procedures to take more than two arguments, as with the corresponding
2379numerical predicates.
2381<procedure>(substring string start end)</procedure><br>
2383String must be a string, and start and end must be exact integers
2386 0 < start < end < (string-length string)
2388Substring returns a newly allocated string formed from the characters
2389of string beginning with index start (inclusive) and ending with index
2390end (exclusive).
2392<procedure>(string-append string ...)</procedure><br>
2394Returns a newly allocated string whose characters form the
2395concatenation of the given strings.
2397<procedure>(string->list string)</procedure><br>
2398<procedure>(list->string list)</procedure><br>
2400String->list returns a newly allocated list of the characters that make
2401up the given string. List->string returns a newly allocated string
2402formed from the characters in the list list, which must be a list of
2403characters. String->list and list->string are inverses so far as equal?
2404is concerned.
2406<procedure>(string-copy string)</procedure><br>
2408Returns a newly allocated copy of the given string.
2410<procedure>(string-fill! string char)</procedure><br>
2412Stores char in every element of the given string and returns an
2413unspecified value.
2415==== Vectors
2417Vectors are heterogenous structures whose elements are indexed by
2418integers. A vector typically occupies less space than a list of the
2419same length, and the average time required to access a randomly chosen
2420element is typically less for the vector than for the list.
2422The length of a vector is the number of elements that it contains. This
2423number is a non-negative integer that is fixed when the vector is
2424created. The valid indexes of a vector are the exact non-negative
2425integers less than the length of the vector. The first element in a
2426vector is indexed by zero, and the last element is indexed by one less
2427than the length of the vector.
2429Vectors are written using the notation #(obj ...). For example, a
2430vector of length 3 containing the number zero in element 0, the list (2
24312 2 2) in element 1, and the string "Anna" in element 2 can be written
2432as following:
2434 #(0 (2 2 2 2) "Anna")
2436Note that this is the external representation of a vector, not an
2437expression evaluating to a vector. Like list constants, vector
2438constants must be quoted:
2440 '#(0 (2 2 2 2) "Anna") 
2441                 ===>  #(0 (2 2 2 2) "Anna")
2443<procedure>(vector? obj)</procedure><br>
2445Returns #t if obj is a vector, otherwise returns #f.
2447<procedure>(make-vector k)</procedure><br>
2448<procedure>(make-vector k fill)</procedure><br>
2450Returns a newly allocated vector of k elements. If a second argument is
2451given, then each element is initialized to fill. Otherwise the initial
2452contents of each element is unspecified.
2454<procedure>(vector obj ...)</procedure><br>
2456Returns a newly allocated vector whose elements contain the given
2457arguments. Analogous to list.
2459 (vector 'a 'b 'c)                       ===>  #(a b c)
2461<procedure>(vector-length vector)</procedure><br>
2463Returns the number of elements in vector as an exact integer.
2465<procedure>(vector-ref vector k)</procedure><br>
2467k must be a valid index of vector. Vector-ref returns the contents of
2468element k of vector.
2470 (vector-ref '#(1 1 2 3 5 8 13 21)
2471             5) 
2472                 ===>  8
2473 (vector-ref '#(1 1 2 3 5 8 13 21)
2474             (let ((i (round (* 2 (acos -1)))))
2475               (if (inexact? i)
2476                   (inexact->exact i)
2477                   i)))
2478                 ===> 13
2480<procedure>(vector-set! vector k obj)</procedure><br>
2482k must be a valid index of vector. Vector-set! stores obj in element k
2483of vector. The value returned by vector-set! is unspecified.
2485 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
2486   (vector-set! vec 1 '("Sue" "Sue"))
2487   vec)     
2488                 ===>  #(0 ("Sue" "Sue") "Anna")
2490 (vector-set! '#(0 1 2) 1 "doe") 
2491                 ===>  error  ; constant vector
2493<procedure>(vector->list vector)</procedure><br>
2494<procedure>(list->vector list)</procedure><br>
2496Vector->list returns a newly allocated list of the objects contained in
2497the elements of vector. List->vector returns a newly created vector
2498initialized to the elements of the list list.
2500 (vector->list '#(dah dah didah)) 
2501                 ===>  (dah dah didah)
2502 (list->vector '(dididit dah))   
2503                 ===>  #(dididit dah)
2505<procedure>(vector-fill! vector fill)</procedure><br>
2507Stores fill in every element of vector. The value returned by
2508vector-fill! is unspecified.
2510=== Control features
2512This chapter describes various primitive procedures which control the
2513flow of program execution in special ways. The procedure? predicate is
2514also described here.
2516<procedure>(procedure? obj)</procedure><br>
2518Returns #t if obj is a procedure, otherwise returns #f.
2520 (procedure? car)                    ===>  #t
2521 (procedure? 'car)                   ===>  #f
2522 (procedure? (lambda (x) (* x x)))   
2523                                     ===>  #t
2524 (procedure? '(lambda (x) (* x x))) 
2525                                     ===>  #f
2526 (call-with-current-continuation procedure?)
2527                                     ===>  #t
2529<procedure>(apply proc arg[1] ... args)</procedure><br>
2531Proc must be a procedure and args must be a list. Calls proc with the
2532elements of the list (append (list arg[1] ...) args) as the actual
2535 (apply + (list 3 4))                      ===>  7
2537 (define compose
2538   (lambda (f g)
2539     (lambda args
2540       (f (apply g args)))))
2542 ((compose sqrt *) 12 75)                      ===>  30
2544<procedure>(map proc list[1] list[2] ...)</procedure><br>
2546The lists must be lists, and proc must be a procedure taking as many
2547arguments as there are lists and returning a single value. If more than
2548one list is given, then they must all be the same length. Map applies
2549proc element-wise to the elements of the lists and returns a list of
2550the results, in order. The dynamic order in which proc is applied to
2551the elements of the lists is unspecified.
2553 (map cadr '((a b) (d e) (g h)))   
2554                 ===>  (b e h)
2556 (map (lambda (n) (expt n n))
2557      '(1 2 3 4 5))               
2558                 ===>  (1 4 27 256 3125)
2560 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
2562 (let ((count 0))
2563   (map (lambda (ignored)
2564          (set! count (+ count 1))
2565          count)
2566        '(a b)))                         ===>  (1 2) or (2 1)
2568<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
2570The arguments to for-each are like the arguments to map, but for-each
2571calls proc for its side effects rather than for its values. Unlike map,
2572for-each is guaranteed to call proc on the elements of the lists in
2573order from the first element(s) to the last, and the value returned by
2574for-each is unspecified.
2576 (let ((v (make-vector 5)))
2577   (for-each (lambda (i)
2578               (vector-set! v i (* i i)))
2579             '(0 1 2 3 4))
2580   v)                                        ===>  #(0 1 4 9 16)
2582<procedure>(force promise)</procedure><br>
2584Forces the value of promise (see "[[#delayed-evaluation|delayed
2585evaluation]]"). If no value has been computed for the promise, then a
2586value is computed and returned.  The value of the promise is cached
2587(or "memoized") so that if it is forced a second time, the previously
2588computed value is returned.
2590 (force (delay (+ 1 2)))           ===>  3
2591 (let ((p (delay (+ 1 2))))
2592   (list (force p) (force p))) 
2593                                        ===>  (3 3)
2595 (define a-stream
2596   (letrec ((next
2597             (lambda (n)
2598               (cons n (delay (next (+ n 1)))))))
2599     (next 0)))
2600 (define head car)
2601 (define tail
2602   (lambda (stream) (force (cdr stream))))
2604 (head (tail (tail a-stream))) 
2605                                        ===>  2
2607Force and delay are mainly intended for programs written in functional
2608style. The following examples should not be considered to illustrate
2609good programming style, but they illustrate the property that only one
2610value is computed for a promise, no matter how many times it is forced.
2612 (define count 0)
2613 (define p
2614   (delay (begin (set! count (+ count 1))
2615                 (if (> count x)
2616                     count
2617                     (force p)))))
2618 (define x 5)
2619 p                             ===>  a promise
2620 (force p)                     ===>  6
2621 p                             ===>  a promise, still
2622 (begin (set! x 10)
2623        (force p))             ===>  6
2625Here is a possible implementation of delay and force. Promises are
2626implemented here as procedures of no arguments, and force simply calls
2627its argument:
2629 (define force
2630   (lambda (object)
2631     (object)))
2633We define the expression
2635 (delay <expression>)
2637to have the same meaning as the procedure call
2639 (make-promise (lambda () <expression>))
2641as follows
2643 (define-syntax delay
2644   (syntax-rules ()
2645     ((delay expression)
2646      (make-promise (lambda () expression))))),
2648where make-promise is defined as follows:
2650 (define make-promise
2651   (lambda (proc)
2652     (let ((result-ready? #f)
2653           (result #f))
2654       (lambda ()
2655         (if result-ready?
2656             result
2657             (let ((x (proc)))
2658               (if result-ready?
2659                   result
2660                   (begin (set! result-ready? #t)
2661                          (set! result x)
2662                          result))))))))
2664Rationale:   A promise may refer to its own value, as in the last
2665example above. Forcing such a promise may cause the promise to be
2666forced a second time before the value of the first force has been
2667computed. This complicates the definition of make-promise.
2669Various extensions to this semantics of delay and force are supported
2670in some implementations:
2672*   Calling force on an object that is not a promise may simply return
2673    the object.
2675*   It may be the case that there is no means by which a promise can be
2676    operationally distinguished from its forced value. That is,
2677    expressions like the following may evaluate to either #t or to #f,
2678    depending on the implementation:
2680    (eqv? (delay 1) 1)                  ===>  unspecified
2681    (pair? (delay (cons 1 2)))          ===>  unspecified
2683*   Some implementations may implement "implicit forcing," where the
2684    value of a promise is forced by primitive procedures like cdr and
2685    +:
2687    (+ (delay (* 3 7)) 13)          ===>  34
2689<procedure>(call-with-current-continuation proc)</procedure><br>
2691Proc must be a procedure of one argument. The procedure
2692call-with-current-continuation packages up the current continuation
2693(see the rationale below) as an "escape procedure" and passes it as
2694an argument to proc. The escape procedure is a Scheme procedure that,
2695if it is later called, will abandon whatever continuation is in effect
2696at that later time and will instead use the continuation that was in
2697effect when the escape procedure was created. Calling the escape
2698procedure may cause the invocation of before and after thunks installed
2699using dynamic-wind.
2701The escape procedure accepts the same number of arguments as the
2702continuation to the original call to call-with-current-continuation.
2703Except for continuations created by the call-with-values procedure, all
2704continuations take exactly one value. The effect of passing no value or
2705more than one value to continuations that were not created by
2706call-with-values is unspecified.
2708The escape procedure that is passed to proc has unlimited extent just
2709like any other procedure in Scheme. It may be stored in variables or
2710data structures and may be called as many times as desired.
2712The following examples show only the most common ways in which
2713call-with-current-continuation is used. If all real uses were as simple
2714as these examples, there would be no need for a procedure with the
2715power of call-with-current-continuation.
2717 (call-with-current-continuation
2718   (lambda (exit)
2719     (for-each (lambda (x)
2720                 (if (negative? x)
2721                     (exit x)))
2722               '(54 0 37 -3 245 19))
2723     #t))                                ===>  -3
2725 (define list-length
2726   (lambda (obj)
2727     (call-with-current-continuation
2728       (lambda (return)
2729         (letrec ((r
2730                   (lambda (obj)
2731                     (cond ((null? obj) 0)
2732                           ((pair? obj)
2733                            (+ (r (cdr obj)) 1))
2734                           (else (return #f))))))
2735           (r obj))))))
2737 (list-length '(1 2 3 4))                    ===>  4
2739 (list-length '(a b . c))                    ===>  #f
2743A common use of call-with-current-continuation is for structured,
2744non-local exits from loops or procedure bodies, but in fact
2745call-with-current-continuation is extremely useful for implementing
2746a wide variety of advanced control structures.
2748Whenever a Scheme expression is evaluated there is a continuation
2749wanting the result of the expression. The continuation represents
2750an entire (default) future for the computation. If the expression
2751is evaluated at top level, for example, then the continuation might
2752take the result, print it on the screen, prompt for the next input,
2753evaluate it, and so on forever. Most of the time the continuation
2754includes actions specified by user code, as in a continuation that
2755will take the result, multiply it by the value stored in a local
2756variable, add seven, and give the answer to the top level
2757continuation to be printed. Normally these ubiquitous continuations
2758are hidden behind the scenes and programmers do not think much
2759about them. On rare occasions, however, a programmer may need to
2760deal with continuations explicitly. Call-with-current-continuation
2761allows Scheme programmers to do that by creating a procedure that
2762acts just like the current continuation.
2764Most programming languages incorporate one or more special-purpose
2765escape constructs with names like exit, return, or even goto. In
27661965, however, Peter Landin [16] invented a general purpose escape
2767operator called the J-operator. John Reynolds [24] described a
2768simpler but equally powerful construct in 1972. The catch special
2769form described by Sussman and Steele in the 1975 report on Scheme
2770is exactly the same as Reynolds's construct, though its name came
2771from a less general construct in MacLisp. Several Scheme
2772implementors noticed that the full power of the catch construct
2773could be provided by a procedure instead of by a special syntactic
2774construct, and the name call-with-current-continuation was coined
2775in 1982. This name is descriptive, but opinions differ on the
2776merits of such a long name, and some people use the name call/cc
2779<procedure>(values obj ...)</procedure><br>
2781Delivers all of its arguments to its continuation. Except for
2782continuations created by the call-with-values procedure, all
2783continuations take exactly one value. Values might be defined as
2786 (define (values . things)
2787   (call-with-current-continuation
2788     (lambda (cont) (apply cont things))))
2790<procedure>(call-with-values producer consumer)</procedure><br>
2792Calls its producer argument with no values and a continuation that,
2793when passed some values, calls the consumer procedure with those values
2794as arguments. The continuation for the call to consumer is the
2795continuation of the call to call-with-values.
2797 (call-with-values (lambda () (values 4 5))
2798                   (lambda (a b) b))
2799                                                            ===>  5
2801 (call-with-values * -)                                     ===>  -1
2803<procedure>(dynamic-wind before thunk after)</procedure><br>
2805Calls thunk without arguments, returning the result(s) of this call.
2806Before and after are called, also without arguments, as required by the
2807following rules (note that in the absence of calls to continuations
2808captured using call-with-current-continuation the three arguments are
2809called once each, in order). Before is called whenever execution enters
2810the dynamic extent of the call to thunk and after is called whenever it
2811exits that dynamic extent. The dynamic extent of a procedure call is
2812the period between when the call is initiated and when it returns. In
2813Scheme, because of call-with-current-continuation, the dynamic extent
2814of a call may not be a single, connected time period. It is defined as
2817*   The dynamic extent is entered when execution of the body of the
2818    called procedure begins.
2820*   The dynamic extent is also entered when execution is not within the
2821    dynamic extent and a continuation is invoked that was captured
2822    (using call-with-current-continuation) during the dynamic extent.
2824*   It is exited when the called procedure returns.
2826*   It is also exited when execution is within the dynamic extent and a
2827    continuation is invoked that was captured while not within the
2828    dynamic extent.
2830If a second call to dynamic-wind occurs within the dynamic extent of
2831the call to thunk and then a continuation is invoked in such a way that
2832the afters from these two invocations of dynamic-wind are both to be
2833called, then the after associated with the second (inner) call to
2834dynamic-wind is called first.
2836If a second call to dynamic-wind occurs within the dynamic extent of
2837the call to thunk and then a continuation is invoked in such a way that
2838the befores from these two invocations of dynamic-wind are both to be
2839called, then the before associated with the first (outer) call to
2840dynamic-wind is called first.
2842If invoking a continuation requires calling the before from one call to
2843dynamic-wind and the after from another, then the after is called
2846The effect of using a captured continuation to enter or exit the
2847dynamic extent of a call to before or after is undefined.
2849 (let ((path '())
2850       (c #f))
2851   (let ((add (lambda (s)
2852                (set! path (cons s path)))))
2853     (dynamic-wind
2854       (lambda () (add 'connect))
2855       (lambda ()
2856         (add (call-with-current-continuation
2857                (lambda (c0)
2858                  (set! c c0)
2859                  'talk1))))
2860       (lambda () (add 'disconnect)))
2861     (if (< (length path) 4)
2862         (c 'talk2)
2863         (reverse path))))
2865                 ===> (connect talk1 disconnect
2866                       connect talk2 disconnect)
2868=== Eval
2870<procedure>(eval expression environment-specifier)</procedure><br>
2872Evaluates expression in the specified environment and returns its
2873value. Expression must be a valid Scheme expression represented as
2874data, and environment-specifier must be a value returned by one of the
2875three procedures described below. Implementations may extend eval to
2876allow non-expression programs (definitions) as the first argument and
2877to allow other values as environments, with the restriction that eval
2878is not allowed to create new bindings in the environments associated
2879with null-environment or scheme-report-environment.
2881 (eval '(* 7 3) (scheme-report-environment 5))
2882                                                            ===>  21
2884 (let ((f (eval '(lambda (f x) (f x x))
2885                (null-environment 5))))
2886   (f + 10))
2887                                                            ===>  20
2889<procedure>(scheme-report-environment version)</procedure><br>
2890<procedure>(null-environment version)</procedure><br>
2892Version must be either the exact integer 4 or 5, corresponding to the
2893respective revisions of the Scheme report (the Revised^N Report on
2894Scheme).  Scheme-report-environment returns a specifier for an
2895environment that is empty except for all bindings defined in this
2896report that are either required or both optional and supported by the
2897implementation.  Null-environment returns a specifier for an
2898environment that is empty except for the (syntactic) bindings for all
2899syntactic keywords defined in this report that are either required or
2900both optional and supported by the implementation.
2902The environments specified by scheme-report-environment and
2903null-environment are immutable.
2907This procedure returns a specifier for the environment that contains
2908implementation-defined bindings, typically a superset of those listed
2909in the report. The intent is that this procedure will return the
2910environment in which the implementation would evaluate expressions
2911dynamically typed by the user.
2913=== Input and output
2915==== Ports
2917Ports represent input and output devices. To Scheme, an input port is a
2918Scheme object that can deliver characters upon command, while an output
2919port is a Scheme object that can accept characters.
2921<procedure>(call-with-input-file string proc)</procedure><br>
2922<procedure>(call-with-output-file string proc)</procedure><br>
2924String should be a string naming a file, and proc should be a procedure
2925that accepts one argument. For call-with-input-file, the file should
2926already exist; for call-with-output-file, the effect is unspecified if
2927the file already exists. These procedures call proc with one argument:
2928the port obtained by opening the named file for input or output. If the
2929file cannot be opened, an error is signalled. If proc returns, then the
2930port is closed automatically and the value(s) yielded by the proc is
2931(are) returned. If proc does not return, then the port will not be
2932closed automatically unless it is possible to prove that the port will
2933never again be used for a read or write operation.
2935Rationale:   Because Scheme's escape procedures have unlimited
2936extent, it is possible to escape from the current continuation but
2937later to escape back in. If implementations were permitted to close
2938the port on any escape from the current continuation, then it would
2939be impossible to write portable code using both
2940call-with-current-continuation and call-with-input-file or
2943<procedure>(input-port? obj)</procedure><br>
2944<procedure>(output-port? obj)</procedure><br>
2946Returns #t if obj is an input port or output port respectively,
2947otherwise returns #f.
2952Returns the current default input or output port.
2954<procedure>(with-input-from-file string thunk)</procedure><br>
2955<procedure>(with-output-to-file string thunk)</procedure><br>
2957String should be a string naming a file, and proc should be a procedure
2958of no arguments. For with-input-from-file, the file should already
2959exist; for with-output-to-file, the effect is unspecified if the file
2960already exists. The file is opened for input or output, an input or
2961output port connected to it is made the default value returned by
2962current-input-port or current-output-port (and is used by (read),
2963(write obj), and so forth), and the thunk is called with no arguments.
2964When the thunk returns, the port is closed and the previous default is
2965restored. With-input-from-file and with-output-to-file return(s) the
2966value(s) yielded by thunk. If an escape procedure is used to escape
2967from the continuation of these procedures, their behavior is
2968implementation dependent.
2970<procedure>(open-input-file filename)</procedure><br>
2972Takes a string naming an existing file and returns an input port
2973capable of delivering characters from the file. If the file cannot be
2974opened, an error is signalled.
2976<procedure>(open-output-file filename)</procedure><br>
2978Takes a string naming an output file to be created and returns an
2979output port capable of writing characters to a new file by that name.
2980If the file cannot be opened, an error is signalled. If a file with the
2981given name already exists, the effect is unspecified.
2983<procedure>(close-input-port port)</procedure><br>
2984<procedure>(close-output-port port)</procedure><br>
2986Closes the file associated with port, rendering the port incapable of
2987delivering or accepting characters. These routines have no effect if
2988the file has already been closed. The value returned is unspecified.
2990==== Input
2993<procedure>(read port)</procedure><br>
2995Read converts external representations of Scheme objects into the
2996objects themselves. That is, it is a parser for the nonterminal
2997<datum> (see also "[[#pairs-and-lists|pairs and lists]]"). Read
2998returns the next object parsable from the given input port, updating
2999port to point to the first character past the end of the external
3000representation of the object.
3002If an end of file is encountered in the input before any characters are
3003found that can begin an object, then an end of file object is returned.
3004The port remains open, and further attempts to read will also return an
3005end of file object. If an end of file is encountered after the
3006beginning of an object's external representation, but the external
3007representation is incomplete and therefore not parsable, an error is
3010The port argument may be omitted, in which case it defaults to the
3011value returned by current-input-port. It is an error to read from a
3012closed port.
3015<procedure>(read-char port)</procedure><br>
3017Returns the next character available from the input port, updating the
3018port to point to the following character. If no more characters are
3019available, an end of file object is returned. Port may be omitted, in
3020which case it defaults to the value returned by current-input-port.
3023<procedure>(peek-char port)</procedure><br>
3025Returns the next character available from the input port, without
3026updating the port to point to the following character. If no more
3027characters are available, an end of file object is returned. Port may
3028be omitted, in which case it defaults to the value returned by
3031Note:   The value returned by a call to peek-char is the same as
3032the value that would have been returned by a call to read-char with
3033the same port. The only difference is that the very next call to
3034read-char or peek-char on that port will return the value returned
3035by the preceding call to peek-char. In particular, a call to
3036peek-char on an interactive port will hang waiting for input
3037whenever a call to read-char would have hung.
3039<procedure>(eof-object? obj)</procedure><br>
3041Returns #t if obj is an end of file object, otherwise returns #f. The
3042precise set of end of file objects will vary among implementations, but
3043in any case no end of file object will ever be an object that can be
3044read in using read.
3047<procedure>(char-ready? port)</procedure><br>
3049Returns #t if a character is ready on the input port and returns #f
3050otherwise. If char-ready returns #t then the next read-char operation
3051on the given port is guaranteed not to hang. If the port is at end of
3052file then char-ready? returns #t. Port may be omitted, in which case it
3053defaults to the value returned by current-input-port.
3055Rationale:   Char-ready? exists to make it possible for a program
3056to accept characters from interactive ports without getting stuck
3057waiting for input. Any input editors associated with such ports
3058must ensure that characters whose existence has been asserted by
3059char-ready? cannot be rubbed out. If char-ready? were to return #f
3060at end of file, a port at end of file would be indistinguishable
3061from an interactive port that has no ready characters.
3063==== Output
3065<procedure>(write obj)</procedure><br>
3066<procedure>(write obj port)</procedure><br>
3068Writes a written representation of obj to the given port. Strings that
3069appear in the written representation are enclosed in doublequotes, and
3070within those strings backslash and doublequote characters are escaped
3071by backslashes. Character objects are written using the #\ notation.
3072Write returns an unspecified value. The port argument may be omitted,
3073in which case it defaults to the value returned by current-output-port.
3075<procedure>(display obj)</procedure><br>
3076<procedure>(display obj port)</procedure><br>
3078Writes a representation of obj to the given port. Strings that appear
3079in the written representation are not enclosed in doublequotes, and no
3080characters are escaped within those strings. Character objects appear
3081in the representation as if written by write-char instead of by write.
3082Display returns an unspecified value. The port argument may be omitted,
3083in which case it defaults to the value returned by current-output-port.
3085Rationale:   Write is intended for producing machine-readable
3086output and display is for producing human-readable output.
3087Implementations that allow "slashification" within symbols will
3088probably want write but not display to slashify funny characters in
3092<procedure>(newline port)</procedure><br>
3094Writes an end of line to port. Exactly how this is done differs from
3095one operating system to another. Returns an unspecified value. The port
3096argument may be omitted, in which case it defaults to the value
3097returned by current-output-port.
3099<procedure>(write-char char)</procedure><br>
3100<procedure>(write-char char port)</procedure><br>
3102Writes the character char (not an external representation of the
3103character) to the given port and returns an unspecified value. The port
3104argument may be omitted, in which case it defaults to the value
3105returned by current-output-port.
3107==== System interface
3109Questions of system interface generally fall outside of the domain of
3110this report. However, the following operations are important enough to
3111deserve description here.
3113<procedure>(load filename)</procedure><br>
3115Filename should be a string naming an existing file containing Scheme
3116source code. The load procedure reads expressions and definitions from
3117the file and evaluates them sequentially. It is unspecified whether the
3118results of the expressions are printed. The load procedure does not
3119affect the values returned by current-input-port and
3120current-output-port. Load returns an unspecified value.
3122Rationale:   For portability, load must operate on source files.
3123Its operation on other kinds of files necessarily varies among
3126<procedure>(transcript-on filename)</procedure><br>
3129(These procedures are not implemented in Chicken.)
3131Filename must be a string naming an output file to be created. The
3132effect of transcript-on is to open the named file for output, and to
3133cause a transcript of subsequent interaction between the user and the
3134Scheme system to be written to the file. The transcript is ended by a
3135call to transcript-off, which closes the transcript file. Only one
3136transcript may be in progress at any time, though some implementations
3137may relax this restriction. The values returned by these procedures are
3142Previous: [[Supported language]]
3144Next: [[Deviations from the standard]]
Note: See TracBrowser for help on using the repository browser.