~ chicken-core (master) /manual/Module (scheme base)
Trap1[[tags: manual]]2[[toc:]]34== Module scheme56This module provides all of CHICKEN's R7RS procedures and macros.7These descriptions are based directly on the ''Revised^7 Report on the8Algorithmic Language Scheme''.910== Expressions1112Expression types are categorized as primitive or derived. Primitive13expression types include variables and procedure calls. Derived14expression types are not semantically primitive, but can instead be15defined as macros. The distinction which R7RS makes between primitive16and derived is unimportant and does not necessarily reflect how it is17implemented in CHICKEN itself.1819=== Primitive expression types2021==== Variable references2223<macro><variable></macro><br>2425An expression consisting of a variable is a variable reference. The26value of the variable reference is the value stored in the location to27which the variable is bound. It is an error to reference an unbound28variable.2930 (define x 28)31 x ===> 283233==== Literal expressions3435<macro>(quote <datum>)</macro><br>36<macro>'<datum></macro><br>37<macro><constant></macro><br>3839(quote <datum>) evaluates to <datum>. <Datum> may be any external40representation of a Scheme object. This notation is used to include41literal constants in Scheme code.4243 (quote a) ===> a44 (quote #(a b c)) ===> #(a b c)45 (quote (+ 1 2)) ===> (+ 1 2)4647(quote <datum>) may be abbreviated as '<datum>. The two notations are48equivalent in all respects.4950 'a ===> a51 '#(a b c) ===> #(a b c)52 '() ===> ()53 '(+ 1 2) ===> (+ 1 2)54 '(quote a) ===> (quote a)55 ''a ===> (quote a)5657Numerical constants, string constants, character constants, and boolean58constants evaluate "to themselves"; they need not be quoted.5960 '"abc" ===> "abc"61 "abc" ===> "abc"62 '145932 ===> 14593263 145932 ===> 14593264 '#t ===> #t65 #t ===> #t66 '#(a 10) ===> #(a 10)67 #(a 10) ===> #(a 10)68 '#u8(64 65) ===> #u8(64 65)69 #u8(64 65) ===> #u8(64 65)7071It is an error to alter a constant (i.e. the value of a literal72expression) using a mutation procedure like set-car! or string-set!.73In the current implementation of CHICKEN, identical constants don't74share memory and it is possible to mutate them, but this may change in75the future.7677==== Procedure calls7879<macro>(<operator> <operand[1]> ...)</macro><br>8081A procedure call is written by simply enclosing in parentheses82expressions for the procedure to be called and the arguments to be83passed to it. The operator and operand expressions are evaluated (in an84unspecified order) and the resulting procedure is passed the resulting85arguments.8687 (+ 3 4) ===> 788 ((if #f + *) 3 4) ===> 128990A number of procedures are available as the values of variables in the91initial environment; for example, the addition and multiplication92procedures in the above examples are the values of the variables + and93*. New procedures are created by evaluating lambda94expressions. Procedure calls may return any number of values (see the95{{values}} procedure [[#control-features|below]]).9697Procedure calls are also called combinations.9899Note: In contrast to other dialects of Lisp, the order of100evaluation is unspecified, and the operator expression and the101operand expressions are always evaluated with the same evaluation102rules.103104Note: Although the order of evaluation is otherwise unspecified,105the effect of any concurrent evaluation of the operator and operand106expressions is constrained to be consistent with some sequential107order of evaluation. The order of evaluation may be chosen108differently for each procedure call.109110Note: In many dialects of Lisp, the empty combination, (), is a111legitimate expression. In Scheme, combinations must have at least112one subexpression, so () is not a syntactically valid expression.113114==== Procedures115116<macro>(lambda <formals> <body>)</macro><br>117118Syntax: <Formals> should be a formal arguments list as described below,119and <body> should be a sequence of one or more expressions.120121Semantics: A lambda expression evaluates to a procedure. The122environment in effect when the lambda expression was evaluated is123remembered as part of the procedure. When the procedure is later called124with some actual arguments, the environment in which the lambda125expression was evaluated will be extended by binding the variables in126the formal argument list to fresh locations, the corresponding actual127argument values will be stored in those locations, and the expressions128in the body of the lambda expression will be evaluated sequentially in129the extended environment. The result(s) of the last expression in the130body will be returned as the result(s) of the procedure call.131132 (lambda (x) (+ x x)) ===> a procedure133 ((lambda (x) (+ x x)) 4) ===> 8134135 (define reverse-subtract136 (lambda (x y) (- y x)))137 (reverse-subtract 7 10) ===> 3138139 (define add4140 (let ((x 4))141 (lambda (y) (+ x y))))142 (add4 6) ===> 10143144<Formals> should have one of the following forms:145146* (<variable[1]> ...): The procedure takes a fixed number of147 arguments; when the procedure is called, the arguments will be148 stored in the bindings of the corresponding variables.149150* <variable>: The procedure takes any number of arguments; when the151 procedure is called, the sequence of actual arguments is converted152 into a newly allocated list, and the list is stored in the binding153 of the <variable>.154155* (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a156 space-delimited period precedes the last variable, then the157 procedure takes n or more arguments, where n is the number of158 formal arguments before the period (there must be at least one).159 The value stored in the binding of the last variable will be a160 newly allocated list of the actual arguments left over after all161 the other actual arguments have been matched up against the other162 formal arguments.163164It is an error for a <variable> to appear more than once in <formals>.165166 ((lambda x x) 3 4 5 6) ===> (3 4 5 6)167 ((lambda (x y . z) z)168 3 4 5 6) ===> (5 6)169170Each procedure created as the result of evaluating a lambda expression171is (conceptually) tagged with a storage location, in order to make eqv?172and eq? work on procedures.173174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style175parameter lists, which allows embedded special keywords. Such a176keyword gives a special meaning to the {{<formal>}} it precedes.177DSSSL parameter lists are defined by the following grammar:178179 <parameter-list> ==> <required-parameter>*180 [#!optional <optional-parameter>*]181 [#!rest <rest-parameter>]182 [#!key <keyword-parameter>*]183 <required-parameter> ==> <ident>184 <optional-parameter> ==> <ident>185 | (<ident> <initializer>)186 <rest-parameter> ==> <ident>187 <keyword-parameter> ==> <ident>188 | (<ident> <initializer>)189 <initializer> ==> <expr>190191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:192193* 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.194* 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.195* 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.196* 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.197198Needing a special mention is the close relationship between the199rest-parameter and possible keyword-parameters. Declaring a200rest-parameter binds up all remaining arguments in a list, as201described above. These same remaining arguments are also used for202attempted matches with declared keyword-parameters, as described203above, in which case a matching keyword-parameter binds to the204corresponding value argument at the same time that both the keyword205and value arguments are added to the rest parameter list. Note that206for efficiency reasons, the keyword-parameter matching does nothing207more than simply attempt to match with pairs that may exist in the208remaining arguments. Extra arguments that don't match are simply209unused and forgotten if no rest-parameter has been declared. Because210of this, the caller of a procedure containing one or more211keyword-parameters cannot rely on any kind of system error to report212wrong keywords being passed in.213214It shall be an error for an {{<ident>}} to appear more than once in a215parameter-list.216217If 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.218219220Example:221222 ((lambda x x) 3 4 5 6) => (3 4 5 6)223 ((lambda (x y #!rest z) z)224 3 4 5 6) => (5 6)225 ((lambda (x y #!optional z #!rest r #!key i (j 1))226 (list x y z i: i j: j))227 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)228229230231==== Conditionals232233<macro>(if <test> <consequent> <alternate>)</macro><br>234<macro>(if <test> <consequent>)</macro><br>235236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary237expressions.238239Semantics: An if expression is evaluated as follows: first, <test> is240evaluated. If it yields a true value (see [[#Booleans|the section241about booleans]] below), then <consequent> is evaluated and its242value(s) is(are) returned. Otherwise <alternate> is evaluated and its243value(s) is(are) returned. If <test> yields a false value and no244<alternate> is specified, then the result of the expression is245unspecified.246247 (if (> 3 2) 'yes 'no) ===> yes248 (if (> 2 3) 'yes 'no) ===> no249 (if (> 3 2)250 (- 3 2)251 (+ 3 2)) ===> 1252253==== Assignments254255<macro>(set! <variable> <expression>)</macro><br>256257<Expression> is evaluated, and the resulting value is stored in the258location to which <variable> is bound. <Variable> must be bound either259in some region enclosing the set! expression or at top level. The260result of the set! expression is unspecified.261262 (define x 2)263 (+ x 1) ===> 3264 (set! x 4) ===> unspecified265 (+ x 1) ===> 5266267As an extension to R7RS, {{set!}} for unbound toplevel variables is268allowed. Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].270271==== Inclusion272273<macro>(include STRING1 STRING2 ...)</macro>274<macro>(include-ci STRING1 STRING2 ...)</macro>275276Semantics: Both {{include}} and {{include-ci}} take one or277more filenames expressed as string literals, apply an278implementation-specific algorithm to find corresponding279files, read the contents of the files in the specified order280as if by repeated applications of {{read}}, and effectively replace the {{include}}281or {{include-ci}} expression with a {{begin}}282expression containing what was read from the files. The283difference between the two is that {{include-ci}} reads each284file as if it began with the {{#!fold-case}} directive, while285{{include}} does not.286287288=== Derived expression types289290The constructs in this section are hygienic. For reference purposes,291these macro definitions will convert most of the constructs described292in this section into the primitive constructs described in the293previous section. This does not necessarily mean that's exactly how294it's implemented in CHICKEN.295296==== Conditionals297298<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>299300Syntax: Each <clause> should be of the form301302 (<test> <expression[1]> ...)303304where <test> is any expression. Alternatively, a <clause> may be of the305form306307 (<test> => <expression>)308309The last <clause> may be an "else clause," which has the form310311 (else <expression[1]> <expression[2]> ...).312313Semantics: A cond expression is evaluated by evaluating the <test>314expressions of successive <clause>s in order until one of them315evaluates to a true value (see [[#Booleans|the section about316booleans]] below). When a <test> evaluates to a true value, then the317remaining <expression>s in its <clause> are evaluated in order, and318the result(s) of the last <expression> in the <clause> is(are)319returned as the result(s) of the entire cond expression. If the320selected <clause> contains only the <test> and no <expression>s, then321the value of the <test> is returned as the result. If the selected322<clause> uses the => alternate form, then the <expression> is323evaluated. Its value must be a procedure that accepts one argument;324this procedure is then called on the value of the <test> and the325value(s) returned by this procedure is(are) returned by the cond326expression. If all <test>s evaluate to false values, and there is no327else clause, then the result of the conditional expression is328unspecified; if there is an else clause, then its <expression>s are329evaluated, and the value(s) of the last one is(are) returned.330331 (cond ((> 3 2) 'greater)332 ((< 3 2) 'less)) ===> greater333 (cond ((> 3 3) 'greater)334 ((< 3 3) 'less)335 (else 'equal)) ===> equal336 (cond ((assv 'b '((a 1) (b 2))) => cadr)337 (else #f)) ===> 2338339340As an extension to R7RS, CHICKEN also supports the341[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:342343 (<generator> <guard> => <expression>)344345In this situation, {{generator}} is ''always'' evaluated. Its346resulting value(s) are used as argument(s) for the {{guard}}347procedure. Finally, if {{guard}} returns a non-{{#f}} value, the348{{expression}} is evaluated by calling it with the result of349{{guard}}. Otherwise, evaluation procedes to the next clause.350351<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>352353Syntax: <Key> may be any expression. Each <clause> should have the form354355 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),356357where each <datum> is an external representation of some object.358Alternatively, as per R7RS, a <clause> may be of the form359360 ((<datum[1]> ...) => <expression>).361362All the <datum>s must be distinct. The last <clause> may be an363"else clause," which has one of the following two forms:364365 (else <expression[1]> <expression[2]> ...)366 (else => <expression>).367368Semantics: A case expression is evaluated as follows. <Key> is369evaluated and its result is compared against each <datum>. If the370result of evaluating <key> is equivalent (in the sense of {{eqv?}};371see [[#equivalence-predicates|below]]) to a <datum>, then the372expressions in the corresponding <clause> are evaluated from left to373right and the result(s) of the last expression in the <clause> is(are)374returned as the result(s) of the case expression. If the selected375<clause> uses the => alternate form (an R7RS extension), then the376<expression> is evaluated. Its value must be a procedure that accepts377one argument; this procedure is then called on the value of the <key>378and the value(s) returned by this procedure is(are) returned by the379case expression. If the result of evaluating <key> is different from380every <datum>, then if there is an else clause its expressions are381evaluated and the result(s) of the last is(are) the result(s) of the382case expression; otherwise the result of the case expression is383unspecified.384385 (case (* 2 3)386 ((2 3 5 7) 'prime)387 ((1 4 6 8 9) 'composite)) ===> composite388 (case (car '(c d))389 ((a) 'a)390 ((b) 'b)) ===> unspecified391 (case (car '(c d))392 ((a e i o u) 'vowel)393 ((w y) 'semivowel)394 (else 'consonant)) ===> consonant395396<macro>(and <test[1]> ...)</macro><br>397398The <test> expressions are evaluated from left to right, and the value399of the first expression that evaluates to a false value (see400[[#Booleans|the section about booleans]]) is returned. Any remaining401expressions are not evaluated. If all the expressions evaluate to true402values, the value of the last expression is returned. If there are no403expressions then #t is returned.404405 (and (= 2 2) (> 2 1)) ===> #t406 (and (= 2 2) (< 2 1)) ===> #f407 (and 1 2 'c '(f g)) ===> (f g)408 (and) ===> #t409410<macro>(or <test[1]> ...)</macro><br>411412The <test> expressions are evaluated from left to right, and the value413of the first expression that evaluates to a true value (see414[[#Booleans|the section about booleans]]) is returned. Any remaining415expressions are not evaluated. If all expressions evaluate to false416values, the value of the last expression is returned. If there are no417expressions then #f is returned.418419 (or (= 2 2) (> 2 1)) ===> #t420 (or (= 2 2) (< 2 1)) ===> #t421 (or #f #f #f) ===> #f422 (or (memq 'b '(a b c))423 (/ 3 0)) ===> (b c)424425<macro>(unless TEST EXP1 EXP2 ...)</macro>426427Equivalent to:428429<enscript highlight=scheme>430(if (not TEST) (begin EXP1 EXP2 ...))431</enscript>432433<macro>(when TEST EXP1 EXP2 ...)</macro>434435Equivalent to:436437<enscript highlight=scheme>438(if TEST (begin EXP1 EXP2 ...))439</enscript>440441<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>442443The {{cond-expand}} expression type provides a way444to statically expand different expressions depending on the445implementation. A <ce-clause> takes the following form:446447{{448(<feature requirement> <expression> ...)449}}450451The last clause can be an "else clause," which has the form452453{{454(else <expression> ...)455}}]456457A ⟨feature requirement⟩ takes one of the following forms:458459<feature identifier>460461{{(library <library name>)}}462463{{(and <feature requirement> ...)}}464465{{(or <feature requirement> ...)}}466467{{(not <feature requirement>)}}468469Each implementation maintains a list of470feature identifiers which are present, as well as a list471of libraries which can be imported.472The value of a <feature requirement> is determined by replacing each473<feature identifier> and {{(library <library name>)}} on the474implementation’s lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under475the normal interpretation of {{and}}, {{or}}, and {{not}}.476477A {{cond-expand}} is then expanded by evaluating the478<feature requirement>s of successive <ce-clause>s in order479until one of them returns {{#t}}. When a true clause is found,480the corresponding <expression>s are expanded to a {{begin}},481and the remaining clauses are ignored.482483If none of the484<feature requirement>s evaluate to {{#t}}, then if there is an485{{else}} clause, its <expression>s are included. Otherwise, the486behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},487{{cond-expand}} does not depend on the value of any variables.488489The following features are built-in and always available by default:490{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},491{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},492{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},493{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.494495There are also situation-specific feature identifiers: {{compiling}} during496compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}497when running within the compiler.498499The symbols returned by the following procedures from500[[Module (chicken platform)|(chicken platform)]] are also available501as feature-identifiers in all situations: {{(machine-byte-order)}},502{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For503example, the {{machine-type}} class of feature-identifiers include504{{arm}}, {{alpha}}, {{mips}}, etc.505506Platform endianness is indicated by the {{little-endian}} and {{big-endian}}507features.508509In addition the following feature-identifiers may exist: {{cross-chicken}},510{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.511512513==== Binding constructs514515The three binding constructs let, let*, and letrec give Scheme a block516structure, like Algol 60. The syntax of the three constructs is517identical, but they differ in the regions they establish for their518variable bindings. In a let expression, the initial values are computed519before any of the variables become bound; in a let* expression, the520bindings and evaluations are performed sequentially; while in a letrec521expression, all the bindings are in effect while their initial values522are being computed, thus allowing mutually recursive definitions.523524<macro>(let <bindings> <body>)</macro><br>525526Syntax: <Bindings> should have the form527528 ((<variable[1]> <init[1]>) ...),529530where each <init> is an expression, and <body> should be a sequence of531one or more expressions. It is an error for a <variable> to appear more532than once in the list of variables being bound.533534Semantics: The <init>s are evaluated in the current environment (in535some unspecified order), the <variable>s are bound to fresh locations536holding the results, the <body> is evaluated in the extended537environment, and the value(s) of the last expression of <body> is(are)538returned. Each binding of a <variable> has <body> as its region.539540 (let ((x 2) (y 3))541 (* x y)) ===> 6542543 (let ((x 2) (y 3))544 (let ((x 7)545 (z (+ x y)))546 (* z x))) ===> 35547548See also "named let", [[#iteration|below]].549550<macro>(let* <bindings> <body>)</macro><br>551552Syntax: <Bindings> should have the form553554 ((<variable[1]> <init[1]>) ...),555556and <body> should be a sequence of one or more expressions.557558Semantics: Let* is similar to let, but the bindings are performed559sequentially from left to right, and the region of a binding indicated560by (<variable> <init>) is that part of the let* expression to the right561of the binding. Thus the second binding is done in an environment in562which the first binding is visible, and so on.563564 (let ((x 2) (y 3))565 (let* ((x 7)566 (z (+ x y)))567 (* z x))) ===> 70568569<macro>(letrec <bindings> <body>)</macro><br>570571Syntax: <Bindings> should have the form572573 ((<variable[1]> <init[1]>) ...),574575and <body> should be a sequence of one or more expressions. It is an576error for a <variable> to appear more than once in the list of577variables being bound.578579Semantics: The <variable>s are bound to fresh locations holding580undefined values, the <init>s are evaluated in the resulting581environment (in some unspecified order), each <variable> is assigned to582the result of the corresponding <init>, the <body> is evaluated in the583resulting environment, and the value(s) of the last expression in584<body> is(are) returned. Each binding of a <variable> has the entire585letrec expression as its region, making it possible to define mutually586recursive procedures.587588 (letrec ((even?589 (lambda (n)590 (if (zero? n)591 #t592 (odd? (- n 1)))))593 (odd?594 (lambda (n)595 (if (zero? n)596 #f597 (even? (- n 1))))))598 (even? 88))599 ===> #t600601One restriction on letrec is very important: it must be possible to602evaluate each <init> without assigning or referring to the value of any603<variable>. If this restriction is violated, then it is an error. The604restriction is necessary because Scheme passes arguments by value605rather than by name. In the most common uses of letrec, all the <init>s606are lambda expressions and the restriction is satisfied automatically.607608<macro>(letrec* <bindings> <body>) </macro>609610Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}}, and611<body> is a sequence of zero or more612definitions followed by one or more expressions as described in section 4.1.4.613It is an error for a <variable> to appear more than once in the list of614variables being bound.615616Semantics: The <variable>s are bound to fresh locations, each <variable> is617assigned in left-to-right order to the result of evaluating the corresponding618<init> (interleaving evaluations and assignments), the <body> is evaluated in619the resulting environment, and the values of the last expression in <body> are620returned. Despite the left-to-right evaluation and assignment order, each621binding of a <variable> has the entire letrec* expression as its region, making622it possible to define mutually recursive procedures.623624If it is not possible to evaluate each <init> without assigning or referring to625the value of the corresponding <variable> or the <variable> of any of the626bindings that follow it in <bindings>, it is an error. Another restriction is627that it is an error to invoke the continuation of an <init> more than once.628629 ;; Returns the arithmetic, geometric, and630 ;; harmonic means of a nested list of numbers631 (define (means ton)632 (letrec*633 ((mean634 (lambda (f g)635 (f (/ (sum g ton) n))))636 (sum637 (lambda (g ton)638 (if (null? ton)639 (+)640 (if (number? ton)641 (g ton)642 (+ (sum g (car ton))643 (sum g (cdr ton)))))))644 (n (sum (lambda (x) 1) ton)))645 (values (mean values values)646 (mean exp log)647 (mean / /))))648649Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666650(approximately), and 36/19.651652<macro>(let-values <mv binding spec> <body>)</macro>653654Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},655where each <init> is an expression, and <body> is656zero or more definitions followed by a sequence of one or more expressions as657described in section 4.1.4. It is an error for a variable to appear more than658once in the set of <formals>.659660Semantics: The <init>s are evaluated in the current environment (in some661unspecified order) as if by invoking call-with-values, and the variables662occurring in the <formals> are bound to fresh locations holding the values663returned by the <init>s, where the <formals> are matched to the return values664in the same way that the <formals> in a lambda expression are matched to the665arguments in a procedure call. Then, the <body> is evaluated in the extended666environment, and the values of the last expression of <body> are returned. Each667binding of a <variable> has <body> as its region.668669It is an error if the <formals> do not match the number of values returned by670the corresponding <init>.671672 (let-values (((root rem) (exact-integer-sqrt 32)))673 (* root rem)) ==> 35674675<macro>(let*-values <mv binding spec> <body>)</macro>676677Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},678and <body> is a sequence of zero or more definitions679followed by one or more expressions as described in section 4.1.4. In each680<formals>, it is an error if any variable appears more than once.681682Semantics: The let*-values construct is similar to let-values, but the <init>s683are evaluated and bindings created sequentially from left to right, with the684region of the bindings of each <formals> including the <init>s to its right as685well as <body>. Thus the second <init> is evaluated in an environment in which686the first set of bindings is visible and initialized, and so on.687688 (let ((a 'a) (b 'b) (x 'x) (y 'y))689 (let*-values (((a b) (values x y))690 ((x y) (values a b)))691 (list a b x y))) ⟹ (x y x y)692693==== Sequencing694695<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>696697The <expression>s are evaluated sequentially from left to right, and698the value(s) of the last <expression> is(are) returned. This expression699type is used to sequence side effects such as input and output.700701 (define x 0)702703 (begin (set! x 5)704 (+ x 1)) ===> 6705706 (begin (display "4 plus 1 equals ")707 (display (+ 4 1))) ===> unspecified708 and prints 4 plus 1 equals 5709710As an extension to R7RS, CHICKEN also allows {{(begin)}} without body711expressions in any context, not just at toplevel. This simply712evaluates to the unspecified value.713714715==== Iteration716717<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>718719Do is an iteration construct. It specifies a set of variables to be720bound, how they are to be initialized at the start, and how they are to721be updated on each iteration. When a termination condition is met, the722loop exits after evaluating the <expression>s.723724Do expressions are evaluated as follows: The <init> expressions are725evaluated (in some unspecified order), the <variable>s are bound to726fresh locations, the results of the <init> expressions are stored in727the bindings of the <variable>s, and then the iteration phase begins.728729Each iteration begins by evaluating <test>; if the result is false730(see [[#Booleans|the section about booleans]]), then the <command>731expressions are evaluated in order for effect, the <step> expressions732are evaluated in some unspecified order, the <variable>s are bound to733fresh locations, the results of the <step>s are stored in the bindings734of the <variable>s, and the next iteration begins.735736If <test> evaluates to a true value, then the <expression>s are737evaluated from left to right and the value(s) of the last <expression>738is(are) returned. If no <expression>s are present, then the value of739the do expression is unspecified.740741The region of the binding of a <variable> consists of the entire do742expression except for the <init>s. It is an error for a <variable> to743appear more than once in the list of do variables.744745A <step> may be omitted, in which case the effect is the same as if746(<variable> <init> <variable>) had been written instead of (<variable>747<init>).748749 (do ((vec (make-vector 5))750 (i 0 (+ i 1)))751 ((= i 5) vec)752 (vector-set! vec i i)) ===> #(0 1 2 3 4)753754 (let ((x '(1 3 5 7 9)))755 (do ((x x (cdr x))756 (sum 0 (+ sum (car x))))757 ((null? x) sum))) ===> 25758759<macro>(let <variable> <bindings> <body>)</macro><br>760761"Named let" is a variant on the syntax of let which provides a more762general looping construct than do and may also be used to express763recursions. It has the same syntax and semantics as ordinary let except764that <variable> is bound within <body> to a procedure whose formal765arguments are the bound variables and whose body is <body>. Thus the766execution of <body> may be repeated by invoking the procedure named by767<variable>.768769 (let loop ((numbers '(3 -2 1 6 -5))770 (nonneg '())771 (neg '()))772 (cond ((null? numbers) (list nonneg neg))773 ((>= (car numbers) 0)774 (loop (cdr numbers)775 (cons (car numbers) nonneg)776 neg))777 ((< (car numbers) 0)778 (loop (cdr numbers)779 nonneg780 (cons (car numbers) neg)))))781 ===> ((6 1 3) (-5 -2))782783==== Dynamic bindings784785The dynamic extent of a procedure call is the time between when it is initiated786and when it returns. In Scheme, {{call-with-current-continuation}}787allows reentering a dynamic extent after its procedure call has returned. Thus,788the dynamic extent of a call might not be a single, continuous time period.789790This sections introduces parameter objects, which can be bound to new values791for the duration of a dynamic extent. The set of all parameter bindings at a792given time is called the dynamic environment.793794<procedure>(make-parameter init [converter])</procedure>795796Returns a newly allocated parameter object, which is a procedure that accepts797zero arguments and returns the value associated with the parameter object.798Initially, this value is the value of {{(converter init)}}, or of {{init}}799if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed800using {{parameterize}}, which is described below.801802The effect of passing arguments to a parameter object is803implementation-dependent.804805<syntax>(parameterize ((<param[1]> <value[1]>) ...) <body>)</syntax>806807Syntax: Both <param[1]> and <value[1]> are expressions.808809It is an error if the value of any <param> expression is not a parameter810object.811812Semantics: A parameterize expression is used to change the values returned by813specified parameter objects during the evaluation of the body.814815The <param> and <value> expressions are evaluated in an unspecified order. The816<body> is evaluated in a dynamic environment in which calls to the parameters817return the results of passing the corresponding values to the conversion818procedure specified when the parameters were created. Then the previous values819of the parameters are restored without passing them to the conversion820procedure. The results of the last expression in the <body> are returned as the821results of the entire parameterize expression.822823Note: If the conversion procedure is not idempotent, the results of824(parameterize ((x (x))) ...), which appears to bind the parameter825826x to its current value, might not be what the user expects.827828If an implementation supports multiple threads of execution, then parameterize829must not change the associated values of any parameters in any thread other830than the current thread and threads created inside <body>.831832Parameter objects can be used to specify configurable settings for a833computation without the need to pass the value to every procedure in the call834chain explicitly.835836 (define radix837 (make-parameter838 10839 (lambda (x)840 (if (and (exact-integer? x) (<= 2 x 16))841 x842 (error "invalid radix")))))843844 (define (f n) (number->string n (radix)))845846 (f 12) ==> "12"847 (parameterize ((radix 2))848 (f 12)) ==> "1100"849 (f 12) ==> "12"850851 (radix 16) ==> unspecified852853 (parameterize ((radix 0))854 (f 12)) ==> error855856==== Exception handling857858<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>859860Syntax: Each <cond clause> is as in the specification of cond.861862Semantics: The <body> is evaluated with an exception handler that binds the863raised object (see {{raise}}) to <variable> and, within the scope864of that binding, evaluates the clauses as if they were the clauses of a cond865expression. That implicit cond expression is evaluated with the continuation866and dynamic environment of the guard expression. If every <cond clause>'s867<test> evaluates to #f and there is no else clause, then raise-continuable is868invoked on the raised object within the dynamic environment of the original869call to raise or raise-continuable, except that the current exception handler870is that of the guard expression.871872 (guard (condition873 ((assq 'a condition) => cdr)874 ((assq 'b condition)))875 (raise (list (cons 'a 42))))876 ==> 42877878 (guard (condition879 ((assq 'a condition) => cdr)880 ((assq 'b condition)))881 (raise (list (cons 'b 23))))882 ==> (b . 23)883884==== Quasiquotation885886<macro>(quasiquote <qq template>)</macro><br>887<macro>`<qq template></macro><br>888889"Backquote" or "quasiquote" expressions are useful for constructing890a list or vector structure when most but not all of the desired891structure is known in advance. If no commas appear within the <qq892template>, the result of evaluating `<qq template> is equivalent to the893result of evaluating '<qq template>. If a comma appears within the <qq894template>, however, the expression following the comma is evaluated895("unquoted") and its result is inserted into the structure instead of896the comma and the expression. If a comma appears followed immediately897by an at-sign (@), then the following expression must evaluate to a898list; the opening and closing parentheses of the list are then899"stripped away" and the elements of the list are inserted in place of900the comma at-sign expression sequence. A comma at-sign should only901appear within a list or vector <qq template>.902903 `(list ,(+ 1 2) 4) ===> (list 3 4)904 (let ((name 'a)) `(list ,name ',name))905 ===> (list a (quote a))906 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)907 ===> (a 3 4 5 6 b)908 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))909 ===> ((foo 7) . cons)910 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)911 ===> #(10 5 2 4 3 8)912913Quasiquote forms may be nested. Substitutions are made only for914unquoted components appearing at the same nesting level as the915outermost backquote. The nesting level increases by one inside each916successive quasiquotation, and decreases by one inside each917unquotation.918919 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)920 ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)921 (let ((name1 'x)922 (name2 'y))923 `(a `(b ,,name1 ,',name2 d) e))924 ===> (a `(b ,x ,'y d) e)925926The two notations `<qq template> and (quasiquote <qq template>) are927identical in all respects. ,<expression> is identical to (unquote928<expression>), and ,@<expression> is identical to (unquote-splicing929<expression>). The external syntax generated by write for two-element930lists whose car is one of these symbols may vary between931implementations.932933 (quasiquote (list (unquote (+ 1 2)) 4))934 ===> (list 3 4)935 '(quasiquote (list (unquote (+ 1 2)) 4))936 ===> `(list ,(+ 1 2) 4)937 i.e., (quasiquote (list (unquote (+ 1 2)) 4))938939Unpredictable behavior can result if any of the symbols quasiquote,940unquote, or unquote-splicing appear in positions within a <qq template>941otherwise than as described above.942943=== Macros944945Scheme programs can define and use new derived expression types, called946macros. Program-defined expression types have the syntax947948 (<keyword> <datum> ...)949950where <keyword> is an identifier that uniquely determines the951expression type. This identifier is called the syntactic keyword, or952simply keyword, of the macro. The number of the <datum>s, and their953syntax, depends on the expression type.954955Each instance of a macro is called a use of the macro. The set of rules956that specifies how a use of a macro is transcribed into a more957primitive expression is called the transformer of the macro.958959The macro definition facility consists of two parts:960961* A set of expressions used to establish that certain identifiers are962 macro keywords, associate them with macro transformers, and control963 the scope within which a macro is defined, and964965* a pattern language for specifying macro transformers.966967The syntactic keyword of a macro may shadow variable bindings, and968local variable bindings may shadow keyword bindings. All macros defined969using the pattern language are "hygienic" and "referentially970transparent" and thus preserve Scheme's lexical scoping:971972* If a macro transformer inserts a binding for an identifier973 (variable or keyword), the identifier will in effect be renamed974 throughout its scope to avoid conflicts with other identifiers.975 Note that a define at top level may or may not introduce a binding;976 this depends on whether the binding already existed before (in which977 case its value will be overridden).978979* If a macro transformer inserts a free reference to an identifier,980 the reference refers to the binding that was visible where the981 transformer was specified, regardless of any local bindings that982 may surround the use of the macro.983984==== Binding constructs for syntactic keywords985986Let-syntax and letrec-syntax are analogous to let and letrec, but they987bind syntactic keywords to macro transformers instead of binding988variables to locations that contain values. Syntactic keywords may also989be bound at top level.990991<macro>(let-syntax <bindings> <body>)</macro><br>992993Syntax: <Bindings> should have the form994995 ((<keyword> <transformer spec>) ...)996997Each <keyword> is an identifier, each <transformer spec> is an instance998of syntax-rules, and <body> should be a sequence of one or more999expressions. It is an error for a <keyword> to appear more than once in1000the list of keywords being bound.10011002Semantics: The <body> is expanded in the syntactic environment obtained1003by extending the syntactic environment of the let-syntax expression1004with macros whose keywords are the <keyword>s, bound to the specified1005transformers. Each binding of a <keyword> has <body> as its region.10061007 (let-syntax ((when (syntax-rules ()1008 ((when test stmt1 stmt2 ...)1009 (if test1010 (begin stmt11011 stmt2 ...))))))1012 (let ((if #t))1013 (when if (set! if 'now))1014 if)) ===> now10151016 (let ((x 'outer))1017 (let-syntax ((m (syntax-rules () ((m) x))))1018 (let ((x 'inner))1019 (m)))) ===> outer10201021<macro>(letrec-syntax <bindings> <body>)</macro><br>10221023Syntax: Same as for let-syntax.10241025Semantics: The <body> is expanded in the syntactic environment obtained1026by extending the syntactic environment of the letrec-syntax expression1027with macros whose keywords are the <keyword>s, bound to the specified1028transformers. Each binding of a <keyword> has the <bindings> as well as1029the <body> within its region, so the transformers can transcribe1030expressions into uses of the macros introduced by the letrec-syntax1031expression.10321033 (letrec-syntax1034 ((my-or (syntax-rules ()1035 ((my-or) #f)1036 ((my-or e) e)1037 ((my-or e1 e2 ...)1038 (let ((temp e1))1039 (if temp1040 temp1041 (my-or e2 ...)))))))1042 (let ((x #f)1043 (y 7)1044 (temp 8)1045 (let odd?)1046 (if even?))1047 (my-or x1048 (let temp)1049 (if y)1050 y))) ===> 710511052==== Pattern language10531054A <transformer spec> has the following form:10551056 (syntax-rules <literals> <syntax rule> ...)10571058Syntax: <Literals> is a list of identifiers and each <syntax rule>1059should be of the form10601061 (<pattern> <template>)10621063The <pattern> in a <syntax rule> is a list <pattern> that begins with1064the keyword for the macro.10651066A <pattern> is either an identifier, a constant, or one of the1067following10681069 (<pattern> ...)1070 (<pattern> <pattern> ... . <pattern>)1071 (<pattern> ... <pattern> <ellipsis> <pattern> ...)1072 #(<pattern> ...)1073 #(<pattern> ... <pattern> <ellipsis>)10741075and a template is either an identifier, a constant, or one of the1076following10771078 (<element> ...)1079 (<element> <element> ... . <template>)1080 (<ellipsis> <template>)1081 #(<element> ...)10821083where an <element> is a <template> optionally followed by an <ellipsis>1084and an <ellipsis> is the identifier "...".10851086Semantics: An instance of syntax-rules produces a new macro transformer1087by specifying a sequence of hygienic rewrite rules. A use of a macro1088whose keyword is associated with a transformer specified by1089syntax-rules is matched against the patterns contained in the <syntax1090rule>s, beginning with the leftmost <syntax rule>. When a match is1091found, the macro use is transcribed hygienically according to the1092template.10931094An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal1095identifier listed in the list of <pattern literal>s, or the <ellipsis>. All1096other identifiers appearing within a <pattern> are pattern variables.10971098The keyword at the beginning of the pattern in a <syntax rule> is not involved1099in the matching and is considered neither a pattern variable nor a literal1100identifier.11011102Pattern variables match arbitrary input elements and are used to refer to1103elements of the input in the template. It is an error for the same pattern1104variable to appear more than once in a <pattern>.11051106Underscores also match arbitrary input elements but are not pattern variables1107and so cannot be used to refer to those elements. If an underscore appears in1108the <pattern literal>s list, then that takes precedence and underscores in the1109<pattern> match as literals. Multiple underscores can appear in a <pattern>.11101111Identifiers that appear in (<pattern literal> …) are interpreted as literal1112identifiers to be matched against corresponding elements of the input. An1113element in the input matches a literal identifier if and only if it is an1114identifier and either both its occurrence in the macro expression and its1115occurrence in the macro definition have the same lexical binding, or the two1116identifiers are the same and both have no lexical binding.11171118A subpattern followed by <ellipsis> can match zero or more elements of the1119input, unless <ellipsis> appears in the <pattern literal>s, in which case it is1120matched as a literal.11211122More formally, an input form F matches a pattern P if and only if:11231124* P is an underscore (_).11251126* P is a non-literal identifier; or11271128* P is a literal identifier and F is an identifier with the same1129 binding; or11301131* P is a list (P[1] ... P[n]) and F is a list of n forms that match P1132 [1] through P[n], respectively; or11331134* P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list1135 or improper list of n or more forms that match P[1] through P[n],1136 respectively, and whose nth "cdr" matches P[n+1]; or11371138* P is of the form (P[1] … P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E1139 is a list or improper list of n elements, the first k of which match P[1]1140 through P[k], whose next m−k elements each match P[e], whose remaining n−m1141 elements match P[m+1] through P[n], and whose nth and final cdr matches P[x1142 ]; or11431144* P is a vector of the form #(P[1] ... P[n]) and F is a vector of n1145 forms that match P[1] through P[n]; or11461147* P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a1148 vector of n elements the first k of which match P[1] through P[k], whose1149 next m−k elements each match P[e], and whose remaining n−m elements match P1150 [m+1] through P[n]; or11511152* P is a datum and F is equal to P in the sense of the equal?1153 procedure.11541155It is an error to use a macro keyword, within the scope of its binding,1156in an expression that does not match any of the patterns.11571158When a macro use is transcribed according to the template of the matching1159<syntax rule>, pattern variables that occur in the template are replaced by the1160elements they match in the input. Pattern variables that occur in subpatterns1161followed by one or more instances of the identifier <ellipsis> are allowed only1162in subtemplates that are followed by as many instances of <ellipsis>. They are1163replaced in the output by all of the elements they match in the input,1164distributed as indicated. It is an error if the output cannot be built up as1165specified.11661167Identifiers that appear in the template but are not pattern variables or the1168identifier <ellipsis> are inserted into the output as literal identifiers. If a1169literal identifier is inserted as a free identifier then it refers to the1170binding of that identifier within whose scope the instance of syntax-rules1171appears. If a literal identifier is inserted as a bound identifier then it is1172in effect renamed to prevent inadvertent captures of free identifiers.11731174A template of the form (<ellipsis> <template>) is identical to <template>,1175except that ellipses within the template have no special meaning. That is, any1176ellipses contained within <template> are treated as ordinary identifiers. In1177particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.1178This allows syntactic abstractions to expand into code containing ellipses.11791180{{1181(define-syntax be-like-begin1182 (syntax-rules ()1183 ((be-like-begin name)1184 (define-syntax name1185 (syntax-rules ()1186 ((name expr (... ...))1187 (begin expr (... ...))))))))11881189(be-like-begin sequence)11901191(sequence 1 2 3 4) ==> 41192}}11931194As an example, if {{let}} and {{cond}} have their standard meaning1195then they are hygienic (as required) and the following is not an1196error.11971198 (let ((=> #f))1199 (cond (#t => 'ok))) ===> ok12001201The macro transformer for cond recognizes => as a local variable, and1202hence an expression, and not as the top-level identifier =>, which the1203macro transformer treats as a syntactic keyword. Thus the example1204expands into12051206 (let ((=> #f))1207 (if #t (begin => 'ok)))12081209instead of12101211 (let ((=> #f))1212 (let ((temp #t))1213 (if temp ('ok temp))))12141215which would result in an invalid procedure call.12161217==== Signaling errors in macro transformers12181219<macro>(syntax-error <message> <args> ...)</macro>12201221{{syntax-error}} behaves similarly to {{error}} except that implementations with1222an expansion pass separate from evaluation should signal an error as soon as1223{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a1224<pattern> that is an invalid use of the macro, which can provide more1225descriptive error messages. <message> is a string literal, and <args> arbitrary1226expressions providing additional information. Applications cannot count on1227being able to catch syntax errors with exception handlers or guards.12281229 (define-syntax simple-let1230 (syntax-rules ()1231 ((_ (head ... ((x . y) val) . tail)1232 body1 body2 ...)1233 (syntax-error1234 "expected an identifier but got"1235 (x . y)))1236 ((_ ((name val) ...) body1 body2 ...)1237 ((lambda (name ...) body1 body2 ...)1238 val ...))))123912401241== Program structure12421243=== Programs12441245A Scheme program consists of a sequence of expressions, definitions,1246and syntax definitions. Expressions are described in chapter 4;1247definitions and syntax definitions are the subject of the rest of the1248present chapter.12491250Programs are typically stored in files or entered interactively to a1251running Scheme system, although other paradigms are possible;1252questions of user interface lie outside the scope of this1253report. (Indeed, Scheme would still be useful as a notation for1254expressing computational methods even in the absence of a mechanical1255implementation.)12561257Definitions and syntax definitions occurring at the top level of a1258program can be interpreted declaratively. They cause bindings to be1259created in the top level environment or modify the value of existing1260top-level bindings. Expressions occurring at the top level of a1261program are interpreted imperatively; they are executed in order when1262the program is invoked or loaded, and typically perform some kind of1263initialization.12641265At the top level of a program (begin <form1> ...) is equivalent to the1266sequence of expressions, definitions, and syntax definitions that form1267the body of the begin.12681269=== Import declarations12701271<macro>(import IMPORT-SET ...)</macro>12721273An import declaration provides a way to import identifiers exported by a1274library. Each <import set> names a set of bindings from a library and possibly1275specifies local names for the imported bindings. It takes one of the following1276forms:12771278* <library name>12791280* {{(only <import set> <identifier> ...)}}12811282* {{(except <import set> <identifier> ...)}}12831284* {{(prefix <import set> <identifier>)}}12851286* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}12871288In the first form, all of the identifiers in the named library’s export clauses1289are imported with the same names (or the exported names if exported with rename1290). The additional <import set> forms modify this set as follows:12911292* only produces a subset of the given <import set> including only the listed1293 identifiers (after any renaming). It is an error if any of the listed1294 identifiers are not found in the original set.12951296* except produces a subset of the given <import set>, excluding the listed1297 identifiers (after any renaming). It is an error if any of the listed1298 identifiers are not found in the original set.12991300* rename modifies the given <import set>, replacing each instance of1301 <identifier[1]> with <identifier[2]>. It is an error if any of the listed1302 <identifier[1]>s are not found in the original set.13031304* prefix automatically renames all identifiers in the given <import set>,1305 prefixing each with the specified <identifier>.13061307=== Definitions13081309Definitions are valid in some, but not all, contexts where expressions1310are allowed. They are valid only at the top level of a <program> and1311at the beginning of a <body>.13121313A definition should have one of the following forms:13141315<macro>(define <variable> <expression>)</macro><br>1316<macro>(define (<variable> <formals>) <body>)</macro><br>13171318<Formals> should be either a sequence of zero or more variables, or a1319sequence of one or more variables followed by a space-delimited period1320and another variable (as in a lambda expression). This form is1321equivalent to13221323 (define <variable>1324 (lambda (<formals>) <body>)).13251326<macro>(define <variable>)</macro>13271328This form is a CHICKEN extension to R7RS, and is equivalent to13291330 (define <variable> (void))13311332<macro>(define (<variable> . <formal>) <body>)</macro><br>13331334<Formal> should be a single variable. This form is equivalent to13351336 (define <variable>1337 (lambda <formal> <body>)).13381339<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>13401341As an extension to R7RS, CHICKEN allows ''curried'' definitions, where1342the variable name may also be a list specifying a name and a nested1343lambda list. For example,13441345 (define ((make-adder x) y) (+ x y))13461347is equivalent to13481349 (define (make-adder x) (lambda (y) (+ x y))).13501351This type of curried definition can be nested arbitrarily and combined1352with dotted tail notation or DSSSL keywords.13531354==== Top level definitions13551356At the top level of a program, a definition13571358 (define <variable> <expression>)13591360has essentially the same effect as the assignment expression13611362 (set! <variable> <expression>)13631364if <variable> is bound. If <variable> is not bound, however, then the1365definition will bind <variable> to a new location before performing1366the assignment, whereas it would be an error to perform a set! on an1367unbound variable in standard Scheme. In CHICKEN, {{set!}} at toplevel1368has the same effect as a definition, unless inside a module, in which1369case it is an error.13701371 (define add31372 (lambda (x) (+ x 3)))1373 (add3 3) ===> 61374 (define first car)1375 (first '(1 2)) ===> 113761377Some implementations of Scheme use an initial environment in which all1378possible variables are bound to locations, most of which contain1379undefined values. Top level definitions in such an implementation are1380truly equivalent to assignments. In CHICKEN, attempting to evaluate1381an unbound identifier will result in an error, but you ''can'' use1382{{set!}} to bind an initial value to it.13831384==== Internal definitions13851386Definitions may occur at the beginning of a <body> (that is, the body1387of a lambda, let, let*, letrec, let-syntax, or letrec-syntax1388expression or that of a definition of an appropriate form). Such1389definitions are known as internal definitions as opposed to the top1390level definitions described above. The variable defined by an internal1391definition is local to the <body>. That is, <variable> is bound rather1392than assigned, and the region of the binding is the entire <body>. For1393example,13941395 (let ((x 5))1396 (define foo (lambda (y) (bar x y)))1397 (define bar (lambda (a b) (+ (* a b) a)))1398 (foo (+ x 3))) ===> 4513991400A <body> containing internal definitions can always be converted into1401a completely equivalent letrec expression. For example, the let1402expression in the above example is equivalent to14031404 (let ((x 5))1405 (letrec ((foo (lambda (y) (bar x y)))1406 (bar (lambda (a b) (+ (* a b) a))))1407 (foo (+ x 3))))14081409Just as for the equivalent letrec expression, it must be possible to1410evaluate each <expression> of every internal definition in a <body>1411without assigning or referring to the value of any <variable> being1412defined.14131414Wherever an internal definition may occur (begin <definition1> ...) is1415equivalent to the sequence of definitions that form the body of the1416begin.14171418CHICKEN extends the R7RS semantics by allowing internal definitions1419everywhere, and not only at the beginning of a body. A set of internal1420definitions is equivalent to a {{letrec}} form enclosing all following1421expressions in the body:14221423 (let ((foo 123))1424 (bar)1425 (define foo 456)1426 (baz foo) )14271428expands into14291430 (let ((foo 123))1431 (bar)1432 (letrec ((foo 456))1433 (baz foo) ) )14341435Local sequences of {{define-syntax}} forms are translated into1436equivalent {{letrec-syntax}} forms that enclose the following forms as1437the body of the expression.14381439=== Multiple-value definitions14401441Another kind of definition is provided by define-values, which creates multiple1442definitions from a single expression returning multiple values. It is allowed1443wherever define is allowed.14441445<macro>(define-values <formals> <expression>)</macro>14461447It is an error if a variable appears more than once in the set of <formals>.14481449Semantics: <Expression> is evaluated, and the <formals> are bound to the return1450values in the same way that the <formals> in a lambda expression are matched to1451the arguments in a procedure call.14521453 (define-values (x y) (exact-integer-sqrt 17))1454 (list x y) ==> (4 1)14551456 (let ()1457 (define-values (x y) (values 1 2))1458 (+ x y)) ==> 314591460=== Syntax definitions14611462Syntax definitions are valid only at the top level of a1463<program>. They have the following form:14641465<macro>(define-syntax <keyword> <transformer spec>)</macro>14661467{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should1468be an instance of {{syntax-rules}}. Note that CHICKEN also supports1469{{er-macro-transformer}} and {{ir-macro-transformer}} here. For more1470information see [[Module (chicken syntax)|the (chicken syntax) module]].14711472The top-level syntactic environment is extended by binding the1473<keyword> to the specified transformer.14741475In standard Scheme, there is no define-syntax analogue of internal1476definitions in, but CHICKEN allows these as an extension to the1477standard. This means {{define-syntax}} may be used to define local1478macros that are visible throughout the rest of the body in which the1479definition occurred, i.e.14801481 (let ()1482 ...1483 (define-syntax foo ...)1484 (define-syntax bar ...)1485 ...)14861487is expanded into14881489 (let ()1490 ...1491 (letrec-syntax ((foo ...) (bar ...))1492 ...) )14931494{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]1495in allowing the ellipsis identifier to be user-defined by passing it as the first1496argument to the {{syntax-rules}} form. Also, "tail" patterns of the form14971498 (syntax-rules ()1499 ((_ (a b ... c)1500 ...15011502are supported.15031504The effect of destructively modifying the s-expression passed to a1505transformer procedure is undefined.15061507Although macros may expand into definitions and syntax definitions in1508any context that permits them, it is an error for a definition or1509syntax definition to shadow a syntactic keyword whose meaning is1510needed to determine whether some form in the group of forms that1511contains the shadowing definition is in fact a definition, or, for1512internal definitions, is needed to determine the boundary between the1513group and the expressions that follow the group. For example, the1514following are errors:15151516 (define define 3)15171518 (begin (define begin list))15191520 (let-syntax1521 ((foo (syntax-rules ()1522 ((foo (proc args ...) body ...)1523 (define proc1524 (lambda (args ...)1525 body ...))))))1526 (let ((x 3))1527 (foo (plus x y) (+ x y))1528 (define foo x)1529 (plus foo x)))15301531=== Record-type definitions15321533Record-type definitions are used to introduce new data types, called record1534types. Like other definitions, they can appear either at the outermost level or1535in a body. The values of a record type are called records and are aggregations1536of zero or more fields, each of which holds a single location. A predicate, a1537constructor, and field accessors and mutators are defined for each record type.15381539<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>15401541Syntax: <name> and <pred> are identifiers. The <constructor> is of the form1542{{(<constructor name> <field name> ...)}} and each <field> is either of the form1543{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once1544as a field name. It is also an error for the same identifier to occur more than1545once as an accessor or mutator name.15461547The define-record-type construct is generative: each use creates a new record1548type that is distinct from all existing types, including Scheme’s predefined1549types and other record types — even record types of the same name or structure.15501551An instance of define-record-type is equivalent to the following definitions:15521553* <name> is bound to a representation of the record type itself. This may be1554 a run-time object or a purely syntactic representation. The representation1555 is not utilized in this report, but it serves as a means to identify the1556 record type for use by further language extensions.15571558* <constructor name> is bound to a procedure that takes as many arguments as1559 there are <field name>s in the {{(<constructor name> ...)}} subexpression and1560 returns a new record of type <name>. Fields whose names are listed with1561 <constructor name> have the corresponding argument as their initial value.1562 The initial values of all other fields are unspecified. It is an error for1563 a field name to appear in <constructor> but not as a <field name>.15641565* <pred> is bound to a predicate that returns #t when given a value returned1566 by the procedure bound to <constructor name> and #f for everything else.15671568* Each <accessor name> is bound to a procedure that takes a record of type1569 <name> and returns the current value of the corresponding field. It is an1570 error to pass an accessor a value which is not a record of the appropriate1571 type.15721573* Each <modifier name> is bound to a procedure that takes a record of type1574 <name> and a value which becomes the new value of the corresponding field;1575 an unspecified value is returned. It is an error to pass a modifier a first1576 argument which is not a record of the appropriate type.15771578For instance, the following record-type definition15791580 (define-record-type <pare>1581 (kons x y)1582 pare?1583 (x kar set-kar!)1584 (y kdr))15851586defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a1587modifier, and pare? to be a predicate for instances of <pare>.15881589 (pare? (kons 1 2)) ⟹ #t1590 (pare? (cons 1 2)) ⟹ #f1591 (kar (kons 1 2)) ⟹ 11592 (kdr (kons 1 2)) ⟹ 21593 (let ((k (kons 1 2)))1594 (set-kar! k 3)1595 (kar k)) ⟹ 315961597=== Libraries15981599Libraries provide a way to organize Scheme programs into reusable parts with1600explicitly defined interfaces to the rest of the program. This section defines1601the notation and semantics for libraries.16021603==== Library Syntax16041605A library definition takes the following form:16061607<macro>(define-library <library name> <library declaration> ...)</macro>16081609<library name> is a list whose members are identifiers and exact non-negative1610integers. It is used to identify the library uniquely when importing from other1611programs or libraries. Libraries whose first identifier is scheme are reserved1612for use by this report and future versions of this report. Libraries whose1613first identifier is srfi are reserved for libraries implementing Scheme1614Requests for Implementation. It is inadvisable, but not an error, for1615identifiers in library names to contain any of the characters | \ ? * < " : > +1616[ ] / or control characters after escapes are expanded.16171618A <library declaration> is any of:16191620* {{(export <export spec> ...)}}16211622* {{(import <import set> ...)}}16231624* {{(begin <command or definition> ...)}}16251626* {{(include <filename[1]> <filename[2]> ...)}}16271628* {{(include-ci <filename[1]> <filename[2]> ...)}}16291630* {{(include-library-declarations <filename[1]> <filename[2]> ...)}}16311632* {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}16331634An export declaration specifies a list of identifiers which can be made visible1635to other libraries or programs. An <export spec> takes one of the following1636forms:16371638* <identifier>16391640* {{(rename <identifier[1]> <identifier[2]>)}}16411642In an <export spec>, an <identifier> names a single binding defined within or1643imported into the library, where the external name for the export is the same1644as the name of the binding within the library. A {{rename}} spec exports the1645binding defined within or imported into the library and named by <identifier1646[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>1647as the external name.16481649An import declaration provides a way to import the identifiers exported by1650another library.16511652The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of1653the library. They have the same syntax and semantics as the corresponding1654expression types. This form of begin is analogous to, but not the same as, the1655two types of begin defined in section 4.2.3.16561657The {{include-library-declarations}} declaration is similar to {{include}} except that1658the contents of the file are spliced directly into the current library1659definition. This can be used, for example, to share the same export declaration1660among multiple libraries as a simple form of library interface.16611662The {{cond-expand}} declaration has the same syntax and semantics as the1663{{cond-expand}} expression type, except that it expands to spliced-in library1664declarations rather than expressions enclosed in begin.16651666One possible implementation of libraries is as follows: After all {{cond-expand}}1667library declarations are expanded, a new environment is constructed for the1668library consisting of all imported bindings. The expressions from all begin,1669{{include}} and {{include-ci}} library declarations are expanded in that environment in1670the order in which they occur in the library. Alternatively, {{cond-expand}} and1671{{import}} declarations may be processed in left to right order interspersed with1672the processing of other declarations, with the environment growing as imported1673bindings are added to it by each import declaration.16741675When a library is loaded, its expressions are executed in textual order. If a1676library’s definitions are referenced in the expanded form of a program or1677library body, then that library must be loaded before the expanded program or1678library body is evaluated. This rule applies transitively. If a library is1679imported by more than one program or library, it may possibly be loaded1680additional times.16811682Similarly, during the expansion of a library (foo), if any syntax keywords1683imported from another library (bar) are needed to expand the library, then the1684library (bar) must be expanded and its syntax definitions evaluated before the1685expansion of (foo).168616871688== Standard procedures16891690This chapter describes Scheme's built-in procedures. The initial (or1691"top level") Scheme environment starts out with a number of variables1692bound to locations containing useful values, most of which are1693primitive procedures that manipulate data. For example, the variable1694abs is bound to (a location initially containing) a procedure of one1695argument that computes the absolute value of a number, and the variable1696+ is bound to a procedure that computes sums. Built-in procedures that1697can easily be written in terms of other built-in procedures are1698identified as "library procedures".16991700A program may use a top-level definition to bind any variable. It may1701subsequently alter any such binding by an assignment (see1702[[#assignments|assignments]], above). These operations do1703not modify the behavior of Scheme's built-in procedures. Altering any1704top-level binding that has not been introduced by a definition has an1705unspecified effect on the behavior of the built-in procedures.17061707=== Equivalence predicates17081709A predicate is a procedure that always returns a boolean value (#t or #f).1710An equivalence predicate is the computational analogue of a1711mathematical equivalence relation (it is symmetric, reflexive, and1712transitive). Of the equivalence predicates described in this section,1713eq? is the finest or most discriminating, and equal? is the coarsest.1714eqv? is slightly less discriminating than eq?.17151716<procedure>(eqv? obj[1] obj[2])</procedure><br>17171718The eqv? procedure defines a useful equivalence relation on objects.1719Briefly, it returns #t if obj[1] and obj[2] should normally be regarded1720as the same object. This relation is left slightly open to1721interpretation, but the following partial specification of eqv? holds1722for all implementations of Scheme.17231724The eqv? procedure returns #t if:17251726* obj[1] and obj[2] are both #t or both #f.17271728* obj[1] and obj[2] are both symbols and17291730 (string=? (symbol->string obj1)1731 (symbol->string obj2))1732 ===> #t17331734Note: This assumes that neither obj[1] nor obj[2] is an "uninterned1735symbol" as alluded to in the section on [[#symbols|symbols]]. This1736report does not presume to specify the behavior of eqv? on1737implementation-dependent extensions.17381739* obj[1] and obj[2] are both numbers, are numerically equal (see =,1740 under [[#numerical-operations|numerical operations]]), and are1741 either both exact or both inexact.17421743* obj[1] and obj[2] are both characters and are the same character1744 according to the char=? procedure (see "[[#characters|characters]]").17451746* both obj[1] and obj[2] are the empty list.17471748* obj[1] and obj[2] are pairs, vectors, or strings that denote the1749 same locations in the store.17501751* obj[1] and obj[2] are procedures whose location tags are equal1752 (see "[[#procedures|procedures]]").17531754The eqv? procedure returns #f if:17551756* obj[1] and obj[2] are of different types.17571758* one of obj[1] and obj[2] is #t but the other is #f.17591760* obj[1] and obj[2] are symbols but17611762 (string=? (symbol->string obj[1])1763 (symbol->string obj[2]))1764 ===> #f17651766* one of obj[1] and obj[2] is an exact number but the other is an1767 inexact number.17681769* obj[1] and obj[2] are numbers for which the = procedure returns #f.17701771* obj[1] and obj[2] are characters for which the char=? procedure1772 returns #f.17731774* one of obj[1] and obj[2] is the empty list but the other is not.17751776* obj[1] and obj[2] are pairs, vectors, or strings that denote1777 distinct locations.17781779* obj[1] and obj[2] are procedures that would behave differently1780 (return different value(s) or have different side effects) for some1781 arguments.17821783 (eqv? 'a 'a) ===> #t1784 (eqv? 'a 'b) ===> #f1785 (eqv? 2 2) ===> #t1786 (eqv? '() '()) ===> #t1787 (eqv? 100000000 100000000) ===> #t1788 (eqv? (cons 1 2) (cons 1 2)) ===> #f1789 (eqv? (lambda () 1)1790 (lambda () 2)) ===> #f1791 (eqv? #f 'nil) ===> #f1792 (let ((p (lambda (x) x)))1793 (eqv? p p)) ===> #t17941795The following examples illustrate cases in which the above rules do not1796fully specify the behavior of eqv?. All that can be said about such1797cases is that the value returned by eqv? must be a boolean.17981799 (eqv? "" "") ===> unspecified1800 (eqv? '#() '#()) ===> unspecified1801 (eqv? (lambda (x) x)1802 (lambda (x) x)) ===> unspecified1803 (eqv? (lambda (x) x)1804 (lambda (y) y)) ===> unspecified18051806The next set of examples shows the use of eqv? with procedures that1807have local state. Gen-counter must return a distinct procedure every1808time, since each procedure has its own internal counter. Gen-loser,1809however, returns equivalent procedures each time, since the local state1810does not affect the value or side effects of the procedures.18111812 (define gen-counter1813 (lambda ()1814 (let ((n 0))1815 (lambda () (set! n (+ n 1)) n))))1816 (let ((g (gen-counter)))1817 (eqv? g g)) ===> #t1818 (eqv? (gen-counter) (gen-counter))1819 ===> #f1820 (define gen-loser1821 (lambda ()1822 (let ((n 0))1823 (lambda () (set! n (+ n 1)) 27))))1824 (let ((g (gen-loser)))1825 (eqv? g g)) ===> #t1826 (eqv? (gen-loser) (gen-loser))1827 ===> unspecified18281829 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))1830 (g (lambda () (if (eqv? f g) 'both 'g))))1831 (eqv? f g))1832 ===> unspecified18331834 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))1835 (g (lambda () (if (eqv? f g) 'g 'both))))1836 (eqv? f g))1837 ===> #f18381839Since it is an error to modify constant objects (those returned by1840literal expressions), implementations are permitted, though not1841required, to share structure between constants where appropriate. Thus1842the value of eqv? on constants is sometimes implementation-dependent.18431844 (eqv? '(a) '(a)) ===> unspecified1845 (eqv? "a" "a") ===> unspecified1846 (eqv? '(b) (cdr '(a b))) ===> unspecified1847 (let ((x '(a)))1848 (eqv? x x)) ===> #t18491850Rationale: The above definition of eqv? allows implementations1851latitude in their treatment of procedures and literals:1852implementations are free either to detect or to fail to detect that1853two procedures or two literals are equivalent to each other, and1854can decide whether or not to merge representations of equivalent1855objects by using the same pointer or bit pattern to represent both.18561857<procedure>(eq? obj[1] obj[2])</procedure><br>18581859Eq? is similar to eqv? except that in some cases it is capable of1860discerning distinctions finer than those detectable by eqv?.18611862Eq? and eqv? are guaranteed to have the same behavior on symbols,1863booleans, the empty list, pairs, procedures, and non-empty strings and1864vectors. Eq?'s behavior on numbers and characters is1865implementation-dependent, but it will always return either true or1866false, and will return true only when eqv? would also return true. Eq?1867may also behave differently from eqv? on empty vectors and empty1868strings.18691870 (eq? 'a 'a) ===> #t1871 (eq? '(a) '(a)) ===> unspecified1872 (eq? (list 'a) (list 'a)) ===> #f1873 (eq? "a" "a") ===> unspecified1874 (eq? "" "") ===> unspecified1875 (eq? '() '()) ===> #t1876 (eq? 2 2) ===> unspecified1877 (eq? #\A #\A) ===> unspecified1878 (eq? car car) ===> #t1879 (let ((n (+ 2 3)))1880 (eq? n n)) ===> unspecified1881 (let ((x '(a)))1882 (eq? x x)) ===> #t1883 (let ((x '#()))1884 (eq? x x)) ===> #t1885 (let ((p (lambda (x) x)))1886 (eq? p p)) ===> #t18871888Rationale: It will usually be possible to implement eq? much more1889efficiently than eqv?, for example, as a simple pointer comparison1890instead of as some more complicated operation. One reason is that1891it may not be possible to compute eqv? of two numbers in constant1892time, whereas eq? implemented as pointer comparison will always1893finish in constant time. Eq? may be used like eqv? in applications1894using procedures to implement objects with state since it obeys the1895same constraints as eqv?.18961897<procedure>(equal? obj[1] obj[2])</procedure><br>18981899Equal? recursively compares the contents of pairs, vectors, and1900strings, applying eqv? on other objects such as numbers and symbols. A1901rule of thumb is that objects are generally equal? if they print the1902same. Equal? may fail to terminate if its arguments are circular data1903structures.19041905 (equal? 'a 'a) ===> #t1906 (equal? '(a) '(a)) ===> #t1907 (equal? '(a (b) c)1908 '(a (b) c)) ===> #t1909 (equal? "abc" "abc") ===> #t1910 (equal? 2 2) ===> #t1911 (equal? (make-vector 5 'a)1912 (make-vector 5 'a)) ===> #t1913 (equal? (lambda (x) x)1914 (lambda (y) y)) ===> unspecified19151916=== Numbers19171918Numerical computation has traditionally been neglected by the Lisp1919community. Until Common Lisp there was no carefully thought out1920strategy for organizing numerical computation, and with the exception1921of the MacLisp system [20] little effort was made to execute numerical1922code efficiently. This report recognizes the excellent work of the1923Common Lisp committee and accepts many of their recommendations. In1924some ways this report simplifies and generalizes their proposals in a1925manner consistent with the purposes of Scheme.19261927It is important to distinguish between the mathematical numbers, the1928Scheme numbers that attempt to model them, the machine representations1929used to implement the Scheme numbers, and notations used to write1930numbers. This report uses the types number, complex, real, rational,1931and integer to refer to both mathematical numbers and Scheme numbers.1932Machine representations such as fixed point and floating point are1933referred to by names such as fixnum and flonum.19341935==== Numerical types19361937Mathematically, numbers may be arranged into a tower of subtypes in1938which each level is a subset of the level above it:19391940 number1941 complex1942 real1943 rational1944 integer19451946For example, 3 is an integer. Therefore 3 is also a rational, a real,1947and a complex. The same is true of the Scheme numbers that model 3. For1948Scheme numbers, these types are defined by the predicates number?,1949complex?, real?, rational?, and integer?.19501951There is no simple relationship between a number's type and its1952representation inside a computer. Although most implementations of1953Scheme will offer at least two different representations of 3, these1954different representations denote the same integer.19551956Scheme's numerical operations treat numbers as abstract data, as1957independent of their representation as possible. Although an1958implementation of Scheme may use fixnum, flonum, and perhaps other1959representations for numbers, this should not be apparent to a casual1960programmer writing simple programs.19611962It is necessary, however, to distinguish between numbers that are1963represented exactly and those that may not be. For example, indexes1964into data structures must be known exactly, as must some polynomial1965coefficients in a symbolic algebra system. On the other hand, the1966results of measurements are inherently inexact, and irrational numbers1967may be approximated by rational and therefore inexact approximations.1968In order to catch uses of inexact numbers where exact numbers are1969required, Scheme explicitly distinguishes exact from inexact numbers.1970This distinction is orthogonal to the dimension of type.19711972==== Exactness19731974Scheme numbers are either exact or inexact. A number is exact if it was1975written as an exact constant or was derived from exact numbers using1976only exact operations. A number is inexact if it was written as an1977inexact constant, if it was derived using inexact ingredients, or if it1978was derived using inexact operations. Thus inexactness is a contagious1979property of a number. If two implementations produce exact results for1980a computation that did not involve inexact intermediate results, the1981two ultimate results will be mathematically equivalent. This is1982generally not true of computations involving inexact numbers since1983approximate methods such as floating point arithmetic may be used, but1984it is the duty of each implementation to make the result as close as1985practical to the mathematically ideal result.19861987Rational operations such as + should always produce exact results when1988given exact arguments. If the operation is unable to produce an exact1989result, then it may either report the violation of an implementation1990restriction or it may silently coerce its result to an inexact value.1991See [[#implementation-restrictions|the next section]].19921993With the exception of inexact->exact, the operations described in this1994section must generally return inexact results when given any inexact1995arguments. An operation may, however, return an exact result if it can1996prove that the value of the result is unaffected by the inexactness of1997its arguments. For example, multiplication of any number by an exact1998zero may produce an exact zero result, even if the other argument is1999inexact.20002001==== Implementation restrictions20022003Implementations of Scheme are not required to implement the whole2004tower of subtypes given under "[[#Numerical types|Numerical types]]",2005but they must implement a coherent subset consistent with both the2006purposes of the implementation and the spirit of the Scheme2007language. For example, an implementation in which all numbers are real2008may still be quite useful.20092010Implementations may also support only a limited range of numbers of any2011type, subject to the requirements of this section. The supported range2012for exact numbers of any type may be different from the supported range2013for inexact numbers of that type. For example, an implementation that2014uses flonums to represent all its inexact real numbers may support a2015practically unbounded range of exact integers and rationals while2016limiting the range of inexact reals (and therefore the range of inexact2017integers and rationals) to the dynamic range of the flonum format.2018Furthermore the gaps between the representable inexact integers and2019rationals are likely to be very large in such an implementation as the2020limits of this range are approached.20212022An implementation of Scheme must support exact integers throughout the2023range of numbers that may be used for indexes of lists, vectors, and2024strings or that may result from computing the length of a list, vector,2025or string. The length, vector-length, and string-length procedures must2026return an exact integer, and it is an error to use anything but an2027exact integer as an index. Furthermore any integer constant within the2028index range, if expressed by an exact integer syntax, will indeed be2029read as an exact integer, regardless of any implementation restrictions2030that may apply outside this range. Finally, the procedures listed below2031will always return an exact integer result provided all their arguments2032are exact integers and the mathematically expected result is2033representable as an exact integer within the implementation:20342035 - *2036 + abs2037 ceiling denominator2038 exact-integer-sqrt expt2039 floor floor/2040 floor-quotient floor-remainder2041 gcd lcm2042 max min2043 modulo numerator2044 quotient rationalize2045 remainder round2046 square truncate2047 truncate/ truncate-quotient2048 truncate-remainder20492050CHICKEN follows the IEEE 32-bit and 64-bit floating point2051standards on all supported platforms.20522053It is the programmer’s responsibility to avoid using inexact number objects2054with magnitude or significand too large to be represented in the2055implementation.20562057In addition, implementations may distinguish special numbers called positive2058infinity, negative infinity, NaN, and negative zero.20592060Positive infinity is regarded as an inexact real (but not rational) number that2061represents an indeterminate value greater than the numbers represented by all2062rational numbers. Negative infinity is regarded as an inexact real (but not2063rational) number that represents an indeterminate value less than the numbers2064represented by all rational numbers.20652066Adding or multiplying an infinite value by any finite real value results in an2067appropriately signed infinity; however, the sum of positive and negative2068infinities is a NaN. Positive infinity is the reciprocal of zero, and negative2069infinity is the reciprocal of negative zero. The behavior of the transcendental2070functions is sensitive to infinity in accordance with IEEE 754.20712072A NaN is regarded as an inexact real (but not rational) number so indeterminate2073that it might represent any real value, including positive or negative2074infinity, and might even be greater than positive infinity or less than2075negative infinity. An implementation that does not support non-real numbers may2076use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).20772078A NaN always compares false to any number, including a NaN. An arithmetic2079operation where one operand is NaN returns NaN, unless the implementation can2080prove that the result would be the same if the NaN were replaced by any2081rational number. Dividing zero by zero results in NaN unless both zeros are2082exact.20832084Negative zero is an inexact real value written -0.0 and is distinct (in the2085sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish2086negative zero. If it does, however, the behavior of the transcendental2087functions is sensitive to the distinction in accordance with IEEE 754.2088Specifically, in a Scheme implementing both complex numbers and negative zero,2089the branch cut of the complex logarithm function is such that (imag-part (log2090-1.0-0.0i)) is −π rather than π.20912092Furthermore, the negation of negative zero is ordinary zero and vice versa.2093This implies that the sum of two or more negative zeros is negative, and the2094result of subtracting (positive) zero from a negative zero is likewise2095negative. However, numerical comparisons treat negative zero as equal to zero.20962097Note that both the real and the imaginary parts of a complex number can be2098infinities, NaNs, or negative zero.209921002101==== Syntax of numerical constants21022103For a complete formal description of the syntax of the written2104representations for numbers, see the R7RS report. Note that case is2105not significant in numerical constants.21062107A number may be written in binary, octal, decimal, or hexadecimal by2108the use of a radix prefix. The radix prefixes are #b (binary), #o2109(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a2110number is assumed to be expressed in decimal.21112112A numerical constant may be specified to be either exact or inexact by2113a prefix. The prefixes are #e for exact, and #i for inexact. An2114exactness prefix may appear before or after any radix prefix that is2115used. If the written representation of a number has no exactness2116prefix, the constant may be either inexact or exact. It is inexact if2117it contains a decimal point, an exponent, or a "#" character in the2118place of a digit, otherwise it is exact. In systems with inexact2119numbers of varying precisions it may be useful to specify the precision2120of a constant. For this purpose, numerical constants may be written2121with an exponent marker that indicates the desired precision of the2122inexact representation. The letters s, f, d, and l specify the use of2123short, single, double, and long precision, respectively. (When fewer2124than four internal inexact representations exist, the four size2125specifications are mapped onto those available. For example, an2126implementation with two internal representations may map short and2127single together and long and double together.) In addition, the2128exponent marker e specifies the default precision for the2129implementation. The default precision has at least as much precision as2130double, but implementations may wish to allow this default to be set by2131the user.21322133 3.14159265358979F02134 Round to single --- 3.1415932135 0.6L02136 Extend to long --- .60000000000000021372138==== Numerical operations21392140The numerical routines described below have argument restrictions,2141which are encoded in the naming conventions of the arguments as2142given in the procedure's signature. The conventions are as follows:21432144; {{obj}} : any object2145; {{list, list1, ... listj, ... list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)2146; {{z, z1, ... zj, ...}} : complex number2147; {{x, x1, ... xj, ...}} : real number2148; {{y, y1, ... yj, ...}} : real number2149; {{q, q1, ... qj, ...}} : rational number2150; {{n, n1, ... nj, ...}} : integer2151; {{k, k1, ... kj, ...}} : exact non-negative integer21522153The examples used in this section assume that any2154numerical constant written using an exact notation is indeed2155represented as an exact number. Some examples also assume that certain2156numerical constants written using an inexact notation can be2157represented without loss of accuracy; the inexact constants were chosen2158so that this is likely to be true in implementations that use flonums2159to represent inexact numbers.21602161<procedure>(number? obj)</procedure><br>2162<procedure>(complex? obj)</procedure><br>2163<procedure>(real? obj)</procedure><br>2164<procedure>(rational? obj)</procedure><br>2165<procedure>(integer? obj)</procedure><br>21662167These numerical type predicates can be applied to any kind of argument,2168including non-numbers. They return #t if the object is of the named2169type, and otherwise they return #f. In general, if a type predicate is2170true of a number then all higher type predicates are also true of that2171number. Consequently, if a type predicate is false of a number, then2172all lower type predicates are also false of that number. If z is an2173inexact complex number, then (real? z) is true if and only if (zero?2174(imag-part z)) is true. If x is an inexact real number, then (integer?2175x) is true if and only if (= x (round x)).21762177 (complex? 3+4i) ===> #t2178 (complex? 3) ===> #t2179 (real? 3) ===> #t2180 (real? -2.5+0.0i) ===> #t2181 (real? #e1e10) ===> #t2182 (rational? 6/10) ===> #t2183 (rational? 6/3) ===> #t2184 (integer? 3+0i) ===> #t2185 (integer? 3.0) ===> #t2186 (integer? 8/4) ===> #t21872188Note: The behavior of these type predicates on inexact numbers is2189unreliable, since any inaccuracy may affect the result.21902191Note: In many implementations the rational? procedure will be the2192same as real?, and the complex? procedure will be the same as2193number?, but unusual implementations may be able to represent some2194irrational numbers exactly or may extend the number system to2195support some kind of non-complex numbers.21962197<procedure>(exact? z)</procedure><br>2198<procedure>(inexact? z)</procedure><br>21992200These numerical predicates provide tests for the exactness of a2201quantity. For any Scheme number, precisely one of these predicates is2202true.22032204<procedure>(exact-integer? z)</procedure>22052206Returns #t if z is both exact and an integer; otherwise returns #f.22072208 (exact-integer? 32) ===> #t2209 (exact-integer? 32.0) ===> #f2210 (exact-integer? 32/5) ===> #f22112212<procedure>(= z[1] z[2] z[3] ...)</procedure><br>2213<procedure>(< x[1] x[2] x[3] ...)</procedure><br>2214<procedure>(> x[1] x[2] x[3] ...)</procedure><br>2215<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>2216<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>22172218These procedures return #t if their arguments are (respectively):2219equal, monotonically increasing, monotonically decreasing,2220monotonically nondecreasing, or monotonically nonincreasing.22212222These predicates are required to be transitive.22232224Note: The traditional implementations of these predicates in2225Lisp-like languages are not transitive.22262227Note: While it is not an error to compare inexact numbers using2228these predicates, the results may be unreliable because a small2229inaccuracy may affect the result; this is especially true of = and2230zero?. When in doubt, consult a numerical analyst.22312232<procedure>(zero? z)</procedure><br>2233<procedure>(positive? x)</procedure><br>2234<procedure>(negative? x)</procedure><br>2235<procedure>(odd? n)</procedure><br>2236<procedure>(even? n)</procedure><br>22372238These numerical predicates test a number for a particular property,2239returning #t or #f. See note above.22402241<procedure>(max x[1] x[2] ...)</procedure><br>2242<procedure>(min x[1] x[2] ...)</procedure><br>22432244These procedures return the maximum or minimum of their arguments.22452246 (max 3 4) ===> 4 ; exact2247 (max 3.9 4) ===> 4.0 ; inexact22482249Note: If any argument is inexact, then the result will also be2250inexact (unless the procedure can prove that the inaccuracy is not2251large enough to affect the result, which is possible only in2252unusual implementations). If min or max is used to compare numbers2253of mixed exactness, and the numerical value of the result cannot be2254represented as an inexact number without loss of accuracy, then the2255procedure may report a violation of an implementation restriction.22562257<procedure>(+ z[1] ...)</procedure><br>2258<procedure>(* z[1] ...)</procedure><br>22592260These procedures return the sum or product of their arguments.22612262 (+ 3 4) ===> 72263 (+ 3) ===> 32264 (+) ===> 02265 (* 4) ===> 42266 (*) ===> 122672268<procedure>(- z[1] z[2])</procedure><br>2269<procedure>(- z)</procedure><br>2270<procedure>(- z[1] z[2] ...)</procedure><br>2271<procedure>(/ z[1] z[2])</procedure><br>2272<procedure>(/ z)</procedure><br>2273<procedure>(/ z[1] z[2] ...)</procedure><br>22742275With two or more arguments, these procedures return the difference or2276quotient of their arguments, associating to the left. With one2277argument, however, they return the additive or multiplicative inverse2278of their argument.22792280 (- 3 4) ===> -12281 (- 3 4 5) ===> -62282 (- 3) ===> -32283 (/ 3 4 5) ===> 3/202284 (/ 3) ===> 1/322852286<procedure>(abs x)</procedure><br>22872288Abs returns the absolute value of its argument.22892290 (abs -7) ===> 722912292<procedure>(floor/ n[1] n[2])</procedure><br>2293<procedure>(floor-quotient n[1] n[2])</procedure><br>2294<procedure>(floor-remainder n[1] n[2])</procedure><br>2295<procedure>(truncate/ n[1] n[2])</procedure><br>2296<procedure>(truncate-quotient n[1] n[2])</procedure><br>2297<procedure>(truncate-remainder n[1] n[2])</procedure><br>22982299These procedures implement number-theoretic (integer) division. It is an error2300if n[2] is zero. The procedures ending in / return two integers; the other2301procedures return an integer. All the procedures compute a quotient n[q] and remainder2302n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as2303follows:23042305 (<operator>/ n[1] n[2]) ==> n[q] n[r]2306 (<operator>-quotient n[1] n[2]) ==> n[q]2307 (<operator>-remainder n[1] n[2]) ==> n[r]23082309The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] − n[2] * n[q]. Each set of operators uses a different choice of n[q]:23102311 floor n[q] = ⌊n[1] / n[2]⌋2312 truncate n[q] = runcate(n[1] / n[2])23132314For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,23152316 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))2317 (<operator>-remainder n[1] n[2])))2318 ==> #t23192320provided all numbers involved in that computation are exact.23212322Examples:23232324 (floor/ 5 2) ==> 2 12325 (floor/ -5 2) ==> -3 12326 (floor/ 5 -2) ==> -3 -12327 (floor/ -5 -2) ==> 2 -12328 (truncate/ 5 2) ==> 2 12329 (truncate/ -5 2) ==> -2 -12330 (truncate/ 5 -2) ==> -2 12331 (truncate/ -5 -2) ==> 2 -12332 (truncate/ -5.0 -2) ==> 2.0 -1.023332334<procedure>(quotient n[1] n[2])</procedure><br>2335<procedure>(remainder n[1] n[2])</procedure><br>2336<procedure>(modulo n[1] n[2])</procedure><br>23372338These procedures implement number-theoretic (integer) division. n[2]2339should be non-zero. All three procedures return integers. If n[1]/n[2]2340is an integer:23412342 (quotient n[1] n[2]) ===> n[1]/n[2]2343 (remainder n[1] n[2]) ===> 02344 (modulo n[1] n[2]) ===> 023452346If n[1]/n[2] is not an integer:23472348 (quotient n[1] n[2]) ===> n[q]2349 (remainder n[1] n[2]) ===> n[r]2350 (modulo n[1] n[2]) ===> n[m]23512352where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <2353|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],2354n[r] has the same sign as n[1], and n[m] has the same sign as n[2].23552356From this we can conclude that for integers n[1] and n[2] with n[2] not2357equal to 0,23582359 (= n[1] (+ (* n[2] (quotient n[1] n[2]))2360 (remainder n[1] n[2])))2361 ===> #t23622363provided all numbers involved in that computation are exact.23642365 (modulo 13 4) ===> 12366 (remainder 13 4) ===> 123672368 (modulo -13 4) ===> 32369 (remainder -13 4) ===> -123702371 (modulo 13 -4) ===> -32372 (remainder 13 -4) ===> 123732374 (modulo -13 -4) ===> -12375 (remainder -13 -4) ===> -123762377 (remainder -13 -4.0) ===> -1.0 ; inexact23782379<procedure>(gcd n[1] ...)</procedure><br>2380<procedure>(lcm n[1] ...)</procedure><br>23812382These procedures return the greatest common divisor or least common2383multiple of their arguments. The result is always non-negative.23842385 (gcd 32 -36) ===> 42386 (gcd) ===> 02387 (lcm 32 -36) ===> 2882388 (lcm 32.0 -36) ===> 288.0 ; inexact2389 (lcm) ===> 123902391<procedure>(numerator q)</procedure><br>2392<procedure>(denominator q)</procedure><br>23932394These procedures return the numerator or denominator of their argument;2395the result is computed as if the argument was represented as a fraction2396in lowest terms. The denominator is always positive. The denominator of23970 is defined to be 1.23982399 (numerator (/ 6 4)) ===> 32400 (denominator (/ 6 4)) ===> 22401 (denominator2402 (exact->inexact (/ 6 4))) ===> 2.024032404<procedure>(floor x)</procedure><br>2405<procedure>(ceiling x)</procedure><br>2406<procedure>(truncate x)</procedure><br>2407<procedure>(round x)</procedure><br>24082409These procedures return integers. Floor returns the largest integer not2410larger than x. Ceiling returns the smallest integer not smaller than x.2411Truncate returns the integer closest to x whose absolute value is not2412larger than the absolute value of x. Round returns the closest integer2413to x, rounding to even when x is halfway between two integers.24142415Rationale: Round rounds to even for consistency with the default2416rounding mode specified by the IEEE floating point standard.24172418Note: If the argument to one of these procedures is inexact, then2419the result will also be inexact. If an exact value is needed, the2420result should be passed to the inexact->exact procedure.24212422 (floor -4.3) ===> -5.02423 (ceiling -4.3) ===> -4.02424 (truncate -4.3) ===> -4.02425 (round -4.3) ===> -4.024262427 (floor 3.5) ===> 3.02428 (ceiling 3.5) ===> 4.02429 (truncate 3.5) ===> 3.02430 (round 3.5) ===> 4.0 ; inexact24312432 (round 7/2) ===> 4 ; exact2433 (round 7) ===> 724342435<procedure>(rationalize x y)</procedure><br>24362437Rationalize returns the simplest rational number differing from x by no2438more than y. A rational number r[1] is simpler than another rational2439number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)2440and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.2441Although not all rationals are comparable in this ordering (consider 2/24427 and 3/5) any interval contains a rational number that is simpler than2443every other rational number in that interval (the simpler 2/5 lies2444between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of2445all.24462447 (rationalize2448 (inexact->exact .3) 1/10) ===> 1/3 ; exact2449 (rationalize .3 1/10) ===> #i1/3 ; inexact24502451<procedure>(exp z)</procedure><br>2452<procedure>(log z [z2])</procedure><br>2453<procedure>(sin z)</procedure><br>2454<procedure>(cos z)</procedure><br>2455<procedure>(tan z)</procedure><br>2456<procedure>(asin z)</procedure><br>2457<procedure>(acos z)</procedure><br>2458<procedure>(atan z)</procedure><br>2459<procedure>(atan y x)</procedure><br>24602461These procedures are part of every implementation that supports general2462real numbers; they compute the usual transcendental functions. The Log2463procedure computes the natural logarithm of z (not the base ten logarithm)2464if a single argument is given, or the base-z2 logarithm of z1 if two arguments are2465given.2466Asin, acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and2467arctangent (tan^-1), respectively. The two-argument variant of atan2468computes (angle (make-rectangular x y)) (see below), even in2469implementations that don't support general complex numbers.24702471In general, the mathematical functions log, arcsine, arccosine, and2472arctangent are multiply defined. The value of log z is defined to be2473the one whose imaginary part lies in the range from -pi2474(exclusive) to pi (inclusive). log 0 is undefined. With log2475defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are2476according to the following formulae:24772478 sin^-1 z = - i log (i z + (1 - z^2)^1/2)24792480 cos^-1 z = pi / 2 - sin^-1 z24812482 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)24832484The above specification follows [27], which in turn cites [19]; refer2485to these sources for more detailed discussion of branch cuts, boundary2486conditions, and implementation of these functions. When it is possible2487these procedures produce a real result from a real argument.24882489<procedure>(square z)</procedure>24902491Returns the square of z. This is equivalent to {{(* z z)}}-24922493 (square 42) ==> 17642494 (square 2.0) ==> 4.024952496<procedure>(exact-integer-sqrt k)</procedure>24972498Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.24992500 (exact-integer-sqrt 4) ==> 2 02501 (exact-integer-sqrt 5) ==> 2 125022503<procedure>(expt z[1] z[2])</procedure><br>25042505Returns z[1] raised to the power z[2]. For z[1] != 025062507 z[1]^z[2] = e^z[2] log z[1]250825090^z is 1 if z = 0 and 0 otherwise.25102511<procedure>(exact z)</procedure><br>2512<procedure>(inexact z)</procedure><br>25132514The procedure {{inexact}} returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the2515argument. For inexact arguments, the result is the same as the argument. For2516exact complex numbers, the result is a complex number whose real and imaginary2517parts are the result of applying inexact to the real and imaginary parts of the2518argument, respectively. If an exact argument has no reasonably close inexact2519equivalent (in the sense of =), then a violation of an implementation2520restriction may be reported.25212522The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the2523argument. For exact arguments, the result is the same as the argument. For2524inexact non-integral real arguments, the implementation may return a rational2525approximation, or may report an implementation violation. For inexact complex2526arguments, the result is a complex number whose real and imaginary parts are2527the result of applying exact to the real and imaginary parts of the argument,2528respectively. If an inexact argument has no reasonably close exact equivalent,2529(in the sense of =), then a violation of an implementation restriction may be2530reported.25312532==== Numerical input and output25332534<procedure>(number->string z [radix])</procedure>25352536Radix must be an exact integer. The R7RS standard only requires2537implementations to support 2, 8, 10, or 16, but CHICKEN allows any2538radix between 2 and 36, inclusive (note: a bug in CHICKEN 5 currently2539limits the upper bound to 16). If omitted, radix defaults to254010. The procedure number->string takes a number and a radix and2541returns as a string an external representation of the given number in2542the given radix such that25432544 (let ((number number)2545 (radix radix))2546 (eqv? number2547 (string->number (number->string number2548 radix)2549 radix)))25502551is true. It is an error if no possible result makes this expression2552true.25532554If z is inexact, the radix is 10, and the above expression can be2555satisfied by a result that contains a decimal point, then the result2556contains a decimal point and is expressed using the minimum number of2557digits (exclusive of exponent and trailing zeroes) needed to make the2558above expression true [3, 5]; otherwise the format of the result is2559unspecified.25602561The result returned by number->string never contains an explicit radix2562prefix.25632564Note: The error case can occur only when z is not a complex2565number or is a complex number with a non-rational real or imaginary2566part.25672568Rationale: If z is an inexact number represented using flonums,2569and the radix is 10, then the above expression is normally2570satisfied by a result containing a decimal point. The unspecified2571case allows for infinities, NaNs, and non-flonum representations.25722573As an extension to R7RS, CHICKEN supports reading and writing the2574special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',2575as well as negative zero.25762577<procedure>(string->number string)</procedure><br>2578<procedure>(string->number string radix)</procedure><br>25792580Returns a number of the maximally precise representation expressed by2581the given string. Radix must be an exact integer. The R7RS standard2582only requires implementations to support 2, 8, 10, or 16, but CHICKEN2583allows any radix between 2 and 36, inclusive. If supplied, radix is a2584default radix that may be overridden by an explicit radix prefix in2585string (e.g. "#o177"). If radix is not supplied, then the default2586radix is 10. If string is not a syntactically valid notation for a2587number, then string->number returns #f.25882589 (string->number "100") ===> 1002590 (string->number "100" 16) ===> 2562591 (string->number "1e2") ===> 100.02592 (string->number "15##") ===> 1500.025932594Note: The domain of string->number may be restricted by2595implementations in the following ways. String->number is permitted2596to return #f whenever string contains an explicit radix prefix. If2597all numbers supported by an implementation are real, then string->2598number is permitted to return #f whenever string uses the polar or2599rectangular notations for complex numbers. If all numbers are2600integers, then string->number may return #f whenever the fractional2601notation is used. If all numbers are exact, then string->number may2602return #f whenever an exponent marker or explicit exactness prefix2603is used, or if a # appears in place of a digit. If all inexact2604numbers are integers, then string->number may return #f whenever a2605decimal point is used.26062607=== Other data types26082609This section describes operations on some of Scheme's non-numeric data2610types: booleans, pairs, lists, symbols, characters, strings and2611vectors.26122613==== Booleans26142615The standard boolean objects for true and false are written as #t and #f.2616What really matters, though, are the objects that the Scheme2617conditional expressions (if, cond, and, or, do) treat as true or false.2618The phrase "a true value" (or sometimes just "true") means any2619object treated as true by the conditional expressions, and the phrase2620"a false value" (or "false") means any object treated as false by2621the conditional expressions.26222623Of all the standard Scheme values, only #f counts as false in2624conditional expressions. Except for #f, all standard Scheme values,2625including #t, pairs, the empty list, symbols, numbers, strings,2626vectors, and procedures, count as true.26272628Note: Programmers accustomed to other dialects of Lisp should be2629aware that Scheme distinguishes both #f and the empty list from the2630symbol nil.26312632Boolean constants evaluate to themselves, so they do not need to be2633quoted in programs.26342635 #t ===> #t2636 #f ===> #f2637 '#f ===> #f26382639<procedure>(not obj)</procedure><br>26402641Not returns #t if obj is false, and returns #f otherwise.26422643 (not #t) ===> #f2644 (not 3) ===> #f2645 (not (list 3)) ===> #f2646 (not #f) ===> #t2647 (not '()) ===> #f2648 (not (list)) ===> #f2649 (not 'nil) ===> #f26502651<procedure>(boolean? obj)</procedure><br>26522653Boolean? returns #t if obj is either #t or #f and returns #f otherwise.26542655 (boolean? #f) ===> #t2656 (boolean? 0) ===> #f2657 (boolean? '()) ===> #f26582659<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>26602661Returns #t if all the arguments are #t or all are #f.26622663==== Pairs and lists26642665A pair (sometimes called a dotted pair) is a record structure with two2666fields called the car and cdr fields (for historical reasons). Pairs2667are created by the procedure cons. The car and cdr fields are accessed2668by the procedures car and cdr. The car and cdr fields are assigned by2669the procedures set-car! and set-cdr!.26702671Pairs are used primarily to represent lists. A list can be defined2672recursively as either the empty list or a pair whose cdr is a list.2673More precisely, the set of lists is defined as the smallest set X such2674that26752676* The empty list is in X.2677* If list is in X, then any pair whose cdr field contains list is2678 also in X.26792680The objects in the car fields of successive pairs of a list are the2681elements of the list. For example, a two-element list is a pair whose2682car is the first element and whose cdr is a pair whose car is the2683second element and whose cdr is the empty list. The length of a list is2684the number of elements, which is the same as the number of pairs.26852686The empty list is a special object of its own type (it is not a pair);2687it has no elements and its length is zero.26882689Note: The above definitions imply that all lists have finite2690length and are terminated by the empty list.26912692The most general notation (external representation) for Scheme pairs is2693the "dotted" notation (c[1] . c[2]) where c[1] is the value of the2694car field and c[2] is the value of the cdr field. For example (4 . 5)2695is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the2696external representation of a pair, not an expression that evaluates to2697a pair.26982699A more streamlined notation can be used for lists: the elements of the2700list are simply enclosed in parentheses and separated by spaces. The2701empty list is written () . For example,27022703 (a b c d e)27042705and27062707 (a . (b . (c . (d . (e . ())))))27082709are equivalent notations for a list of symbols.27102711A chain of pairs not ending in the empty list is called an improper2712list. Note that an improper list is not a list. The list and dotted2713notations can be combined to represent improper lists:27142715 (a b c . d)27162717is equivalent to27182719 (a . (b . (c . d)))27202721Whether a given pair is a list depends upon what is stored in the cdr2722field. When the set-cdr! procedure is used, an object can be a list one2723moment and not the next:27242725 (define x (list 'a 'b 'c))2726 (define y x)2727 y ===> (a b c)2728 (list? y) ===> #t2729 (set-cdr! x 4) ===> unspecified2730 x ===> (a . 4)2731 (eqv? x y) ===> #t2732 y ===> (a . 4)2733 (list? y) ===> #f2734 (set-cdr! x x) ===> unspecified2735 (list? x) ===> #f27362737Within literal expressions and representations of objects read by the2738read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>2739denote two-element lists whose first elements are the symbols quote,2740quasiquote, unquote, and unquote-splicing, respectively. The second2741element in each case is <datum>. This convention is supported so that2742arbitrary Scheme programs may be represented as lists. That is,2743according to Scheme's grammar, every <expression> is also a <datum>.2744Among other things, this permits the use of the read procedure to2745parse Scheme programs.27462747<procedure>(pair? obj)</procedure><br>27482749Pair? returns #t if obj is a pair, and otherwise returns #f.27502751 (pair? '(a . b)) ===> #t2752 (pair? '(a b c)) ===> #t2753 (pair? '()) ===> #f2754 (pair? '#(a b)) ===> #f27552756<procedure>(cons obj[1] obj[2])</procedure><br>27572758Returns a newly allocated pair whose car is obj[1] and whose cdr is2759obj[2]. The pair is guaranteed to be different (in the sense of eqv?)2760from every existing object.27612762 (cons 'a '()) ===> (a)2763 (cons '(a) '(b c d)) ===> ((a) b c d)2764 (cons "a" '(b c)) ===> ("a" b c)2765 (cons 'a 3) ===> (a . 3)2766 (cons '(a b) 'c) ===> ((a b) . c)27672768<procedure>(car pair)</procedure><br>27692770Returns the contents of the car field of pair. Note that it is an error2771to take the car of the empty list.27722773 (car '(a b c)) ===> a2774 (car '((a) b c d)) ===> (a)2775 (car '(1 . 2)) ===> 12776 (car '()) ===> error27772778<procedure>(cdr pair)</procedure><br>27792780Returns the contents of the cdr field of pair. Note that it is an error2781to take the cdr of the empty list.27822783 (cdr '((a) b c d)) ===> (b c d)2784 (cdr '(1 . 2)) ===> 22785 (cdr '()) ===> error27862787<procedure>(set-car! pair obj)</procedure><br>27882789Stores obj in the car field of pair. The value returned by set-car! is2790unspecified.27912792 (define (f) (list 'not-a-constant-list))2793 (define (g) '(constant-list))2794 (set-car! (f) 3) ===> unspecified2795 (set-car! (g) 3) ===> error27962797<procedure>(set-cdr! pair obj)</procedure><br>27982799Stores obj in the cdr field of pair. The value returned by set-cdr! is2800unspecified.28012802<procedure>(null? obj)</procedure><br>28032804Returns #t if obj is the empty list, otherwise returns #f.28052806<procedure>(list? obj)</procedure><br>28072808Returns #t if obj is a list, otherwise returns #f. By definition, all2809lists have finite length and are terminated by the empty list.28102811 (list? '(a b c)) ===> #t2812 (list? '()) ===> #t2813 (list? '(a . b)) ===> #f2814 (let ((x (list 'a)))2815 (set-cdr! x x)2816 (list? x)) ===> #f28172818<procedure>(make-list k [fill]}</procedure>28192820Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.28212822 (make-list 2 3) ==> (3 3)28232824<procedure>(list obj ...)</procedure><br>28252826Returns a newly allocated list of its arguments.28272828 (list 'a (+ 3 4) 'c) ===> (a 7 c)2829 (list) ===> ()28302831<procedure>(length list)</procedure><br>28322833Returns the length of list.28342835 (length '(a b c)) ===> 32836 (length '(a (b) (c d e))) ===> 32837 (length '()) ===> 028382839<procedure>(append list ...)</procedure><br>28402841Returns a list consisting of the elements of the first list followed by2842the elements of the other lists.28432844 (append '(x) '(y)) ===> (x y)2845 (append '(a) '(b c d)) ===> (a b c d)2846 (append '(a (b)) '((c))) ===> (a (b) (c))28472848The resulting list is always newly allocated, except that it shares2849structure with the last list argument. The last argument may actually2850be any object; an improper list results if the last argument is not a2851proper list.28522853 (append '(a b) '(c . d)) ===> (a b c . d)2854 (append '() 'a) ===> a28552856<procedure>(reverse list)</procedure><br>28572858Returns a newly allocated list consisting of the elements of list in2859reverse order.28602861 (reverse '(a b c)) ===> (c b a)2862 (reverse '(a (b c) d (e (f))))2863 ===> ((e (f)) d (b c) a)28642865<procedure>(list-tail list k)</procedure><br>28662867Returns the sublist of list obtained by omitting the first k elements.2868It is an error if list has fewer than k elements. List-tail could be2869defined by28702871 (define list-tail2872 (lambda (x k)2873 (if (zero? k)2874 x2875 (list-tail (cdr x) (- k 1)))))28762877<procedure>(list-ref list k)</procedure><br>28782879Returns the kth element of list. (This is the same as the car of2880(list-tail list k).) It is an error if list has fewer than k elements.28812882 (list-ref '(a b c d) 2) ===> c2883 (list-ref '(a b c d)2884 (inexact->exact (round 1.8)))2885 ===> c28862887<procedure>(list-set! list k obj)</procedure>28882889It is an error if k is not a valid index of list.28902891The {{list-set!}} procedure stores obj in element k of list.28922893 (let ((ls (list 'one 'two 'five!)))2894 (list-set! ls 2 'three)2895 ls)2896 ==> (one two three)28972898 (list-set! '(0 1 2) 1 "oops")2899 ==> error ; constant list29002901<procedure>(memq obj list)</procedure><br>2902<procedure>(memv obj list)</procedure><br>2903<procedure>(member obj list [compare])</procedure><br>29042905These procedures return the first sublist of list whose car is obj,2906where the sublists of list are the non-empty lists returned by2907{{(list-tail list k)}} for k less than the length of list. If obj does not2908occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}2909to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and2910member {{compare}} if given, and {{equal?}} otherwise.29112912 (memq 'a '(a b c)) ===> (a b c)2913 (memq 'b '(a b c)) ===> (b c)2914 (memq 'a '(b c d)) ===> #f2915 (memq (list 'a) '(b (a) c)) ===> #f2916 (member (list 'a)2917 '(b (a) c)) ===> ((a) c)2918 (memq 101 '(100 101 102)) ===> unspecified2919 (memv 101 '(100 101 102)) ===> (101 102)29202921<procedure>(assq obj alist)</procedure><br>2922<procedure>(assv obj alist)</procedure><br>2923<procedure>(assoc obj alist [compare])</procedure><br>29242925Alist (for "association list") must be a list of pairs. These2926procedures find the first pair in alist whose car field is obj, and2927returns that pair. If no pair in alist has obj as its car, then #f (not2928the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car2929fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses2930{{compare}}, if given, otherwise {{equal?}}.29312932 (define e '((a 1) (b 2) (c 3)))2933 (assq 'a e) ===> (a 1)2934 (assq 'b e) ===> (b 2)2935 (assq 'd e) ===> #f2936 (assq (list 'a) '(((a)) ((b)) ((c))))2937 ===> #f2938 (assoc (list 'a) '(((a)) ((b)) ((c))))2939 ===> ((a))2940 (assq 5 '((2 3) (5 7) (11 13)))2941 ===> unspecified2942 (assv 5 '((2 3) (5 7) (11 13)))2943 ===> (5 7)29442945Rationale: Although they are ordinarily used as predicates, memq,2946memv, member, assq, assv, and assoc do not have question marks in2947their names because they return useful values rather than just #t2948or #f.29492950<procedure>(list-copy obj)</procedure>29512952Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in2953the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if2954obj is a circular list.29552956 (define a '(1 8 2 8)) ; a may be immutable2957 (define b (list-copy a))2958 (set-car! b 3) ; b is mutable2959 b ==> (3 8 2 8)2960 a ==> (1 8 2 8)29612962==== Symbols29632964Symbols are objects whose usefulness rests on the fact that two symbols2965are identical (in the sense of eqv?) if and only if their names are2966spelled the same way. This is exactly the property needed to represent2967identifiers in programs, and so most implementations of Scheme use them2968internally for that purpose. Symbols are useful for many other2969applications; for instance, they may be used the way enumerated values2970are used in Pascal.29712972The rules for writing a symbol are exactly the same as the rules for2973writing an identifier.29742975It is guaranteed that any symbol that has been returned as part of a2976literal expression, or read using the read procedure, and subsequently2977written out using the write procedure, will read back in as the2978identical symbol (in the sense of eqv?). The string->symbol procedure,2979however, can create symbols for which this write/read invariance may2980not hold because their names contain special characters or letters in2981the non-standard case.29822983Note: Some implementations of Scheme have a feature known as2984"slashification" in order to guarantee write/read invariance for2985all symbols, but historically the most important use of this2986feature has been to compensate for the lack of a string data type.29872988Some implementations also have "uninterned symbols", which defeat2989write/read invariance even in implementations with slashification,2990and also generate exceptions to the rule that two symbols are the2991same if and only if their names are spelled the same.29922993<procedure>(symbol? obj)</procedure><br>29942995Returns #t if obj is a symbol, otherwise returns #f.29962997 (symbol? 'foo) ===> #t2998 (symbol? (car '(a b))) ===> #t2999 (symbol? "bar") ===> #f3000 (symbol? 'nil) ===> #t3001 (symbol? '()) ===> #f3002 (symbol? #f) ===> #f30033004<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>30053006Returns #t if all the arguments all have the same names in the sense of {{string=?}}.30073008Note: The definition above assumes that none of the arguments are uninterned symbols.30093010<procedure>(symbol->string symbol)</procedure><br>30113012Returns the name of symbol as a string. If the symbol was part of an3013object returned as the value of a literal expression (see3014"[[#literal-expressions|literal expressions]]") or by a call to the3015read procedure, and its name contains alphabetic characters, then the3016string returned will contain characters in the implementation's3017preferred standard case -- some implementations will prefer upper3018case, others lower case. If the symbol was returned by string->symbol,3019the case of characters in the string returned will be the same as the3020case in the string that was passed to string->symbol. It is an error3021to apply mutation procedures like string-set! to strings returned by3022this procedure.30233024The following examples assume that the implementation's standard case3025is lower case:30263027 (symbol->string 'flying-fish)3028 ===> "flying-fish"3029 (symbol->string 'Martin) ===> "martin"3030 (symbol->string3031 (string->symbol "Malvina"))3032 ===> "Malvina"30333034<procedure>(string->symbol string)</procedure><br>30353036Returns the symbol whose name is string. This procedure can create3037symbols with names containing special characters or letters in the3038non-standard case, but it is usually a bad idea to create such symbols3039because in some implementations of Scheme they cannot be read as3040themselves. See symbol->string.30413042The following examples assume that the implementation's standard case3043is lower case:30443045 (eq? 'mISSISSIppi 'mississippi)3046 ===> #t3047 (string->symbol "mISSISSIppi")3048 ===> the symbol with name "mISSISSIppi"3049 (eq? 'bitBlt (string->symbol "bitBlt"))3050 ===> #f3051 (eq? 'JollyWog3052 (string->symbol3053 (symbol->string 'JollyWog)))3054 ===> #t3055 (string=? "K. Harper, M.D."3056 (symbol->string3057 (string->symbol "K. Harper, M.D.")))3058 ===> #t30593060==== Characters30613062Characters are objects that represent printed characters such as3063letters and digits. Characters are written using the notation #\3064<character> or #\<character name>. For example:30653066Characters are written using the notation {{#\<character>}} or {{#\<character name>}}3067or {{#\x<hex scalar value>}}.30683069The following character names must be supported by all implementations with the3070given values. Implementations may add other names provided they cannot be3071interpreted as hex scalar values preceded by x.30723073 #\alarm ; U+00073074 #\backspace ; U+00083075 #\delete ; U+007F3076 #\escape ; U+001B3077 #\newline ; the linefeed character, U+000A3078 #\null ; the null character, U+00003079 #\return ; the return character, U+000D3080 #\space ; the preferred way to write a space3081 #\tab ; the tab character, U+000930823083Here are some additional examples:30843085 #\a ; lower case letter3086 #\A ; upper case letter3087 #\( ; left parenthesis3088 #\ ; the space character3089 #\space ; the preferred way to write a space3090 #\newline ; the newline character30913092Case is significant in #\<character>, but not in #\<character name>. If3093<character> in #\<character> is alphabetic, then the character3094following <character> must be a delimiter character such as a space or3095parenthesis. This rule resolves the ambiguous case where, for example,3096the sequence of characters "#\space" could be taken to be either a3097representation of the space character or a representation of the3098character "#\s" followed by a representation of the symbol "pace."30993100Characters written in the #\ notation are self-evaluating. That is,3101they do not have to be quoted in programs. Some of the procedures that3102operate on characters ignore the difference between upper case and3103lower case. The procedures that ignore case have "-ci" (for "case3104insensitive") embedded in their names.31053106<procedure>(char? obj)</procedure><br>31073108Returns #t if obj is a character, otherwise returns #f.31093110<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>3111<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>3112<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>3113<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>3114<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>31153116These procedures impose a total ordering on the set of characters. It3117is guaranteed that under this ordering:31183119* The upper case characters are in order. For example, (char<? #\A #\3120 B) returns #t.3121* The lower case characters are in order. For example, (char<? #\a #\3122 b) returns #t.3123* The digits are in order. For example, (char<? #\0 #\9) returns #t.3124* Either all the digits precede all the upper case letters, or vice3125 versa.3126* Either all the digits precede all the lower case letters, or vice3127 versa.31283129Some implementations may generalize these procedures to take more than3130two arguments, as with the corresponding numerical predicates.31313132<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>3133<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>3134<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>3135<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>3136<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>31373138These procedures are similar to char=? et cetera, but they treat upper3139case and lower case letters as the same. For example, (char-ci=? #\A #\3140a) returns #t. Some implementations may generalize these procedures to3141take more than two arguments, as with the corresponding numerical3142predicates.31433144<procedure>(char-alphabetic? char)</procedure><br>3145<procedure>(char-numeric? char)</procedure><br>3146<procedure>(char-whitespace? char)</procedure><br>3147<procedure>(char-upper-case? letter)</procedure><br>3148<procedure>(char-lower-case? letter)</procedure><br>31493150These procedures return #t if their arguments are alphabetic, numeric,3151whitespace, upper case, or lower case characters, respectively,3152otherwise they return #f. The following remarks, which are specific to3153the ASCII character set, are intended only as a guide: The alphabetic3154characters are the 52 upper and lower case letters. The numeric3155characters are the ten decimal digits. The whitespace characters are3156space, tab, line feed, form feed, and carriage return.31573158<procedure>(char->integer char)</procedure><br>3159<procedure>(integer->char n)</procedure><br>31603161Given a character, char->integer returns an exact integer3162representation of the character. Given an exact integer that is the3163image of a character under char->integer, integer->char returns that3164character. These procedures implement order-preserving isomorphisms3165between the set of characters under the char<=? ordering and some3166subset of the integers under the <= ordering. That is, if31673168 (char<=? a b) ===> #t and (<= x y) ===> #t31693170and x and y are in the domain of integer->char, then31713172 (<= (char->integer a)3173 (char->integer b)) ===> #t31743175 (char<=? (integer->char x)3176 (integer->char y)) ===> #t31773178Note that {{integer->char}} does currently not detect3179a negative argument and will quietly convert {{-1}} to3180{{#x1ffff}} in CHICKEN.31813182==== Strings31833184Strings are sequences of characters. Strings are written as sequences of3185characters enclosed within quotation marks ("). Within a string literal,3186various escape sequences represent characters other than themselves. Escape3187sequences always start with a backslash (\):31883189* \a : alarm, U+000731903191* \b : backspace, U+000831923193* \t : character tabulation, U+000931943195* \n : linefeed, U+000A31963197* \r : return, U+000D31983199* \" : double quote, U+002232003201* \\ : backslash, U+005C32023203* \| : vertical line, U+007C32043205* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing32063207* \x<hex scalar value>; : specified character (note the terminating3208 semi-colon).32093210The result is unspecified if any other character in a string occurs after a3211backslash.32123213Except for a line ending, any character outside of an escape sequence stands3214for itself in the string literal. A line ending which is preceded by \3215<intraline whitespace> expands to nothing (along with any trailing intraline3216whitespace), and can be used to indent strings for improved legibility. Any3217other line ending has the same effect as inserting a \n character into the3218string.32193220Examples:32213222 "The word \"recursion\" has many meanings."3223 "Another example:\ntwo lines of text"3224 "Here's text \3225 containing just one line"3226 "\x03B1; is named GREEK SMALL LETTER ALPHA."32273228The length of a string is the3229number of characters that it contains. This number is an exact, non-negative3230integer that is fixed when the string is created. The valid indexes of a string3231are the exact non-negative integers less than the length of the string. The3232first character of a string has index 0, the second has index 1, and so on.32333234<procedure>(string? obj)</procedure><br>32353236Returns #t if obj is a string, otherwise returns #f.32373238<procedure>(make-string k)</procedure><br>3239<procedure>(make-string k char)</procedure><br>32403241Make-string returns a newly allocated string of length k. If char is3242given, then all elements of the string are initialized to char,3243otherwise the contents of the string are unspecified.32443245<procedure>(string char ...)</procedure><br>32463247Returns a newly allocated string composed of the arguments.32483249<procedure>(string-length string)</procedure><br>32503251Returns the number of characters in the given string.32523253<procedure>(string-ref string k)</procedure><br>32543255k must be a valid index of string. String-ref returns character k of3256string using zero-origin indexing.32573258<procedure>(string-set! string k char)</procedure><br>32593260k must be a valid index of string. String-set! stores char in element k3261of string and returns an unspecified value.32623263 (define (f) (make-string 3 #\*))3264 (define (g) "***")3265 (string-set! (f) 0 #\?) ===> unspecified3266 (string-set! (g) 0 #\?) ===> error3267 (string-set! (symbol->string 'immutable)3268 03269 #\?) ===> error32703271<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>32723273Returns #t if the two strings are the same length and contain the same3274characters in the same positions, otherwise returns #f.32753276<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>3277<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>3278<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>3279<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>32803281These procedures are the lexicographic extensions to strings of the3282corresponding orderings on characters. For example, string<? is the3283lexicographic ordering on strings induced by the ordering char<? on3284characters. If two strings differ in length but are the same up to the3285length of the shorter string, the shorter string is considered to be3286lexicographically less than the longer string.32873288<procedure>(substring string start [end])</procedure><br>32893290String must be a string, and start and end must be exact integers3291satisfying32923293 0 <= start <= end <= (string-length string)32943295Substring returns a newly allocated string formed from the characters3296of string beginning with index start (inclusive) and ending with index3297end (exclusive). The {{end}} argument is optional and defaults to the3298length of the string, this is a non-standard extension in CHICKEN.32993300<procedure>(string-append string ...)</procedure><br>33013302Returns a newly allocated string whose characters form the3303concatenation of the given strings.33043305<procedure>(string->list string [start [end]])</procedure><br>3306<procedure>(list->string list)</procedure><br>33073308String->list returns a newly allocated list of the characters that make3309up the given string between start and end. List->string returns a newly allocated string3310formed from the characters in the list list, which must be a list of3311characters. String->list and list->string are inverses so far as equal?3312is concerned.33133314<procedure>(string-copy string [start [end]])</procedure><br>33153316Returns a newly allocated copy of the given string.33173318<procedure>(string-copy! to at from [start [end]])</procedure>33193320It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.33213322Copies the characters of string from between start and end to string to, starting at3323at. The order in which characters are copied is unspecified, except that if the3324source and destination overlap, copying takes place as if the source is first3325copied into a temporary string and then into the destination. This can be3326achieved without allocating storage by making sure to copy in the correct3327direction in such circumstances.33283329 (define a "12345")3330 (define b (string-copy "abcde"))3331 (string-copy! b 1 a 0 2)3332 b ==> "a12de"33333334<procedure>(string-fill! string char +#!optional start end)</procedure><br>33353336Stores char in every element of the given string and returns an3337unspecified value. The optional start and end arguments specify3338the part of the string to be filled and default to the complete string.33393340==== Vectors33413342Vectors are heterogenous structures whose elements are indexed by3343integers. A vector typically occupies less space than a list of the3344same length, and the average time required to access a randomly chosen3345element is typically less for the vector than for the list.33463347The length of a vector is the number of elements that it contains. This3348number is a non-negative integer that is fixed when the vector is3349created. The valid indexes of a vector are the exact non-negative3350integers less than the length of the vector. The first element in a3351vector is indexed by zero, and the last element is indexed by one less3352than the length of the vector.33533354Vectors are written using the notation #(obj ...). For example, a3355vector of length 3 containing the number zero in element 0, the list (233562 2 2) in element 1, and the string "Anna" in element 2 can be written3357as following:33583359 #(0 (2 2 2 2) "Anna")33603361Vector constants are self-evaluating, so they do not need3362to be quoted in programs.33633364<procedure>(vector? obj)</procedure><br>33653366Returns #t if obj is a vector, otherwise returns #f.33673368<procedure>(make-vector k)</procedure><br>3369<procedure>(make-vector k fill)</procedure><br>33703371Returns a newly allocated vector of k elements. If a second argument is3372given, then each element is initialized to fill. Otherwise the initial3373contents of each element is unspecified.33743375<procedure>(vector obj ...)</procedure><br>33763377Returns a newly allocated vector whose elements contain the given3378arguments. Analogous to list.33793380 (vector 'a 'b 'c) ===> #(a b c)33813382<procedure>(vector-length vector)</procedure><br>33833384Returns the number of elements in vector as an exact integer.33853386<procedure>(vector-ref vector k)</procedure><br>33873388k must be a valid index of vector. Vector-ref returns the contents of3389element k of vector.33903391 (vector-ref '#(1 1 2 3 5 8 13 21)3392 5)3393 ===> 83394 (vector-ref '#(1 1 2 3 5 8 13 21)3395 (let ((i (round (* 2 (acos -1)))))3396 (if (inexact? i)3397 (inexact->exact i)3398 i)))3399 ===> 1334003401<procedure>(vector-set! vector k obj)</procedure><br>34023403k must be a valid index of vector. Vector-set! stores obj in element k3404of vector. The value returned by vector-set! is unspecified.34053406 (let ((vec (vector 0 '(2 2 2 2) "Anna")))3407 (vector-set! vec 1 '("Sue" "Sue"))3408 vec)3409 ===> #(0 ("Sue" "Sue") "Anna")34103411 (vector-set! '#(0 1 2) 1 "doe")3412 ===> error ; constant vector34133414<procedure>(vector->list vector [start [end]])</procedure><br>3415<procedure>(list->vector list)</procedure><br>34163417Vector->list returns a newly allocated list of the objects contained in3418the elements of vector. List->vector returns a newly created vector3419initialized to the elements of the list list.34203421 (vector->list '#(dah dah didah))3422 ===> (dah dah didah)3423 (list->vector '(dididit dah))3424 ===> #(dididit dah)34253426<procedure>(vector-fill! vector fill)</procedure><br>34273428Stores fill in every element of vector. The value returned by3429vector-fill! is unspecified.34303431<procedure>(vector->string vector [start [end]])</procedure><br>3432<procedure(string->vector string [start [end]])</procedure>34333434It is an error if any element of vector between start and end is not a character.34353436The vector->string procedure returns a newly allocated string of the objects3437contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to3438the elements of the string string between start and end.34393440In both procedures, order is preserved.34413442 (string->vector "ABC") ==> #(#\A #\B #\C)3443 (vector->string #(#\1 #\2 #\3) ==> "123"34443445<procedure>(vector-copy vector [start [end]])</procedure>34463447Returns a newly allocated copy of the elements of the given vector between3448start and end. The elements of the new vector are the same (in the sense of eqv?) as the3449elements of the old.34503451 (define a #(1 8 2 8)) ; a may be immutable3452 (define b (vector-copy a))3453 (vector-set! b 0 3) ; b is mutable3454 b ==> #(3 8 2 8)3455 (define c (vector-copy b 1 3))3456 c ==> #(8 2)34573458<procedure>(vector-copy! to at from [start [end]])</procedure>34593460It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.34613462Copies the elements of vector from between start and end to vector to, starting at3463at. The order in which elements are copied is unspecified, except that if the3464source and destination overlap, copying takes place as if the source is first3465copied into a temporary vector and then into the destination. This can be3466achieved without allocating storage by making sure to copy in the correct3467direction in such circumstances.34683469 (define a (vector 1 2 3 4 5))3470 (define b (vector 10 20 30 40 50))3471 (vector-copy! b 1 a 0 2)3472 b ==> #(10 1 2 40 50)34733474<procedure>(vector-append vector ....)</procedure>34753476Returns a newly allocated vector whose elements are the concatenation of the3477elements of the given vectors.34783479 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)34803481<procedure>(vector-fill! vector fill [start [end)]])</procedure>34823483The vector-fill! procedure stores fill in the elements of vector between start and3484end.34853486 (define a (vector 1 2 3 4 5))3487 (vector-fill! a 'smash 2 4)3488 a ==>#(1 2 smash smash 5)34893490==== Bytevectors34913492Bytevectors represent blocks of binary data. They are fixed-length sequences of3493bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A3494bytevector is typically more space-efficient than a vector containing the same3495values.34963497See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more3498information. {{(scheme base)}} re-exports all R7RS-specific procedures from3499that module.35003501=== Control features35023503This chapter describes various primitive procedures which control the3504flow of program execution in special ways. The procedure? predicate is3505also described here.35063507<procedure>(procedure? obj)</procedure><br>35083509Returns #t if obj is a procedure, otherwise returns #f.35103511 (procedure? car) ===> #t3512 (procedure? 'car) ===> #f3513 (procedure? (lambda (x) (* x x)))3514 ===> #t3515 (procedure? '(lambda (x) (* x x)))3516 ===> #f3517 (call-with-current-continuation procedure?)3518 ===> #t35193520<procedure>(apply proc arg[1] ... args)</procedure><br>35213522Proc must be a procedure and args must be a list. Calls proc with the3523elements of the list (append (list arg[1] ...) args) as the actual3524arguments.35253526 (apply + (list 3 4)) ===> 735273528 (define compose3529 (lambda (f g)3530 (lambda args3531 (f (apply g args)))))35323533 ((compose sqrt *) 12 75) ===> 3035343535<procedure>(map proc list[1] list[2] ...)</procedure><br>35363537The lists must be lists, and proc must be a procedure taking as many3538arguments as there are lists and returning a single value. Map applies3539proc element-wise to the elements of the lists and returns a list of3540the results, in order. The dynamic order in which proc is applied to3541the elements of the lists is unspecified.35423543Like in SRFI-1, this procedure allows the arguments to be of unequal3544length; it terminates when the shortest list runs out. This is a3545CHICKEN extension to R7RS.35463547 (map cadr '((a b) (d e) (g h)))3548 ===> (b e h)35493550 (map (lambda (n) (expt n n))3551 '(1 2 3 4 5))3552 ===> (1 4 27 256 3125)35533554 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)35553556 (let ((count 0))3557 (map (lambda (ignored)3558 (set! count (+ count 1))3559 count)3560 '(a b))) ===> (1 2) or (2 1)35613562<procedure>(string-map proc string[1] string[2] ...)</procedure>35633564It is an error if proc does not accept as many arguments as there are strings and return a single character.35653566The string-map procedure applies proc element-wise to the elements of the3567strings and returns a string of the results, in order. If more than one3568string is given and not all strings have the same length, string-map terminates3569when the shortest string runs out. The dynamic order in which3570proc is applied to the elements of the3571strings is unspecified. If multiple returns occur from string-map, the values3572returned by earlier returns are not mutated.35733574 (string-map char-foldcase "AbdEgH") ==> "abdegh"35753576 (string-map3577 (lambda (c)3578 (integer->char (+ 1 (char->integer c))))3579 "HAL") ==> "IBM"35803581 (string-map3582 (lambda (c k)3583 ((if (eqv? k #\u) char-upcase char-downcase)3584 c))3585 "studlycaps xxx"3586 "ululululul") ==> "StUdLyCaPs"35873588<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>35893590It is an error if proc does not accept as many arguments as there are vectors and return a single value.35913592The vector-map procedure applies proc element-wise to the elements of the3593vectors and returns a vector of the results, in order. If more than one3594vector is given and not all vectors have the same length, vector-map terminates3595when the shortest vector runs out. The dynamic order in which3596proc is applied to the elements of the3597vectors is unspecified. If multiple returns occur from vector-map, the values3598returned by earlier returns are not mutated.35993600 (vector-map cadr '#((a b) (d e) (g h)))3601 ==> #(b e h)36023603 (vector-map (lambda (n) (expt n n))3604 '#(1 2 3 4 5))3605 ==> #(1 4 27 256 3125)36063607 (vector-map + '#(1 2 3) '#(4 5 6 7))3608 ==> #(5 7 9)36093610 (let ((count 0))3611 (vector-map3612 (lambda (ignored)3613 (set! count (+ count 1))3614 count)3615 '#(a b))) ==> #(1 2) or #(2 1)36163617<procedure>(for-each proc list[1] list[2] ...)</procedure><br>36183619The arguments to for-each are like the arguments to map, but for-each3620calls proc for its side effects rather than for its values. Unlike map,3621for-each is guaranteed to call proc on the elements of the lists in3622order from the first element(s) to the last, and the value returned by3623for-each is unspecified.36243625 (let ((v (make-vector 5)))3626 (for-each (lambda (i)3627 (vector-set! v i (* i i)))3628 '(0 1 2 3 4))3629 v) ===> #(0 1 4 9 16)36303631Like in SRFI-1, this procedure allows the arguments to be of unequal3632length; it terminates when the shortest list runs out. This is a3633CHICKEN extension to R7RS.36343635<procedure>(string-for-each proc string[1] string[2] ...)</procedure>36363637It is an error if proc does not accept as many arguments as there are strings.3638The arguments to string-for-each are like the arguments to string-map, but3639string-for-each calls3640proc for its side effects rather than for its values. Unlike string-map,3641string-for-each is guaranteed to call3642proc on the elements of the3643strings in order from the first element(s) to the last, and the value returned3644by string-for-each is unspecified. If more than one3645string is given and not all strings have the same length, string-for-each3646terminates when the shortest string runs out. It is an error for3647proc to mutate any of the strings.36483649 (let ((v '()))3650 (string-for-each3651 (lambda (c) (set! v (cons (char->integer c) v)))3652 "abcde")3653 v) ==> (101 100 99 98 97)36543655<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>36563657It is an error if proc does not accept as many arguments as there are vectors.3658The arguments to vector-for-each are like the arguments to vector-map, but3659vector-for-each calls3660proc for its side effects rather than for its values. Unlike vector-map,3661vector-for-each is guaranteed to call3662proc on the elements of the3663vectors in order from the first element(s) to the last, and the value returned3664by vector-for-each is unspecified. If more than one3665vector is given and not all vectors have the same length, vector-for-each3666terminates when the shortest vector runs out. It is an error for3667proc to mutate any of the vectors.36683669 (let ((v (make-list 5)))3670 (vector-for-each3671 (lambda (i) (list-set! v i (* i i)))3672 '#(0 1 2 3 4))3673 v) ==> (0 1 4 9 16)36743675<procedure>(call-with-current-continuation proc)</procedure><br>3676<procedure>(call/cc proc)</procedure><br>36773678Proc must be a procedure of one argument. The procedure3679call-with-current-continuation packages up the current continuation3680(see the rationale below) as an "escape procedure" and passes it as3681an argument to proc. The escape procedure is a Scheme procedure that,3682if it is later called, will abandon whatever continuation is in effect3683at that later time and will instead use the continuation that was in3684effect when the escape procedure was created. Calling the escape3685procedure may cause the invocation of before and after thunks installed3686using dynamic-wind.36873688The escape procedure accepts the same number of arguments as the3689continuation to the original call to call-with-current-continuation.3690Except for continuations created by the call-with-values procedure, all3691continuations take exactly one value. The effect of passing no value or3692more than one value to continuations that were not created by3693call-with-values is unspecified.36943695The escape procedure that is passed to proc has unlimited extent just3696like any other procedure in Scheme. It may be stored in variables or3697data structures and may be called as many times as desired.36983699The following examples show only the most common ways in which3700call-with-current-continuation is used. If all real uses were as simple3701as these examples, there would be no need for a procedure with the3702power of call-with-current-continuation.37033704 (call-with-current-continuation3705 (lambda (exit)3706 (for-each (lambda (x)3707 (if (negative? x)3708 (exit x)))3709 '(54 0 37 -3 245 19))3710 #t)) ===> -337113712 (define list-length3713 (lambda (obj)3714 (call-with-current-continuation3715 (lambda (return)3716 (letrec ((r3717 (lambda (obj)3718 (cond ((null? obj) 0)3719 ((pair? obj)3720 (+ (r (cdr obj)) 1))3721 (else (return #f))))))3722 (r obj))))))37233724 (list-length '(1 2 3 4)) ===> 437253726 (list-length '(a b . c)) ===> #f37273728Rationale:37293730A common use of call-with-current-continuation is for structured,3731non-local exits from loops or procedure bodies, but in fact3732call-with-current-continuation is extremely useful for implementing3733a wide variety of advanced control structures.37343735Whenever a Scheme expression is evaluated there is a continuation3736wanting the result of the expression. The continuation represents3737an entire (default) future for the computation. If the expression3738is evaluated at top level, for example, then the continuation might3739take the result, print it on the screen, prompt for the next input,3740evaluate it, and so on forever. Most of the time the continuation3741includes actions specified by user code, as in a continuation that3742will take the result, multiply it by the value stored in a local3743variable, add seven, and give the answer to the top level3744continuation to be printed. Normally these ubiquitous continuations3745are hidden behind the scenes and programmers do not think much3746about them. On rare occasions, however, a programmer may need to3747deal with continuations explicitly. Call-with-current-continuation3748allows Scheme programmers to do that by creating a procedure that3749acts just like the current continuation.37503751Most programming languages incorporate one or more special-purpose3752escape constructs with names like exit, return, or even goto. In37531965, however, Peter Landin [16] invented a general purpose escape3754operator called the J-operator. John Reynolds [24] described a3755simpler but equally powerful construct in 1972. The catch special3756form described by Sussman and Steele in the 1975 report on Scheme3757is exactly the same as Reynolds's construct, though its name came3758from a less general construct in MacLisp. Several Scheme3759implementors noticed that the full power of the catch construct3760could be provided by a procedure instead of by a special syntactic3761construct, and the name call-with-current-continuation was coined3762in 1982. This name is descriptive, but opinions differ on the3763merits of such a long name, and some people use the name call/cc3764instead.37653766<procedure>(values obj ...)</procedure><br>37673768Delivers all of its arguments to its continuation. Except for3769continuations created by the call-with-values procedure, all3770continuations take exactly one value. Values might be defined as3771follows:37723773 (define (values . things)3774 (call-with-current-continuation3775 (lambda (cont) (apply cont things))))37763777<procedure>(call-with-values producer consumer)</procedure><br>37783779Calls its producer argument with no values and a continuation that,3780when passed some values, calls the consumer procedure with those values3781as arguments. The continuation for the call to consumer is the3782continuation of the call to call-with-values.37833784 (call-with-values (lambda () (values 4 5))3785 (lambda (a b) b))3786 ===> 537873788 (call-with-values * -) ===> -137893790<procedure>(dynamic-wind before thunk after)</procedure><br>37913792Calls thunk without arguments, returning the result(s) of this call.3793Before and after are called, also without arguments, as required by the3794following rules (note that in the absence of calls to continuations3795captured using call-with-current-continuation the three arguments are3796called once each, in order). Before is called whenever execution enters3797the dynamic extent of the call to thunk and after is called whenever it3798exits that dynamic extent. The dynamic extent of a procedure call is3799the period between when the call is initiated and when it returns. In3800Scheme, because of call-with-current-continuation, the dynamic extent3801of a call may not be a single, connected time period. It is defined as3802follows:38033804* The dynamic extent is entered when execution of the body of the3805 called procedure begins.38063807* The dynamic extent is also entered when execution is not within the3808 dynamic extent and a continuation is invoked that was captured3809 (using call-with-current-continuation) during the dynamic extent.38103811* It is exited when the called procedure returns.38123813* It is also exited when execution is within the dynamic extent and a3814 continuation is invoked that was captured while not within the3815 dynamic extent.38163817If a second call to dynamic-wind occurs within the dynamic extent of3818the call to thunk and then a continuation is invoked in such a way that3819the afters from these two invocations of dynamic-wind are both to be3820called, then the after associated with the second (inner) call to3821dynamic-wind is called first.38223823If a second call to dynamic-wind occurs within the dynamic extent of3824the call to thunk and then a continuation is invoked in such a way that3825the befores from these two invocations of dynamic-wind are both to be3826called, then the before associated with the first (outer) call to3827dynamic-wind is called first.38283829If invoking a continuation requires calling the before from one call to3830dynamic-wind and the after from another, then the after is called3831first.38323833The effect of using a captured continuation to enter or exit the3834dynamic extent of a call to before or after is undefined. However,3835in CHICKEN it is safe to do this, and they will execute in the outer3836dynamic context of the {{dynamic-wind}} form.38373838 (let ((path '())3839 (c #f))3840 (let ((add (lambda (s)3841 (set! path (cons s path)))))3842 (dynamic-wind3843 (lambda () (add 'connect))3844 (lambda ()3845 (add (call-with-current-continuation3846 (lambda (c0)3847 (set! c c0)3848 'talk1))))3849 (lambda () (add 'disconnect)))3850 (if (< (length path) 4)3851 (c 'talk2)3852 (reverse path))))38533854 ===> (connect talk1 disconnect3855 connect talk2 disconnect)38563857=== Exceptions38583859This section describes Scheme’s exception-handling and exception-raising3860procedures.38613862Exception handlers are one-argument procedures that determine the action the3863program takes when an exceptional situation is signaled. The system implicitly3864maintains a current exception handler in the dynamic environment.38653866The program raises an exception by invoking the current exception handler,3867passing it an object encapsulating information about the exception. Any3868procedure accepting one argument can serve as an exception handler and any3869object can be used to represent an exception.38703871<procedure>(with-exception-handler handler thunk)</procedure>38723873It is an error if handler does not accept one argument. It is also an error if3874thunk does not accept zero arguments.3875The with-exception-handler procedure returns the results of invoking3876thunk.3877Handler is installed as the current exception handler in the dynamic3878environment used for the invocation of3879thunk.38803881 (call-with-current-continuation3882 (lambda (k)3883 (with-exception-handler3884 (lambda (x)3885 (display "condition: ")3886 (write x)3887 (newline)3888 (k 'exception))3889 (lambda ()3890 (+ 1 (raise 'an-error))))))3891 ==> exception and prints "condition: an-error"38923893 (with-exception-handler3894 (lambda (x)3895 (display "something went wrong\n"))3896 (lambda ()3897 (+ 1 (raise 'an-error))))38983899prints "something went wrong"3900After printing, the second example then raises another exception.39013902<procedure>(raise obj)</procedure>39033904Raises an exception by invoking the current exception handler on3905obj. The handler is called with the same dynamic environment as that of the3906call to raise, except that the current exception handler is the one that was in3907place when the handler being called was installed. If the handler returns, a3908secondary exception is raised in the same dynamic environment as the handler.3909The relationship between3910obj and the object raised by the secondary exception is unspecified.39113912<procedure>(raise-continuable obj)</procedure>39133914Raises an exception by invoking the current exception handler on3915obj. The handler is called with the same dynamic environment as the call to3916raise-continuable, except that: (1) the current exception handler is the one3917that was in place when the handler being called was installed, and (2) if the3918handler being called returns, then it will again become the current exception3919handler. If the handler returns, the values it returns become the values3920returned by the call to raise-continuable.39213922 (with-exception-handler3923 (lambda (con)3924 (cond3925 ((string? con)3926 (display con))3927 (else3928 (display "a warning has been issued")))3929 42)3930 (lambda ()3931 (+ (raise-continuable "should be a number")3932 23)))3933 prints: "should be a number"3934 ==> 6539353936<procedure>(error [location] message obj ...)</procedure>39373938Message should be a string.3939Raises an exception as if by calling raise on a newly allocated3940implementation-defined object which encapsulates the information provided by3941message, as well as any3942objs, known as the irritants. The procedure error-object? must return #t on3943such objects.39443945 (define (null-list? l)3946 (cond ((pair? l) #f)3947 ((null? l) #t)3948 (else3949 (error3950 "null-list?: argument out of domain"3951 l))))39523953If location is given and a symbol, it indicates the name of the procedure where3954the error occurred.39553956<procedure>(error-object? obj)</procedure>39573958Returns #t if3959obj is an object created by error or one of an implementation-defined set of3960objects. Otherwise, it returns #f. The objects used to signal errors, including3961those which satisfy the predicates file-error? and read-error?, may or may not3962satisfy error-object?.39633964<procedure>(error-object-message error-object)</procedure>39653966Returns the message encapsulated by3967error-object.39683969<procedure>(error-object-irritants error-object)</procedure>39703971Returns a list of the irritants encapsulated by3972error-object.39733974<procedure>(read-error? obj)</procedure><br>3975<procedure>(file-error? obj)</procedure>39763977Error type predicates. Returns #t if3978obj is an object raised by the read procedure or by the inability to open an3979input or output port on a file, respectively. Otherwise, it returns #f.39803981=== Eval39823983<procedure>(eval expression [environment-specifier])</procedure><br>39843985Evaluates expression in the specified environment and returns its3986value. Expression must be a valid Scheme expression represented as3987data, and environment-specifier must be a value returned by one of the3988three procedures described below. Implementations may extend eval to3989allow non-expression programs (definitions) as the first argument and3990to allow other values as environments, with the restriction that eval3991is not allowed to create new bindings in the environments associated3992with null-environment or scheme-report-environment.39933994 (eval '(* 7 3) (scheme-report-environment 5))3995 ===> 2139963997 (let ((f (eval '(lambda (f x) (f x x))3998 (null-environment 5))))3999 (f + 10))4000 ===> 2040014002The {{environment-specifier}} is optional, and if not provided it4003defaults to the value of {{(interaction-environment)}}. This is a4004CHICKEN extension to R7RS, which, though strictly nonportable, is very4005common among Scheme implementations.40064007=== Input and output40084009==== Ports40104011Ports represent input and output devices. To Scheme, an input port is a Scheme4012object that can deliver data upon command, while an output port is a Scheme4013object that can accept data.40144015Different port types operate on different data. Scheme implementations are4016required to support textual ports and binary ports, but may also provide other4017port types.40184019A textual port supports reading or writing of individual characters from or to4020a backing store containing characters using read-char and write-char below, and4021it supports operations defined in terms of characters, such as read and write.40224023A binary port supports reading or writing of individual bytes from or to a4024backing store containing bytes using read-u8 and write-u8 below, as well as4025operations defined in terms of bytes. Whether the textual and binary port types4026are disjoint is implementation-dependent.40274028Ports can be used to access files, devices, and similar things on the host4029system on which the Scheme program is running.40304031<procedure>(call-with-port port proc)</procedure>40324033It is an error if4034proc does not accept one argument.4035The call-with-port procedure calls4036proc with4037port as an argument. If4038proc returns, then the port is closed automatically and the values yielded by4039the4040proc are returned. If40414042proc does not return, then the port must not be closed automatically unless it4043is possible to prove that the port will never again be used for a read or write4044operation.40454046 Rationale: Because Scheme’s escape procedures have unlimited extent, it is4047 possible to escape from the current continuation but later to resume it. If4048 implementations were permitted to close the port on any escape from the4049 current continuation, then it would be impossible to write portable code4050 using both call-with-current-continuation and call-with-port.40514052Ports represent input and output devices. To Scheme, an input port is a4053Scheme object that can deliver characters upon command, while an output4054port is a Scheme object that can accept characters.40554056<procedure>(input-port? obj)</procedure><br>4057<procedure>(output-port? obj)</procedure><br>4058<procedure>(textual-port? obj)</procedure><br>4059<procedure>(binary-port? obj)</procedure><br>4060<procedure>(port? obj)</procedure>40614062These procedures return #t if4063obj is an input port, output port, textual port, binary port, or any kind of4064port, respectively. Otherwise they return #f.40654066<procedure>(input-port-open? port)</procedure><br>4067<procedure>(output-port-open? port)</procedure>40684069Returns #t if4070port is still open and capable of performing input or output, respectively, and4071#f otherwise.40724073<procedure>(current-input-port [port])</procedure><br>4074<procedure>(current-output-port [port])</procedure><br>4075<procedure>(current-error-port [port])</procedure><br>40764077Returns the current default input, output or error port.40784079If the optional {{port}} argument is passed, the current input or4080output port is changed to the provided port. It can also be used with4081{{parameterize}} to temporarily bind the port to another value. This4082is a CHICKEN extension to the R7RS standard.40834084Note that the default output port is not buffered. Use4085[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]4086if you need a different behavior.40874088<procedure>(open-input-file filename [mode ...])</procedure><br>4089<procedure>(open-binary-input-file filename [mode ...])</procedure>40904091Takes a string naming an existing file and returns an input port4092capable of delivering textual or binary data from the file. If the file cannot be4093opened, an error is signalled.40944095Additional {{mode}} arguments can be passed in, which should be any of4096the keywords {{#:text}} or {{#:binary}}. These indicate the mode in4097which to open the file (this has an effect on non-UNIX platforms4098only). The extra {{mode}} arguments are CHICKEN extensions to the4099R7RS standard.41004101<procedure>(close-port port)</procedure><br>4102<procedure>(close-input-port port)</procedure><br>4103<procedure>(close-output-port port)</procedure><br>41044105Closes the resource associated with4106port, rendering the4107port incapable of delivering or accepting data. It is an error to apply the4108last two procedures to a port which is not an input or output port,4109respectively. Scheme implementations may provide ports which are simultaneously4110input and output ports, such as sockets; the close-input-port and4111close-output-port procedures can then be used to close the input and output4112sides of the port independently.41134114These routines have no effect if the port has already been closed.41154116<procedure>(open-input-string string)</procedure>41174118Takes a string and returns a textual input port that delivers characters from4119the string. If the string is modified, the effect is unspecified.41204121<procedure>(open-output-string)</procedure>41224123Returns a textual output port that will accumulate characters for retrieval by4124get-output-string.41254126<procedure>(get-output-string port)</procedure>41274128It is an error if4129port was not created with open-output-string.4130Returns a string consisting of the characters that have been output to the port4131so far in the order they were output. If the result string is modified, the4132effect is unspecified.41334134 (parameterize4135 ((current-output-port4136 (open-output-string)))4137 (display "piece")4138 (display " by piece ")4139 (display "by piece.")4140 (newline)4141 (get-output-string (current-output-port)))4142 ==> "piece by piece by piece.\n"41434144<procedure>(open-input-bytevector bytevector)</procedure>41454146Takes a bytevector and returns a binary input port that delivers bytes from the4147bytevector.41484149<procedure>(open-output-bytevector)</procedure>41504151Returns a binary output port that will accumulate bytes for retrieval by4152get-output-bytevector.41534154<procedure>(get-output-bytevector port)</procedure>41554156It is an error if4157port was not created with open-output-bytevector.4158Returns a bytevector consisting of the bytes that have been output to the port4159so far in the order they were output.41604161==== Input41624163If port is omitted from any input procedure, it defaults to the value returned by4164(current-input-port). It is an error to attempt an input operation on a closed4165port.41664167<procedure>(read-char [port])</procedure><br>41684169Returns the next character available from the input port, updating the4170port to point to the following character. If no more characters are4171available, an end of file object is returned. Port may be omitted, in4172which case it defaults to the value returned by current-input-port.41734174<procedure>(peek-char [port])</procedure><br>41754176Returns the next character available from the input port, without4177updating the port to point to the following character. If no more4178characters are available, an end of file object is returned. Port may4179be omitted, in which case it defaults to the value returned by4180current-input-port.41814182Note: The value returned by a call to peek-char is the same as4183the value that would have been returned by a call to read-char with4184the same port. The only difference is that the very next call to4185read-char or peek-char on that port will return the value returned4186by the preceding call to peek-char. In particular, a call to4187peek-char on an interactive port will hang waiting for input4188whenever a call to read-char would have hung.41894190<procedure>(read-line [port])</procedure>41914192Returns the next line of text available from the textual input4193port, updating the4194port to point to the following character. If an end of line is read, a string4195containing all of the text up to (but not including) the end of line is4196returned, and the port is updated to point just past the end of line. If an end4197of file is encountered before any end of line is read, but some characters have4198been read, a string containing those characters is returned. If an end of file4199is encountered before any characters are read, an end-of-file object is4200returned. For the purpose of this procedure, an end of line consists of either4201a linefeed character, a carriage return character, or a sequence of a carriage4202return character followed by a linefeed character. Implementations may also4203recognize other end of line characters or sequences.42044205<procedure>(eof-object? obj)</procedure><br>42064207Returns #t if obj is an end of file object, otherwise returns #f. The4208precise set of end of file objects will vary among implementations, but4209in any case no end of file object will ever be an object that can be4210read in using read.42114212<procedure>(eof-object)</procedure>42134214Returns an end-of-file object, not necessarily unique.42154216<procedure>(char-ready? [port])</procedure><br>42174218Returns #t if a character is ready on the input port and returns #f4219otherwise. If char-ready returns #t then the next read-char operation4220on the given port is guaranteed not to hang. If the port is at end of4221file then char-ready? returns #t. Port may be omitted, in which case it4222defaults to the value returned by current-input-port.42234224Rationale: Char-ready? exists to make it possible for a program4225to accept characters from interactive ports without getting stuck4226waiting for input. Any input editors associated with such ports4227must ensure that characters whose existence has been asserted by4228char-ready? cannot be rubbed out. If char-ready? were to return #f4229at end of file, a port at end of file would be indistinguishable4230from an interactive port that has no ready characters.42314232<procedure>(read-string k [port])</procedure>42334234See [[Module (chicken io)|(chicken io) module]] for more information.42354236<procedure>(read-u8 [port])</procedure>42374238Returns the next byte available from the binary input4239port, updating the4240port to point to the following byte. If no more bytes are available, an4241end-of-file object is returned.42424243<procedure>(peek-u8 [port])</procedure>42444245Returns the next byte available from the binary input4246port, but without updating the4247port to point to the following byte. If no more bytes are available, an4248end-of-file object is returned.42494250<procedure>(u8-ready? [port])</procedure>42514252Returns #t if a byte is ready on the binary input4253port and returns #f otherwise. If u8-ready? returns #t then the next read-u84254operation on the given4255port is guaranteed not to hang. If the4256port is at end of file then u8-ready? returns #t.42574258<procedure>(read-bytevector k [port])</procedure><br>4259<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>42604261See [[Module (chicken io)|(chicken io) module]] for more information.42624263==== Output42644265If port is omitted from any output procedure, it defaults to the value returned by4266(current-output-port). It is an error to attempt an output operation on a4267closed port.42684269<procedure>(newline)</procedure><br>4270<procedure>(newline port)</procedure><br>42714272Writes an end of line to port. Exactly how this is done differs from4273one operating system to another. Returns an unspecified value. The port4274argument may be omitted, in which case it defaults to the value4275returned by current-output-port.42764277<procedure>(write-char char)</procedure><br>4278<procedure>(write-char char port)</procedure><br>42794280Writes the character char (not an external representation of the4281character) to the given port and returns an unspecified value. The port4282argument may be omitted, in which case it defaults to the value4283returned by current-output-port.42844285<procedure>(write-string string [port [start [end]]])</procedurew>42864287Writes the characters of4288string from4289start to4290end in left-to-right order to the textual output4291port.42924293<procedure>(write-u8 byte [port])</procedure>42944295Writes the4296byte to the given binary output4297port and returns an unspecified value.42984299<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>43004301See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more4302information.43034304<procedure>(flush-output-port [port])</procedure>43054306Flushes any buffered output from the buffer of output-port to the underlying4307file or device and returns an unspecified value.43084309==== System interface43104311Questions of system interface generally fall outside of the domain of4312this report. However, the following operations are important enough to4313deserve description here.43144315<procedure>(features)</procedure>43164317Returns a list of the feature identifiers which cond-expand treats as true. It4318is an error to modify this list. Here is an example of what features might4319return:43204321 (features) ==>4322 (r7rs ratios exact-complex full-unicode4323 gnu-linux little-endian4324 fantastic-scheme4325 fantastic-scheme-1.04326 space-ship-control-system)43274328---4329Previous: [[Module scheme]]43304331Next: [[Module (scheme case-lambda)]]