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

Last change on this file since 35531 was 35531, checked in by felix winkelmann, 3 years ago

man/5: fixed links, some additions and improvements

File size: 139.4 KB
1[[tags: manual]]
4== Module scheme
6This module provides all of CHICKEN's R5RS procedures and macros.
7These descriptions are based directly on the ''Revised^5 Report on the
8Algorithmic Language Scheme''.
10This module is used by default, unless a program is compiled with
11the {{-explicit-use}} option.
13== Expressions
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.
24=== Primitive expression types
26==== Variable references
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
35 (define x 28)
36 x           ===>  28
38==== Literal expressions
40<macro>(quote <datum>)</macro><br>
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.
48 (quote a)                    ===>  a
49 (quote #(a b c))             ===>  #(a b c)
50 (quote (+ 1 2))              ===>  (+ 1 2)
52(quote <datum>) may be abbreviated as '<datum>. The two notations are
53equivalent in all respects.
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)
62Numerical constants, string constants, character constants, and boolean
63constants evaluate "to themselves"; they need not be quoted.
65 '"abc"             ===>  "abc"
66 "abc"              ===>  "abc"
67 '145932            ===>  145932
68 145932             ===>  145932
69 '#t                ===>  #t
70 #t                 ===>  #t
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.
78==== Procedure calls
80<macro>(<operator> <operand[1]> ...)</macro><br>
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
88 (+ 3 4)                           ===>  7
89 ((if #f + *) 3 4)                 ===>  12
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]]).
98Procedure calls are also called combinations.
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
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.
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.
115==== Procedures
117<macro>(lambda <formals> <body>)</macro><br>
119Syntax: <Formals> should be a formal arguments list as described below,
120and <body> should be a sequence of one or more expressions.
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.
133 (lambda (x) (+ x x))              ===>  a procedure
134 ((lambda (x) (+ x x)) 4)          ===>  8
136 (define reverse-subtract
137   (lambda (x y) (- y x)))
138 (reverse-subtract 7 10)           ===>  3
140 (define add4
141   (let ((x 4))
142     (lambda (y) (+ x y))))
143 (add4 6)                          ===>  10
145<Formals> should have one of the following forms:
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.
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>.
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.
165It is an error for a <variable> to appear more than once in <formals>.
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)
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.
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:
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>
192When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
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.
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.
215It shall be an error for an {{<ident>}} to appear more than once in a
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.
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)
232==== Conditionals
234<macro>(if <test> <consequent> <alternate>)</macro><br>
235<macro>(if <test> <consequent>)</macro><br>
237Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
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
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
254==== Assignments
256<macro>(set! <variable> <expression>)</macro><br>
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.
263 (define x 2)
264 (+ x 1)                         ===>  3
265 (set! x 4)                      ===>  unspecified
266 (+ x 1)                         ===>  5
268As an extension to R5RS, {{set!}} for unbound toplevel variables is
269allowed.  Also, {{set! (PROCEDURE ...) ...)}} is supported, as CHICKEN
270implements [[|SRFI-17]].
272=== Derived expression types
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.
280==== Conditionals
282<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
284Syntax: Each <clause> should be of the form
286 (<test> <expression[1]> ...)
288where <test> is any expression. Alternatively, a <clause> may be of the
291 (<test> => <expression>)
293The last <clause> may be an "else clause," which has the form
295 (else <expression[1]> <expression[2]> ...).
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.
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
324As an extension to R5RS, CHICKEN also supports the
325[[|SRFI-61]] syntax:
327 (<generator> <guard> => <expression>)
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.
335<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
337Syntax: <Key> may be any expression. Each <clause> should have the form
339 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
341where each <datum> is an external representation of some object.
342Alternatively, as per R7RS, a <clause> may be of the form
344 ((<datum[1]> ...) => <expression>).
346All the <datum>s must be distinct. The last <clause> may be an
347"else clause," which has one of the following two forms:
349 (else <expression[1]> <expression[2]> ...)
350 (else => <expression>).      ; R7RS extension
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
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
380<macro>(and <test[1]> ...)</macro><br>
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.
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
394<macro>(or <test[1]> ...)</macro><br>
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.
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)
409==== Binding constructs
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.
420<macro>(let <bindings> <body>)</macro><br>
422Syntax: <Bindings> should have the form
424 ((<variable[1]> <init[1]>) ...),
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.
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.
436 (let ((x 2) (y 3))
437   (* x y))                              ===>  6
439 (let ((x 2) (y 3))
440   (let ((x 7)
441         (z (+ x y)))
442     (* z x)))                           ===>  35
444See also "named let", [[#iteration|below]].
446<macro>(let* <bindings> <body>)</macro><br>
448Syntax: <Bindings> should have the form
450 ((<variable[1]> <init[1]>) ...),
452and <body> should be a sequence of one or more expressions.
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.
460 (let ((x 2) (y 3))
461   (let* ((x 7)
462          (z (+ x y)))
463     (* z x)))                     ===>  70
465<macro>(letrec <bindings> <body>)</macro><br>
467Syntax: <Bindings> should have the form
469 ((<variable[1]> <init[1]>) ...),
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.
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.
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
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.
504==== Sequencing
506<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
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.
512 (define x 0)
514 (begin (set! x 5)
515        (+ x 1))                          ===>  6
517 (begin (display "4 plus 1 equals ")
518        (display (+ 4 1)))                ===>  unspecified
519   and prints  4 plus 1 equals 5
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.
526==== Iteration
528<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
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.
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.
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.
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.
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.
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>
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)
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
570<macro>(let <variable> <bindings> <body>)</macro><br>
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
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))
594==== Delayed evaluation
596<macro>(delay <expression>)</macro><br>
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.
606See the description of {{force}} (under [[#control-features|Control
607features]], below) for a more complete description of {{delay}}.
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.
615==== Quasiquotation
617<macro>(quasiquote <qq template>)</macro><br>
618<macro>`<qq template></macro><br>
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>.
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)
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
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)
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
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))
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.
674=== Macros
676Scheme programs can define and use new derived expression types, called
677macros. Program-defined expression types have the syntax
679 (<keyword> <datum> ...)
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.
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.
690The macro definition facility consists of two parts:
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
696*   a pattern language for specifying macro transformers.
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:
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).
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.
715==== Binding constructs for syntactic keywords
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.
722<macro>(let-syntax <bindings> <body>)</macro><br>
724Syntax: <Bindings> should have the form
726 ((<keyword> <transformer spec>) ...)
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.
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.
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
747 (let ((x 'outer))
748   (let-syntax ((m (syntax-rules () ((m) x))))
749     (let ((x 'inner))
750       (m))))                               ===>  outer
752<macro>(letrec-syntax <bindings> <body>)</macro><br>
754Syntax: Same as for let-syntax.
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
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
783==== Pattern language
785A <transformer spec> has the following form:
787 (syntax-rules <literals> <syntax rule> ...)
789Syntax: <Literals> is a list of identifiers and each <syntax rule>
790should be of the form
792 (<pattern> <template>)
794The <pattern> in a <syntax rule> is a list <pattern> that begins with
795the keyword for the macro.
797A <pattern> is either an identifier, a constant, or one of the
800 (<pattern> ...)
801 (<pattern> <pattern> ... . <pattern>)
802 (<pattern> ... <pattern> <ellipsis>)
803 #(<pattern> ...)
804 #(<pattern> ... <pattern> <ellipsis>)
806and a template is either an identifier, a constant, or one of the
809 (<element> ...)
810 (<element> <element> ... . <template>)
811 #(<element> ...)
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).
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
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>.
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.
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.
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
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.
856More formally, an input form F matches a pattern P if and only if:
858*   P is a non-literal identifier; or
860*   P is a literal identifier and F is an identifier with the same
861    binding; or
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
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
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
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
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
883*   P is a datum and F is equal to P in the sense of the equal?
884    procedure.
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.
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.
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.
906As an example, if let and cond are defined as usual, then they are
907hygienic (as required) and the following is not an error.
909 (let ((=> #f))
910   (cond (#t => 'ok)))                   ===> ok
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
917 (let ((=> #f))
918   (if #t (begin => 'ok)))
920instead of
922 (let ((=> #f))
923   (let ((temp #t))
924     (if temp ('ok temp))))
926which would result in an invalid procedure call.
928== Program structure
930=== Programs
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.
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
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
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.
956=== Definitions
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>.
962A definition should have one of the following forms:
964<macro>(define <variable> <expression>)</macro><br>
965<macro>(define (<variable> <formals>) <body>)</macro><br>
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
972 (define <variable>
973   (lambda (<formals>) <body>)).
975<macro>(define <variable>)</macro>
977This form is a CHICKEN extension to R5RS, and is equivalent to
979 (define <variable> (void))
981<macro>(define (<variable> . <formal>) <body>)</macro><br>
983<Formal> should be a single variable. This form is equivalent to
985 (define <variable>
986   (lambda <formal> <body>)).
988<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>
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,
994 (define ((make-adder x) y) (+ x y))
996is equivalent to
998 (define (make-adder x) (lambda (y) (+ x y))).
1000This type of curried definition can be nested arbitrarily and combined
1001with dotted tail notation or DSSSL keywords.
1003==== Top level definitions
1005At the top level of a program, a definition
1007 (define <variable> <expression>)
1009has essentially the same effect as the assignment expression
1011 (set! <variable> <expression>)
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.
1020 (define add3
1021   (lambda (x) (+ x 3)))
1022 (add3 3)                         ===>  6
1023 (define first car)
1024 (first '(1 2))                   ===>  1
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.
1033==== Internal definitions
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
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
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
1053 (let ((x 5))
1054   (letrec ((foo (lambda (y) (bar x y)))
1055            (bar (lambda (a b) (+ (* a b) a))))
1056     (foo (+ x 3))))
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
1063Wherever an internal definition may occur (begin <definition1> ...) is
1064equivalent to the sequence of definitions that form the body of the
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:
1072 (let ((foo 123))
1073   (bar)
1074   (define foo 456)
1075   (baz foo) )
1077expands into
1079 (let ((foo 123))
1080   (bar)
1081   (letrec ((foo 456))
1082     (baz foo) ) )
1084Local sequences of {{define-syntax}} forms are translated into
1085equivalent {{letrec-syntax}} forms that enclose the following forms as
1086the body of the expression.
1089=== Syntax definitions
1091Syntax definitions are valid only at the top level of a
1092<program>. They have the following form:
1094<macro>(define-syntax <keyword> <transformer spec>)</macro>
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]].
1101The top-level syntactic environment is extended by binding the
1102<keyword> to the specified transformer.
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.
1110  (let ()
1111    ...
1112    (define-syntax foo ...)
1113    (define-syntax bar ...)
1114    ...)
1116is expanded into
1118  (let ()
1119    ...
1120    (letrec-syntax ((foo ...) (bar ...))
1121      ...) )
1123{{syntax-rules}} supports [[|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
1127  (syntax-rules ()
1128    ((_ (a b ... c)
1129      ...
1131are supported.
1133The effect of destructively modifying the s-expression passed to a
1134transformer procedure is undefined.
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:
1145 (define define 3)
1147 (begin (define begin list))
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)))
1160== Standard procedures
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".
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.
1179=== Equivalence predicates
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?.
1188<procedure>(eqv? obj[1] obj[2])</procedure><br>
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.
1196The eqv? procedure returns #t if:
1198*   obj[1] and obj[2] are both #t or both #f.
1200*   obj[1] and obj[2] are both symbols and
1202    (string=? (symbol->string obj1)
1203              (symbol->string obj2))
1204                ===>  #t
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.
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.
1215*   obj[1] and obj[2] are both characters and are the same character
1216    according to the char=? procedure (see "[[#characters|characters]]").
1218*   both obj[1] and obj[2] are the empty list.
1220*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
1221    same locations in the store.
1223*   obj[1] and obj[2] are procedures whose location tags are equal
1224    (see "[[#procedures|procedures]]").
1226The eqv? procedure returns #f if:
1228*   obj[1] and obj[2] are of different types.
1230*   one of obj[1] and obj[2] is #t but the other is #f.
1232*   obj[1] and obj[2] are symbols but
1234    (string=? (symbol->string obj[1])
1235              (symbol->string obj[2]))
1236                ===>  #f
1238*   one of obj[1] and obj[2] is an exact number but the other is an
1239    inexact number.
1241*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
1243*   obj[1] and obj[2] are characters for which the char=? procedure
1244    returns #f.
1246*   one of obj[1] and obj[2] is the empty list but the other is not.
1248*   obj[1] and obj[2] are pairs, vectors, or strings that denote
1249    distinct locations.
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.
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
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.
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
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.
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
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
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
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.
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
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.
1329<procedure>(eq? obj[1] obj[2])</procedure><br>
1331Eq? is similar to eqv? except that in some cases it is capable of
1332discerning distinctions finer than those detectable by eqv?.
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
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
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?.
1369<procedure>(equal? obj[1] obj[2])</procedure><br>
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
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
1388=== Numbers
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.
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.
1407==== Numerical types
1409Mathematically, numbers may be arranged into a tower of subtypes in
1410which each level is a subset of the level above it:
1412    number
1413    complex
1414    real
1415    rational
1416    integer
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?.
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.
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.
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.
1444==== Exactness
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.
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]].
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
1473==== Implementation restrictions
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.
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.
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:
1507 +            -             *
1508 quotient     remainder     modulo
1509 max          min           abs
1510 numerator    denominator   gcd
1511 lcm          floor         ceiling
1512 truncate     round         rationalize
1513 expt
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
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].
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.
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.
1555==== Syntax of numerical constants
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.
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.
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.
1587 3.14159265358979F0
1588         Round to single --- 3.141593
1589 0.6L0
1590         Extend to long --- .600000000000000
1592==== Numerical operations
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:
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
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.
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>
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)).
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
1642Note:   The behavior of these type predicates on inexact numbers is
1643unreliable, since any inaccuracy may affect the result.
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.
1651<procedure>(exact? z)</procedure><br>
1652<procedure>(inexact? z)</procedure><br>
1654These numerical predicates provide tests for the exactness of a
1655quantity. For any Scheme number, precisely one of these predicates is
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>
1664These procedures return #t if their arguments are (respectively):
1665equal, monotonically increasing, monotonically decreasing,
1666monotonically nondecreasing, or monotonically nonincreasing.
1668These predicates are required to be transitive.
1670Note:   The traditional implementations of these predicates in
1671Lisp-like languages are not transitive.
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.
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>
1684These numerical predicates test a number for a particular property,
1685returning #t or #f. See note above.
1687<procedure>(max x[1] x[2] ...)</procedure><br>
1688<procedure>(min x[1] x[2] ...)</procedure><br>
1690These procedures return the maximum or minimum of their arguments.
1692 (max 3 4)                      ===>  4    ; exact
1693 (max 3.9 4)                    ===>  4.0  ; inexact
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.
1703<procedure>(+ z[1] ...)</procedure><br>
1704<procedure>(* z[1] ...)</procedure><br>
1706These procedures return the sum or product of their arguments.
1708 (+ 3 4)                         ===>  7
1709 (+ 3)                           ===>  3
1710 (+)                             ===>  0
1711 (* 4)                           ===>  4
1712 (*)                             ===>  1
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>
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.
1726 (- 3 4)                         ===>  -1
1727 (- 3 4 5)                       ===>  -6
1728 (- 3)                           ===>  -3
1729 (/ 3 4 5)                       ===>  3/20
1730 (/ 3)                           ===>  1/3
1732<procedure>(abs x)</procedure><br>
1734Abs returns the absolute value of its argument.
1736 (abs -7)                        ===>  7
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>
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:
1746    (quotient n[1] n[2])           ===> n[1]/n[2]
1747    (remainder n[1] n[2])          ===> 0
1748    (modulo n[1] n[2])             ===> 0
1750If n[1]/n[2] is not an integer:
1752    (quotient n[1] n[2])           ===> n[q]
1753    (remainder n[1] n[2])          ===> n[r]
1754    (modulo n[1] n[2])             ===> n[m]
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].
1760From this we can conclude that for integers n[1] and n[2] with n[2] not
1761equal to 0,
1763     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
1764           (remainder n[1] n[2])))
1765                                         ===>  #t
1767provided all numbers involved in that computation are exact.
1769 (modulo 13 4)                   ===>  1
1770 (remainder 13 4)                ===>  1
1772 (modulo -13 4)                  ===>  3
1773 (remainder -13 4)               ===>  -1
1775 (modulo 13 -4)                  ===>  -3
1776 (remainder 13 -4)               ===>  1
1778 (modulo -13 -4)                 ===>  -1
1779 (remainder -13 -4)              ===>  -1
1781 (remainder -13 -4.0)            ===>  -1.0  ; inexact
1783<procedure>(gcd n[1] ...)</procedure><br>
1784<procedure>(lcm n[1] ...)</procedure><br>
1786These procedures return the greatest common divisor or least common
1787multiple of their arguments. The result is always non-negative.
1789 (gcd 32 -36)                    ===>  4
1790 (gcd)                           ===>  0
1791 (lcm 32 -36)                    ===>  288
1792 (lcm 32.0 -36)                  ===>  288.0  ; inexact
1793 (lcm)                           ===>  1
1795<procedure>(numerator q)</procedure><br>
1796<procedure>(denominator q)</procedure><br>
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.
1803 (numerator (/ 6 4))            ===>  3
1804 (denominator (/ 6 4))          ===>  2
1805 (denominator
1806   (exact->inexact (/ 6 4)))    ===> 2.0
1808<procedure>(floor x)</procedure><br>
1809<procedure>(ceiling x)</procedure><br>
1810<procedure>(truncate x)</procedure><br>
1811<procedure>(round x)</procedure><br>
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.
1819Rationale:   Round rounds to even for consistency with the default
1820rounding mode specified by the IEEE floating point standard.
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.
1826 (floor -4.3)                  ===>  -5.0
1827 (ceiling -4.3)                ===>  -4.0
1828 (truncate -4.3)               ===>  -4.0
1829 (round -4.3)                  ===>  -4.0
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
1836 (round 7/2)                   ===>  4    ; exact
1837 (round 7)                     ===>  7
1839<procedure>(rationalize x y)</procedure><br>
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
1851 (rationalize
1852   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
1853 (rationalize .3 1/10)                ===> #i1/3  ; inexact
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>
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.
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:
1880 sin^-1 z = - i log (i z + (1 - z^2)^1/2)
1882 cos^-1 z = pi / 2 - sin^-1 z
1884 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
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.
1891<procedure>(sqrt z)</procedure><br>
1893Returns the principal square root of z. The result will have either
1894positive real part, or zero real part and non-negative imaginary part.
1896<procedure>(expt z[1] z[2])</procedure><br>
1898Returns z[1] raised to the power z[2]. For z[1] != 0
1900 z[1]^z[2] = e^z[2] log z[1]
19020^z is 1 if z = 0 and 0 otherwise.
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>
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
1915 z = x[1] + x[2]i = x[3] . e^i x[4]
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]
1926where - pi < x[angle] < pi with x[angle] = x[4] + 2 pi n
1927for some integer n.
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
1934<procedure>(exact->inexact z)</procedure><br>
1935<procedure>(inexact->exact z)</procedure><br>
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
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.
1948These procedures implement the natural one-to-one correspondence
1949between exact and inexact integers throughout an
1950implementation-dependent range.
1951See "[[#implementation-restrictions|Implementation restrictions]]".
1953==== Numerical input and output
1955<procedure>(number->string z [radix])</procedure>
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.  If omitted, radix defaults to
196010. The procedure number->string takes a number and a radix and
1961returns as a string an external representation of the given number in
1962the given radix such that
1964 (let ((number number)
1965       (radix radix))
1966   (eqv? number
1967         (string->number (number->string number
1968                                         radix)
1969                         radix)))
1971is true. It is an error if no possible result makes this expression
1974If z is inexact, the radix is 10, and the above expression can be
1975satisfied by a result that contains a decimal point, then the result
1976contains a decimal point and is expressed using the minimum number of
1977digits (exclusive of exponent and trailing zeroes) needed to make the
1978above expression true [3, 5]; otherwise the format of the result is
1981The result returned by number->string never contains an explicit radix
1984Note:   The error case can occur only when z is not a complex
1985number or is a complex number with a non-rational real or imaginary
1988Rationale:   If z is an inexact number represented using flonums,
1989and the radix is 10, then the above expression is normally
1990satisfied by a result containing a decimal point. The unspecified
1991case allows for infinities, NaNs, and non-flonum representations.
1993As an extension to R5RS, CHICKEN supports reading and writing the
1994special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
1995as well as negative zero.
1997<procedure>(string->number string)</procedure><br>
1998<procedure>(string->number string radix)</procedure><br>
2000Returns a number of the maximally precise representation expressed by
2001the given string.  Radix must be an exact integer.  The R5RS standard
2002only requires implementations to support 2, 8, 10, or 16, but CHICKEN
2003allows any radix between 2 and 36, inclusive.  If supplied, radix is a
2004default radix that may be overridden by an explicit radix prefix in
2005string (e.g. "#o177"). If radix is not supplied, then the default
2006radix is 10. If string is not a syntactically valid notation for a
2007number, then string->number returns #f.
2009 (string->number "100")                ===>  100
2010 (string->number "100" 16)             ===>  256
2011 (string->number "1e2")                ===>  100.0
2012 (string->number "15##")               ===>  1500.0
2014Note:   The domain of string->number may be restricted by
2015implementations in the following ways. String->number is permitted
2016to return #f whenever string contains an explicit radix prefix. If
2017all numbers supported by an implementation are real, then string->
2018number is permitted to return #f whenever string uses the polar or
2019rectangular notations for complex numbers. If all numbers are
2020integers, then string->number may return #f whenever the fractional
2021notation is used. If all numbers are exact, then string->number may
2022return #f whenever an exponent marker or explicit exactness prefix
2023is used, or if a # appears in place of a digit. If all inexact
2024numbers are integers, then string->number may return #f whenever a
2025decimal point is used.
2027As an extension to R5RS, CHICKEN supports reading and writing the
2028special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
2029as well as negative zero.
2031=== Other data types
2033This section describes operations on some of Scheme's non-numeric data
2034types: booleans, pairs, lists, symbols, characters, strings and
2037==== Booleans
2039The standard boolean objects for true and false are written as #t and #f.
2040What really matters, though, are the objects that the Scheme
2041conditional expressions (if, cond, and, or, do) treat as true or false.
2042The phrase "a true value" (or sometimes just "true") means any
2043object treated as true by the conditional expressions, and the phrase
2044"a false value" (or "false") means any object treated as false by
2045the conditional expressions.
2047Of all the standard Scheme values, only #f counts as false in
2048conditional expressions. Except for #f, all standard Scheme values,
2049including #t, pairs, the empty list, symbols, numbers, strings,
2050vectors, and procedures, count as true.
2052Note:   Programmers accustomed to other dialects of Lisp should be
2053aware that Scheme distinguishes both #f and the empty list from the
2054symbol nil.
2056Boolean constants evaluate to themselves, so they do not need to be
2057quoted in programs.
2059 #t                ===>  #t
2060 #f                ===>  #f
2061 '#f               ===>  #f
2063<procedure>(not obj)</procedure><br>
2065Not returns #t if obj is false, and returns #f otherwise.
2067 (not #t)           ===>  #f
2068 (not 3)            ===>  #f
2069 (not (list 3))     ===>  #f
2070 (not #f)           ===>  #t
2071 (not '())          ===>  #f
2072 (not (list))       ===>  #f
2073 (not 'nil)         ===>  #f
2075<procedure>(boolean? obj)</procedure><br>
2077Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
2079 (boolean? #f)                 ===>  #t
2080 (boolean? 0)                  ===>  #f
2081 (boolean? '())                ===>  #f
2083==== Pairs and lists
2085A pair (sometimes called a dotted pair) is a record structure with two
2086fields called the car and cdr fields (for historical reasons). Pairs
2087are created by the procedure cons. The car and cdr fields are accessed
2088by the procedures car and cdr. The car and cdr fields are assigned by
2089the procedures set-car! and set-cdr!.
2091Pairs are used primarily to represent lists. A list can be defined
2092recursively as either the empty list or a pair whose cdr is a list.
2093More precisely, the set of lists is defined as the smallest set X such
2096*   The empty list is in X.
2097*   If list is in X, then any pair whose cdr field contains list is
2098    also in X.
2100The objects in the car fields of successive pairs of a list are the
2101elements of the list. For example, a two-element list is a pair whose
2102car is the first element and whose cdr is a pair whose car is the
2103second element and whose cdr is the empty list. The length of a list is
2104the number of elements, which is the same as the number of pairs.
2106The empty list is a special object of its own type (it is not a pair);
2107it has no elements and its length is zero.
2109Note:   The above definitions imply that all lists have finite
2110length and are terminated by the empty list.
2112The most general notation (external representation) for Scheme pairs is
2113the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
2114car field and c[2] is the value of the cdr field. For example (4 . 5)
2115is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
2116external representation of a pair, not an expression that evaluates to
2117a pair.
2119A more streamlined notation can be used for lists: the elements of the
2120list are simply enclosed in parentheses and separated by spaces. The
2121empty list is written () . For example,
2123 (a b c d e)
2127 (a . (b . (c . (d . (e . ())))))
2129are equivalent notations for a list of symbols.
2131A chain of pairs not ending in the empty list is called an improper
2132list. Note that an improper list is not a list. The list and dotted
2133notations can be combined to represent improper lists:
2135 (a b c . d)
2137is equivalent to
2139 (a . (b . (c . d)))
2141Whether a given pair is a list depends upon what is stored in the cdr
2142field. When the set-cdr! procedure is used, an object can be a list one
2143moment and not the next:
2145 (define x (list 'a 'b 'c))
2146 (define y x)
2147 y                               ===>  (a b c)
2148 (list? y)                       ===>  #t
2149 (set-cdr! x 4)                  ===>  unspecified
2150 x                               ===>  (a . 4)
2151 (eqv? x y)                      ===>  #t
2152 y                               ===>  (a . 4)
2153 (list? y)                       ===>  #f
2154 (set-cdr! x x)                  ===>  unspecified
2155 (list? x)                       ===>  #f
2157Within literal expressions and representations of objects read by the
2158read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2159denote two-element lists whose first elements are the symbols quote,
2160quasiquote, unquote, and unquote-splicing, respectively. The second
2161element in each case is <datum>. This convention is supported so that
2162arbitrary Scheme programs may be represented as lists. That is,
2163according to Scheme's grammar, every <expression> is also a <datum>.
2164Among other things, this permits the use of the read procedure to
2165parse Scheme programs.
2167<procedure>(pair? obj)</procedure><br>
2169Pair? returns #t if obj is a pair, and otherwise returns #f.
2171 (pair? '(a . b))                ===>  #t
2172 (pair? '(a b c))                ===>  #t
2173 (pair? '())                     ===>  #f
2174 (pair? '#(a b))                 ===>  #f
2176<procedure>(cons obj[1] obj[2])</procedure><br>
2178Returns a newly allocated pair whose car is obj[1] and whose cdr is
2179obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2180from every existing object.
2182 (cons 'a '())                   ===>  (a)
2183 (cons '(a) '(b c d))            ===>  ((a) b c d)
2184 (cons "a" '(b c))               ===>  ("a" b c)
2185 (cons 'a 3)                     ===>  (a . 3)
2186 (cons '(a b) 'c)                ===>  ((a b) . c)
2188<procedure>(car pair)</procedure><br>
2190Returns the contents of the car field of pair. Note that it is an error
2191to take the car of the empty list.
2193 (car '(a b c))                  ===>  a
2194 (car '((a) b c d))              ===>  (a)
2195 (car '(1 . 2))                  ===>  1
2196 (car '())                       ===>  error
2198<procedure>(cdr pair)</procedure><br>
2200Returns the contents of the cdr field of pair. Note that it is an error
2201to take the cdr of the empty list.
2203 (cdr '((a) b c d))              ===>  (b c d)
2204 (cdr '(1 . 2))                  ===>  2
2205 (cdr '())                       ===>  error
2207<procedure>(set-car! pair obj)</procedure><br>
2209Stores obj in the car field of pair. The value returned by set-car! is
2212 (define (f) (list 'not-a-constant-list))
2213 (define (g) '(constant-list))
2214 (set-car! (f) 3)                     ===>  unspecified
2215 (set-car! (g) 3)                     ===>  error
2217<procedure>(set-cdr! pair obj)</procedure><br>
2219Stores obj in the cdr field of pair. The value returned by set-cdr! is
2222<procedure>(caar pair)</procedure><br>
2223<procedure>(cadr pair)</procedure><br>
2224<procedure>(cdar pair)</procedure><br>
2225<procedure>(cddr pair)</procedure><br>
2226<procedure>(caaar pair)</procedure><br>
2227<procedure>(caadr pair)</procedure><br>
2228<procedure>(cadar pair)</procedure><br>
2229<procedure>(caddr pair)</procedure><br>
2230<procedure>(cdaar pair)</procedure><br>
2231<procedure>(cdadr pair)</procedure><br>
2232<procedure>(cddar pair)</procedure><br>
2233<procedure>(cdddr pair)</procedure><br>
2234<procedure>(caaaar pair)</procedure><br>
2235<procedure>(caaadr pair)</procedure><br>
2236<procedure>(caadar pair)</procedure><br>
2237<procedure>(caaddr pair)</procedure><br>
2238<procedure>(cadaar pair)</procedure><br>
2239<procedure>(cadadr pair)</procedure><br>
2240<procedure>(caddar pair)</procedure><br>
2241<procedure>(cadddr pair)</procedure><br>
2242<procedure>(cdaaar pair)</procedure><br>
2243<procedure>(cdaadr pair)</procedure><br>
2244<procedure>(cdadar pair)</procedure><br>
2245<procedure>(cdaddr pair)</procedure><br>
2246<procedure>(cddaar pair)</procedure><br>
2247<procedure>(cddadr pair)</procedure><br>
2248<procedure>(cdddar pair)</procedure><br>
2249<procedure>(cddddr pair)</procedure><br>
2251These procedures are compositions of car and cdr, where for example
2252caddr could be defined by
2254 (define caddr (lambda (x) (car (cdr (cdr x))))).
2256<procedure>(null? obj)</procedure><br>
2258Returns #t if obj is the empty list, otherwise returns #f.
2260<procedure>(list? obj)</procedure><br>
2262Returns #t if obj is a list, otherwise returns #f. By definition, all
2263lists have finite length and are terminated by the empty list.
2265 (list? '(a b c))             ===>  #t
2266 (list? '())                  ===>  #t
2267 (list? '(a . b))             ===>  #f
2268 (let ((x (list 'a)))
2269   (set-cdr! x x)
2270   (list? x))                 ===>  #f
2272<procedure>(list obj ...)</procedure><br>
2274Returns a newly allocated list of its arguments.
2276 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
2277 (list)                                  ===>  ()
2279<procedure>(length list)</procedure><br>
2281Returns the length of list.
2283 (length '(a b c))                       ===>  3
2284 (length '(a (b) (c d e)))               ===>  3
2285 (length '())                            ===>  0
2287<procedure>(append list ...)</procedure><br>
2289Returns a list consisting of the elements of the first list followed by
2290the elements of the other lists.
2292 (append '(x) '(y))                      ===>  (x y)
2293 (append '(a) '(b c d))                  ===>  (a b c d)
2294 (append '(a (b)) '((c)))                ===>  (a (b) (c))
2296The resulting list is always newly allocated, except that it shares
2297structure with the last list argument. The last argument may actually
2298be any object; an improper list results if the last argument is not a
2299proper list.
2301 (append '(a b) '(c . d))                ===>  (a b c . d)
2302 (append '() 'a)                         ===>  a
2304<procedure>(reverse list)</procedure><br>
2306Returns a newly allocated list consisting of the elements of list in
2307reverse order.
2309 (reverse '(a b c))                      ===>  (c b a)
2310 (reverse '(a (b c) d (e (f))))
2311                 ===>  ((e (f)) d (b c) a)
2313<procedure>(list-tail list k)</procedure><br>
2315Returns the sublist of list obtained by omitting the first k elements.
2316It is an error if list has fewer than k elements. List-tail could be
2317defined by
2319 (define list-tail
2320   (lambda (x k)
2321     (if (zero? k)
2322         x
2323         (list-tail (cdr x) (- k 1)))))
2325<procedure>(list-ref list k)</procedure><br>
2327Returns the kth element of list. (This is the same as the car of
2328(list-tail list k).) It is an error if list has fewer than k elements.
2330 (list-ref '(a b c d) 2)                ===>  c
2331 (list-ref '(a b c d)
2332           (inexact->exact (round 1.8)))
2333                 ===>  c
2335<procedure>(memq obj list)</procedure><br>
2336<procedure>(memv obj list)</procedure><br>
2337<procedure>(member obj list)</procedure><br>
2339These procedures return the first sublist of list whose car is obj,
2340where the sublists of list are the non-empty lists returned by
2341(list-tail list k) for k less than the length of list. If obj does not
2342occur in list, then #f (not the empty list) is returned. Memq uses eq?
2343to compare obj with the elements of list, while memv uses eqv? and
2344member uses equal?.
2346 (memq 'a '(a b c))                      ===>  (a b c)
2347 (memq 'b '(a b c))                      ===>  (b c)
2348 (memq 'a '(b c d))                      ===>  #f
2349 (memq (list 'a) '(b (a) c))             ===>  #f
2350 (member (list 'a)
2351         '(b (a) c))                     ===>  ((a) c)
2352 (memq 101 '(100 101 102))               ===>  unspecified
2353 (memv 101 '(100 101 102))               ===>  (101 102)
2355<procedure>(assq obj alist)</procedure><br>
2356<procedure>(assv obj alist)</procedure><br>
2357<procedure>(assoc obj alist)</procedure><br>
2359Alist (for "association list") must be a list of pairs. These
2360procedures find the first pair in alist whose car field is obj, and
2361returns that pair. If no pair in alist has obj as its car, then #f (not
2362the empty list) is returned. Assq uses eq? to compare obj with the car
2363fields of the pairs in alist, while assv uses eqv? and assoc uses
2366 (define e '((a 1) (b 2) (c 3)))
2367 (assq 'a e)             ===>  (a 1)
2368 (assq 'b e)             ===>  (b 2)
2369 (assq 'd e)             ===>  #f
2370 (assq (list 'a) '(((a)) ((b)) ((c))))
2371                         ===>  #f
2372 (assoc (list 'a) '(((a)) ((b)) ((c))))   
2373                                    ===>  ((a))
2374 (assq 5 '((2 3) (5 7) (11 13)))   
2375                                    ===>  unspecified
2376 (assv 5 '((2 3) (5 7) (11 13)))   
2377                                    ===>  (5 7)
2379Rationale:   Although they are ordinarily used as predicates, memq,
2380memv, member, assq, assv, and assoc do not have question marks in
2381their names because they return useful values rather than just #t
2382or #f.
2384==== Symbols
2386Symbols are objects whose usefulness rests on the fact that two symbols
2387are identical (in the sense of eqv?) if and only if their names are
2388spelled the same way. This is exactly the property needed to represent
2389identifiers in programs, and so most implementations of Scheme use them
2390internally for that purpose. Symbols are useful for many other
2391applications; for instance, they may be used the way enumerated values
2392are used in Pascal.
2394The rules for writing a symbol are exactly the same as the rules for
2395writing an identifier.
2397It is guaranteed that any symbol that has been returned as part of a
2398literal expression, or read using the read procedure, and subsequently
2399written out using the write procedure, will read back in as the
2400identical symbol (in the sense of eqv?). The string->symbol procedure,
2401however, can create symbols for which this write/read invariance may
2402not hold because their names contain special characters or letters in
2403the non-standard case.
2405Note:   Some implementations of Scheme have a feature known as
2406"slashification" in order to guarantee write/read invariance for
2407all symbols, but historically the most important use of this
2408feature has been to compensate for the lack of a string data type.
2410Some implementations also have "uninterned symbols", which defeat
2411write/read invariance even in implementations with slashification,
2412and also generate exceptions to the rule that two symbols are the
2413same if and only if their names are spelled the same.
2415<procedure>(symbol? obj)</procedure><br>
2417Returns #t if obj is a symbol, otherwise returns #f.
2419 (symbol? 'foo)                  ===>  #t
2420 (symbol? (car '(a b)))          ===>  #t
2421 (symbol? "bar")                 ===>  #f
2422 (symbol? 'nil)                  ===>  #t
2423 (symbol? '())                   ===>  #f
2424 (symbol? #f)                    ===>  #f
2426<procedure>(symbol->string symbol)</procedure><br>
2428Returns the name of symbol as a string. If the symbol was part of an
2429object returned as the value of a literal expression (see
2430"[[#literal-expressions|literal expressions]]") or by a call to the
2431read procedure, and its name contains alphabetic characters, then the
2432string returned will contain characters in the implementation's
2433preferred standard case -- some implementations will prefer upper
2434case, others lower case. If the symbol was returned by string->symbol,
2435the case of characters in the string returned will be the same as the
2436case in the string that was passed to string->symbol.  It is an error
2437to apply mutation procedures like string-set! to strings returned by
2438this procedure.
2440The following examples assume that the implementation's standard case
2441is lower case:
2443 (symbol->string 'flying-fish)     
2444                                           ===>  "flying-fish"
2445 (symbol->string 'Martin)                  ===>  "martin"
2446 (symbol->string
2447    (string->symbol "Malvina"))     
2448                                           ===>  "Malvina"
2450<procedure>(string->symbol string)</procedure><br>
2452Returns the symbol whose name is string. This procedure can create
2453symbols with names containing special characters or letters in the
2454non-standard case, but it is usually a bad idea to create such symbols
2455because in some implementations of Scheme they cannot be read as
2456themselves. See symbol->string.
2458The following examples assume that the implementation's standard case
2459is lower case:
2461 (eq? 'mISSISSIppi 'mississippi) 
2462                 ===>  #t
2463 (string->symbol "mISSISSIppi") 
2464                 ===>  the symbol with name "mISSISSIppi"
2465 (eq? 'bitBlt (string->symbol "bitBlt"))     
2466                 ===>  #f
2467 (eq? 'JollyWog
2468      (string->symbol
2469        (symbol->string 'JollyWog))) 
2470                 ===>  #t
2471 (string=? "K. Harper, M.D."
2472           (symbol->string
2473             (string->symbol "K. Harper, M.D."))) 
2474                 ===>  #t
2476==== Characters
2478Characters are objects that represent printed characters such as
2479letters and digits. Characters are written using the notation #\
2480<character> or #\<character name>. For example:
2482 #\a       ; lower case letter
2483 #\A       ; upper case letter
2484 #\(       ; left parenthesis
2485 #\        ; the space character
2486 #\space   ; the preferred way to write a space
2487 #\newline ; the newline character
2489Case is significant in #\<character>, but not in #\<character name>. If
2490<character> in #\<character> is alphabetic, then the character
2491following <character> must be a delimiter character such as a space or
2492parenthesis. This rule resolves the ambiguous case where, for example,
2493the sequence of characters "#\space" could be taken to be either a
2494representation of the space character or a representation of the
2495character "#\s" followed by a representation of the symbol "pace."
2497Characters written in the #\ notation are self-evaluating. That is,
2498they do not have to be quoted in programs. Some of the procedures that
2499operate on characters ignore the difference between upper case and
2500lower case. The procedures that ignore case have "-ci" (for "case
2501insensitive") embedded in their names.
2503<procedure>(char? obj)</procedure><br>
2505Returns #t if obj is a character, otherwise returns #f.
2507<procedure>(char=? char[1] char[2])</procedure><br>
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>
2513These procedures impose a total ordering on the set of characters. It
2514is guaranteed that under this ordering:
2516*   The upper case characters are in order. For example, (char<? #\A #\
2517    B) returns #t.
2518*   The lower case characters are in order. For example, (char<? #\a #\
2519    b) returns #t.
2520*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
2521*   Either all the digits precede all the upper case letters, or vice
2522    versa.
2523*   Either all the digits precede all the lower case letters, or vice
2524    versa.
2526Some implementations may generalize these procedures to take more than
2527two arguments, as with the corresponding numerical predicates.
2529<procedure>(char-ci=? char[1] char[2])</procedure><br>
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>
2535These procedures are similar to char=? et cetera, but they treat upper
2536case and lower case letters as the same. For example, (char-ci=? #\A #\
2537a) returns #t. Some implementations may generalize these procedures to
2538take more than two arguments, as with the corresponding numerical
2541<procedure>(char-alphabetic? char)</procedure><br>
2542<procedure>(char-numeric? char)</procedure><br>
2543<procedure>(char-whitespace? char)</procedure><br>
2544<procedure>(char-upper-case? letter)</procedure><br>
2545<procedure>(char-lower-case? letter)</procedure><br>
2547These procedures return #t if their arguments are alphabetic, numeric,
2548whitespace, upper case, or lower case characters, respectively,
2549otherwise they return #f. The following remarks, which are specific to
2550the ASCII character set, are intended only as a guide: The alphabetic
2551characters are the 52 upper and lower case letters. The numeric
2552characters are the ten decimal digits. The whitespace characters are
2553space, tab, line feed, form feed, and carriage return.
2555<procedure>(char->integer char)</procedure><br>
2556<procedure>(integer->char n)</procedure><br>
2558Given a character, char->integer returns an exact integer
2559representation of the character. Given an exact integer that is the
2560image of a character under char->integer, integer->char returns that
2561character. These procedures implement order-preserving isomorphisms
2562between the set of characters under the char<=? ordering and some
2563subset of the integers under the <= ordering. That is, if
2565 (char<=? a b) ===> #t  and  (<= x y) ===> #t
2567and x and y are in the domain of integer->char, then
2569 (<= (char->integer a)
2570     (char->integer b))                  ===>  #t
2572 (char<=? (integer->char x)
2573          (integer->char y))             ===>  #t
2575Note that {{integer->char}} does currently not detect
2576a negative argument and will quietly convert {{-1}} to
2577{{#x1ffff}} in CHICKEN.
2579<procedure>(char-upcase char)</procedure><br>
2580<procedure>(char-downcase char)</procedure><br>
2582These procedures return a character char[2] such that (char-ci=? char
2583char[2]). In addition, if char is alphabetic, then the result of
2584char-upcase is upper case and the result of char-downcase is lower
2587==== Strings
2589Strings are sequences of characters. Strings are written as sequences
2590of characters enclosed within doublequotes ("). A doublequote can be
2591written inside a string only by escaping it with a backslash (\), as in
2593"The word \"recursion\" has many meanings."
2595A backslash can be written inside a string only by escaping it with
2596another backslash. Scheme does not specify the effect of a backslash
2597within a string that is not followed by a doublequote or backslash.
2599A string constant may continue from one line to the next, but the exact
2600contents of such a string are unspecified. The length of a string is
2601the number of characters that it contains. This number is an exact,
2602non-negative integer that is fixed when the string is created. The
2603valid indexes of a string are the exact non-negative integers less than
2604the length of the string. The first character of a string has index 0,
2605the second has index 1, and so on.
2607In phrases such as "the characters of string beginning with index
2608start and ending with index end," it is understood that the index
2609start is inclusive and the index end is exclusive. Thus if start and
2610end are the same index, a null substring is referred to, and if start
2611is zero and end is the length of string, then the entire string is
2612referred to.
2614Some of the procedures that operate on strings ignore the difference
2615between upper and lower case. The versions that ignore case have
2616"-ci" (for "case insensitive") embedded in their names.
2618<procedure>(string? obj)</procedure><br>
2620Returns #t if obj is a string, otherwise returns #f.
2622<procedure>(make-string k)</procedure><br>
2623<procedure>(make-string k char)</procedure><br>
2625Make-string returns a newly allocated string of length k. If char is
2626given, then all elements of the string are initialized to char,
2627otherwise the contents of the string are unspecified.
2629<procedure>(string char ...)</procedure><br>
2631Returns a newly allocated string composed of the arguments.
2633<procedure>(string-length string)</procedure><br>
2635Returns the number of characters in the given string.
2637<procedure>(string-ref string k)</procedure><br>
2639k must be a valid index of string. String-ref returns character k of
2640string using zero-origin indexing.
2642<procedure>(string-set! string k char)</procedure><br>
2644k must be a valid index of string. String-set! stores char in element k
2645of string and returns an unspecified value.
2647 (define (f) (make-string 3 #\*))
2648 (define (g) "***")
2649 (string-set! (f) 0 #\?)          ===>  unspecified
2650 (string-set! (g) 0 #\?)          ===>  error
2651 (string-set! (symbol->string 'immutable)
2652              0
2653              #\?)          ===>  error
2655<procedure>(string=? string[1] string[2])</procedure><br>
2656<procedure>(string-ci=? string[1] string[2])</procedure><br>
2658Returns #t if the two strings are the same length and contain the same
2659characters in the same positions, otherwise returns #f. String-ci=?
2660treats upper and lower case letters as though they were the same
2661character, but string=? treats upper and lower case as distinct
2664<procedure>(string<? string[1] string[2])</procedure><br>
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-ci<? 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>
2673These procedures are the lexicographic extensions to strings of the
2674corresponding orderings on characters. For example, string<? is the
2675lexicographic ordering on strings induced by the ordering char<? on
2676characters. If two strings differ in length but are the same up to the
2677length of the shorter string, the shorter string is considered to be
2678lexicographically less than the longer string.
2680Implementations may generalize these and the string=? and string-ci=?
2681procedures to take more than two arguments, as with the corresponding
2682numerical predicates.
2684<procedure>(substring string start [end])</procedure><br>
2686String must be a string, and start and end must be exact integers
2689 0 <= start <= end <= (string-length string)
2691Substring returns a newly allocated string formed from the characters
2692of string beginning with index start (inclusive) and ending with index
2693end (exclusive). The {{end}} argument is optional and defaults to the
2694length of the string, this is a non-standard extension in CHICKEN.
2696<procedure>(string-append string ...)</procedure><br>
2698Returns a newly allocated string whose characters form the
2699concatenation of the given strings.
2701<procedure>(string->list string)</procedure><br>
2702<procedure>(list->string list)</procedure><br>
2704String->list returns a newly allocated list of the characters that make
2705up the given string. List->string returns a newly allocated string
2706formed from the characters in the list list, which must be a list of
2707characters. String->list and list->string are inverses so far as equal?
2708is concerned.
2710<procedure>(string-copy string)</procedure><br>
2712Returns a newly allocated copy of the given string.
2714<procedure>(string-fill! string char)</procedure><br>
2716Stores char in every element of the given string and returns an
2717unspecified value.
2719==== Vectors
2721Vectors are heterogenous structures whose elements are indexed by
2722integers. A vector typically occupies less space than a list of the
2723same length, and the average time required to access a randomly chosen
2724element is typically less for the vector than for the list.
2726The length of a vector is the number of elements that it contains. This
2727number is a non-negative integer that is fixed when the vector is
2728created. The valid indexes of a vector are the exact non-negative
2729integers less than the length of the vector. The first element in a
2730vector is indexed by zero, and the last element is indexed by one less
2731than the length of the vector.
2733Vectors are written using the notation #(obj ...). For example, a
2734vector of length 3 containing the number zero in element 0, the list (2
27352 2 2) in element 1, and the string "Anna" in element 2 can be written
2736as following:
2738 #(0 (2 2 2 2) "Anna")
2740Note that this is the external representation of a vector, not an
2741expression evaluating to a vector. Like list constants, vector
2742constants must be quoted:
2744 '#(0 (2 2 2 2) "Anna") 
2745                 ===>  #(0 (2 2 2 2) "Anna")
2747<procedure>(vector? obj)</procedure><br>
2749Returns #t if obj is a vector, otherwise returns #f.
2751<procedure>(make-vector k)</procedure><br>
2752<procedure>(make-vector k fill)</procedure><br>
2754Returns a newly allocated vector of k elements. If a second argument is
2755given, then each element is initialized to fill. Otherwise the initial
2756contents of each element is unspecified.
2758<procedure>(vector obj ...)</procedure><br>
2760Returns a newly allocated vector whose elements contain the given
2761arguments. Analogous to list.
2763 (vector 'a 'b 'c)                       ===>  #(a b c)
2765<procedure>(vector-length vector)</procedure><br>
2767Returns the number of elements in vector as an exact integer.
2769<procedure>(vector-ref vector k)</procedure><br>
2771k must be a valid index of vector. Vector-ref returns the contents of
2772element k of vector.
2774 (vector-ref '#(1 1 2 3 5 8 13 21)
2775             5) 
2776                 ===>  8
2777 (vector-ref '#(1 1 2 3 5 8 13 21)
2778             (let ((i (round (* 2 (acos -1)))))
2779               (if (inexact? i)
2780                   (inexact->exact i)
2781                   i)))
2782                 ===> 13
2784<procedure>(vector-set! vector k obj)</procedure><br>
2786k must be a valid index of vector. Vector-set! stores obj in element k
2787of vector. The value returned by vector-set! is unspecified.
2789 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
2790   (vector-set! vec 1 '("Sue" "Sue"))
2791   vec)     
2792                 ===>  #(0 ("Sue" "Sue") "Anna")
2794 (vector-set! '#(0 1 2) 1 "doe") 
2795                 ===>  error  ; constant vector
2797<procedure>(vector->list vector)</procedure><br>
2798<procedure>(list->vector list)</procedure><br>
2800Vector->list returns a newly allocated list of the objects contained in
2801the elements of vector. List->vector returns a newly created vector
2802initialized to the elements of the list list.
2804 (vector->list '#(dah dah didah)) 
2805                 ===>  (dah dah didah)
2806 (list->vector '(dididit dah))   
2807                 ===>  #(dididit dah)
2809<procedure>(vector-fill! vector fill)</procedure><br>
2811Stores fill in every element of vector. The value returned by
2812vector-fill! is unspecified.
2814=== Control features
2816This chapter describes various primitive procedures which control the
2817flow of program execution in special ways. The procedure? predicate is
2818also described here.
2820<procedure>(procedure? obj)</procedure><br>
2822Returns #t if obj is a procedure, otherwise returns #f.
2824 (procedure? car)                    ===>  #t
2825 (procedure? 'car)                   ===>  #f
2826 (procedure? (lambda (x) (* x x)))   
2827                                     ===>  #t
2828 (procedure? '(lambda (x) (* x x))) 
2829                                     ===>  #f
2830 (call-with-current-continuation procedure?)
2831                                     ===>  #t
2833<procedure>(apply proc arg[1] ... args)</procedure><br>
2835Proc must be a procedure and args must be a list. Calls proc with the
2836elements of the list (append (list arg[1] ...) args) as the actual
2839 (apply + (list 3 4))                      ===>  7
2841 (define compose
2842   (lambda (f g)
2843     (lambda args
2844       (f (apply g args)))))
2846 ((compose sqrt *) 12 75)                      ===>  30
2848<procedure>(map proc list[1] list[2] ...)</procedure><br>
2850The lists must be lists, and proc must be a procedure taking as many
2851arguments as there are lists and returning a single value. If more than
2852one list is given, then they must all be the same length. Map applies
2853proc element-wise to the elements of the lists and returns a list of
2854the results, in order. The dynamic order in which proc is applied to
2855the elements of the lists is unspecified.
2857 (map cadr '((a b) (d e) (g h)))   
2858                 ===>  (b e h)
2860 (map (lambda (n) (expt n n))
2861      '(1 2 3 4 5))               
2862                 ===>  (1 4 27 256 3125)
2864 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
2866 (let ((count 0))
2867   (map (lambda (ignored)
2868          (set! count (+ count 1))
2869          count)
2870        '(a b)))                         ===>  (1 2) or (2 1)
2872<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
2874The arguments to for-each are like the arguments to map, but for-each
2875calls proc for its side effects rather than for its values. Unlike map,
2876for-each is guaranteed to call proc on the elements of the lists in
2877order from the first element(s) to the last, and the value returned by
2878for-each is unspecified.
2880 (let ((v (make-vector 5)))
2881   (for-each (lambda (i)
2882               (vector-set! v i (* i i)))
2883             '(0 1 2 3 4))
2884   v)                                        ===>  #(0 1 4 9 16)
2886<procedure>(force promise)</procedure><br>
2888Forces the value of promise (see "[[#delayed-evaluation|delayed
2889evaluation]]"). If no value has been computed for the promise, then a
2890value is computed and returned.  The value of the promise is cached
2891(or "memoized") so that if it is forced a second time, the previously
2892computed value is returned.
2894 (force (delay (+ 1 2)))           ===>  3
2895 (let ((p (delay (+ 1 2))))
2896   (list (force p) (force p))) 
2897                                        ===>  (3 3)
2899 (define a-stream
2900   (letrec ((next
2901             (lambda (n)
2902               (cons n (delay (next (+ n 1)))))))
2903     (next 0)))
2904 (define head car)
2905 (define tail
2906   (lambda (stream) (force (cdr stream))))
2908 (head (tail (tail a-stream))) 
2909                                        ===>  2
2911Force and delay are mainly intended for programs written in functional
2912style. The following examples should not be considered to illustrate
2913good programming style, but they illustrate the property that only one
2914value is computed for a promise, no matter how many times it is forced.
2916 (define count 0)
2917 (define p
2918   (delay (begin (set! count (+ count 1))
2919                 (if (> count x)
2920                     count
2921                     (force p)))))
2922 (define x 5)
2923 p                             ===>  a promise
2924 (force p)                     ===>  6
2925 p                             ===>  a promise, still
2926 (begin (set! x 10)
2927        (force p))             ===>  6
2929Here is a possible implementation of delay and force. Promises are
2930implemented here as procedures of no arguments, and force simply calls
2931its argument:
2933 (define force
2934   (lambda (object)
2935     (object)))
2937We define the expression
2939 (delay <expression>)
2941to have the same meaning as the procedure call
2943 (make-promise (lambda () <expression>))
2945as follows
2947 (define-syntax delay
2948   (syntax-rules ()
2949     ((delay expression)
2950      (make-promise (lambda () expression))))),
2952where make-promise is defined as follows:
2954 (define make-promise
2955   (lambda (proc)
2956     (let ((result-ready? #f)
2957           (result #f))
2958       (lambda ()
2959         (if result-ready?
2960             result
2961             (let ((x (proc)))
2962               (if result-ready?
2963                   result
2964                   (begin (set! result-ready? #t)
2965                          (set! result x)
2966                          result))))))))
2968Rationale:   A promise may refer to its own value, as in the last
2969example above. Forcing such a promise may cause the promise to be
2970forced a second time before the value of the first force has been
2971computed. This complicates the definition of make-promise.
2973Various extensions to this semantics of delay and force are supported
2974in some implementations:
2976*   Calling force on an object that is not a promise may simply return
2977    the object (this is the case in CHICKEN).
2979*   It may be the case that there is no means by which a promise can be
2980    operationally distinguished from its forced value. That is,
2981    expressions like the following may evaluate to either #t or to #f,
2982    depending on the implementation:
2984    (eqv? (delay 1) 1)                  ===>  unspecified
2985    (pair? (delay (cons 1 2)))          ===>  unspecified
2987    In CHICKEN, promises are separate objects, so the above expressions
2988    will both evaluate to {{#f}}.
2990*   Some implementations may implement "implicit forcing," where the
2991    value of a promise is forced by primitive procedures like cdr and
2992    +:
2994    (+ (delay (* 3 7)) 13)          ===>  34
2996    This is '''not''' the case in CHICKEN.
2999<procedure>(call-with-current-continuation proc)</procedure><br>
3001Proc must be a procedure of one argument. The procedure
3002call-with-current-continuation packages up the current continuation
3003(see the rationale below) as an "escape procedure" and passes it as
3004an argument to proc. The escape procedure is a Scheme procedure that,
3005if it is later called, will abandon whatever continuation is in effect
3006at that later time and will instead use the continuation that was in
3007effect when the escape procedure was created. Calling the escape
3008procedure may cause the invocation of before and after thunks installed
3009using dynamic-wind.
3011The escape procedure accepts the same number of arguments as the
3012continuation to the original call to call-with-current-continuation.
3013Except for continuations created by the call-with-values procedure, all
3014continuations take exactly one value. The effect of passing no value or
3015more than one value to continuations that were not created by
3016call-with-values is unspecified.
3018The escape procedure that is passed to proc has unlimited extent just
3019like any other procedure in Scheme. It may be stored in variables or
3020data structures and may be called as many times as desired.
3022The following examples show only the most common ways in which
3023call-with-current-continuation is used. If all real uses were as simple
3024as these examples, there would be no need for a procedure with the
3025power of call-with-current-continuation.
3027 (call-with-current-continuation
3028   (lambda (exit)
3029     (for-each (lambda (x)
3030                 (if (negative? x)
3031                     (exit x)))
3032               '(54 0 37 -3 245 19))
3033     #t))                                ===>  -3
3035 (define list-length
3036   (lambda (obj)
3037     (call-with-current-continuation
3038       (lambda (return)
3039         (letrec ((r
3040                   (lambda (obj)
3041                     (cond ((null? obj) 0)
3042                           ((pair? obj)
3043                            (+ (r (cdr obj)) 1))
3044                           (else (return #f))))))
3045           (r obj))))))
3047 (list-length '(1 2 3 4))                    ===>  4
3049 (list-length '(a b . c))                    ===>  #f
3053A common use of call-with-current-continuation is for structured,
3054non-local exits from loops or procedure bodies, but in fact
3055call-with-current-continuation is extremely useful for implementing
3056a wide variety of advanced control structures.
3058Whenever a Scheme expression is evaluated there is a continuation
3059wanting the result of the expression. The continuation represents
3060an entire (default) future for the computation. If the expression
3061is evaluated at top level, for example, then the continuation might
3062take the result, print it on the screen, prompt for the next input,
3063evaluate it, and so on forever. Most of the time the continuation
3064includes actions specified by user code, as in a continuation that
3065will take the result, multiply it by the value stored in a local
3066variable, add seven, and give the answer to the top level
3067continuation to be printed. Normally these ubiquitous continuations
3068are hidden behind the scenes and programmers do not think much
3069about them. On rare occasions, however, a programmer may need to
3070deal with continuations explicitly. Call-with-current-continuation
3071allows Scheme programmers to do that by creating a procedure that
3072acts just like the current continuation.
3074Most programming languages incorporate one or more special-purpose
3075escape constructs with names like exit, return, or even goto. In
30761965, however, Peter Landin [16] invented a general purpose escape
3077operator called the J-operator. John Reynolds [24] described a
3078simpler but equally powerful construct in 1972. The catch special
3079form described by Sussman and Steele in the 1975 report on Scheme
3080is exactly the same as Reynolds's construct, though its name came
3081from a less general construct in MacLisp. Several Scheme
3082implementors noticed that the full power of the catch construct
3083could be provided by a procedure instead of by a special syntactic
3084construct, and the name call-with-current-continuation was coined
3085in 1982. This name is descriptive, but opinions differ on the
3086merits of such a long name, and some people use the name call/cc
3089<procedure>(values obj ...)</procedure><br>
3091Delivers all of its arguments to its continuation. Except for
3092continuations created by the call-with-values procedure, all
3093continuations take exactly one value. Values might be defined as
3096 (define (values . things)
3097   (call-with-current-continuation
3098     (lambda (cont) (apply cont things))))
3100<procedure>(call-with-values producer consumer)</procedure><br>
3102Calls its producer argument with no values and a continuation that,
3103when passed some values, calls the consumer procedure with those values
3104as arguments. The continuation for the call to consumer is the
3105continuation of the call to call-with-values.
3107 (call-with-values (lambda () (values 4 5))
3108                   (lambda (a b) b))
3109                                                            ===>  5
3111 (call-with-values * -)                                     ===>  -1
3113<procedure>(dynamic-wind before thunk after)</procedure><br>
3115Calls thunk without arguments, returning the result(s) of this call.
3116Before and after are called, also without arguments, as required by the
3117following rules (note that in the absence of calls to continuations
3118captured using call-with-current-continuation the three arguments are
3119called once each, in order). Before is called whenever execution enters
3120the dynamic extent of the call to thunk and after is called whenever it
3121exits that dynamic extent. The dynamic extent of a procedure call is
3122the period between when the call is initiated and when it returns. In
3123Scheme, because of call-with-current-continuation, the dynamic extent
3124of a call may not be a single, connected time period. It is defined as
3127*   The dynamic extent is entered when execution of the body of the
3128    called procedure begins.
3130*   The dynamic extent is also entered when execution is not within the
3131    dynamic extent and a continuation is invoked that was captured
3132    (using call-with-current-continuation) during the dynamic extent.
3134*   It is exited when the called procedure returns.
3136*   It is also exited when execution is within the dynamic extent and a
3137    continuation is invoked that was captured while not within the
3138    dynamic extent.
3140If a second call to dynamic-wind occurs within the dynamic extent of
3141the call to thunk and then a continuation is invoked in such a way that
3142the afters from these two invocations of dynamic-wind are both to be
3143called, then the after associated with the second (inner) call to
3144dynamic-wind is called first.
3146If a second call to dynamic-wind occurs within the dynamic extent of
3147the call to thunk and then a continuation is invoked in such a way that
3148the befores from these two invocations of dynamic-wind are both to be
3149called, then the before associated with the first (outer) call to
3150dynamic-wind is called first.
3152If invoking a continuation requires calling the before from one call to
3153dynamic-wind and the after from another, then the after is called
3156The effect of using a captured continuation to enter or exit the
3157dynamic extent of a call to before or after is undefined.  However,
3158in CHICKEN it is safe to do this, and they will execute in the outer
3159dynamic context of the {{dynamic-wind}} form.
3161 (let ((path '())
3162       (c #f))
3163   (let ((add (lambda (s)
3164                (set! path (cons s path)))))
3165     (dynamic-wind
3166       (lambda () (add 'connect))
3167       (lambda ()
3168         (add (call-with-current-continuation
3169                (lambda (c0)
3170                  (set! c c0)
3171                  'talk1))))
3172       (lambda () (add 'disconnect)))
3173     (if (< (length path) 4)
3174         (c 'talk2)
3175         (reverse path))))
3177                 ===> (connect talk1 disconnect
3178                       connect talk2 disconnect)
3180=== Eval
3182<procedure>(eval expression [environment-specifier])</procedure><br>
3184Evaluates expression in the specified environment and returns its
3185value. Expression must be a valid Scheme expression represented as
3186data, and environment-specifier must be a value returned by one of the
3187three procedures described below. Implementations may extend eval to
3188allow non-expression programs (definitions) as the first argument and
3189to allow other values as environments, with the restriction that eval
3190is not allowed to create new bindings in the environments associated
3191with null-environment or scheme-report-environment.
3193 (eval '(* 7 3) (scheme-report-environment 5))
3194                                                            ===>  21
3196 (let ((f (eval '(lambda (f x) (f x x))
3197                (null-environment 5))))
3198   (f + 10))
3199                                                            ===>  20
3201The {{environment-specifier}} is optional, and if not provided it
3202defaults to the value of {{(interaction-environment)}}.  This is a
3203CHICKEN extension to R5RS, which, though strictly nonportable, is very
3204common among Scheme implementations.
3206<procedure>(scheme-report-environment version [mutable])</procedure><br>
3207<procedure>(null-environment version [mutable])</procedure><br>
3209Version must be either the exact integer 4 or 5, corresponding to the
3210respective revisions of the Scheme report (the Revised^N Report on
3211Scheme).  Scheme-report-environment returns a specifier for an
3212environment that is empty except for all bindings defined in this
3213report that are either required or both optional and supported by the
3214implementation.  Null-environment returns a specifier for an
3215environment that is empty except for the (syntactic) bindings for all
3216syntactic keywords defined in this report that are either required or
3217both optional and supported by the implementation.
3219The environments specified by scheme-report-environment and
3220null-environment are immutable by default.  In CHICKEN, as an
3221extension to R5RS, an extra {{mutable}} argument can be passed, which
3222makes the environments mutable when non-{{#f}}.  Mutability means new
3223top-level definitions are accepted and the values of existing
3224top-level bindings can be mutated.
3228This procedure returns a specifier for the environment that contains
3229implementation-defined bindings, typically a superset of those listed
3230in the report. The intent is that this procedure will return the
3231environment in which the implementation would evaluate expressions
3232dynamically typed by the user.
3234=== Input and output
3236==== Ports
3238Ports represent input and output devices. To Scheme, an input port is a
3239Scheme object that can deliver characters upon command, while an output
3240port is a Scheme object that can accept characters.
3242<procedure>(call-with-input-file string proc [mode ...])</procedure><br>
3243<procedure>(call-with-output-file string proc [mode ...])</procedure><br>
3245String should be a string naming a file, and proc should be a procedure
3246that accepts one argument. For call-with-input-file, the file should
3247already exist; for call-with-output-file, the effect is unspecified if
3248the file already exists. These procedures call proc with one argument:
3249the port obtained by opening the named file for input or output. If the
3250file cannot be opened, an error is signalled. If proc returns, then the
3251port is closed automatically and the value(s) yielded by the proc is
3252(are) returned. If proc does not return, then the port will not be
3253closed automatically unless it is possible to prove that the port will
3254never again be used for a read or write operation.
3256Rationale:   Because Scheme's escape procedures have unlimited
3257extent, it is possible to escape from the current continuation but
3258later to escape back in. If implementations were permitted to close
3259the port on any escape from the current continuation, then it would
3260be impossible to write portable code using both
3261call-with-current-continuation and call-with-input-file or
3264Additional {{mode}} arguments can be passed in, which should be any of
3265the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3266{{#:binary}} indicate the mode in which to open the file (this has an
3267effect on non-UNIX platforms only), while {{#:append}} indicates that
3268instead of truncating the file on open, data written to it should be
3269appended at the end (only for output files).  The extra {{mode}}
3270arguments are CHICKEN extensions to the R5RS standard.
3272<procedure>(input-port? obj)</procedure><br>
3273<procedure>(output-port? obj)</procedure><br>
3275Returns #t if obj is an input port or output port respectively,
3276otherwise returns #f.
3278<procedure>(current-input-port [port])</procedure><br>
3279<procedure>(current-output-port [port])</procedure><br>
3281Returns the current default input or output port.
3283If the optional {{port}} argument is passed, the current input or
3284output port is changed to the provided port.  It can also be used with
3285{{parameterize}} to temporarily bind the port to another value.  This
3286is a CHICKEN extension to the R5RS standard.
3288Note that the default output port is not buffered. Use
3289[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]
3290if you need a different behavior.
3293<procedure>(with-input-from-file string thunk [mode ...])</procedure><br>
3294<procedure>(with-output-to-file string thunk [mode ...])</procedure><br>
3296String should be a string naming a file, and proc should be a procedure
3297of no arguments. For with-input-from-file, the file should already
3298exist; for with-output-to-file, the effect is unspecified if the file
3299already exists. The file is opened for input or output, an input or
3300output port connected to it is made the default value returned by
3301current-input-port or current-output-port (and is used by (read),
3302(write obj), and so forth), and the thunk is called with no arguments.
3303When the thunk returns, the port is closed and the previous default is
3304restored. With-input-from-file and with-output-to-file return(s) the
3305value(s) yielded by thunk. If an escape procedure is used to escape
3306from the continuation of these procedures, their behavior is
3307implementation dependent.
3309Additional {{mode}} arguments can be passed in, which should be any of
3310the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3311{{#:binary}} indicate the mode in which to open the file (this has an
3312effect on non-UNIX platforms only), while {{#:append}} indicates that
3313instead of truncating the file on open, data written to it should be
3314appended at the end (only for output files).  The extra {{mode}}
3315arguments are CHICKEN extensions to the R5RS standard.
3317<procedure>(open-input-file filename [mode ...])</procedure><br>
3319Takes a string naming an existing file and returns an input port
3320capable of delivering characters from the file. If the file cannot be
3321opened, an error is signalled.
3323Additional {{mode}} arguments can be passed in, which should be any of
3324the keywords {{#:text}} or {{#:binary}}.  These indicate the mode in
3325which to open the file (this has an effect on non-UNIX platforms
3326only).  The extra {{mode}} arguments are CHICKEN extensions to the
3327R5RS standard.
3329<procedure>(open-output-file filename [mode ...])</procedure><br>
3331Takes a string naming an output file to be created and returns an
3332output port capable of writing characters to a new file by that name.
3333If the file cannot be opened, an error is signalled. If a file with the
3334given name already exists, the effect is unspecified.
3336Additional {{mode}} arguments can be passed in, which should be any of
3337the keywords {{#:text}}, {{#:binary}} or {{#:append}}.  {{#:text}} and
3338{{#:binary}} indicate the mode in which to open the file (this has an
3339effect on non-UNIX platforms only), while {{#:append}} indicates that
3340instead of truncating the file on open, data written to it should be
3341appended at the end.  The extra {{mode}} arguments are CHICKEN
3342extensions to the R5RS standard.
3344<procedure>(close-input-port port)</procedure><br>
3345<procedure>(close-output-port port)</procedure><br>
3347Closes the file associated with port, rendering the port incapable of
3348delivering or accepting characters. These routines have no effect if
3349the file has already been closed. The value returned is unspecified.
3351==== Input
3354<procedure>(read port)</procedure><br>
3356Read converts external representations of Scheme objects into the
3357objects themselves. That is, it is a parser for the nonterminal
3358<datum> (see also "[[#pairs-and-lists|pairs and lists]]"). Read
3359returns the next object parsable from the given input port, updating
3360port to point to the first character past the end of the external
3361representation of the object.
3363If an end of file is encountered in the input before any characters are
3364found that can begin an object, then an end of file object is returned.
3365The port remains open, and further attempts to read will also return an
3366end of file object. If an end of file is encountered after the
3367beginning of an object's external representation, but the external
3368representation is incomplete and therefore not parsable, an error is
3371The port argument may be omitted, in which case it defaults to the
3372value returned by current-input-port. It is an error to read from a
3373closed port.
3376<procedure>(read-char port)</procedure><br>
3378Returns the next character available from the input port, updating the
3379port to point to the following character. If no more characters are
3380available, an end of file object is returned. Port may be omitted, in
3381which case it defaults to the value returned by current-input-port.
3384<procedure>(peek-char port)</procedure><br>
3386Returns the next character available from the input port, without
3387updating the port to point to the following character. If no more
3388characters are available, an end of file object is returned. Port may
3389be omitted, in which case it defaults to the value returned by
3392Note:   The value returned by a call to peek-char is the same as
3393the value that would have been returned by a call to read-char with
3394the same port. The only difference is that the very next call to
3395read-char or peek-char on that port will return the value returned
3396by the preceding call to peek-char. In particular, a call to
3397peek-char on an interactive port will hang waiting for input
3398whenever a call to read-char would have hung.
3400<procedure>(eof-object? obj)</procedure><br>
3402Returns #t if obj is an end of file object, otherwise returns #f. The
3403precise set of end of file objects will vary among implementations, but
3404in any case no end of file object will ever be an object that can be
3405read in using read.
3408<procedure>(char-ready? port)</procedure><br>
3410Returns #t if a character is ready on the input port and returns #f
3411otherwise. If char-ready returns #t then the next read-char operation
3412on the given port is guaranteed not to hang. If the port is at end of
3413file then char-ready? returns #t. Port may be omitted, in which case it
3414defaults to the value returned by current-input-port.
3416Rationale:   Char-ready? exists to make it possible for a program
3417to accept characters from interactive ports without getting stuck
3418waiting for input. Any input editors associated with such ports
3419must ensure that characters whose existence has been asserted by
3420char-ready? cannot be rubbed out. If char-ready? were to return #f
3421at end of file, a port at end of file would be indistinguishable
3422from an interactive port that has no ready characters.
3424==== Output
3426<procedure>(write obj)</procedure><br>
3427<procedure>(write obj port)</procedure><br>
3429Writes a written representation of obj to the given port. Strings that
3430appear in the written representation are enclosed in doublequotes, and
3431within those strings backslash and doublequote characters are escaped
3432by backslashes. Character objects are written using the #\ notation.
3433Write returns an unspecified value. The port argument may be omitted,
3434in which case it defaults to the value returned by current-output-port.
3436<procedure>(display obj)</procedure><br>
3437<procedure>(display obj port)</procedure><br>
3439Writes a representation of obj to the given port. Strings that appear
3440in the written representation are not enclosed in doublequotes, and no
3441characters are escaped within those strings. Character objects appear
3442in the representation as if written by write-char instead of by write.
3443Display returns an unspecified value. The port argument may be omitted,
3444in which case it defaults to the value returned by current-output-port.
3446Rationale:   Write is intended for producing machine-readable
3447output and display is for producing human-readable output.
3448Implementations that allow "slashification" within symbols will
3449probably want write but not display to slashify funny characters in
3453<procedure>(newline port)</procedure><br>
3455Writes an end of line to port. Exactly how this is done differs from
3456one operating system to another. Returns an unspecified value. The port
3457argument may be omitted, in which case it defaults to the value
3458returned by current-output-port.
3460<procedure>(write-char char)</procedure><br>
3461<procedure>(write-char char port)</procedure><br>
3463Writes the character char (not an external representation of the
3464character) to the given port and returns an unspecified value. The port
3465argument may be omitted, in which case it defaults to the value
3466returned by current-output-port.
3468==== System interface
3470Questions of system interface generally fall outside of the domain of
3471this report. However, the following operations are important enough to
3472deserve description here.
3474<procedure>(load filename [evalproc])</procedure><br>
3476Filename should be a string naming an existing file containing Scheme
3477source code. The load procedure reads expressions and definitions from
3478the file and evaluates them sequentially. It is unspecified whether the
3479results of the expressions are printed. The load procedure does not
3480affect the values returned by current-input-port and
3481current-output-port. Load returns an unspecified value.
3483CHICKEN offers a few extensions to the R5RS definition of {{load}}:
3485* The {{filename}} may also be an input port.
3486* 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}}.
3487* On platforms that support it (currently BSD, Haiku, MacOS X, Linux, Solaris, and Windows), {{load}} can be used to load shared objects.
3489Example for loading compiled programs:
3491 % cat x.scm
3492 (define (hello) (print "Hello!"))
3493 % csc -s x.scm
3494 % csi -q
3495 #;1> (load "")
3496 ; loading ...
3497 #;2> (hello)
3498 Hello!
3499 #;3>
3501There are some limitations and caveats to the CHICKEN extensions you
3502need to be aware of:
3504* The second argument to {{load}} is ignored when loading compiled code.
3505* If source code is loaded from a port, then that port is closed after all expressions have been read.
3506* A compiled file can only be loaded once. Subsequent attempts to load the same file have no effect.
3509<procedure>(transcript-on filename)</procedure><br>
3512(These procedures are not implemented in CHICKEN.)
3514Filename must be a string naming an output file to be created. The
3515effect of transcript-on is to open the named file for output, and to
3516cause a transcript of subsequent interaction between the user and the
3517Scheme system to be written to the file. The transcript is ended by a
3518call to transcript-off, which closes the transcript file. Only one
3519transcript may be in progress at any time, though some implementations
3520may relax this restriction. The values returned by these procedures are
3524Previous: [[Included modules]]
3526Next: [[Module r5rs]]
Note: See TracBrowser for help on using the repository browser.