source: project/wiki/man/5/Module scheme @ 34052

Last change on this file since 34052 was 34052, checked in by sjamaan, 12 months ago

Add initial (still heavy WIP) layout for CHICKEN 5 manual

File size: 129.0 KB
1[[tags: manual]]
4== Module scheme
6This module provides all of CHICKEN's R5RS procedures and macros.
7These descriptions are based directly on the ''Revised^5 Report on the
8Algorithmic Language Scheme''.
10== Expressions
12Expression types are categorized as primitive or derived. Primitive
13expression types include variables and procedure calls. Derived
14expression types are not semantically primitive, but can instead be
15defined as macros. With the exception of quasiquote, whose macro
16definition is complex, the derived expressions are classified as
17library features.  The distinction which R5RS makes between primitive
18and derived is unimportant and does not necessarily reflect how it's
19implemented in CHICKEN itself.
21=== Primitive expression types
23==== Variable references
27An expression consisting of a variable is a variable reference. The
28value of the variable reference is the value stored in the location to
29which the variable is bound. It is an error to reference an unbound
32 (define x 28)
33 x           ===>  28
35==== Literal expressions
37<macro>(quote <datum>)</macro><br>
41(quote <datum>) evaluates to <datum>. <Datum> may be any external
42representation of a Scheme object. This notation is used to include
43literal constants in Scheme code.
45 (quote a)                    ===>  a
46 (quote #(a b c))             ===>  #(a b c)
47 (quote (+ 1 2))              ===>  (+ 1 2)
49(quote <datum>) may be abbreviated as '<datum>. The two notations are
50equivalent in all respects.
52 'a                           ===>  a
53 '#(a b c)                    ===>  #(a b c)
54 '()                          ===>  ()
55 '(+ 1 2)                     ===>  (+ 1 2)
56 '(quote a)                   ===>  (quote a)
57 ''a                          ===>  (quote a)
59Numerical constants, string constants, character constants, and boolean
60constants evaluate "to themselves"; they need not be quoted.
62 '"abc"             ===>  "abc"
63 "abc"              ===>  "abc"
64 '145932            ===>  145932
65 145932             ===>  145932
66 '#t                ===>  #t
67 #t                 ===>  #t
69It is an error to alter a constant (i.e. the value of a literal
70expression) using a mutation procedure like set-car! or string-set!.
71In the current implementation of CHICKEN, identical constants don't
72share memory and it is possible to mutate them, but this may change in
73the future.
75==== Procedure calls
77<macro>(<operator> <operand[1]> ...)</macro><br>
79A procedure call is written by simply enclosing in parentheses
80expressions for the procedure to be called and the arguments to be
81passed to it. The operator and operand expressions are evaluated (in an
82unspecified order) and the resulting procedure is passed the resulting
85 (+ 3 4)                           ===>  7
86 ((if #f + *) 3 4)                 ===>  12
88A number of procedures are available as the values of variables in the
89initial environment; for example, the addition and multiplication
90procedures in the above examples are the values of the variables + and
91*.  New procedures are created by evaluating lambda
92expressions. Procedure calls may return any number of values (see the
93{{values}} procedure [[#control-features|below]]).
95Procedure calls are also called combinations.
97Note:   In contrast to other dialects of Lisp, the order of
98evaluation is unspecified, and the operator expression and the
99operand expressions are always evaluated with the same evaluation
102Note:   Although the order of evaluation is otherwise unspecified,
103the effect of any concurrent evaluation of the operator and operand
104expressions is constrained to be consistent with some sequential
105order of evaluation. The order of evaluation may be chosen
106differently for each procedure call.
108Note:   In many dialects of Lisp, the empty combination, (), is a
109legitimate expression. In Scheme, combinations must have at least
110one subexpression, so () is not a syntactically valid expression.
112==== Procedures
114<macro>(lambda <formals> <body>)</macro><br>
116Syntax: <Formals> should be a formal arguments list as described below,
117and <body> should be a sequence of one or more expressions.
119Semantics: A lambda expression evaluates to a procedure. The
120environment in effect when the lambda expression was evaluated is
121remembered as part of the procedure. When the procedure is later called
122with some actual arguments, the environment in which the lambda
123expression was evaluated will be extended by binding the variables in
124the formal argument list to fresh locations, the corresponding actual
125argument values will be stored in those locations, and the expressions
126in the body of the lambda expression will be evaluated sequentially in
127the extended environment. The result(s) of the last expression in the
128body will be returned as the result(s) of the procedure call.
130 (lambda (x) (+ x x))              ===>  a procedure
131 ((lambda (x) (+ x x)) 4)          ===>  8
133 (define reverse-subtract
134   (lambda (x y) (- y x)))
135 (reverse-subtract 7 10)           ===>  3
137 (define add4
138   (let ((x 4))
139     (lambda (y) (+ x y))))
140 (add4 6)                          ===>  10
142<Formals> should have one of the following forms:
144*   (<variable[1]> ...): The procedure takes a fixed number of
145    arguments; when the procedure is called, the arguments will be
146    stored in the bindings of the corresponding variables.
148*   <variable>: The procedure takes any number of arguments; when the
149    procedure is called, the sequence of actual arguments is converted
150    into a newly allocated list, and the list is stored in the binding
151    of the <variable>.
153*   (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
154    space-delimited period precedes the last variable, then the
155    procedure takes n or more arguments, where n is the number of
156    formal arguments before the period (there must be at least one).
157    The value stored in the binding of the last variable will be a
158    newly allocated list of the actual arguments left over after all
159    the other actual arguments have been matched up against the other
160    formal arguments.
162It is an error for a <variable> to appear more than once in <formals>.
164 ((lambda x x) 3 4 5 6)                  ===>  (3 4 5 6)
165 ((lambda (x y . z) z)
166  3 4 5 6)                               ===>  (5 6)
168Each procedure created as the result of evaluating a lambda expression
169is (conceptually) tagged with a storage location, in order to make eqv?
170and eq? work on procedures.
172==== Conditionals
174<macro>(if <test> <consequent> <alternate>)</macro><br>
175<macro>(if <test> <consequent>)</macro><br>
177Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
180Semantics: An if expression is evaluated as follows: first, <test> is
181evaluated. If it yields a true value (see [[#booleans|the section
182about booleans]] below), then <consequent> is evaluated and its
183value(s) is(are) returned. Otherwise <alternate> is evaluated and its
184value(s) is(are) returned. If <test> yields a false value and no
185<alternate> is specified, then the result of the expression is
188 (if (> 3 2) 'yes 'no)                   ===>  yes
189 (if (> 2 3) 'yes 'no)                   ===>  no
190 (if (> 3 2)
191     (- 3 2)
192     (+ 3 2))                            ===>  1
194==== Assignments
196<macro>(set! <variable> <expression>)</macro><br>
198<Expression> is evaluated, and the resulting value is stored in the
199location to which <variable> is bound. <Variable> must be bound either
200in some region enclosing the set! expression or at top level. The
201result of the set! expression is unspecified.
203 (define x 2)
204 (+ x 1)                         ===>  3
205 (set! x 4)                      ===>  unspecified
206 (+ x 1)                         ===>  5
208=== Derived expression types
210The constructs in this section are hygienic.  For reference purposes,
211these macro definitions will convert most of the constructs described
212in this section into the primitive constructs described in the
213previous section.  This does not necessarily mean that's exactly how
214it's implemented in CHICKEN.
216==== Conditionals
218<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
220Syntax: Each <clause> should be of the form
222 (<test> <expression[1]> ...)
224where <test> is any expression. Alternatively, a <clause> may be of the
227 (<test> => <expression>)
229The last <clause> may be an "else clause," which has the form
231 (else <expression[1]> <expression[2]> ...).
233Semantics: A cond expression is evaluated by evaluating the <test>
234expressions of successive <clause>s in order until one of them
235evaluates to a true value (see [[#booleans|the section about
236booleans]] below). When a <test> evaluates to a true value, then the
237remaining <expression>s in its <clause> are evaluated in order, and
238the result(s) of the last <expression> in the <clause> is(are)
239returned as the result(s) of the entire cond expression. If the
240selected <clause> contains only the <test> and no <expression>s, then
241the value of the <test> is returned as the result.  If the selected
242<clause> uses the => alternate form, then the <expression> is
243evaluated. Its value must be a procedure that accepts one argument;
244this procedure is then called on the value of the <test> and the
245value(s) returned by this procedure is(are) returned by the cond
246expression. If all <test>s evaluate to false values, and there is no
247else clause, then the result of the conditional expression is
248unspecified; if there is an else clause, then its <expression>s are
249evaluated, and the value(s) of the last one is(are) returned.
251 (cond ((> 3 2) 'greater)
252       ((< 3 2) 'less))           ===>  greater
253 (cond ((> 3 3) 'greater)
254       ((< 3 3) 'less)
255       (else 'equal))             ===>  equal
256 (cond ((assv 'b '((a 1) (b 2))) => cadr)
257       (else #f))                 ===>  2
259<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
261Syntax: <Key> may be any expression. Each <clause> should have the form
263 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
265where each <datum> is an external representation of some object.
266Alternatively, as per R7RS, a <clause> may be of the form
268 ((<datum[1]> ...) => <expression>).
270All the <datum>s must be distinct. The last <clause> may be an
271"else clause," which has one of the following two forms:
273 (else <expression[1]> <expression[2]> ...)
274 (else => <expression>).      ; R7RS extension
276Semantics: A case expression is evaluated as follows. <Key> is
277evaluated and its result is compared against each <datum>. If the
278result of evaluating <key> is equivalent (in the sense of {{eqv?}};
279see [[#equivalence-predicates|below]]) to a <datum>, then the
280expressions in the corresponding <clause> are evaluated from left to
281right and the result(s) of the last expression in the <clause> is(are)
282returned as the result(s) of the case expression. If the selected
283<clause> uses the => alternate form (an R7RS extension), then the
284<expression> is evaluated. Its value must be a procedure that accepts
285one argument; this procedure is then called on the value of the <key>
286and the value(s) returned by this procedure is(are) returned by the
287case expression.  If the result of evaluating <key> is different from
288every <datum>, then if there is an else clause its expressions are
289evaluated and the result(s) of the last is(are) the result(s) of the
290case expression; otherwise the result of the case expression is
293 (case (* 2 3)
294   ((2 3 5 7) 'prime)
295   ((1 4 6 8 9) 'composite))             ===>  composite
296 (case (car '(c d))
297   ((a) 'a)
298   ((b) 'b))                             ===>  unspecified
299 (case (car '(c d))
300   ((a e i o u) 'vowel)
301   ((w y) 'semivowel)
302   (else 'consonant))                    ===>  consonant
304<macro>(and <test[1]> ...)</macro><br>
306The <test> expressions are evaluated from left to right, and the value
307of the first expression that evaluates to a false value (see
308[[#booleans|the section about booleans]]) is returned. Any remaining
309expressions are not evaluated. If all the expressions evaluate to true
310values, the value of the last expression is returned. If there are no
311expressions then #t is returned.
313 (and (= 2 2) (> 2 1))                   ===>  #t
314 (and (= 2 2) (< 2 1))                   ===>  #f
315 (and 1 2 'c '(f g))                     ===>  (f g)
316 (and)                                   ===>  #t
318<macro>(or <test[1]> ...)</macro><br>
320The <test> expressions are evaluated from left to right, and the value
321of the first expression that evaluates to a true value (see
322[[#booleans|the section about booleans]]) is returned. Any remaining
323expressions are not evaluated. If all expressions evaluate to false
324values, the value of the last expression is returned. If there are no
325expressions then #f is returned.
327 (or (= 2 2) (> 2 1))                    ===>  #t
328 (or (= 2 2) (< 2 1))                    ===>  #t
329 (or #f #f #f)         ===>  #f
330 (or (memq 'b '(a b c))
331     (/ 3 0))                            ===>  (b c)
333==== Binding constructs
335The three binding constructs let, let*, and letrec give Scheme a block
336structure, like Algol 60. The syntax of the three constructs is
337identical, but they differ in the regions they establish for their
338variable bindings. In a let expression, the initial values are computed
339before any of the variables become bound; in a let* expression, the
340bindings and evaluations are performed sequentially; while in a letrec
341expression, all the bindings are in effect while their initial values
342are being computed, thus allowing mutually recursive definitions.
344<macro>(let <bindings> <body>)</macro><br>
346Syntax: <Bindings> should have the form
348 ((<variable[1]> <init[1]>) ...),
350where each <init> is an expression, and <body> should be a sequence of
351one or more expressions. It is an error for a <variable> to appear more
352than once in the list of variables being bound.
354Semantics: The <init>s are evaluated in the current environment (in
355some unspecified order), the <variable>s are bound to fresh locations
356holding the results, the <body> is evaluated in the extended
357environment, and the value(s) of the last expression of <body> is(are)
358returned. Each binding of a <variable> has <body> as its region.
360 (let ((x 2) (y 3))
361   (* x y))                              ===>  6
363 (let ((x 2) (y 3))
364   (let ((x 7)
365         (z (+ x y)))
366     (* z x)))                           ===>  35
368See also "named let", [[#iteration|below]].
370<macro>(let* <bindings> <body>)</macro><br>
372Syntax: <Bindings> should have the form
374 ((<variable[1]> <init[1]>) ...),
376and <body> should be a sequence of one or more expressions.
378Semantics: Let* is similar to let, but the bindings are performed
379sequentially from left to right, and the region of a binding indicated
380by (<variable> <init>) is that part of the let* expression to the right
381of the binding. Thus the second binding is done in an environment in
382which the first binding is visible, and so on.
384 (let ((x 2) (y 3))
385   (let* ((x 7)
386          (z (+ x y)))
387     (* z x)))                     ===>  70
389<macro>(letrec <bindings> <body>)</macro><br>
391Syntax: <Bindings> should have the form
393 ((<variable[1]> <init[1]>) ...),
395and <body> should be a sequence of one or more expressions. It is an
396error for a <variable> to appear more than once in the list of
397variables being bound.
399Semantics: The <variable>s are bound to fresh locations holding
400undefined values, the <init>s are evaluated in the resulting
401environment (in some unspecified order), each <variable> is assigned to
402the result of the corresponding <init>, the <body> is evaluated in the
403resulting environment, and the value(s) of the last expression in
404<body> is(are) returned. Each binding of a <variable> has the entire
405letrec expression as its region, making it possible to define mutually
406recursive procedures.
408 (letrec ((even?
409           (lambda (n)
410             (if (zero? n)
411                 #t
412                 (odd? (- n 1)))))
413          (odd?
414           (lambda (n)
415             (if (zero? n)
416                 #f
417                 (even? (- n 1))))))
418   (even? 88))
419                         ===>  #t
421One restriction on letrec is very important: it must be possible to
422evaluate each <init> without assigning or referring to the value of any
423<variable>. If this restriction is violated, then it is an error. The
424restriction is necessary because Scheme passes arguments by value
425rather than by name. In the most common uses of letrec, all the <init>s
426are lambda expressions and the restriction is satisfied automatically.
428==== Sequencing
430<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
432The <expression>s are evaluated sequentially from left to right, and
433the value(s) of the last <expression> is(are) returned. This expression
434type is used to sequence side effects such as input and output.
436 (define x 0)
438 (begin (set! x 5)
439        (+ x 1))                          ===>  6
441 (begin (display "4 plus 1 equals ")
442        (display (+ 4 1)))                ===>  unspecified
443   and prints  4 plus 1 equals 5
445==== Iteration
447<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
449Do is an iteration construct. It specifies a set of variables to be
450bound, how they are to be initialized at the start, and how they are to
451be updated on each iteration. When a termination condition is met, the
452loop exits after evaluating the <expression>s.
454Do expressions are evaluated as follows: The <init> expressions are
455evaluated (in some unspecified order), the <variable>s are bound to
456fresh locations, the results of the <init> expressions are stored in
457the bindings of the <variable>s, and then the iteration phase begins.
459Each iteration begins by evaluating <test>; if the result is false
460(see [[#booleans|the section about booleans]]), then the <command>
461expressions are evaluated in order for effect, the <step> expressions
462are evaluated in some unspecified order, the <variable>s are bound to
463fresh locations, the results of the <step>s are stored in the bindings
464of the <variable>s, and the next iteration begins.
466If <test> evaluates to a true value, then the <expression>s are
467evaluated from left to right and the value(s) of the last <expression>
468is(are) returned. If no <expression>s are present, then the value of
469the do expression is unspecified.
471The region of the binding of a <variable> consists of the entire do
472expression except for the <init>s. It is an error for a <variable> to
473appear more than once in the list of do variables.
475A <step> may be omitted, in which case the effect is the same as if
476(<variable> <init> <variable>) had been written instead of (<variable>
479 (do ((vec (make-vector 5))
480      (i 0 (+ i 1)))
481     ((= i 5) vec)
482   (vector-set! vec i i))                    ===>  #(0 1 2 3 4)
484 (let ((x '(1 3 5 7 9)))
485   (do ((x x (cdr x))
486        (sum 0 (+ sum (car x))))
487       ((null? x) sum)))                     ===>  25
489<macro>(let <variable> <bindings> <body>)</macro><br>
491"Named let" is a variant on the syntax of let which provides a more
492general looping construct than do and may also be used to express
493recursions. It has the same syntax and semantics as ordinary let except
494that <variable> is bound within <body> to a procedure whose formal
495arguments are the bound variables and whose body is <body>. Thus the
496execution of <body> may be repeated by invoking the procedure named by
499 (let loop ((numbers '(3 -2 1 6 -5))
500            (nonneg '())
501            (neg '()))
502   (cond ((null? numbers) (list nonneg neg))
503         ((>= (car numbers) 0)
504          (loop (cdr numbers)
505                (cons (car numbers) nonneg)
506                neg))
507         ((< (car numbers) 0)
508          (loop (cdr numbers)
509                nonneg
510                (cons (car numbers) neg)))))
511                 ===>  ((6 1 3) (-5 -2))
513==== Delayed evaluation
515<macro>(delay <expression>)</macro><br>
517The delay construct is used together with the procedure force to
518implement lazy evaluation or call by need. {{(delay <expression>)}}
519returns an object called a promise which at some point in the future
520may be asked (by the force procedure) to evaluate {{<expression>}},
521and deliver the resulting value. The {{<expression>}} may return
522multiple values, which will be correctly memoized and returned by
523subsequent calls to {{force}}.  This is a CHICKEN extension to R5RS.
525See the description of {{force}} (under [[#control-features|Control
526features]], below) for a more complete description of {{delay}}.
528<macro>(delay-force <expression>)</macro><br>
530The expression {{(delay-force expression)}} is conceptually similar to
531{{(delay (force expression))}}, with the difference that forcing the
532result of {{delay-force}} will in effect result in a tail call to
533{{(force expression)}}, while forcing the result of
534{{(delay (force expression))}} might not.
536Thus iterative lazy algorithms that might result in a long series of
537chains of delay and force can be rewritten using delay-force to
538prevent consuming unbounded space during evaluation.
540The {{delay-force}} macro is a CHICKEN extension to R5RS, taken from
543See the description of force (under [[#control-features|Control
544features]], below) for a more complete description of delayed
547<procedure>(make-promise obj)</procedure>
549The make-promise procedure returns a promise which, when forced, will
550return {{obj}} . It is similar to {{delay}}, but does not delay its
551argument: it is a procedure rather than syntax. If {{obj}} is already
552a promise, it is returned.
554This procedure is a CHICKEN extension to R5RS, taken from R7RS.
556==== Quasiquotation
558<macro>(quasiquote <qq template>)</macro><br>
559<macro>`<qq template></macro><br>
561"Backquote" or "quasiquote" expressions are useful for constructing
562a list or vector structure when most but not all of the desired
563structure is known in advance. If no commas appear within the <qq
564template>, the result of evaluating `<qq template> is equivalent to the
565result of evaluating '<qq template>. If a comma appears within the <qq
566template>, however, the expression following the comma is evaluated
567("unquoted") and its result is inserted into the structure instead of
568the comma and the expression. If a comma appears followed immediately
569by an at-sign (@), then the following expression must evaluate to a
570list; the opening and closing parentheses of the list are then
571"stripped away" and the elements of the list are inserted in place of
572the comma at-sign expression sequence. A comma at-sign should only
573appear within a list or vector <qq template>.
575 `(list ,(+ 1 2) 4)          ===>  (list 3 4)
576 (let ((name 'a)) `(list ,name ',name))           
577                 ===>  (list a (quote a))
578 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)           
579                 ===>  (a 3 4 5 6 b)
580 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))           
581                 ===>  ((foo 7) . cons)
582 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)           
583                 ===>  #(10 5 2 4 3 8)
585Quasiquote forms may be nested. Substitutions are made only for
586unquoted components appearing at the same nesting level as the
587outermost backquote. The nesting level increases by one inside each
588successive quasiquotation, and decreases by one inside each
591 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)           
592                 ===>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
593 (let ((name1 'x)
594       (name2 'y))
595   `(a `(b ,,name1 ,',name2 d) e))           
596                 ===>  (a `(b ,x ,'y d) e)
598The two notations `<qq template> and (quasiquote <qq template>) are
599identical in all respects. ,<expression> is identical to (unquote
600<expression>), and ,@<expression> is identical to (unquote-splicing
601<expression>). The external syntax generated by write for two-element
602lists whose car is one of these symbols may vary between
605 (quasiquote (list (unquote (+ 1 2)) 4))           
606                 ===>  (list 3 4)
607 '(quasiquote (list (unquote (+ 1 2)) 4))           
608                 ===>  `(list ,(+ 1 2) 4)
609      i.e., (quasiquote (list (unquote (+ 1 2)) 4))
611Unpredictable behavior can result if any of the symbols quasiquote,
612unquote, or unquote-splicing appear in positions within a <qq template>
613otherwise than as described above.
615=== Macros
617Scheme programs can define and use new derived expression types, called
618macros. Program-defined expression types have the syntax
620 (<keyword> <datum> ...)
622where <keyword> is an identifier that uniquely determines the
623expression type. This identifier is called the syntactic keyword, or
624simply keyword, of the macro. The number of the <datum>s, and their
625syntax, depends on the expression type.
627Each instance of a macro is called a use of the macro. The set of rules
628that specifies how a use of a macro is transcribed into a more
629primitive expression is called the transformer of the macro.
631The macro definition facility consists of two parts:
633*   A set of expressions used to establish that certain identifiers are
634    macro keywords, associate them with macro transformers, and control
635    the scope within which a macro is defined, and
637*   a pattern language for specifying macro transformers.
639The syntactic keyword of a macro may shadow variable bindings, and
640local variable bindings may shadow keyword bindings. All macros defined
641using the pattern language are "hygienic" and "referentially
642transparent" and thus preserve Scheme's lexical scoping:
644*   If a macro transformer inserts a binding for an identifier
645    (variable or keyword), the identifier will in effect be renamed
646    throughout its scope to avoid conflicts with other identifiers.
647    Note that a define at top level may or may not introduce a binding;
648    this depends on whether the binding already existed before (in which
649    case its value will be overridden).
651*   If a macro transformer inserts a free reference to an identifier,
652    the reference refers to the binding that was visible where the
653    transformer was specified, regardless of any local bindings that
654    may surround the use of the macro.
656==== Binding constructs for syntactic keywords
658Let-syntax and letrec-syntax are analogous to let and letrec, but they
659bind syntactic keywords to macro transformers instead of binding
660variables to locations that contain values. Syntactic keywords may also
661be bound at top level.
663<macro>(let-syntax <bindings> <body>)</macro><br>
665Syntax: <Bindings> should have the form
667 ((<keyword> <transformer spec>) ...)
669Each <keyword> is an identifier, each <transformer spec> is an instance
670of syntax-rules, and <body> should be a sequence of one or more
671expressions. It is an error for a <keyword> to appear more than once in
672the list of keywords being bound.
674Semantics: The <body> is expanded in the syntactic environment obtained
675by extending the syntactic environment of the let-syntax expression
676with macros whose keywords are the <keyword>s, bound to the specified
677transformers. Each binding of a <keyword> has <body> as its region.
679 (let-syntax ((when (syntax-rules ()
680                      ((when test stmt1 stmt2 ...)
681                       (if test
682                           (begin stmt1
683                                  stmt2 ...))))))
684   (let ((if #t))
685     (when if (set! if 'now))
686     if))                                   ===>  now
688 (let ((x 'outer))
689   (let-syntax ((m (syntax-rules () ((m) x))))
690     (let ((x 'inner))
691       (m))))                               ===>  outer
693<macro>(letrec-syntax <bindings> <body>)</macro><br>
695Syntax: Same as for let-syntax.
697Semantics: The <body> is expanded in the syntactic environment obtained
698by extending the syntactic environment of the letrec-syntax expression
699with macros whose keywords are the <keyword>s, bound to the specified
700transformers. Each binding of a <keyword> has the <bindings> as well as
701the <body> within its region, so the transformers can transcribe
702expressions into uses of the macros introduced by the letrec-syntax
705 (letrec-syntax
706   ((my-or (syntax-rules ()
707             ((my-or) #f)
708             ((my-or e) e)
709             ((my-or e1 e2 ...)
710              (let ((temp e1))
711                (if temp
712                    temp
713                    (my-or e2 ...)))))))
714   (let ((x #f)
715         (y 7)
716         (temp 8)
717         (let odd?)
718         (if even?))
719     (my-or x
720            (let temp)
721            (if y)
722            y)))                ===>  7
724==== Pattern language
726A <transformer spec> has the following form:
728 (syntax-rules <literals> <syntax rule> ...)
730Syntax: <Literals> is a list of identifiers and each <syntax rule>
731should be of the form
733 (<pattern> <template>)
735The <pattern> in a <syntax rule> is a list <pattern> that begins with
736the keyword for the macro.
738A <pattern> is either an identifier, a constant, or one of the
741 (<pattern> ...)
742 (<pattern> <pattern> ... . <pattern>)
743 (<pattern> ... <pattern> <ellipsis>)
744 #(<pattern> ...)
745 #(<pattern> ... <pattern> <ellipsis>)
747and a template is either an identifier, a constant, or one of the
750 (<element> ...)
751 (<element> <element> ... . <template>)
752 #(<element> ...)
754where an <element> is a <template> optionally followed by an <ellipsis>
755and an <ellipsis> is the identifier "..." (which cannot be used as an
756identifier in either a template or a pattern).
758Semantics: An instance of syntax-rules produces a new macro transformer
759by specifying a sequence of hygienic rewrite rules. A use of a macro
760whose keyword is associated with a transformer specified by
761syntax-rules is matched against the patterns contained in the <syntax
762rule>s, beginning with the leftmost <syntax rule>. When a match is
763found, the macro use is transcribed hygienically according to the
766An identifier that appears in the pattern of a <syntax rule> is a
767pattern variable, unless it is the keyword that begins the pattern, is
768listed in <literals>, or is the identifier "...". Pattern variables
769match arbitrary input elements and are used to refer to elements of the
770input in the template. It is an error for the same pattern variable to
771appear more than once in a <pattern>.
773The keyword at the beginning of the pattern in a <syntax rule> is not
774involved in the matching and is not considered a pattern variable or
775literal identifier.
777Rationale:   The scope of the keyword is determined by the
778expression or syntax definition that binds it to the associated
779macro transformer. If the keyword were a pattern variable or
780literal identifier, then the template that follows the pattern
781would be within its scope regardless of whether the keyword were
782bound by let-syntax or by letrec-syntax.
784Identifiers that appear in <literals> are interpreted as literal
785identifiers to be matched against corresponding subforms of the input.
786A subform in the input matches a literal identifier if and only if it
787is an identifier and either both its occurrence in the macro expression
788and its occurrence in the macro definition have the same lexical
789binding, or the two identifiers are equal and both have no lexical
792A subpattern followed by ... can match zero or more elements of the
793input. It is an error for ... to appear in <literals>. Within a pattern
794the identifier ... must follow the last element of a nonempty sequence
795of subpatterns.
797More formally, an input form F matches a pattern P if and only if:
799*   P is a non-literal identifier; or
801*   P is a literal identifier and F is an identifier with the same
802    binding; or
804*   P is a list (P[1] ... P[n]) and F is a list of n forms that match P
805    [1] through P[n], respectively; or
807*   P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
808    or improper list of n or more forms that match P[1] through P[n],
809    respectively, and whose nth "cdr" matches P[n+1]; or
811*   P is of the form (P[1] ... P[n] P[n+1] <ellipsis>) where <ellipsis>
812    is the identifier ... and F is a proper list of at least n forms,
813    the first n of which match P[1] through P[n], respectively, and
814    each remaining element of F matches P[n+1]; or
816*   P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
817    forms that match P[1] through P[n]; or
819*   P is of the form #(P[1] ... P[n] P[n+1] <ellipsis>) where
820    <ellipsis> is the identifier ... and F is a vector of n or more
821    forms the first n of which match P[1] through P[n], respectively,
822    and each remaining element of F matches P[n+1]; or
824*   P is a datum and F is equal to P in the sense of the equal?
825    procedure.
827It is an error to use a macro keyword, within the scope of its binding,
828in an expression that does not match any of the patterns.
830When a macro use is transcribed according to the template of the
831matching <syntax rule>, pattern variables that occur in the template
832are replaced by the subforms they match in the input. Pattern variables
833that occur in subpatterns followed by one or more instances of the
834identifier ... are allowed only in subtemplates that are followed by as
835many instances of .... They are replaced in the output by all of the
836subforms they match in the input, distributed as indicated. It is an
837error if the output cannot be built up as specified.
839Identifiers that appear in the template but are not pattern variables
840or the identifier ... are inserted into the output as literal
841identifiers. If a literal identifier is inserted as a free identifier
842then it refers to the binding of that identifier within whose scope the
843instance of syntax-rules appears. If a literal identifier is inserted
844as a bound identifier then it is in effect renamed to prevent
845inadvertent captures of free identifiers.
847As an example, if let and cond are defined as usual, then they are
848hygienic (as required) and the following is not an error.
850 (let ((=> #f))
851   (cond (#t => 'ok)))                   ===> ok
853The macro transformer for cond recognizes => as a local variable, and
854hence an expression, and not as the top-level identifier =>, which the
855macro transformer treats as a syntactic keyword. Thus the example
856expands into
858 (let ((=> #f))
859   (if #t (begin => 'ok)))
861instead of
863 (let ((=> #f))
864   (let ((temp #t))
865     (if temp ('ok temp))))
867which would result in an invalid procedure call.
869== Program structure
871=== Programs
873A Scheme program consists of a sequence of expressions, definitions,
874and syntax definitions. Expressions are described in chapter 4;
875definitions and syntax definitions are the subject of the rest of the
876present chapter.
878Programs are typically stored in files or entered interactively to a
879running Scheme system, although other paradigms are possible;
880questions of user interface lie outside the scope of this
881report. (Indeed, Scheme would still be useful as a notation for
882expressing computational methods even in the absence of a mechanical
885Definitions and syntax definitions occurring at the top level of a
886program can be interpreted declaratively. They cause bindings to be
887created in the top level environment or modify the value of existing
888top-level bindings. Expressions occurring at the top level of a
889program are interpreted imperatively; they are executed in order when
890the program is invoked or loaded, and typically perform some kind of
893At the top level of a program (begin <form1> ...) is equivalent to the
894sequence of expressions, definitions, and syntax definitions that form
895the body of the begin.
897=== Definitions
899Definitions are valid in some, but not all, contexts where expressions
900are allowed. They are valid only at the top level of a <program> and
901at the beginning of a <body>.
903A definition should have one of the following forms:
905<macro>(define <variable> <expression>)</macro><br>
906<macro>(define (<variable> <formals>) <body>)</macro><br>
908<Formals> should be either a sequence of zero or more variables, or a
909sequence of one or more variables followed by a space-delimited period
910and another variable (as in a lambda expression). This form is
911equivalent to
913 (define <variable>
914   (lambda (<formals>) <body>)).
916<macro>(define (<variable> . <formal>) <body>)</macro><br>
918<Formal> should be a single variable. This form is equivalent to
920 (define <variable>
921   (lambda <formal> <body>)).
923==== Top level definitions
925At the top level of a program, a definition
927 (define <variable> <expression>)
929has essentially the same effect as the assignment expression
931 (set! <variable> <expression>)
933if <variable> is bound. If <variable> is not bound, however, then the
934definition will bind <variable> to a new location before performing
935the assignment, whereas it would be an error to perform a set! on an
936unbound variable.
938 (define add3
939   (lambda (x) (+ x 3)))
940 (add3 3)                         ===>  6
941 (define first car)
942 (first '(1 2))                   ===>  1
944Some implementations of Scheme use an initial environment in which all
945possible variables are bound to locations, most of which contain
946undefined values. Top level definitions in such an implementation are
947truly equivalent to assignments.
949==== Internal definitions
951Definitions may occur at the beginning of a <body> (that is, the body
952of a lambda, let, let*, letrec, let-syntax, or letrec-syntax
953expression or that of a definition of an appropriate form). Such
954definitions are known as internal definitions as opposed to the top
955level definitions described above. The variable defined by an internal
956definition is local to the <body>. That is, <variable> is bound rather
957than assigned, and the region of the binding is the entire <body>. For
960 (let ((x 5))
961   (define foo (lambda (y) (bar x y)))
962   (define bar (lambda (a b) (+ (* a b) a)))
963   (foo (+ x 3)))                        ===>  45
965A <body> containing internal definitions can always be converted into
966a completely equivalent letrec expression. For example, the let
967expression in the above example is equivalent to
969 (let ((x 5))
970   (letrec ((foo (lambda (y) (bar x y)))
971            (bar (lambda (a b) (+ (* a b) a))))
972     (foo (+ x 3))))
974Just as for the equivalent letrec expression, it must be possible to
975evaluate each <expression> of every internal definition in a <body>
976without assigning or referring to the value of any <variable> being
979Wherever an internal definition may occur (begin <definition1> ...) is
980equivalent to the sequence of definitions that form the body of the
983=== Syntax definitions
985Syntax definitions are valid only at the top level of a
986<program>. They have the following form:
988 (define-syntax <keyword> <transformer spec>)
990<Keyword> is an identifier, and the <transformer spec> should be an
991instance of syntax-rules. The top-level syntactic environment is
992extended by binding the <keyword> to the specified transformer.
994There is no define-syntax analogue of internal definitions.
996Although macros may expand into definitions and syntax definitions in
997any context that permits them, it is an error for a definition or
998syntax definition to shadow a syntactic keyword whose meaning is
999needed to determine whether some form in the group of forms that
1000contains the shadowing definition is in fact a definition, or, for
1001internal definitions, is needed to determine the boundary between the
1002group and the expressions that follow the group. For example, the
1003following are errors:
1005 (define define 3)
1007 (begin (define begin list))
1009 (let-syntax
1010   ((foo (syntax-rules ()
1011           ((foo (proc args ...) body ...)
1012            (define proc
1013              (lambda (args ...)
1014                body ...))))))
1015   (let ((x 3))
1016     (foo (plus x y) (+ x y))
1017     (define foo x)
1018     (plus foo x)))
1020== Standard procedures
1022This chapter describes Scheme's built-in procedures. The initial (or
1023"top level") Scheme environment starts out with a number of variables
1024bound to locations containing useful values, most of which are
1025primitive procedures that manipulate data. For example, the variable
1026abs is bound to (a location initially containing) a procedure of one
1027argument that computes the absolute value of a number, and the variable
1028+ is bound to a procedure that computes sums. Built-in procedures that
1029can easily be written in terms of other built-in procedures are
1030identified as "library procedures".
1032A program may use a top-level definition to bind any variable. It may
1033subsequently alter any such binding by an assignment (see
1034[[#assignments|assignments]], above). These operations do
1035not modify the behavior of Scheme's built-in procedures. Altering any
1036top-level binding that has not been introduced by a definition has an
1037unspecified effect on the behavior of the built-in procedures.
1039=== Equivalence predicates
1041A predicate is a procedure that always returns a boolean value (#t or #f).
1042An equivalence predicate is the computational analogue of a
1043mathematical equivalence relation (it is symmetric, reflexive, and
1044transitive). Of the equivalence predicates described in this section,
1045eq? is the finest or most discriminating, and equal? is the coarsest.
1046eqv? is slightly less discriminating than eq?.
1048<procedure>(eqv? obj[1] obj[2])</procedure><br>
1050The eqv? procedure defines a useful equivalence relation on objects.
1051Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
1052as the same object. This relation is left slightly open to
1053interpretation, but the following partial specification of eqv? holds
1054for all implementations of Scheme.
1056The eqv? procedure returns #t if:
1058*   obj[1] and obj[2] are both #t or both #f.
1060*   obj[1] and obj[2] are both symbols and
1062    (string=? (symbol->string obj1)
1063              (symbol->string obj2))
1064                ===>  #t
1066Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
1067symbol" as alluded to in the section on [[#symbols|symbols]]. This
1068report does not presume to specify the behavior of eqv? on
1069implementation-dependent extensions.
1071*   obj[1] and obj[2] are both numbers, are numerically equal (see =,
1072    under [[#numerical-operations|numerical operations]]), and are
1073    either both exact or both inexact.
1075*   obj[1] and obj[2] are both characters and are the same character
1076    according to the char=? procedure (see "[[#characters|characters]]").
1078*   both obj[1] and obj[2] are the empty list.
1080*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
1081    same locations in the store.
1083*   obj[1] and obj[2] are procedures whose location tags are equal
1084    (see "[[#procedures|procedures]]").
1086The eqv? procedure returns #f if:
1088*   obj[1] and obj[2] are of different types.
1090*   one of obj[1] and obj[2] is #t but the other is #f.
1092*   obj[1] and obj[2] are symbols but
1094    (string=? (symbol->string obj[1])
1095              (symbol->string obj[2]))
1096                ===>  #f
1098*   one of obj[1] and obj[2] is an exact number but the other is an
1099    inexact number.
1101*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
1103*   obj[1] and obj[2] are characters for which the char=? procedure
1104    returns #f.
1106*   one of obj[1] and obj[2] is the empty list but the other is not.
1108*   obj[1] and obj[2] are pairs, vectors, or strings that denote
1109    distinct locations.
1111*   obj[1] and obj[2] are procedures that would behave differently
1112    (return different value(s) or have different side effects) for some
1113    arguments.
1115 (eqv? 'a 'a)                             ===>  #t
1116 (eqv? 'a 'b)                             ===>  #f
1117 (eqv? 2 2)                               ===>  #t
1118 (eqv? '() '())                           ===>  #t
1119 (eqv? 100000000 100000000)               ===>  #t
1120 (eqv? (cons 1 2) (cons 1 2))             ===>  #f
1121 (eqv? (lambda () 1)
1122       (lambda () 2))                     ===>  #f
1123 (eqv? #f 'nil)                           ===>  #f
1124 (let ((p (lambda (x) x)))
1125   (eqv? p p))                            ===>  #t
1127The following examples illustrate cases in which the above rules do not
1128fully specify the behavior of eqv?. All that can be said about such
1129cases is that the value returned by eqv? must be a boolean.
1131 (eqv? "" "")                     ===>  unspecified
1132 (eqv? '#() '#())                 ===>  unspecified
1133 (eqv? (lambda (x) x)
1134       (lambda (x) x))            ===>  unspecified
1135 (eqv? (lambda (x) x)
1136       (lambda (y) y))            ===>  unspecified
1138The next set of examples shows the use of eqv? with procedures that
1139have local state. Gen-counter must return a distinct procedure every
1140time, since each procedure has its own internal counter. Gen-loser,
1141however, returns equivalent procedures each time, since the local state
1142does not affect the value or side effects of the procedures.
1144 (define gen-counter
1145   (lambda ()
1146     (let ((n 0))
1147       (lambda () (set! n (+ n 1)) n))))
1148 (let ((g (gen-counter)))
1149   (eqv? g g))                   ===>  #t
1150 (eqv? (gen-counter) (gen-counter))
1151                                 ===>  #f
1152 (define gen-loser
1153   (lambda ()
1154     (let ((n 0))
1155       (lambda () (set! n (+ n 1)) 27))))
1156 (let ((g (gen-loser)))
1157   (eqv? g g))                   ===>  #t
1158 (eqv? (gen-loser) (gen-loser))
1159                                 ===>  unspecified
1161 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1162          (g (lambda () (if (eqv? f g) 'both 'g))))
1163   (eqv? f g))
1164                                 ===>  unspecified
1166 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1167          (g (lambda () (if (eqv? f g) 'g 'both))))
1168   (eqv? f g))
1169                                 ===>  #f
1171Since it is an error to modify constant objects (those returned by
1172literal expressions), implementations are permitted, though not
1173required, to share structure between constants where appropriate. Thus
1174the value of eqv? on constants is sometimes implementation-dependent.
1176 (eqv? '(a) '(a))                         ===>  unspecified
1177 (eqv? "a" "a")                           ===>  unspecified
1178 (eqv? '(b) (cdr '(a b)))                 ===>  unspecified
1179 (let ((x '(a)))
1180   (eqv? x x))                            ===>  #t
1182Rationale:   The above definition of eqv? allows implementations
1183latitude in their treatment of procedures and literals:
1184implementations are free either to detect or to fail to detect that
1185two procedures or two literals are equivalent to each other, and
1186can decide whether or not to merge representations of equivalent
1187objects by using the same pointer or bit pattern to represent both.
1189<procedure>(eq? obj[1] obj[2])</procedure><br>
1191Eq? is similar to eqv? except that in some cases it is capable of
1192discerning distinctions finer than those detectable by eqv?.
1194Eq? and eqv? are guaranteed to have the same behavior on symbols,
1195booleans, the empty list, pairs, procedures, and non-empty strings and
1196vectors. Eq?'s behavior on numbers and characters is
1197implementation-dependent, but it will always return either true or
1198false, and will return true only when eqv? would also return true. Eq?
1199may also behave differently from eqv? on empty vectors and empty
1202 (eq? 'a 'a)                             ===>  #t
1203 (eq? '(a) '(a))                         ===>  unspecified
1204 (eq? (list 'a) (list 'a))               ===>  #f
1205 (eq? "a" "a")                           ===>  unspecified
1206 (eq? "" "")                             ===>  unspecified
1207 (eq? '() '())                           ===>  #t
1208 (eq? 2 2)                               ===>  unspecified
1209 (eq? #\A #\A)                           ===>  unspecified
1210 (eq? car car)                           ===>  #t
1211 (let ((n (+ 2 3)))
1212   (eq? n n))              ===>  unspecified
1213 (let ((x '(a)))
1214   (eq? x x))              ===>  #t
1215 (let ((x '#()))
1216   (eq? x x))              ===>  #t
1217 (let ((p (lambda (x) x)))
1218   (eq? p p))              ===>  #t
1220Rationale:   It will usually be possible to implement eq? much more
1221efficiently than eqv?, for example, as a simple pointer comparison
1222instead of as some more complicated operation. One reason is that
1223it may not be possible to compute eqv? of two numbers in constant
1224time, whereas eq? implemented as pointer comparison will always
1225finish in constant time. Eq? may be used like eqv? in applications
1226using procedures to implement objects with state since it obeys the
1227same constraints as eqv?.
1229<procedure>(equal? obj[1] obj[2])</procedure><br>
1231Equal? recursively compares the contents of pairs, vectors, and
1232strings, applying eqv? on other objects such as numbers and symbols. A
1233rule of thumb is that objects are generally equal? if they print the
1234same. Equal? may fail to terminate if its arguments are circular data
1237 (equal? 'a 'a)                          ===>  #t
1238 (equal? '(a) '(a))                      ===>  #t
1239 (equal? '(a (b) c)
1240         '(a (b) c))                     ===>  #t
1241 (equal? "abc" "abc")                    ===>  #t
1242 (equal? 2 2)                            ===>  #t
1243 (equal? (make-vector 5 'a)
1244         (make-vector 5 'a))             ===>  #t
1245 (equal? (lambda (x) x)
1246         (lambda (y) y))          ===>  unspecified
1248=== Numbers
1250Numerical computation has traditionally been neglected by the Lisp
1251community. Until Common Lisp there was no carefully thought out
1252strategy for organizing numerical computation, and with the exception
1253of the MacLisp system [20] little effort was made to execute numerical
1254code efficiently. This report recognizes the excellent work of the
1255Common Lisp committee and accepts many of their recommendations. In
1256some ways this report simplifies and generalizes their proposals in a
1257manner consistent with the purposes of Scheme.
1259It is important to distinguish between the mathematical numbers, the
1260Scheme numbers that attempt to model them, the machine representations
1261used to implement the Scheme numbers, and notations used to write
1262numbers. This report uses the types number, complex, real, rational,
1263and integer to refer to both mathematical numbers and Scheme numbers.
1264Machine representations such as fixed point and floating point are
1265referred to by names such as fixnum and flonum.
1267==== Numerical types
1269Mathematically, numbers may be arranged into a tower of subtypes in
1270which each level is a subset of the level above it:
1272    number
1273    complex
1274    real
1275    rational
1276    integer
1278For example, 3 is an integer. Therefore 3 is also a rational, a real,
1279and a complex. The same is true of the Scheme numbers that model 3. For
1280Scheme numbers, these types are defined by the predicates number?,
1281complex?, real?, rational?, and integer?.
1283There is no simple relationship between a number's type and its
1284representation inside a computer. Although most implementations of
1285Scheme will offer at least two different representations of 3, these
1286different representations denote the same integer.
1288Scheme's numerical operations treat numbers as abstract data, as
1289independent of their representation as possible. Although an
1290implementation of Scheme may use fixnum, flonum, and perhaps other
1291representations for numbers, this should not be apparent to a casual
1292programmer writing simple programs.
1294It is necessary, however, to distinguish between numbers that are
1295represented exactly and those that may not be. For example, indexes
1296into data structures must be known exactly, as must some polynomial
1297coefficients in a symbolic algebra system. On the other hand, the
1298results of measurements are inherently inexact, and irrational numbers
1299may be approximated by rational and therefore inexact approximations.
1300In order to catch uses of inexact numbers where exact numbers are
1301required, Scheme explicitly distinguishes exact from inexact numbers.
1302This distinction is orthogonal to the dimension of type.
1304==== Exactness
1306Scheme numbers are either exact or inexact. A number is exact if it was
1307written as an exact constant or was derived from exact numbers using
1308only exact operations. A number is inexact if it was written as an
1309inexact constant, if it was derived using inexact ingredients, or if it
1310was derived using inexact operations. Thus inexactness is a contagious
1311property of a number. If two implementations produce exact results for
1312a computation that did not involve inexact intermediate results, the
1313two ultimate results will be mathematically equivalent. This is
1314generally not true of computations involving inexact numbers since
1315approximate methods such as floating point arithmetic may be used, but
1316it is the duty of each implementation to make the result as close as
1317practical to the mathematically ideal result.
1319Rational operations such as + should always produce exact results when
1320given exact arguments. If the operation is unable to produce an exact
1321result, then it may either report the violation of an implementation
1322restriction or it may silently coerce its result to an inexact value.
1323See [[#implementation-restrictions|the next section]].
1325With the exception of inexact->exact, the operations described in this
1326section must generally return inexact results when given any inexact
1327arguments. An operation may, however, return an exact result if it can
1328prove that the value of the result is unaffected by the inexactness of
1329its arguments. For example, multiplication of any number by an exact
1330zero may produce an exact zero result, even if the other argument is
1333==== Implementation restrictions
1335Implementations of Scheme are not required to implement the whole
1336tower of subtypes given under "[[#numerical-types|Numerical types]]",
1337but they must implement a coherent subset consistent with both the
1338purposes of the implementation and the spirit of the Scheme
1339language. For example, an implementation in which all numbers are real
1340may still be quite useful.
1342Implementations may also support only a limited range of numbers of any
1343type, subject to the requirements of this section. The supported range
1344for exact numbers of any type may be different from the supported range
1345for inexact numbers of that type. For example, an implementation that
1346uses flonums to represent all its inexact real numbers may support a
1347practically unbounded range of exact integers and rationals while
1348limiting the range of inexact reals (and therefore the range of inexact
1349integers and rationals) to the dynamic range of the flonum format.
1350Furthermore the gaps between the representable inexact integers and
1351rationals are likely to be very large in such an implementation as the
1352limits of this range are approached.
1354An implementation of Scheme must support exact integers throughout the
1355range of numbers that may be used for indexes of lists, vectors, and
1356strings or that may result from computing the length of a list, vector,
1357or string. The length, vector-length, and string-length procedures must
1358return an exact integer, and it is an error to use anything but an
1359exact integer as an index. Furthermore any integer constant within the
1360index range, if expressed by an exact integer syntax, will indeed be
1361read as an exact integer, regardless of any implementation restrictions
1362that may apply outside this range. Finally, the procedures listed below
1363will always return an exact integer result provided all their arguments
1364are exact integers and the mathematically expected result is
1365representable as an exact integer within the implementation:
1367 +            -             *
1368 quotient     remainder     modulo
1369 max          min           abs
1370 numerator    denominator   gcd
1371 lcm          floor         ceiling
1372 truncate     round         rationalize
1373 expt
1375Implementations are encouraged, but not required, to support exact
1376integers and exact rationals of practically unlimited size and
1377precision, and to implement the above procedures and the / procedure in
1378such a way that they always return exact results when given exact
1379arguments. If one of these procedures is unable to deliver an exact
1380result when given exact arguments, then it may either report a
1381violation of an implementation restriction or it may silently coerce
1382its result to an inexact number. Such a coercion may cause an error
1385An implementation may use floating point and other approximate
1386representation strategies for inexact numbers. This report recommends,
1387but does not require, that the IEEE 32-bit and 64-bit floating point
1388standards be followed by implementations that use flonum
1389representations, and that implementations using other representations
1390should match or exceed the precision achievable using these floating
1391point standards [12].
1393In particular, implementations that use flonum representations must
1394follow these rules: A flonum result must be represented with at least
1395as much precision as is used to express any of the inexact arguments to
1396that operation. It is desirable (but not required) for potentially
1397inexact operations such as sqrt, when applied to exact arguments, to
1398produce exact answers whenever possible (for example the square root of
1399an exact 4 ought to be an exact 2). If, however, an exact number is
1400operated upon so as to produce an inexact result (as by sqrt), and if
1401the result is represented as a flonum, then the most precise flonum
1402format available must be used; but if the result is represented in some
1403other way then the representation must have at least as much precision
1404as the most precise flonum format available.
1406Although Scheme allows a variety of written notations for numbers, any
1407particular implementation may support only some of them. For example,
1408an implementation in which all numbers are real need not support the
1409rectangular and polar notations for complex numbers. If an
1410implementation encounters an exact numerical constant that it cannot
1411represent as an exact number, then it may either report a violation of
1412an implementation restriction or it may silently represent the constant
1413by an inexact number.
1415==== Syntax of numerical constants
1417For a complete formal description of the syntax of the written
1418representations for numbers, see the R5RS report. Note that case is
1419not significant in numerical constants.
1421A number may be written in binary, octal, decimal, or hexadecimal by
1422the use of a radix prefix. The radix prefixes are #b (binary), #o
1423(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
1424number is assumed to be expressed in decimal.
1426A numerical constant may be specified to be either exact or inexact by
1427a prefix. The prefixes are #e for exact, and #i for inexact. An
1428exactness prefix may appear before or after any radix prefix that is
1429used. If the written representation of a number has no exactness
1430prefix, the constant may be either inexact or exact. It is inexact if
1431it contains a decimal point, an exponent, or a "#" character in the
1432place of a digit, otherwise it is exact. In systems with inexact
1433numbers of varying precisions it may be useful to specify the precision
1434of a constant. For this purpose, numerical constants may be written
1435with an exponent marker that indicates the desired precision of the
1436inexact representation. The letters s, f, d, and l specify the use of
1437short, single, double, and long precision, respectively. (When fewer
1438than four internal inexact representations exist, the four size
1439specifications are mapped onto those available. For example, an
1440implementation with two internal representations may map short and
1441single together and long and double together.) In addition, the
1442exponent marker e specifies the default precision for the
1443implementation. The default precision has at least as much precision as
1444double, but implementations may wish to allow this default to be set by
1445the user.
1447 3.14159265358979F0
1448         Round to single --- 3.141593
1449 0.6L0
1450         Extend to long --- .600000000000000
1452==== Numerical operations
1454The numerical routines described below have argument restrictions,
1455which are encoded in the naming conventions of the arguments as
1456given in the procedure's signature.  The conventions are as follows:
1458; {{obj}} : any object
1459; {{list, list1, ... listj, ... list : (see "[[#pairs-and-lists|Pairs and lists]]" below)
1460; {{z, z1, ... zj, ...}} : complex number (currently not supported by CHICKEN core, see the "[[/egg/numbers|numbers]]" egg)
1461; {{x, x1, ... xj, ...}} : real number
1462; {{y, y1, ... yj, ...}} : real number
1463; {{q, q1, ... qj, ...}} : rational number (NOTE: fractional numbers are not supported by CHICKEN core, see the "[[/egg/numbers|numbers]]" egg)
1464; {{n, n1, ... nj, ...}} : integer
1465; {{k, k1, ... kj, ...}} : exact non-negative integer
1467The examples used in this section assume that any
1468numerical constant written using an exact notation is indeed
1469represented as an exact number. Some examples also assume that certain
1470numerical constants written using an inexact notation can be
1471represented without loss of accuracy; the inexact constants were chosen
1472so that this is likely to be true in implementations that use flonums
1473to represent inexact numbers.
1475<procedure>(number? obj)</procedure><br>
1476<procedure>(complex? obj)</procedure><br>
1477<procedure>(real? obj)</procedure><br>
1478<procedure>(rational? obj)</procedure><br>
1479<procedure>(integer? obj)</procedure><br>
1481These numerical type predicates can be applied to any kind of argument,
1482including non-numbers. They return #t if the object is of the named
1483type, and otherwise they return #f. In general, if a type predicate is
1484true of a number then all higher type predicates are also true of that
1485number. Consequently, if a type predicate is false of a number, then
1486all lower type predicates are also false of that number. If z is an
1487inexact complex number, then (real? z) is true if and only if (zero?
1488(imag-part z)) is true. If x is an inexact real number, then (integer?
1489x) is true if and only if (= x (round x)).
1491 (complex? 3+4i)                 ===>  #t
1492 (complex? 3)                    ===>  #t
1493 (real? 3)                       ===>  #t
1494 (real? -2.5+0.0i)               ===>  #t
1495 (real? #e1e10)                  ===>  #t
1496 (rational? 6/10)                ===>  #t
1497 (rational? 6/3)                 ===>  #t
1498 (integer? 3+0i)                 ===>  #t
1499 (integer? 3.0)                  ===>  #t
1500 (integer? 8/4)                  ===>  #t
1502Note:   The behavior of these type predicates on inexact numbers is
1503unreliable, since any inaccuracy may affect the result.
1505Note:   In many implementations the rational? procedure will be the
1506same as real?, and the complex? procedure will be the same as
1507number?, but unusual implementations may be able to represent some
1508irrational numbers exactly or may extend the number system to
1509support some kind of non-complex numbers.
1511<procedure>(exact? z)</procedure><br>
1512<procedure>(inexact? z)</procedure><br>
1514These numerical predicates provide tests for the exactness of a
1515quantity. For any Scheme number, precisely one of these predicates is
1518<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
1519<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
1520<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
1521<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
1522<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
1524These procedures return #t if their arguments are (respectively):
1525equal, monotonically increasing, monotonically decreasing,
1526monotonically nondecreasing, or monotonically nonincreasing.
1528These predicates are required to be transitive.
1530Note:   The traditional implementations of these predicates in
1531Lisp-like languages are not transitive.
1533Note:   While it is not an error to compare inexact numbers using
1534these predicates, the results may be unreliable because a small
1535inaccuracy may affect the result; this is especially true of = and
1536zero?. When in doubt, consult a numerical analyst.
1538<procedure>(zero? z)</procedure><br>
1539<procedure>(positive? x)</procedure><br>
1540<procedure>(negative? x)</procedure><br>
1541<procedure>(odd? n)</procedure><br>
1542<procedure>(even? n)</procedure><br>
1544These numerical predicates test a number for a particular property,
1545returning #t or #f. See note above.
1547<procedure>(max x[1] x[2] ...)</procedure><br>
1548<procedure>(min x[1] x[2] ...)</procedure><br>
1550These procedures return the maximum or minimum of their arguments.
1552 (max 3 4)                      ===>  4    ; exact
1553 (max 3.9 4)                    ===>  4.0  ; inexact
1555Note:   If any argument is inexact, then the result will also be
1556inexact (unless the procedure can prove that the inaccuracy is not
1557large enough to affect the result, which is possible only in
1558unusual implementations). If min or max is used to compare numbers
1559of mixed exactness, and the numerical value of the result cannot be
1560represented as an inexact number without loss of accuracy, then the
1561procedure may report a violation of an implementation restriction.
1563<procedure>(+ z[1] ...)</procedure><br>
1564<procedure>(* z[1] ...)</procedure><br>
1566These procedures return the sum or product of their arguments.
1568 (+ 3 4)                         ===>  7
1569 (+ 3)                           ===>  3
1570 (+)                             ===>  0
1571 (* 4)                           ===>  4
1572 (*)                             ===>  1
1574<procedure>(- z[1] z[2])</procedure><br>
1575<procedure>(- z)</procedure><br>
1576<procedure>(- z[1] z[2] ...)</procedure><br>
1577<procedure>(/ z[1] z[2])</procedure><br>
1578<procedure>(/ z)</procedure><br>
1579<procedure>(/ z[1] z[2] ...)</procedure><br>
1581With two or more arguments, these procedures return the difference or
1582quotient of their arguments, associating to the left. With one
1583argument, however, they return the additive or multiplicative inverse
1584of their argument.
1586 (- 3 4)                         ===>  -1
1587 (- 3 4 5)                       ===>  -6
1588 (- 3)                           ===>  -3
1589 (/ 3 4 5)                       ===>  3/20
1590 (/ 3)                           ===>  1/3
1592<procedure>(abs x)</procedure><br>
1594Abs returns the absolute value of its argument.
1596 (abs -7)                        ===>  7
1598<procedure>(quotient n[1] n[2])</procedure><br>
1599<procedure>(remainder n[1] n[2])</procedure><br>
1600<procedure>(modulo n[1] n[2])</procedure><br>
1602These procedures implement number-theoretic (integer) division. n[2]
1603should be non-zero. All three procedures return integers. If n[1]/n[2]
1604is an integer:
1606    (quotient n[1] n[2])           ===> n[1]/n[2]
1607    (remainder n[1] n[2])          ===> 0
1608    (modulo n[1] n[2])             ===> 0
1610If n[1]/n[2] is not an integer:
1612    (quotient n[1] n[2])           ===> n[q]
1613    (remainder n[1] n[2])          ===> n[r]
1614    (modulo n[1] n[2])             ===> n[m]
1616where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
1617|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
1618n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
1620From this we can conclude that for integers n[1] and n[2] with n[2] not
1621equal to 0,
1623     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
1624           (remainder n[1] n[2])))
1625                                         ===>  #t
1627provided all numbers involved in that computation are exact.
1629 (modulo 13 4)                   ===>  1
1630 (remainder 13 4)                ===>  1
1632 (modulo -13 4)                  ===>  3
1633 (remainder -13 4)               ===>  -1
1635 (modulo 13 -4)                  ===>  -3
1636 (remainder 13 -4)               ===>  1
1638 (modulo -13 -4)                 ===>  -1
1639 (remainder -13 -4)              ===>  -1
1641 (remainder -13 -4.0)            ===>  -1.0  ; inexact
1643<procedure>(gcd n[1] ...)</procedure><br>
1644<procedure>(lcm n[1] ...)</procedure><br>
1646These procedures return the greatest common divisor or least common
1647multiple of their arguments. The result is always non-negative.
1649 (gcd 32 -36)                    ===>  4
1650 (gcd)                           ===>  0
1651 (lcm 32 -36)                    ===>  288
1652 (lcm 32.0 -36)                  ===>  288.0  ; inexact
1653 (lcm)                           ===>  1
1655<procedure>(numerator q)</procedure><br>
1656<procedure>(denominator q)</procedure><br>
1658These procedures return the numerator or denominator of their argument;
1659the result is computed as if the argument was represented as a fraction
1660in lowest terms. The denominator is always positive. The denominator of
16610 is defined to be 1.
1663 (numerator (/ 6 4))            ===>  3
1664 (denominator (/ 6 4))          ===>  2
1665 (denominator
1666   (exact->inexact (/ 6 4)))    ===> 2.0
1668<procedure>(floor x)</procedure><br>
1669<procedure>(ceiling x)</procedure><br>
1670<procedure>(truncate x)</procedure><br>
1671<procedure>(round x)</procedure><br>
1673These procedures return integers. Floor returns the largest integer not
1674larger than x. Ceiling returns the smallest integer not smaller than x.
1675Truncate returns the integer closest to x whose absolute value is not
1676larger than the absolute value of x. Round returns the closest integer
1677to x, rounding to even when x is halfway between two integers.
1679Rationale:   Round rounds to even for consistency with the default
1680rounding mode specified by the IEEE floating point standard.
1682Note:   If the argument to one of these procedures is inexact, then
1683the result will also be inexact. If an exact value is needed, the
1684result should be passed to the inexact->exact procedure.
1686 (floor -4.3)                  ===>  -5.0
1687 (ceiling -4.3)                ===>  -4.0
1688 (truncate -4.3)               ===>  -4.0
1689 (round -4.3)                  ===>  -4.0
1691 (floor 3.5)                   ===>  3.0
1692 (ceiling 3.5)                 ===>  4.0
1693 (truncate 3.5)                ===>  3.0
1694 (round 3.5)                   ===>  4.0  ; inexact
1696 (round 7/2)                   ===>  4    ; exact
1697 (round 7)                     ===>  7
1699<procedure>(rationalize x y)</procedure><br>
1701Rationalize returns the simplest rational number differing from x by no
1702more than y. A rational number r[1] is simpler than another rational
1703number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
1704and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
1705Although not all rationals are comparable in this ordering (consider 2/
17067 and 3/5) any interval contains a rational number that is simpler than
1707every other rational number in that interval (the simpler 2/5 lies
1708between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
1711 (rationalize
1712   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
1713 (rationalize .3 1/10)                ===> #i1/3  ; inexact
1715<procedure>(exp z)</procedure><br>
1716<procedure>(log z)</procedure><br>
1717<procedure>(sin z)</procedure><br>
1718<procedure>(cos z)</procedure><br>
1719<procedure>(tan z)</procedure><br>
1720<procedure>(asin z)</procedure><br>
1721<procedure>(acos z)</procedure><br>
1722<procedure>(atan z)</procedure><br>
1723<procedure>(atan y x)</procedure><br>
1725These procedures are part of every implementation that supports general
1726real numbers; they compute the usual transcendental functions. Log
1727computes the natural logarithm of z (not the base ten logarithm). Asin,
1728acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and
1729arctangent (tan^-1), respectively. The two-argument variant of atan
1730computes (angle (make-rectangular x y)) (see below), even in
1731implementations that don't support general complex numbers.
1733In general, the mathematical functions log, arcsine, arccosine, and
1734arctangent are multiply defined. The value of log z is defined to be
1735the one whose imaginary part lies in the range from -pi
1736(exclusive) to pi (inclusive). log 0 is undefined. With log
1737defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are
1738according to the following formulae:
1740 sin^-1 z = - i log (i z + (1 - z^2)^1/2)
1742 cos^-1 z = pi / 2 - sin^-1 z
1744 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
1746The above specification follows [27], which in turn cites [19]; refer
1747to these sources for more detailed discussion of branch cuts, boundary
1748conditions, and implementation of these functions. When it is possible
1749these procedures produce a real result from a real argument.
1751<procedure>(sqrt z)</procedure><br>
1753Returns the principal square root of z. The result will have either
1754positive real part, or zero real part and non-negative imaginary part.
1756<procedure>(expt z[1] z[2])</procedure><br>
1758Returns z[1] raised to the power z[2]. For z[1] != 0
1760 z[1]^z[2] = e^z[2] log z[1]
17620^z is 1 if z = 0 and 0 otherwise.
1764<procedure>(make-rectangular x[1] x[2])</procedure><br>
1765<procedure>(make-polar x[3] x[4])</procedure><br>
1766<procedure>(real-part z)</procedure><br>
1767<procedure>(imag-part z)</procedure><br>
1768<procedure>(magnitude z)</procedure><br>
1769<procedure>(angle z)</procedure><br>
1771These procedures are part of every implementation that supports general
1772complex numbers. Suppose x[1], x[2], x[3], and x[4] are real numbers
1773and z is a complex number such that
1775 z = x[1] + x[2]i = x[3] . e^i x[4]
1779 (make-rectangular x[1] x[2])         ===> z
1780 (make-polar x[3] x[4])             ===> z
1781 (real-part z)                          ===> x[1]
1782 (imag-part z)                          ===> x[2]
1783 (magnitude z)                          ===> |x[3]|
1784 (angle z)                              ===> x[angle]
1786where - pi < x[angle] < pi with x[angle] = x[4] + 2 pi n
1787for some integer n.
1789Rationale:   Magnitude is the same as abs for a real argument, but
1790abs must be present in all implementations, whereas magnitude need
1791only be present in implementations that support general complex
1794<procedure>(exact->inexact z)</procedure><br>
1795<procedure>(inexact->exact z)</procedure><br>
1797Exact->inexact returns an inexact representation of z. The value
1798returned is the inexact number that is numerically closest to the
1799argument. If an exact argument has no reasonably close inexact
1800equivalent, then a violation of an implementation restriction may be
1803Inexact->exact returns an exact representation of z. The value returned
1804is the exact number that is numerically closest to the argument. If an
1805inexact argument has no reasonably close exact equivalent, then a
1806violation of an implementation restriction may be reported.
1808These procedures implement the natural one-to-one correspondence
1809between exact and inexact integers throughout an
1810implementation-dependent range.
1811See "[[#implementation-restrictions|Implementation restrictions]]".
1813==== Numerical input and output
1815<procedure>(number->string z)</procedure><br>
1816<procedure>(number->string z radix)</procedure><br>
1818Radix must be an exact integer, either 2, 8, 10, or 16. If omitted, radix
1819defaults to 10. The procedure number->string takes a number and a
1820radix and returns as a string an external representation of the given
1821number in the given radix such that
1823 (let ((number number)
1824       (radix radix))
1825   (eqv? number
1826         (string->number (number->string number
1827                                         radix)
1828                         radix)))
1830is true. It is an error if no possible result makes this expression
1833If z is inexact, the radix is 10, and the above expression can be
1834satisfied by a result that contains a decimal point, then the result
1835contains a decimal point and is expressed using the minimum number of
1836digits (exclusive of exponent and trailing zeroes) needed to make the
1837above expression true [3, 5]; otherwise the format of the result is
1840The result returned by number->string never contains an explicit radix
1843Note:   The error case can occur only when z is not a complex
1844number or is a complex number with a non-rational real or imaginary
1847Rationale:   If z is an inexact number represented using flonums,
1848and the radix is 10, then the above expression is normally
1849satisfied by a result containing a decimal point. The unspecified
1850case allows for infinities, NaNs, and non-flonum representations.
1852<procedure>(string->number string)</procedure><br>
1853<procedure>(string->number string radix)</procedure><br>
1855Returns a number of the maximally precise representation expressed by
1856the given string. Radix must be an exact integer, either 2, 8, 10, or
185716. If supplied, radix is a default radix that may be overridden by an
1858explicit radix prefix in string (e.g. "#o177"). If radix is not
1859supplied, then the default radix is 10. If string is not a
1860syntactically valid notation for a number, then string->number
1861returns #f.
1863 (string->number "100")                ===>  100
1864 (string->number "100" 16)             ===>  256
1865 (string->number "1e2")                ===>  100.0
1866 (string->number "15##")               ===>  1500.0
1868Note:   The domain of string->number may be restricted by
1869implementations in the following ways. String->number is permitted
1870to return #f whenever string contains an explicit radix prefix. If
1871all numbers supported by an implementation are real, then string->
1872number is permitted to return #f whenever string uses the polar or
1873rectangular notations for complex numbers. If all numbers are
1874integers, then string->number may return #f whenever the fractional
1875notation is used. If all numbers are exact, then string->number may
1876return #f whenever an exponent marker or explicit exactness prefix
1877is used, or if a # appears in place of a digit. If all inexact
1878numbers are integers, then string->number may return #f whenever a
1879decimal point is used.
1881=== Other data types
1883This section describes operations on some of Scheme's non-numeric data
1884types: booleans, pairs, lists, symbols, characters, strings and
1887==== Booleans
1889The standard boolean objects for true and false are written as #t and #f.
1890What really matters, though, are the objects that the Scheme
1891conditional expressions (if, cond, and, or, do) treat as true or false.
1892The phrase "a true value" (or sometimes just "true") means any
1893object treated as true by the conditional expressions, and the phrase
1894"a false value" (or "false") means any object treated as false by
1895the conditional expressions.
1897Of all the standard Scheme values, only #f counts as false in
1898conditional expressions. Except for #f, all standard Scheme values,
1899including #t, pairs, the empty list, symbols, numbers, strings,
1900vectors, and procedures, count as true.
1902Note:   Programmers accustomed to other dialects of Lisp should be
1903aware that Scheme distinguishes both #f and the empty list from the
1904symbol nil.
1906Boolean constants evaluate to themselves, so they do not need to be
1907quoted in programs.
1909 #t                ===>  #t
1910 #f                ===>  #f
1911 '#f               ===>  #f
1913<procedure>(not obj)</procedure><br>
1915Not returns #t if obj is false, and returns #f otherwise.
1917 (not #t)           ===>  #f
1918 (not 3)            ===>  #f
1919 (not (list 3))     ===>  #f
1920 (not #f)           ===>  #t
1921 (not '())          ===>  #f
1922 (not (list))       ===>  #f
1923 (not 'nil)         ===>  #f
1925<procedure>(boolean? obj)</procedure><br>
1927Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
1929 (boolean? #f)                 ===>  #t
1930 (boolean? 0)                  ===>  #f
1931 (boolean? '())                ===>  #f
1933==== Pairs and lists
1935A pair (sometimes called a dotted pair) is a record structure with two
1936fields called the car and cdr fields (for historical reasons). Pairs
1937are created by the procedure cons. The car and cdr fields are accessed
1938by the procedures car and cdr. The car and cdr fields are assigned by
1939the procedures set-car! and set-cdr!.
1941Pairs are used primarily to represent lists. A list can be defined
1942recursively as either the empty list or a pair whose cdr is a list.
1943More precisely, the set of lists is defined as the smallest set X such
1946*   The empty list is in X.
1947*   If list is in X, then any pair whose cdr field contains list is
1948    also in X.
1950The objects in the car fields of successive pairs of a list are the
1951elements of the list. For example, a two-element list is a pair whose
1952car is the first element and whose cdr is a pair whose car is the
1953second element and whose cdr is the empty list. The length of a list is
1954the number of elements, which is the same as the number of pairs.
1956The empty list is a special object of its own type (it is not a pair);
1957it has no elements and its length is zero.
1959Note:   The above definitions imply that all lists have finite
1960length and are terminated by the empty list.
1962The most general notation (external representation) for Scheme pairs is
1963the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
1964car field and c[2] is the value of the cdr field. For example (4 . 5)
1965is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
1966external representation of a pair, not an expression that evaluates to
1967a pair.
1969A more streamlined notation can be used for lists: the elements of the
1970list are simply enclosed in parentheses and separated by spaces. The
1971empty list is written () . For example,
1973 (a b c d e)
1977 (a . (b . (c . (d . (e . ())))))
1979are equivalent notations for a list of symbols.
1981A chain of pairs not ending in the empty list is called an improper
1982list. Note that an improper list is not a list. The list and dotted
1983notations can be combined to represent improper lists:
1985 (a b c . d)
1987is equivalent to
1989 (a . (b . (c . d)))
1991Whether a given pair is a list depends upon what is stored in the cdr
1992field. When the set-cdr! procedure is used, an object can be a list one
1993moment and not the next:
1995 (define x (list 'a 'b 'c))
1996 (define y x)
1997 y                               ===>  (a b c)
1998 (list? y)                       ===>  #t
1999 (set-cdr! x 4)                  ===>  unspecified
2000 x                               ===>  (a . 4)
2001 (eqv? x y)                      ===>  #t
2002 y                               ===>  (a . 4)
2003 (list? y)                       ===>  #f
2004 (set-cdr! x x)                  ===>  unspecified
2005 (list? x)                       ===>  #f
2007Within literal expressions and representations of objects read by the
2008read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2009denote two-element lists whose first elements are the symbols quote,
2010quasiquote, unquote, and unquote-splicing, respectively. The second
2011element in each case is <datum>. This convention is supported so that
2012arbitrary Scheme programs may be represented as lists. That is,
2013according to Scheme's grammar, every <expression> is also a <datum>.
2014Among other things, this permits the use of the read procedure to
2015parse Scheme programs.
2017<procedure>(pair? obj)</procedure><br>
2019Pair? returns #t if obj is a pair, and otherwise returns #f.
2021 (pair? '(a . b))                ===>  #t
2022 (pair? '(a b c))                ===>  #t
2023 (pair? '())                     ===>  #f
2024 (pair? '#(a b))                 ===>  #f
2026<procedure>(cons obj[1] obj[2])</procedure><br>
2028Returns a newly allocated pair whose car is obj[1] and whose cdr is
2029obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2030from every existing object.
2032 (cons 'a '())                   ===>  (a)
2033 (cons '(a) '(b c d))            ===>  ((a) b c d)
2034 (cons "a" '(b c))               ===>  ("a" b c)
2035 (cons 'a 3)                     ===>  (a . 3)
2036 (cons '(a b) 'c)                ===>  ((a b) . c)
2038<procedure>(car pair)</procedure><br>
2040Returns the contents of the car field of pair. Note that it is an error
2041to take the car of the empty list.
2043 (car '(a b c))                  ===>  a
2044 (car '((a) b c d))              ===>  (a)
2045 (car '(1 . 2))                  ===>  1
2046 (car '())                       ===>  error
2048<procedure>(cdr pair)</procedure><br>
2050Returns the contents of the cdr field of pair. Note that it is an error
2051to take the cdr of the empty list.
2053 (cdr '((a) b c d))              ===>  (b c d)
2054 (cdr '(1 . 2))                  ===>  2
2055 (cdr '())                       ===>  error
2057<procedure>(set-car! pair obj)</procedure><br>
2059Stores obj in the car field of pair. The value returned by set-car! is
2062 (define (f) (list 'not-a-constant-list))
2063 (define (g) '(constant-list))
2064 (set-car! (f) 3)                     ===>  unspecified
2065 (set-car! (g) 3)                     ===>  error
2067<procedure>(set-cdr! pair obj)</procedure><br>
2069Stores obj in the cdr field of pair. The value returned by set-cdr! is
2072<procedure>(caar pair)</procedure><br>
2073<procedure>(cadr pair)</procedure><br>
2074<procedure>(cdar pair)</procedure><br>
2075<procedure>(cddr pair)</procedure><br>
2076<procedure>(caaar pair)</procedure><br>
2077<procedure>(caadr pair)</procedure><br>
2078<procedure>(cadar pair)</procedure><br>
2079<procedure>(caddr pair)</procedure><br>
2080<procedure>(cdaar pair)</procedure><br>
2081<procedure>(cdadr pair)</procedure><br>
2082<procedure>(cddar pair)</procedure><br>
2083<procedure>(cdddr pair)</procedure><br>
2084<procedure>(caaaar pair)</procedure><br>
2085<procedure>(caaadr pair)</procedure><br>
2086<procedure>(caadar pair)</procedure><br>
2087<procedure>(caaddr pair)</procedure><br>
2088<procedure>(cadaar pair)</procedure><br>
2089<procedure>(cadadr pair)</procedure><br>
2090<procedure>(caddar pair)</procedure><br>
2091<procedure>(cadddr pair)</procedure><br>
2092<procedure>(cdaaar pair)</procedure><br>
2093<procedure>(cdaadr pair)</procedure><br>
2094<procedure>(cdadar pair)</procedure><br>
2095<procedure>(cdaddr pair)</procedure><br>
2096<procedure>(cddaar pair)</procedure><br>
2097<procedure>(cddadr pair)</procedure><br>
2098<procedure>(cdddar pair)</procedure><br>
2099<procedure>(cddddr pair)</procedure><br>
2101These procedures are compositions of car and cdr, where for example
2102caddr could be defined by
2104 (define caddr (lambda (x) (car (cdr (cdr x))))).
2106<procedure>(null? obj)</procedure><br>
2108Returns #t if obj is the empty list, otherwise returns #f.
2110<procedure>(list? obj)</procedure><br>
2112Returns #t if obj is a list, otherwise returns #f. By definition, all
2113lists have finite length and are terminated by the empty list.
2115 (list? '(a b c))             ===>  #t
2116 (list? '())                  ===>  #t
2117 (list? '(a . b))             ===>  #f
2118 (let ((x (list 'a)))
2119   (set-cdr! x x)
2120   (list? x))                 ===>  #f
2122<procedure>(list obj ...)</procedure><br>
2124Returns a newly allocated list of its arguments.
2126 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
2127 (list)                                  ===>  ()
2129<procedure>(length list)</procedure><br>
2131Returns the length of list.
2133 (length '(a b c))                       ===>  3
2134 (length '(a (b) (c d e)))               ===>  3
2135 (length '())                            ===>  0
2137<procedure>(append list ...)</procedure><br>
2139Returns a list consisting of the elements of the first list followed by
2140the elements of the other lists.
2142 (append '(x) '(y))                      ===>  (x y)
2143 (append '(a) '(b c d))                  ===>  (a b c d)
2144 (append '(a (b)) '((c)))                ===>  (a (b) (c))
2146The resulting list is always newly allocated, except that it shares
2147structure with the last list argument. The last argument may actually
2148be any object; an improper list results if the last argument is not a
2149proper list.
2151 (append '(a b) '(c . d))                ===>  (a b c . d)
2152 (append '() 'a)                         ===>  a
2154<procedure>(reverse list)</procedure><br>
2156Returns a newly allocated list consisting of the elements of list in
2157reverse order.
2159 (reverse '(a b c))                      ===>  (c b a)
2160 (reverse '(a (b c) d (e (f))))
2161                 ===>  ((e (f)) d (b c) a)
2163<procedure>(list-tail list k)</procedure><br>
2165Returns the sublist of list obtained by omitting the first k elements.
2166It is an error if list has fewer than k elements. List-tail could be
2167defined by
2169 (define list-tail
2170   (lambda (x k)
2171     (if (zero? k)
2172         x
2173         (list-tail (cdr x) (- k 1)))))
2175<procedure>(list-ref list k)</procedure><br>
2177Returns the kth element of list. (This is the same as the car of
2178(list-tail list k).) It is an error if list has fewer than k elements.
2180 (list-ref '(a b c d) 2)                ===>  c
2181 (list-ref '(a b c d)
2182           (inexact->exact (round 1.8)))
2183                 ===>  c
2185<procedure>(memq obj list)</procedure><br>
2186<procedure>(memv obj list)</procedure><br>
2187<procedure>(member obj list)</procedure><br>
2189These procedures return the first sublist of list whose car is obj,
2190where the sublists of list are the non-empty lists returned by
2191(list-tail list k) for k less than the length of list. If obj does not
2192occur in list, then #f (not the empty list) is returned. Memq uses eq?
2193to compare obj with the elements of list, while memv uses eqv? and
2194member uses equal?.
2196 (memq 'a '(a b c))                      ===>  (a b c)
2197 (memq 'b '(a b c))                      ===>  (b c)
2198 (memq 'a '(b c d))                      ===>  #f
2199 (memq (list 'a) '(b (a) c))             ===>  #f
2200 (member (list 'a)
2201         '(b (a) c))                     ===>  ((a) c)
2202 (memq 101 '(100 101 102))               ===>  unspecified
2203 (memv 101 '(100 101 102))               ===>  (101 102)
2205<procedure>(assq obj alist)</procedure><br>
2206<procedure>(assv obj alist)</procedure><br>
2207<procedure>(assoc obj alist)</procedure><br>
2209Alist (for "association list") must be a list of pairs. These
2210procedures find the first pair in alist whose car field is obj, and
2211returns that pair. If no pair in alist has obj as its car, then #f (not
2212the empty list) is returned. Assq uses eq? to compare obj with the car
2213fields of the pairs in alist, while assv uses eqv? and assoc uses
2216 (define e '((a 1) (b 2) (c 3)))
2217 (assq 'a e)             ===>  (a 1)
2218 (assq 'b e)             ===>  (b 2)
2219 (assq 'd e)             ===>  #f
2220 (assq (list 'a) '(((a)) ((b)) ((c))))
2221                         ===>  #f
2222 (assoc (list 'a) '(((a)) ((b)) ((c))))   
2223                                    ===>  ((a))
2224 (assq 5 '((2 3) (5 7) (11 13)))   
2225                                    ===>  unspecified
2226 (assv 5 '((2 3) (5 7) (11 13)))   
2227                                    ===>  (5 7)
2229Rationale:   Although they are ordinarily used as predicates, memq,
2230memv, member, assq, assv, and assoc do not have question marks in
2231their names because they return useful values rather than just #t
2232or #f.
2234==== Symbols
2236Symbols are objects whose usefulness rests on the fact that two symbols
2237are identical (in the sense of eqv?) if and only if their names are
2238spelled the same way. This is exactly the property needed to represent
2239identifiers in programs, and so most implementations of Scheme use them
2240internally for that purpose. Symbols are useful for many other
2241applications; for instance, they may be used the way enumerated values
2242are used in Pascal.
2244The rules for writing a symbol are exactly the same as the rules for
2245writing an identifier.
2247It is guaranteed that any symbol that has been returned as part of a
2248literal expression, or read using the read procedure, and subsequently
2249written out using the write procedure, will read back in as the
2250identical symbol (in the sense of eqv?). The string->symbol procedure,
2251however, can create symbols for which this write/read invariance may
2252not hold because their names contain special characters or letters in
2253the non-standard case.
2255Note:   Some implementations of Scheme have a feature known as
2256"slashification" in order to guarantee write/read invariance for
2257all symbols, but historically the most important use of this
2258feature has been to compensate for the lack of a string data type.
2260Some implementations also have "uninterned symbols", which defeat
2261write/read invariance even in implementations with slashification,
2262and also generate exceptions to the rule that two symbols are the
2263same if and only if their names are spelled the same.
2265<procedure>(symbol? obj)</procedure><br>
2267Returns #t if obj is a symbol, otherwise returns #f.
2269 (symbol? 'foo)                  ===>  #t
2270 (symbol? (car '(a b)))          ===>  #t
2271 (symbol? "bar")                 ===>  #f
2272 (symbol? 'nil)                  ===>  #t
2273 (symbol? '())                   ===>  #f
2274 (symbol? #f)                    ===>  #f
2276<procedure>(symbol->string symbol)</procedure><br>
2278Returns the name of symbol as a string. If the symbol was part of an
2279object returned as the value of a literal expression (see
2280"[[#literal-expressions|literal expressions]]") or by a call to the
2281read procedure, and its name contains alphabetic characters, then the
2282string returned will contain characters in the implementation's
2283preferred standard case -- some implementations will prefer upper
2284case, others lower case. If the symbol was returned by string->symbol,
2285the case of characters in the string returned will be the same as the
2286case in the string that was passed to string->symbol.  It is an error
2287to apply mutation procedures like string-set! to strings returned by
2288this procedure.
2290The following examples assume that the implementation's standard case
2291is lower case:
2293 (symbol->string 'flying-fish)     
2294                                           ===>  "flying-fish"
2295 (symbol->string 'Martin)                  ===>  "martin"
2296 (symbol->string
2297    (string->symbol "Malvina"))     
2298                                           ===>  "Malvina"
2300<procedure>(string->symbol string)</procedure><br>
2302Returns the symbol whose name is string. This procedure can create
2303symbols with names containing special characters or letters in the
2304non-standard case, but it is usually a bad idea to create such symbols
2305because in some implementations of Scheme they cannot be read as
2306themselves. See symbol->string.
2308The following examples assume that the implementation's standard case
2309is lower case:
2311 (eq? 'mISSISSIppi 'mississippi) 
2312                 ===>  #t
2313 (string->symbol "mISSISSIppi") 
2314                 ===>  the symbol with name "mISSISSIppi"
2315 (eq? 'bitBlt (string->symbol "bitBlt"))     
2316                 ===>  #f
2317 (eq? 'JollyWog
2318      (string->symbol
2319        (symbol->string 'JollyWog))) 
2320                 ===>  #t
2321 (string=? "K. Harper, M.D."
2322           (symbol->string
2323             (string->symbol "K. Harper, M.D."))) 
2324                 ===>  #t
2326==== Characters
2328Characters are objects that represent printed characters such as
2329letters and digits. Characters are written using the notation #\
2330<character> or #\<character name>. For example:
2332 #\a       ; lower case letter
2333 #\A       ; upper case letter
2334 #\(       ; left parenthesis
2335 #\        ; the space character
2336 #\space   ; the preferred way to write a space
2337 #\newline ; the newline character
2339Case is significant in #\<character>, but not in #\<character name>. If
2340<character> in #\<character> is alphabetic, then the character
2341following <character> must be a delimiter character such as a space or
2342parenthesis. This rule resolves the ambiguous case where, for example,
2343the sequence of characters "#\space" could be taken to be either a
2344representation of the space character or a representation of the
2345character "#\s" followed by a representation of the symbol "pace."
2347Characters written in the #\ notation are self-evaluating. That is,
2348they do not have to be quoted in programs. Some of the procedures that
2349operate on characters ignore the difference between upper case and
2350lower case. The procedures that ignore case have "-ci" (for "case
2351insensitive") embedded in their names.
2353<procedure>(char? obj)</procedure><br>
2355Returns #t if obj is a character, otherwise returns #f.
2357<procedure>(char=? char[1] char[2])</procedure><br>
2358<procedure>(char<? char[1] char[2])</procedure><br>
2359<procedure>(char>? char[1] char[2])</procedure><br>
2360<procedure>(char<=? char[1] char[2])</procedure><br>
2361<procedure>(char>=? char[1] char[2])</procedure><br>
2363These procedures impose a total ordering on the set of characters. It
2364is guaranteed that under this ordering:
2366*   The upper case characters are in order. For example, (char<? #\A #\
2367    B) returns #t.
2368*   The lower case characters are in order. For example, (char<? #\a #\
2369    b) returns #t.
2370*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
2371*   Either all the digits precede all the upper case letters, or vice
2372    versa.
2373*   Either all the digits precede all the lower case letters, or vice
2374    versa.
2376Some implementations may generalize these procedures to take more than
2377two arguments, as with the corresponding numerical predicates.
2379<procedure>(char-ci=? char[1] char[2])</procedure><br>
2380<procedure>(char-ci<? char[1] char[2])</procedure><br>
2381<procedure>(char-ci>? char[1] char[2])</procedure><br>
2382<procedure>(char-ci<=? char[1] char[2])</procedure><br>
2383<procedure>(char-ci>=? char[1] char[2])</procedure><br>
2385These procedures are similar to char=? et cetera, but they treat upper
2386case and lower case letters as the same. For example, (char-ci=? #\A #\
2387a) returns #t. Some implementations may generalize these procedures to
2388take more than two arguments, as with the corresponding numerical
2391<procedure>(char-alphabetic? char)</procedure><br>
2392<procedure>(char-numeric? char)</procedure><br>
2393<procedure>(char-whitespace? char)</procedure><br>
2394<procedure>(char-upper-case? letter)</procedure><br>
2395<procedure>(char-lower-case? letter)</procedure><br>
2397These procedures return #t if their arguments are alphabetic, numeric,
2398whitespace, upper case, or lower case characters, respectively,
2399otherwise they return #f. The following remarks, which are specific to
2400the ASCII character set, are intended only as a guide: The alphabetic
2401characters are the 52 upper and lower case letters. The numeric
2402characters are the ten decimal digits. The whitespace characters are
2403space, tab, line feed, form feed, and carriage return.
2405<procedure>(char->integer char)</procedure><br>
2406<procedure>(integer->char n)</procedure><br>
2408Given a character, char->integer returns an exact integer
2409representation of the character. Given an exact integer that is the
2410image of a character under char->integer, integer->char returns that
2411character. These procedures implement order-preserving isomorphisms
2412between the set of characters under the char<=? ordering and some
2413subset of the integers under the <= ordering. That is, if
2415 (char<=? a b) ===> #t  and  (<= x y) ===> #t
2417and x and y are in the domain of integer->char, then
2419 (<= (char->integer a)
2420     (char->integer b))                  ===>  #t
2422 (char<=? (integer->char x)
2423          (integer->char y))             ===>  #t
2425Note that {{integer->char}} does currently not detect
2426a negative argument and will quietly convert {{-1}} to
2427{{#x1ffff}} in CHICKEN.
2429<procedure>(char-upcase char)</procedure><br>
2430<procedure>(char-downcase char)</procedure><br>
2432These procedures return a character char[2] such that (char-ci=? char
2433char[2]). In addition, if char is alphabetic, then the result of
2434char-upcase is upper case and the result of char-downcase is lower
2437==== Strings
2439Strings are sequences of characters. Strings are written as sequences
2440of characters enclosed within doublequotes ("). A doublequote can be
2441written inside a string only by escaping it with a backslash (\), as in
2443"The word \"recursion\" has many meanings."
2445A backslash can be written inside a string only by escaping it with
2446another backslash. Scheme does not specify the effect of a backslash
2447within a string that is not followed by a doublequote or backslash.
2449A string constant may continue from one line to the next, but the exact
2450contents of such a string are unspecified. The length of a string is
2451the number of characters that it contains. This number is an exact,
2452non-negative integer that is fixed when the string is created. The
2453valid indexes of a string are the exact non-negative integers less than
2454the length of the string. The first character of a string has index 0,
2455the second has index 1, and so on.
2457In phrases such as "the characters of string beginning with index
2458start and ending with index end," it is understood that the index
2459start is inclusive and the index end is exclusive. Thus if start and
2460end are the same index, a null substring is referred to, and if start
2461is zero and end is the length of string, then the entire string is
2462referred to.
2464Some of the procedures that operate on strings ignore the difference
2465between upper and lower case. The versions that ignore case have
2466"-ci" (for "case insensitive") embedded in their names.
2468<procedure>(string? obj)</procedure><br>
2470Returns #t if obj is a string, otherwise returns #f.
2472<procedure>(make-string k)</procedure><br>
2473<procedure>(make-string k char)</procedure><br>
2475Make-string returns a newly allocated string of length k. If char is
2476given, then all elements of the string are initialized to char,
2477otherwise the contents of the string are unspecified.
2479<procedure>(string char ...)</procedure><br>
2481Returns a newly allocated string composed of the arguments.
2483<procedure>(string-length string)</procedure><br>
2485Returns the number of characters in the given string.
2487<procedure>(string-ref string k)</procedure><br>
2489k must be a valid index of string. String-ref returns character k of
2490string using zero-origin indexing.
2492<procedure>(string-set! string k char)</procedure><br>
2494k must be a valid index of string. String-set! stores char in element k
2495of string and returns an unspecified value.
2497 (define (f) (make-string 3 #\*))
2498 (define (g) "***")
2499 (string-set! (f) 0 #\?)          ===>  unspecified
2500 (string-set! (g) 0 #\?)          ===>  error
2501 (string-set! (symbol->string 'immutable)
2502              0
2503              #\?)          ===>  error
2505<procedure>(string=? string[1] string[2])</procedure><br>
2506<procedure>(string-ci=? string[1] string[2])</procedure><br>
2508Returns #t if the two strings are the same length and contain the same
2509characters in the same positions, otherwise returns #f. String-ci=?
2510treats upper and lower case letters as though they were the same
2511character, but string=? treats upper and lower case as distinct
2514<procedure>(string<? string[1] string[2])</procedure><br>
2515<procedure>(string>? string[1] string[2])</procedure><br>
2516<procedure>(string<=? string[1] string[2])</procedure><br>
2517<procedure>(string>=? string[1] string[2])</procedure><br>
2518<procedure>(string-ci<? string[1] string[2])</procedure><br>
2519<procedure>(string-ci>? string[1] string[2])</procedure><br>
2520<procedure>(string-ci<=? string[1] string[2])</procedure><br>
2521<procedure>(string-ci>=? string[1] string[2])</procedure><br>
2523These procedures are the lexicographic extensions to strings of the
2524corresponding orderings on characters. For example, string<? is the
2525lexicographic ordering on strings induced by the ordering char<? on
2526characters. If two strings differ in length but are the same up to the
2527length of the shorter string, the shorter string is considered to be
2528lexicographically less than the longer string.
2530Implementations may generalize these and the string=? and string-ci=?
2531procedures to take more than two arguments, as with the corresponding
2532numerical predicates.
2534<procedure>(substring string start end)</procedure><br>
2536String must be a string, and start and end must be exact integers
2539 0 <= start <= end <= (string-length string)
2541Substring returns a newly allocated string formed from the characters
2542of string beginning with index start (inclusive) and ending with index
2543end (exclusive).
2545<procedure>(string-append string ...)</procedure><br>
2547Returns a newly allocated string whose characters form the
2548concatenation of the given strings.
2550<procedure>(string->list string)</procedure><br>
2551<procedure>(list->string list)</procedure><br>
2553String->list returns a newly allocated list of the characters that make
2554up the given string. List->string returns a newly allocated string
2555formed from the characters in the list list, which must be a list of
2556characters. String->list and list->string are inverses so far as equal?
2557is concerned.
2559<procedure>(string-copy string)</procedure><br>
2561Returns a newly allocated copy of the given string.
2563<procedure>(string-fill! string char)</procedure><br>
2565Stores char in every element of the given string and returns an
2566unspecified value.
2568==== Vectors
2570Vectors are heterogenous structures whose elements are indexed by
2571integers. A vector typically occupies less space than a list of the
2572same length, and the average time required to access a randomly chosen
2573element is typically less for the vector than for the list.
2575The length of a vector is the number of elements that it contains. This
2576number is a non-negative integer that is fixed when the vector is
2577created. The valid indexes of a vector are the exact non-negative
2578integers less than the length of the vector. The first element in a
2579vector is indexed by zero, and the last element is indexed by one less
2580than the length of the vector.
2582Vectors are written using the notation #(obj ...). For example, a
2583vector of length 3 containing the number zero in element 0, the list (2
25842 2 2) in element 1, and the string "Anna" in element 2 can be written
2585as following:
2587 #(0 (2 2 2 2) "Anna")
2589Note that this is the external representation of a vector, not an
2590expression evaluating to a vector. Like list constants, vector
2591constants must be quoted:
2593 '#(0 (2 2 2 2) "Anna") 
2594                 ===>  #(0 (2 2 2 2) "Anna")
2596<procedure>(vector? obj)</procedure><br>
2598Returns #t if obj is a vector, otherwise returns #f.
2600<procedure>(make-vector k)</procedure><br>
2601<procedure>(make-vector k fill)</procedure><br>
2603Returns a newly allocated vector of k elements. If a second argument is
2604given, then each element is initialized to fill. Otherwise the initial
2605contents of each element is unspecified.
2607<procedure>(vector obj ...)</procedure><br>
2609Returns a newly allocated vector whose elements contain the given
2610arguments. Analogous to list.
2612 (vector 'a 'b 'c)                       ===>  #(a b c)
2614<procedure>(vector-length vector)</procedure><br>
2616Returns the number of elements in vector as an exact integer.
2618<procedure>(vector-ref vector k)</procedure><br>
2620k must be a valid index of vector. Vector-ref returns the contents of
2621element k of vector.
2623 (vector-ref '#(1 1 2 3 5 8 13 21)
2624             5) 
2625                 ===>  8
2626 (vector-ref '#(1 1 2 3 5 8 13 21)
2627             (let ((i (round (* 2 (acos -1)))))
2628               (if (inexact? i)
2629                   (inexact->exact i)
2630                   i)))
2631                 ===> 13
2633<procedure>(vector-set! vector k obj)</procedure><br>
2635k must be a valid index of vector. Vector-set! stores obj in element k
2636of vector. The value returned by vector-set! is unspecified.
2638 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
2639   (vector-set! vec 1 '("Sue" "Sue"))
2640   vec)     
2641                 ===>  #(0 ("Sue" "Sue") "Anna")
2643 (vector-set! '#(0 1 2) 1 "doe") 
2644                 ===>  error  ; constant vector
2646<procedure>(vector->list vector)</procedure><br>
2647<procedure>(list->vector list)</procedure><br>
2649Vector->list returns a newly allocated list of the objects contained in
2650the elements of vector. List->vector returns a newly created vector
2651initialized to the elements of the list list.
2653 (vector->list '#(dah dah didah)) 
2654                 ===>  (dah dah didah)
2655 (list->vector '(dididit dah))   
2656                 ===>  #(dididit dah)
2658<procedure>(vector-fill! vector fill)</procedure><br>
2660Stores fill in every element of vector. The value returned by
2661vector-fill! is unspecified.
2663=== Control features
2665This chapter describes various primitive procedures which control the
2666flow of program execution in special ways. The procedure? predicate is
2667also described here.
2669<procedure>(procedure? obj)</procedure><br>
2671Returns #t if obj is a procedure, otherwise returns #f.
2673 (procedure? car)                    ===>  #t
2674 (procedure? 'car)                   ===>  #f
2675 (procedure? (lambda (x) (* x x)))   
2676                                     ===>  #t
2677 (procedure? '(lambda (x) (* x x))) 
2678                                     ===>  #f
2679 (call-with-current-continuation procedure?)
2680                                     ===>  #t
2682<procedure>(apply proc arg[1] ... args)</procedure><br>
2684Proc must be a procedure and args must be a list. Calls proc with the
2685elements of the list (append (list arg[1] ...) args) as the actual
2688 (apply + (list 3 4))                      ===>  7
2690 (define compose
2691   (lambda (f g)
2692     (lambda args
2693       (f (apply g args)))))
2695 ((compose sqrt *) 12 75)                      ===>  30
2697<procedure>(map proc list[1] list[2] ...)</procedure><br>
2699The lists must be lists, and proc must be a procedure taking as many
2700arguments as there are lists and returning a single value. If more than
2701one list is given, then they must all be the same length. Map applies
2702proc element-wise to the elements of the lists and returns a list of
2703the results, in order. The dynamic order in which proc is applied to
2704the elements of the lists is unspecified.
2706 (map cadr '((a b) (d e) (g h)))   
2707                 ===>  (b e h)
2709 (map (lambda (n) (expt n n))
2710      '(1 2 3 4 5))               
2711                 ===>  (1 4 27 256 3125)
2713 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
2715 (let ((count 0))
2716   (map (lambda (ignored)
2717          (set! count (+ count 1))
2718          count)
2719        '(a b)))                         ===>  (1 2) or (2 1)
2721<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
2723The arguments to for-each are like the arguments to map, but for-each
2724calls proc for its side effects rather than for its values. Unlike map,
2725for-each is guaranteed to call proc on the elements of the lists in
2726order from the first element(s) to the last, and the value returned by
2727for-each is unspecified.
2729 (let ((v (make-vector 5)))
2730   (for-each (lambda (i)
2731               (vector-set! v i (* i i)))
2732             '(0 1 2 3 4))
2733   v)                                        ===>  #(0 1 4 9 16)
2735<procedure>(force promise)</procedure><br>
2737Forces the value of promise (see "[[#delayed-evaluation|delayed
2738evaluation]]"). If no value has been computed for the promise, then a
2739value is computed and returned.  The value of the promise is cached
2740(or "memoized") so that if it is forced a second time, the previously
2741computed value is returned.
2743 (force (delay (+ 1 2)))           ===>  3
2744 (let ((p (delay (+ 1 2))))
2745   (list (force p) (force p))) 
2746                                        ===>  (3 3)
2748 (define a-stream
2749   (letrec ((next
2750             (lambda (n)
2751               (cons n (delay (next (+ n 1)))))))
2752     (next 0)))
2753 (define head car)
2754 (define tail
2755   (lambda (stream) (force (cdr stream))))
2757 (head (tail (tail a-stream))) 
2758                                        ===>  2
2760Force and delay are mainly intended for programs written in functional
2761style. The following examples should not be considered to illustrate
2762good programming style, but they illustrate the property that only one
2763value is computed for a promise, no matter how many times it is forced.
2765 (define count 0)
2766 (define p
2767   (delay (begin (set! count (+ count 1))
2768                 (if (> count x)
2769                     count
2770                     (force p)))))
2771 (define x 5)
2772 p                             ===>  a promise
2773 (force p)                     ===>  6
2774 p                             ===>  a promise, still
2775 (begin (set! x 10)
2776        (force p))             ===>  6
2778Here is a possible implementation of delay and force. Promises are
2779implemented here as procedures of no arguments, and force simply calls
2780its argument:
2782 (define force
2783   (lambda (object)
2784     (object)))
2786We define the expression
2788 (delay <expression>)
2790to have the same meaning as the procedure call
2792 (make-promise (lambda () <expression>))
2794as follows
2796 (define-syntax delay
2797   (syntax-rules ()
2798     ((delay expression)
2799      (make-promise (lambda () expression))))),
2801where make-promise is defined as follows:
2803 (define make-promise
2804   (lambda (proc)
2805     (let ((result-ready? #f)
2806           (result #f))
2807       (lambda ()
2808         (if result-ready?
2809             result
2810             (let ((x (proc)))
2811               (if result-ready?
2812                   result
2813                   (begin (set! result-ready? #t)
2814                          (set! result x)
2815                          result))))))))
2817Rationale:   A promise may refer to its own value, as in the last
2818example above. Forcing such a promise may cause the promise to be
2819forced a second time before the value of the first force has been
2820computed. This complicates the definition of make-promise.
2822Various extensions to this semantics of delay and force are supported
2823in some implementations:
2825*   Calling force on an object that is not a promise may simply return
2826    the object.
2828*   It may be the case that there is no means by which a promise can be
2829    operationally distinguished from its forced value. That is,
2830    expressions like the following may evaluate to either #t or to #f,
2831    depending on the implementation:
2833    (eqv? (delay 1) 1)                  ===>  unspecified
2834    (pair? (delay (cons 1 2)))          ===>  unspecified
2836*   Some implementations may implement "implicit forcing," where the
2837    value of a promise is forced by primitive procedures like cdr and
2838    +:
2840    (+ (delay (* 3 7)) 13)          ===>  34
2842<procedure>(call-with-current-continuation proc)</procedure><br>
2844Proc must be a procedure of one argument. The procedure
2845call-with-current-continuation packages up the current continuation
2846(see the rationale below) as an "escape procedure" and passes it as
2847an argument to proc. The escape procedure is a Scheme procedure that,
2848if it is later called, will abandon whatever continuation is in effect
2849at that later time and will instead use the continuation that was in
2850effect when the escape procedure was created. Calling the escape
2851procedure may cause the invocation of before and after thunks installed
2852using dynamic-wind.
2854The escape procedure accepts the same number of arguments as the
2855continuation to the original call to call-with-current-continuation.
2856Except for continuations created by the call-with-values procedure, all
2857continuations take exactly one value. The effect of passing no value or
2858more than one value to continuations that were not created by
2859call-with-values is unspecified.
2861The escape procedure that is passed to proc has unlimited extent just
2862like any other procedure in Scheme. It may be stored in variables or
2863data structures and may be called as many times as desired.
2865The following examples show only the most common ways in which
2866call-with-current-continuation is used. If all real uses were as simple
2867as these examples, there would be no need for a procedure with the
2868power of call-with-current-continuation.
2870 (call-with-current-continuation
2871   (lambda (exit)
2872     (for-each (lambda (x)
2873                 (if (negative? x)
2874                     (exit x)))
2875               '(54 0 37 -3 245 19))
2876     #t))                                ===>  -3
2878 (define list-length
2879   (lambda (obj)
2880     (call-with-current-continuation
2881       (lambda (return)
2882         (letrec ((r
2883                   (lambda (obj)
2884                     (cond ((null? obj) 0)
2885                           ((pair? obj)
2886                            (+ (r (cdr obj)) 1))
2887                           (else (return #f))))))
2888           (r obj))))))
2890 (list-length '(1 2 3 4))                    ===>  4
2892 (list-length '(a b . c))                    ===>  #f
2896A common use of call-with-current-continuation is for structured,
2897non-local exits from loops or procedure bodies, but in fact
2898call-with-current-continuation is extremely useful for implementing
2899a wide variety of advanced control structures.
2901Whenever a Scheme expression is evaluated there is a continuation
2902wanting the result of the expression. The continuation represents
2903an entire (default) future for the computation. If the expression
2904is evaluated at top level, for example, then the continuation might
2905take the result, print it on the screen, prompt for the next input,
2906evaluate it, and so on forever. Most of the time the continuation
2907includes actions specified by user code, as in a continuation that
2908will take the result, multiply it by the value stored in a local
2909variable, add seven, and give the answer to the top level
2910continuation to be printed. Normally these ubiquitous continuations
2911are hidden behind the scenes and programmers do not think much
2912about them. On rare occasions, however, a programmer may need to
2913deal with continuations explicitly. Call-with-current-continuation
2914allows Scheme programmers to do that by creating a procedure that
2915acts just like the current continuation.
2917Most programming languages incorporate one or more special-purpose
2918escape constructs with names like exit, return, or even goto. In
29191965, however, Peter Landin [16] invented a general purpose escape
2920operator called the J-operator. John Reynolds [24] described a
2921simpler but equally powerful construct in 1972. The catch special
2922form described by Sussman and Steele in the 1975 report on Scheme
2923is exactly the same as Reynolds's construct, though its name came
2924from a less general construct in MacLisp. Several Scheme
2925implementors noticed that the full power of the catch construct
2926could be provided by a procedure instead of by a special syntactic
2927construct, and the name call-with-current-continuation was coined
2928in 1982. This name is descriptive, but opinions differ on the
2929merits of such a long name, and some people use the name call/cc
2932<procedure>(values obj ...)</procedure><br>
2934Delivers all of its arguments to its continuation. Except for
2935continuations created by the call-with-values procedure, all
2936continuations take exactly one value. Values might be defined as
2939 (define (values . things)
2940   (call-with-current-continuation
2941     (lambda (cont) (apply cont things))))
2943<procedure>(call-with-values producer consumer)</procedure><br>
2945Calls its producer argument with no values and a continuation that,
2946when passed some values, calls the consumer procedure with those values
2947as arguments. The continuation for the call to consumer is the
2948continuation of the call to call-with-values.
2950 (call-with-values (lambda () (values 4 5))
2951                   (lambda (a b) b))
2952                                                            ===>  5
2954 (call-with-values * -)                                     ===>  -1
2956<procedure>(dynamic-wind before thunk after)</procedure><br>
2958Calls thunk without arguments, returning the result(s) of this call.
2959Before and after are called, also without arguments, as required by the
2960following rules (note that in the absence of calls to continuations
2961captured using call-with-current-continuation the three arguments are
2962called once each, in order). Before is called whenever execution enters
2963the dynamic extent of the call to thunk and after is called whenever it
2964exits that dynamic extent. The dynamic extent of a procedure call is
2965the period between when the call is initiated and when it returns. In
2966Scheme, because of call-with-current-continuation, the dynamic extent
2967of a call may not be a single, connected time period. It is defined as
2970*   The dynamic extent is entered when execution of the body of the
2971    called procedure begins.
2973*   The dynamic extent is also entered when execution is not within the
2974    dynamic extent and a continuation is invoked that was captured
2975    (using call-with-current-continuation) during the dynamic extent.
2977*   It is exited when the called procedure returns.
2979*   It is also exited when execution is within the dynamic extent and a
2980    continuation is invoked that was captured while not within the
2981    dynamic extent.
2983If a second call to dynamic-wind occurs within the dynamic extent of
2984the call to thunk and then a continuation is invoked in such a way that
2985the afters from these two invocations of dynamic-wind are both to be
2986called, then the after associated with the second (inner) call to
2987dynamic-wind is called first.
2989If a second call to dynamic-wind occurs within the dynamic extent of
2990the call to thunk and then a continuation is invoked in such a way that
2991the befores from these two invocations of dynamic-wind are both to be
2992called, then the before associated with the first (outer) call to
2993dynamic-wind is called first.
2995If invoking a continuation requires calling the before from one call to
2996dynamic-wind and the after from another, then the after is called
2999The effect of using a captured continuation to enter or exit the
3000dynamic extent of a call to before or after is undefined.
3002 (let ((path '())
3003       (c #f))
3004   (let ((add (lambda (s)
3005                (set! path (cons s path)))))
3006     (dynamic-wind
3007       (lambda () (add 'connect))
3008       (lambda ()
3009         (add (call-with-current-continuation
3010                (lambda (c0)
3011                  (set! c c0)
3012                  'talk1))))
3013       (lambda () (add 'disconnect)))
3014     (if (< (length path) 4)
3015         (c 'talk2)
3016         (reverse path))))
3018                 ===> (connect talk1 disconnect
3019                       connect talk2 disconnect)
3021=== Eval
3023<procedure>(eval expression environment-specifier)</procedure><br>
3025Evaluates expression in the specified environment and returns its
3026value. Expression must be a valid Scheme expression represented as
3027data, and environment-specifier must be a value returned by one of the
3028three procedures described below. Implementations may extend eval to
3029allow non-expression programs (definitions) as the first argument and
3030to allow other values as environments, with the restriction that eval
3031is not allowed to create new bindings in the environments associated
3032with null-environment or scheme-report-environment.
3034 (eval '(* 7 3) (scheme-report-environment 5))
3035                                                            ===>  21
3037 (let ((f (eval '(lambda (f x) (f x x))
3038                (null-environment 5))))
3039   (f + 10))
3040                                                            ===>  20
3042<procedure>(scheme-report-environment version)</procedure><br>
3043<procedure>(null-environment version)</procedure><br>
3045Version must be either the exact integer 4 or 5, corresponding to the
3046respective revisions of the Scheme report (the Revised^N Report on
3047Scheme).  Scheme-report-environment returns a specifier for an
3048environment that is empty except for all bindings defined in this
3049report that are either required or both optional and supported by the
3050implementation.  Null-environment returns a specifier for an
3051environment that is empty except for the (syntactic) bindings for all
3052syntactic keywords defined in this report that are either required or
3053both optional and supported by the implementation.
3055The environments specified by scheme-report-environment and
3056null-environment are immutable.
3060This procedure returns a specifier for the environment that contains
3061implementation-defined bindings, typically a superset of those listed
3062in the report. The intent is that this procedure will return the
3063environment in which the implementation would evaluate expressions
3064dynamically typed by the user.
3066=== Input and output
3068==== Ports
3070Ports represent input and output devices. To Scheme, an input port is a
3071Scheme object that can deliver characters upon command, while an output
3072port is a Scheme object that can accept characters.
3074<procedure>(call-with-input-file string proc)</procedure><br>
3075<procedure>(call-with-output-file string proc)</procedure><br>
3077String should be a string naming a file, and proc should be a procedure
3078that accepts one argument. For call-with-input-file, the file should
3079already exist; for call-with-output-file, the effect is unspecified if
3080the file already exists. These procedures call proc with one argument:
3081the port obtained by opening the named file for input or output. If the
3082file cannot be opened, an error is signalled. If proc returns, then the
3083port is closed automatically and the value(s) yielded by the proc is
3084(are) returned. If proc does not return, then the port will not be
3085closed automatically unless it is possible to prove that the port will
3086never again be used for a read or write operation.
3088Rationale:   Because Scheme's escape procedures have unlimited
3089extent, it is possible to escape from the current continuation but
3090later to escape back in. If implementations were permitted to close
3091the port on any escape from the current continuation, then it would
3092be impossible to write portable code using both
3093call-with-current-continuation and call-with-input-file or
3096<procedure>(input-port? obj)</procedure><br>
3097<procedure>(output-port? obj)</procedure><br>
3099Returns #t if obj is an input port or output port respectively,
3100otherwise returns #f.
3105Returns the current default input or output port.
3107<procedure>(with-input-from-file string thunk)</procedure><br>
3108<procedure>(with-output-to-file string thunk)</procedure><br>
3110String should be a string naming a file, and proc should be a procedure
3111of no arguments. For with-input-from-file, the file should already
3112exist; for with-output-to-file, the effect is unspecified if the file
3113already exists. The file is opened for input or output, an input or
3114output port connected to it is made the default value returned by
3115current-input-port or current-output-port (and is used by (read),
3116(write obj), and so forth), and the thunk is called with no arguments.
3117When the thunk returns, the port is closed and the previous default is
3118restored. With-input-from-file and with-output-to-file return(s) the
3119value(s) yielded by thunk. If an escape procedure is used to escape
3120from the continuation of these procedures, their behavior is
3121implementation dependent.
3123<procedure>(open-input-file filename)</procedure><br>
3125Takes a string naming an existing file and returns an input port
3126capable of delivering characters from the file. If the file cannot be
3127opened, an error is signalled.
3129<procedure>(open-output-file filename)</procedure><br>
3131Takes a string naming an output file to be created and returns an
3132output port capable of writing characters to a new file by that name.
3133If the file cannot be opened, an error is signalled. If a file with the
3134given name already exists, the effect is unspecified.
3136<procedure>(close-input-port port)</procedure><br>
3137<procedure>(close-output-port port)</procedure><br>
3139Closes the file associated with port, rendering the port incapable of
3140delivering or accepting characters. These routines have no effect if
3141the file has already been closed. The value returned is unspecified.
3143==== Input
3146<procedure>(read port)</procedure><br>
3148Read converts external representations of Scheme objects into the
3149objects themselves. That is, it is a parser for the nonterminal
3150<datum> (see also "[[#pairs-and-lists|pairs and lists]]"). Read
3151returns the next object parsable from the given input port, updating
3152port to point to the first character past the end of the external
3153representation of the object.
3155If an end of file is encountered in the input before any characters are
3156found that can begin an object, then an end of file object is returned.
3157The port remains open, and further attempts to read will also return an
3158end of file object. If an end of file is encountered after the
3159beginning of an object's external representation, but the external
3160representation is incomplete and therefore not parsable, an error is
3163The port argument may be omitted, in which case it defaults to the
3164value returned by current-input-port. It is an error to read from a
3165closed port.
3168<procedure>(read-char port)</procedure><br>
3170Returns the next character available from the input port, updating the
3171port to point to the following character. If no more characters are
3172available, an end of file object is returned. Port may be omitted, in
3173which case it defaults to the value returned by current-input-port.
3176<procedure>(peek-char port)</procedure><br>
3178Returns the next character available from the input port, without
3179updating the port to point to the following character. If no more
3180characters are available, an end of file object is returned. Port may
3181be omitted, in which case it defaults to the value returned by
3184Note:   The value returned by a call to peek-char is the same as
3185the value that would have been returned by a call to read-char with
3186the same port. The only difference is that the very next call to
3187read-char or peek-char on that port will return the value returned
3188by the preceding call to peek-char. In particular, a call to
3189peek-char on an interactive port will hang waiting for input
3190whenever a call to read-char would have hung.
3192<procedure>(eof-object? obj)</procedure><br>
3194Returns #t if obj is an end of file object, otherwise returns #f. The
3195precise set of end of file objects will vary among implementations, but
3196in any case no end of file object will ever be an object that can be
3197read in using read.
3200<procedure>(char-ready? port)</procedure><br>
3202Returns #t if a character is ready on the input port and returns #f
3203otherwise. If char-ready returns #t then the next read-char operation
3204on the given port is guaranteed not to hang. If the port is at end of
3205file then char-ready? returns #t. Port may be omitted, in which case it
3206defaults to the value returned by current-input-port.
3208Rationale:   Char-ready? exists to make it possible for a program
3209to accept characters from interactive ports without getting stuck
3210waiting for input. Any input editors associated with such ports
3211must ensure that characters whose existence has been asserted by
3212char-ready? cannot be rubbed out. If char-ready? were to return #f
3213at end of file, a port at end of file would be indistinguishable
3214from an interactive port that has no ready characters.
3216==== Output
3218<procedure>(write obj)</procedure><br>
3219<procedure>(write obj port)</procedure><br>
3221Writes a written representation of obj to the given port. Strings that
3222appear in the written representation are enclosed in doublequotes, and
3223within those strings backslash and doublequote characters are escaped
3224by backslashes. Character objects are written using the #\ notation.
3225Write returns an unspecified value. The port argument may be omitted,
3226in which case it defaults to the value returned by current-output-port.
3228<procedure>(display obj)</procedure><br>
3229<procedure>(display obj port)</procedure><br>
3231Writes a representation of obj to the given port. Strings that appear
3232in the written representation are not enclosed in doublequotes, and no
3233characters are escaped within those strings. Character objects appear
3234in the representation as if written by write-char instead of by write.
3235Display returns an unspecified value. The port argument may be omitted,
3236in which case it defaults to the value returned by current-output-port.
3238Rationale:   Write is intended for producing machine-readable
3239output and display is for producing human-readable output.
3240Implementations that allow "slashification" within symbols will
3241probably want write but not display to slashify funny characters in
3245<procedure>(newline port)</procedure><br>
3247Writes an end of line to port. Exactly how this is done differs from
3248one operating system to another. Returns an unspecified value. The port
3249argument may be omitted, in which case it defaults to the value
3250returned by current-output-port.
3252<procedure>(write-char char)</procedure><br>
3253<procedure>(write-char char port)</procedure><br>
3255Writes the character char (not an external representation of the
3256character) to the given port and returns an unspecified value. The port
3257argument may be omitted, in which case it defaults to the value
3258returned by current-output-port.
3260==== System interface
3262Questions of system interface generally fall outside of the domain of
3263this report. However, the following operations are important enough to
3264deserve description here.
3266<procedure>(load filename)</procedure><br>
3268Filename should be a string naming an existing file containing Scheme
3269source code. The load procedure reads expressions and definitions from
3270the file and evaluates them sequentially. It is unspecified whether the
3271results of the expressions are printed. The load procedure does not
3272affect the values returned by current-input-port and
3273current-output-port. Load returns an unspecified value.
3275Rationale:   For portability, load must operate on source files.
3276Its operation on other kinds of files necessarily varies among
3279<procedure>(transcript-on filename)</procedure><br>
3282(These procedures are not implemented in CHICKEN.)
3284Filename must be a string naming an output file to be created. The
3285effect of transcript-on is to open the named file for output, and to
3286cause a transcript of subsequent interaction between the user and the
3287Scheme system to be written to the file. The transcript is ended by a
3288call to transcript-off, which closes the transcript file. Only one
3289transcript may be in progress at any time, though some implementations
3290may relax this restriction. The values returned by these procedures are
3294Previous: [[Included modules]]
3296Next: [[Module r5rs]]
Note: See TracBrowser for help on using the repository browser.