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

Last change on this file since 27461 was 27461, checked in by Ivan Raikov, 8 years ago

manual: synchronizing wiki manual with core manual

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