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

Last change on this file since 37365 was 37365, checked in by Diego, 3 years ago

Add note about number->string bug CHICKEN 5

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