~ 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* {{(export-all)}}16231624* {{(import <import set> ...)}}16251626* {{(begin <command or definition> ...)}}16271628* {{(include <filename[1]> <filename[2]> ...)}}16291630* {{(include-ci <filename[1]> <filename[2]> ...)}}16311632* {{(include-library-declarations <filename[1]> <filename[2]> ...)}}16331634* {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}16351636An export declaration specifies a list of identifiers which can be made visible1637to other libraries or programs. An <export spec> takes one of the following1638forms:16391640* <identifier>16411642* {{(rename <identifier[1]> <identifier[2]>)}}16431644In an <export spec>, an <identifier> names a single binding defined within or1645imported into the library, where the external name for the export is the same1646as the name of the binding within the library. A {{rename}} spec exports the1647binding defined within or imported into the library and named by <identifier1648[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>1649as the external name.16501651As an extension to R7RS, CHICKEN allows the {{(export-all)}} specifier,1652which exports all defined entities to be visible when importing the1653library.16541655An import declaration provides a way to import the identifiers exported by1656another library.16571658The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of1659the library. They have the same syntax and semantics as the corresponding1660expression types. This form of begin is analogous to, but not the same as, the1661two types of begin defined in section 4.2.3.16621663The {{include-library-declarations}} declaration is similar to {{include}} except that1664the contents of the file are spliced directly into the current library1665definition. This can be used, for example, to share the same export declaration1666among multiple libraries as a simple form of library interface.16671668The {{cond-expand}} declaration has the same syntax and semantics as the1669{{cond-expand}} expression type, except that it expands to spliced-in library1670declarations rather than expressions enclosed in begin.16711672One possible implementation of libraries is as follows: After all {{cond-expand}}1673library declarations are expanded, a new environment is constructed for the1674library consisting of all imported bindings. The expressions from all begin,1675{{include}} and {{include-ci}} library declarations are expanded in that environment in1676the order in which they occur in the library. Alternatively, {{cond-expand}} and1677{{import}} declarations may be processed in left to right order interspersed with1678the processing of other declarations, with the environment growing as imported1679bindings are added to it by each import declaration.16801681When a library is loaded, its expressions are executed in textual order. If a1682library’s definitions are referenced in the expanded form of a program or1683library body, then that library must be loaded before the expanded program or1684library body is evaluated. This rule applies transitively. If a library is1685imported by more than one program or library, it may possibly be loaded1686additional times.16871688Similarly, during the expansion of a library (foo), if any syntax keywords1689imported from another library (bar) are needed to expand the library, then the1690library (bar) must be expanded and its syntax definitions evaluated before the1691expansion of (foo).169216931694== Standard procedures16951696This chapter describes Scheme's built-in procedures. The initial (or1697"top level") Scheme environment starts out with a number of variables1698bound to locations containing useful values, most of which are1699primitive procedures that manipulate data. For example, the variable1700abs is bound to (a location initially containing) a procedure of one1701argument that computes the absolute value of a number, and the variable1702+ is bound to a procedure that computes sums. Built-in procedures that1703can easily be written in terms of other built-in procedures are1704identified as "library procedures".17051706A program may use a top-level definition to bind any variable. It may1707subsequently alter any such binding by an assignment (see1708[[#assignments|assignments]], above). These operations do1709not modify the behavior of Scheme's built-in procedures. Altering any1710top-level binding that has not been introduced by a definition has an1711unspecified effect on the behavior of the built-in procedures.17121713=== Equivalence predicates17141715A predicate is a procedure that always returns a boolean value (#t or #f).1716An equivalence predicate is the computational analogue of a1717mathematical equivalence relation (it is symmetric, reflexive, and1718transitive). Of the equivalence predicates described in this section,1719eq? is the finest or most discriminating, and equal? is the coarsest.1720eqv? is slightly less discriminating than eq?.17211722<procedure>(eqv? obj[1] obj[2])</procedure><br>17231724The eqv? procedure defines a useful equivalence relation on objects.1725Briefly, it returns #t if obj[1] and obj[2] should normally be regarded1726as the same object. This relation is left slightly open to1727interpretation, but the following partial specification of eqv? holds1728for all implementations of Scheme.17291730The eqv? procedure returns #t if:17311732* obj[1] and obj[2] are both #t or both #f.17331734* obj[1] and obj[2] are both symbols and17351736 (string=? (symbol->string obj1)1737 (symbol->string obj2))1738 ===> #t17391740Note: This assumes that neither obj[1] nor obj[2] is an "uninterned1741symbol" as alluded to in the section on [[#symbols|symbols]]. This1742report does not presume to specify the behavior of eqv? on1743implementation-dependent extensions.17441745* obj[1] and obj[2] are both numbers, are numerically equal (see =,1746 under [[#numerical-operations|numerical operations]]), and are1747 either both exact or both inexact.17481749* obj[1] and obj[2] are both characters and are the same character1750 according to the char=? procedure (see "[[#characters|characters]]").17511752* both obj[1] and obj[2] are the empty list.17531754* obj[1] and obj[2] are pairs, vectors, or strings that denote the1755 same locations in the store.17561757* obj[1] and obj[2] are procedures whose location tags are equal1758 (see "[[#procedures|procedures]]").17591760The eqv? procedure returns #f if:17611762* obj[1] and obj[2] are of different types.17631764* one of obj[1] and obj[2] is #t but the other is #f.17651766* obj[1] and obj[2] are symbols but17671768 (string=? (symbol->string obj[1])1769 (symbol->string obj[2]))1770 ===> #f17711772* one of obj[1] and obj[2] is an exact number but the other is an1773 inexact number.17741775* obj[1] and obj[2] are numbers for which the = procedure returns #f.17761777* obj[1] and obj[2] are characters for which the char=? procedure1778 returns #f.17791780* one of obj[1] and obj[2] is the empty list but the other is not.17811782* obj[1] and obj[2] are pairs, vectors, or strings that denote1783 distinct locations.17841785* obj[1] and obj[2] are procedures that would behave differently1786 (return different value(s) or have different side effects) for some1787 arguments.17881789 (eqv? 'a 'a) ===> #t1790 (eqv? 'a 'b) ===> #f1791 (eqv? 2 2) ===> #t1792 (eqv? '() '()) ===> #t1793 (eqv? 100000000 100000000) ===> #t1794 (eqv? (cons 1 2) (cons 1 2)) ===> #f1795 (eqv? (lambda () 1)1796 (lambda () 2)) ===> #f1797 (eqv? #f 'nil) ===> #f1798 (let ((p (lambda (x) x)))1799 (eqv? p p)) ===> #t18001801The following examples illustrate cases in which the above rules do not1802fully specify the behavior of eqv?. All that can be said about such1803cases is that the value returned by eqv? must be a boolean.18041805 (eqv? "" "") ===> unspecified1806 (eqv? '#() '#()) ===> unspecified1807 (eqv? (lambda (x) x)1808 (lambda (x) x)) ===> unspecified1809 (eqv? (lambda (x) x)1810 (lambda (y) y)) ===> unspecified18111812The next set of examples shows the use of eqv? with procedures that1813have local state. Gen-counter must return a distinct procedure every1814time, since each procedure has its own internal counter. Gen-loser,1815however, returns equivalent procedures each time, since the local state1816does not affect the value or side effects of the procedures.18171818 (define gen-counter1819 (lambda ()1820 (let ((n 0))1821 (lambda () (set! n (+ n 1)) n))))1822 (let ((g (gen-counter)))1823 (eqv? g g)) ===> #t1824 (eqv? (gen-counter) (gen-counter))1825 ===> #f1826 (define gen-loser1827 (lambda ()1828 (let ((n 0))1829 (lambda () (set! n (+ n 1)) 27))))1830 (let ((g (gen-loser)))1831 (eqv? g g)) ===> #t1832 (eqv? (gen-loser) (gen-loser))1833 ===> unspecified18341835 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))1836 (g (lambda () (if (eqv? f g) 'both 'g))))1837 (eqv? f g))1838 ===> unspecified18391840 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))1841 (g (lambda () (if (eqv? f g) 'g 'both))))1842 (eqv? f g))1843 ===> #f18441845Since it is an error to modify constant objects (those returned by1846literal expressions), implementations are permitted, though not1847required, to share structure between constants where appropriate. Thus1848the value of eqv? on constants is sometimes implementation-dependent.18491850 (eqv? '(a) '(a)) ===> unspecified1851 (eqv? "a" "a") ===> unspecified1852 (eqv? '(b) (cdr '(a b))) ===> unspecified1853 (let ((x '(a)))1854 (eqv? x x)) ===> #t18551856Rationale: The above definition of eqv? allows implementations1857latitude in their treatment of procedures and literals:1858implementations are free either to detect or to fail to detect that1859two procedures or two literals are equivalent to each other, and1860can decide whether or not to merge representations of equivalent1861objects by using the same pointer or bit pattern to represent both.18621863<procedure>(eq? obj[1] obj[2])</procedure><br>18641865Eq? is similar to eqv? except that in some cases it is capable of1866discerning distinctions finer than those detectable by eqv?.18671868Eq? and eqv? are guaranteed to have the same behavior on symbols,1869booleans, the empty list, pairs, procedures, and non-empty strings and1870vectors. Eq?'s behavior on numbers and characters is1871implementation-dependent, but it will always return either true or1872false, and will return true only when eqv? would also return true. Eq?1873may also behave differently from eqv? on empty vectors and empty1874strings.18751876 (eq? 'a 'a) ===> #t1877 (eq? '(a) '(a)) ===> unspecified1878 (eq? (list 'a) (list 'a)) ===> #f1879 (eq? "a" "a") ===> unspecified1880 (eq? "" "") ===> unspecified1881 (eq? '() '()) ===> #t1882 (eq? 2 2) ===> unspecified1883 (eq? #\A #\A) ===> unspecified1884 (eq? car car) ===> #t1885 (let ((n (+ 2 3)))1886 (eq? n n)) ===> unspecified1887 (let ((x '(a)))1888 (eq? x x)) ===> #t1889 (let ((x '#()))1890 (eq? x x)) ===> #t1891 (let ((p (lambda (x) x)))1892 (eq? p p)) ===> #t18931894Rationale: It will usually be possible to implement eq? much more1895efficiently than eqv?, for example, as a simple pointer comparison1896instead of as some more complicated operation. One reason is that1897it may not be possible to compute eqv? of two numbers in constant1898time, whereas eq? implemented as pointer comparison will always1899finish in constant time. Eq? may be used like eqv? in applications1900using procedures to implement objects with state since it obeys the1901same constraints as eqv?.19021903<procedure>(equal? obj[1] obj[2])</procedure><br>19041905Equal? recursively compares the contents of pairs, vectors, and1906strings, applying eqv? on other objects such as numbers and symbols. A1907rule of thumb is that objects are generally equal? if they print the1908same. Equal? may fail to terminate if its arguments are circular data1909structures.19101911 (equal? 'a 'a) ===> #t1912 (equal? '(a) '(a)) ===> #t1913 (equal? '(a (b) c)1914 '(a (b) c)) ===> #t1915 (equal? "abc" "abc") ===> #t1916 (equal? 2 2) ===> #t1917 (equal? (make-vector 5 'a)1918 (make-vector 5 'a)) ===> #t1919 (equal? (lambda (x) x)1920 (lambda (y) y)) ===> unspecified19211922=== Numbers19231924Numerical computation has traditionally been neglected by the Lisp1925community. Until Common Lisp there was no carefully thought out1926strategy for organizing numerical computation, and with the exception1927of the MacLisp system [20] little effort was made to execute numerical1928code efficiently. This report recognizes the excellent work of the1929Common Lisp committee and accepts many of their recommendations. In1930some ways this report simplifies and generalizes their proposals in a1931manner consistent with the purposes of Scheme.19321933It is important to distinguish between the mathematical numbers, the1934Scheme numbers that attempt to model them, the machine representations1935used to implement the Scheme numbers, and notations used to write1936numbers. This report uses the types number, complex, real, rational,1937and integer to refer to both mathematical numbers and Scheme numbers.1938Machine representations such as fixed point and floating point are1939referred to by names such as fixnum and flonum.19401941==== Numerical types19421943Mathematically, numbers may be arranged into a tower of subtypes in1944which each level is a subset of the level above it:19451946 number1947 complex1948 real1949 rational1950 integer19511952For example, 3 is an integer. Therefore 3 is also a rational, a real,1953and a complex. The same is true of the Scheme numbers that model 3. For1954Scheme numbers, these types are defined by the predicates number?,1955complex?, real?, rational?, and integer?.19561957There is no simple relationship between a number's type and its1958representation inside a computer. Although most implementations of1959Scheme will offer at least two different representations of 3, these1960different representations denote the same integer.19611962Scheme's numerical operations treat numbers as abstract data, as1963independent of their representation as possible. Although an1964implementation of Scheme may use fixnum, flonum, and perhaps other1965representations for numbers, this should not be apparent to a casual1966programmer writing simple programs.19671968It is necessary, however, to distinguish between numbers that are1969represented exactly and those that may not be. For example, indexes1970into data structures must be known exactly, as must some polynomial1971coefficients in a symbolic algebra system. On the other hand, the1972results of measurements are inherently inexact, and irrational numbers1973may be approximated by rational and therefore inexact approximations.1974In order to catch uses of inexact numbers where exact numbers are1975required, Scheme explicitly distinguishes exact from inexact numbers.1976This distinction is orthogonal to the dimension of type.19771978==== Exactness19791980Scheme numbers are either exact or inexact. A number is exact if it was1981written as an exact constant or was derived from exact numbers using1982only exact operations. A number is inexact if it was written as an1983inexact constant, if it was derived using inexact ingredients, or if it1984was derived using inexact operations. Thus inexactness is a contagious1985property of a number. If two implementations produce exact results for1986a computation that did not involve inexact intermediate results, the1987two ultimate results will be mathematically equivalent. This is1988generally not true of computations involving inexact numbers since1989approximate methods such as floating point arithmetic may be used, but1990it is the duty of each implementation to make the result as close as1991practical to the mathematically ideal result.19921993Rational operations such as + should always produce exact results when1994given exact arguments. If the operation is unable to produce an exact1995result, then it may either report the violation of an implementation1996restriction or it may silently coerce its result to an inexact value.1997See [[#implementation-restrictions|the next section]].19981999With the exception of inexact->exact, the operations described in this2000section must generally return inexact results when given any inexact2001arguments. An operation may, however, return an exact result if it can2002prove that the value of the result is unaffected by the inexactness of2003its arguments. For example, multiplication of any number by an exact2004zero may produce an exact zero result, even if the other argument is2005inexact.20062007==== Implementation restrictions20082009Implementations of Scheme are not required to implement the whole2010tower of subtypes given under "[[#Numerical types|Numerical types]]",2011but they must implement a coherent subset consistent with both the2012purposes of the implementation and the spirit of the Scheme2013language. For example, an implementation in which all numbers are real2014may still be quite useful.20152016Implementations may also support only a limited range of numbers of any2017type, subject to the requirements of this section. The supported range2018for exact numbers of any type may be different from the supported range2019for inexact numbers of that type. For example, an implementation that2020uses flonums to represent all its inexact real numbers may support a2021practically unbounded range of exact integers and rationals while2022limiting the range of inexact reals (and therefore the range of inexact2023integers and rationals) to the dynamic range of the flonum format.2024Furthermore the gaps between the representable inexact integers and2025rationals are likely to be very large in such an implementation as the2026limits of this range are approached.20272028An implementation of Scheme must support exact integers throughout the2029range of numbers that may be used for indexes of lists, vectors, and2030strings or that may result from computing the length of a list, vector,2031or string. The length, vector-length, and string-length procedures must2032return an exact integer, and it is an error to use anything but an2033exact integer as an index. Furthermore any integer constant within the2034index range, if expressed by an exact integer syntax, will indeed be2035read as an exact integer, regardless of any implementation restrictions2036that may apply outside this range. Finally, the procedures listed below2037will always return an exact integer result provided all their arguments2038are exact integers and the mathematically expected result is2039representable as an exact integer within the implementation:20402041 - *2042 + abs2043 ceiling denominator2044 exact-integer-sqrt expt2045 floor floor/2046 floor-quotient floor-remainder2047 gcd lcm2048 max min2049 modulo numerator2050 quotient rationalize2051 remainder round2052 square truncate2053 truncate/ truncate-quotient2054 truncate-remainder20552056CHICKEN follows the IEEE 32-bit and 64-bit floating point2057standards on all supported platforms.20582059It is the programmer’s responsibility to avoid using inexact number objects2060with magnitude or significand too large to be represented in the2061implementation.20622063In addition, implementations may distinguish special numbers called positive2064infinity, negative infinity, NaN, and negative zero.20652066Positive infinity is regarded as an inexact real (but not rational) number that2067represents an indeterminate value greater than the numbers represented by all2068rational numbers. Negative infinity is regarded as an inexact real (but not2069rational) number that represents an indeterminate value less than the numbers2070represented by all rational numbers.20712072Adding or multiplying an infinite value by any finite real value results in an2073appropriately signed infinity; however, the sum of positive and negative2074infinities is a NaN. Positive infinity is the reciprocal of zero, and negative2075infinity is the reciprocal of negative zero. The behavior of the transcendental2076functions is sensitive to infinity in accordance with IEEE 754.20772078A NaN is regarded as an inexact real (but not rational) number so indeterminate2079that it might represent any real value, including positive or negative2080infinity, and might even be greater than positive infinity or less than2081negative infinity. An implementation that does not support non-real numbers may2082use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).20832084A NaN always compares false to any number, including a NaN. An arithmetic2085operation where one operand is NaN returns NaN, unless the implementation can2086prove that the result would be the same if the NaN were replaced by any2087rational number. Dividing zero by zero results in NaN unless both zeros are2088exact.20892090Negative zero is an inexact real value written -0.0 and is distinct (in the2091sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish2092negative zero. If it does, however, the behavior of the transcendental2093functions is sensitive to the distinction in accordance with IEEE 754.2094Specifically, in a Scheme implementing both complex numbers and negative zero,2095the branch cut of the complex logarithm function is such that (imag-part (log2096-1.0-0.0i)) is −π rather than π.20972098Furthermore, the negation of negative zero is ordinary zero and vice versa.2099This implies that the sum of two or more negative zeros is negative, and the2100result of subtracting (positive) zero from a negative zero is likewise2101negative. However, numerical comparisons treat negative zero as equal to zero.21022103Note that both the real and the imaginary parts of a complex number can be2104infinities, NaNs, or negative zero.210521062107==== Syntax of numerical constants21082109For a complete formal description of the syntax of the written2110representations for numbers, see the R7RS report. Note that case is2111not significant in numerical constants.21122113A number may be written in binary, octal, decimal, or hexadecimal by2114the use of a radix prefix. The radix prefixes are #b (binary), #o2115(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a2116number is assumed to be expressed in decimal.21172118A numerical constant may be specified to be either exact or inexact by2119a prefix. The prefixes are #e for exact, and #i for inexact. An2120exactness prefix may appear before or after any radix prefix that is2121used. If the written representation of a number has no exactness2122prefix, the constant may be either inexact or exact. It is inexact if2123it contains a decimal point, an exponent, or a "#" character in the2124place of a digit, otherwise it is exact. In systems with inexact2125numbers of varying precisions it may be useful to specify the precision2126of a constant. For this purpose, numerical constants may be written2127with an exponent marker that indicates the desired precision of the2128inexact representation. The letters s, f, d, and l specify the use of2129short, single, double, and long precision, respectively. (When fewer2130than four internal inexact representations exist, the four size2131specifications are mapped onto those available. For example, an2132implementation with two internal representations may map short and2133single together and long and double together.) In addition, the2134exponent marker e specifies the default precision for the2135implementation. The default precision has at least as much precision as2136double, but implementations may wish to allow this default to be set by2137the user.21382139 3.14159265358979F02140 Round to single --- 3.1415932141 0.6L02142 Extend to long --- .60000000000000021432144==== Numerical operations21452146The numerical routines described below have argument restrictions,2147which are encoded in the naming conventions of the arguments as2148given in the procedure's signature. The conventions are as follows:21492150; {{obj}} : any object2151; {{list, list1, ... listj, ... list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)2152; {{z, z1, ... zj, ...}} : complex number2153; {{x, x1, ... xj, ...}} : real number2154; {{y, y1, ... yj, ...}} : real number2155; {{q, q1, ... qj, ...}} : rational number2156; {{n, n1, ... nj, ...}} : integer2157; {{k, k1, ... kj, ...}} : exact non-negative integer21582159The examples used in this section assume that any2160numerical constant written using an exact notation is indeed2161represented as an exact number. Some examples also assume that certain2162numerical constants written using an inexact notation can be2163represented without loss of accuracy; the inexact constants were chosen2164so that this is likely to be true in implementations that use flonums2165to represent inexact numbers.21662167<procedure>(number? obj)</procedure><br>2168<procedure>(complex? obj)</procedure><br>2169<procedure>(real? obj)</procedure><br>2170<procedure>(rational? obj)</procedure><br>2171<procedure>(integer? obj)</procedure><br>21722173These numerical type predicates can be applied to any kind of argument,2174including non-numbers. They return #t if the object is of the named2175type, and otherwise they return #f. In general, if a type predicate is2176true of a number then all higher type predicates are also true of that2177number. Consequently, if a type predicate is false of a number, then2178all lower type predicates are also false of that number. If z is an2179inexact complex number, then (real? z) is true if and only if (zero?2180(imag-part z)) is true. If x is an inexact real number, then (integer?2181x) is true if and only if (= x (round x)).21822183 (complex? 3+4i) ===> #t2184 (complex? 3) ===> #t2185 (real? 3) ===> #t2186 (real? -2.5+0.0i) ===> #t2187 (real? #e1e10) ===> #t2188 (rational? 6/10) ===> #t2189 (rational? 6/3) ===> #t2190 (integer? 3+0i) ===> #t2191 (integer? 3.0) ===> #t2192 (integer? 8/4) ===> #t21932194Note: The behavior of these type predicates on inexact numbers is2195unreliable, since any inaccuracy may affect the result.21962197Note: In many implementations the rational? procedure will be the2198same as real?, and the complex? procedure will be the same as2199number?, but unusual implementations may be able to represent some2200irrational numbers exactly or may extend the number system to2201support some kind of non-complex numbers.22022203<procedure>(exact? z)</procedure><br>2204<procedure>(inexact? z)</procedure><br>22052206These numerical predicates provide tests for the exactness of a2207quantity. For any Scheme number, precisely one of these predicates is2208true.22092210<procedure>(exact-integer? z)</procedure>22112212Returns #t if z is both exact and an integer; otherwise returns #f.22132214 (exact-integer? 32) ===> #t2215 (exact-integer? 32.0) ===> #f2216 (exact-integer? 32/5) ===> #f22172218<procedure>(= z[1] z[2] z[3] ...)</procedure><br>2219<procedure>(< x[1] x[2] x[3] ...)</procedure><br>2220<procedure>(> x[1] x[2] x[3] ...)</procedure><br>2221<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>2222<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>22232224These procedures return #t if their arguments are (respectively):2225equal, monotonically increasing, monotonically decreasing,2226monotonically nondecreasing, or monotonically nonincreasing.22272228These predicates are required to be transitive.22292230Note: The traditional implementations of these predicates in2231Lisp-like languages are not transitive.22322233Note: While it is not an error to compare inexact numbers using2234these predicates, the results may be unreliable because a small2235inaccuracy may affect the result; this is especially true of = and2236zero?. When in doubt, consult a numerical analyst.22372238<procedure>(zero? z)</procedure><br>2239<procedure>(positive? x)</procedure><br>2240<procedure>(negative? x)</procedure><br>2241<procedure>(odd? n)</procedure><br>2242<procedure>(even? n)</procedure><br>22432244These numerical predicates test a number for a particular property,2245returning #t or #f. See note above.22462247<procedure>(max x[1] x[2] ...)</procedure><br>2248<procedure>(min x[1] x[2] ...)</procedure><br>22492250These procedures return the maximum or minimum of their arguments.22512252 (max 3 4) ===> 4 ; exact2253 (max 3.9 4) ===> 4.0 ; inexact22542255Note: If any argument is inexact, then the result will also be2256inexact (unless the procedure can prove that the inaccuracy is not2257large enough to affect the result, which is possible only in2258unusual implementations). If min or max is used to compare numbers2259of mixed exactness, and the numerical value of the result cannot be2260represented as an inexact number without loss of accuracy, then the2261procedure may report a violation of an implementation restriction.22622263<procedure>(+ z[1] ...)</procedure><br>2264<procedure>(* z[1] ...)</procedure><br>22652266These procedures return the sum or product of their arguments.22672268 (+ 3 4) ===> 72269 (+ 3) ===> 32270 (+) ===> 02271 (* 4) ===> 42272 (*) ===> 122732274<procedure>(- z[1] z[2])</procedure><br>2275<procedure>(- z)</procedure><br>2276<procedure>(- z[1] z[2] ...)</procedure><br>2277<procedure>(/ z[1] z[2])</procedure><br>2278<procedure>(/ z)</procedure><br>2279<procedure>(/ z[1] z[2] ...)</procedure><br>22802281With two or more arguments, these procedures return the difference or2282quotient of their arguments, associating to the left. With one2283argument, however, they return the additive or multiplicative inverse2284of their argument.22852286 (- 3 4) ===> -12287 (- 3 4 5) ===> -62288 (- 3) ===> -32289 (/ 3 4 5) ===> 3/202290 (/ 3) ===> 1/322912292<procedure>(abs x)</procedure><br>22932294Abs returns the absolute value of its argument.22952296 (abs -7) ===> 722972298<procedure>(floor/ n[1] n[2])</procedure><br>2299<procedure>(floor-quotient n[1] n[2])</procedure><br>2300<procedure>(floor-remainder n[1] n[2])</procedure><br>2301<procedure>(truncate/ n[1] n[2])</procedure><br>2302<procedure>(truncate-quotient n[1] n[2])</procedure><br>2303<procedure>(truncate-remainder n[1] n[2])</procedure><br>23042305These procedures implement number-theoretic (integer) division. It is an error2306if n[2] is zero. The procedures ending in / return two integers; the other2307procedures return an integer. All the procedures compute a quotient n[q] and remainder2308n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as2309follows:23102311 (<operator>/ n[1] n[2]) ==> n[q] n[r]2312 (<operator>-quotient n[1] n[2]) ==> n[q]2313 (<operator>-remainder n[1] n[2]) ==> n[r]23142315The 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]:23162317 floor n[q] = ⌊n[1] / n[2]⌋2318 truncate n[q] = runcate(n[1] / n[2])23192320For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,23212322 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))2323 (<operator>-remainder n[1] n[2])))2324 ==> #t23252326provided all numbers involved in that computation are exact.23272328Examples:23292330 (floor/ 5 2) ==> 2 12331 (floor/ -5 2) ==> -3 12332 (floor/ 5 -2) ==> -3 -12333 (floor/ -5 -2) ==> 2 -12334 (truncate/ 5 2) ==> 2 12335 (truncate/ -5 2) ==> -2 -12336 (truncate/ 5 -2) ==> -2 12337 (truncate/ -5 -2) ==> 2 -12338 (truncate/ -5.0 -2) ==> 2.0 -1.023392340<procedure>(quotient n[1] n[2])</procedure><br>2341<procedure>(remainder n[1] n[2])</procedure><br>2342<procedure>(modulo n[1] n[2])</procedure><br>23432344These procedures implement number-theoretic (integer) division. n[2]2345should be non-zero. All three procedures return integers. If n[1]/n[2]2346is an integer:23472348 (quotient n[1] n[2]) ===> n[1]/n[2]2349 (remainder n[1] n[2]) ===> 02350 (modulo n[1] n[2]) ===> 023512352If n[1]/n[2] is not an integer:23532354 (quotient n[1] n[2]) ===> n[q]2355 (remainder n[1] n[2]) ===> n[r]2356 (modulo n[1] n[2]) ===> n[m]23572358where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <2359|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],2360n[r] has the same sign as n[1], and n[m] has the same sign as n[2].23612362From this we can conclude that for integers n[1] and n[2] with n[2] not2363equal to 0,23642365 (= n[1] (+ (* n[2] (quotient n[1] n[2]))2366 (remainder n[1] n[2])))2367 ===> #t23682369provided all numbers involved in that computation are exact.23702371 (modulo 13 4) ===> 12372 (remainder 13 4) ===> 123732374 (modulo -13 4) ===> 32375 (remainder -13 4) ===> -123762377 (modulo 13 -4) ===> -32378 (remainder 13 -4) ===> 123792380 (modulo -13 -4) ===> -12381 (remainder -13 -4) ===> -123822383 (remainder -13 -4.0) ===> -1.0 ; inexact23842385<procedure>(gcd n[1] ...)</procedure><br>2386<procedure>(lcm n[1] ...)</procedure><br>23872388These procedures return the greatest common divisor or least common2389multiple of their arguments. The result is always non-negative.23902391 (gcd 32 -36) ===> 42392 (gcd) ===> 02393 (lcm 32 -36) ===> 2882394 (lcm 32.0 -36) ===> 288.0 ; inexact2395 (lcm) ===> 123962397<procedure>(numerator q)</procedure><br>2398<procedure>(denominator q)</procedure><br>23992400These procedures return the numerator or denominator of their argument;2401the result is computed as if the argument was represented as a fraction2402in lowest terms. The denominator is always positive. The denominator of24030 is defined to be 1.24042405 (numerator (/ 6 4)) ===> 32406 (denominator (/ 6 4)) ===> 22407 (denominator2408 (exact->inexact (/ 6 4))) ===> 2.024092410<procedure>(floor x)</procedure><br>2411<procedure>(ceiling x)</procedure><br>2412<procedure>(truncate x)</procedure><br>2413<procedure>(round x)</procedure><br>24142415These procedures return integers. Floor returns the largest integer not2416larger than x. Ceiling returns the smallest integer not smaller than x.2417Truncate returns the integer closest to x whose absolute value is not2418larger than the absolute value of x. Round returns the closest integer2419to x, rounding to even when x is halfway between two integers.24202421Rationale: Round rounds to even for consistency with the default2422rounding mode specified by the IEEE floating point standard.24232424Note: If the argument to one of these procedures is inexact, then2425the result will also be inexact. If an exact value is needed, the2426result should be passed to the inexact->exact procedure.24272428 (floor -4.3) ===> -5.02429 (ceiling -4.3) ===> -4.02430 (truncate -4.3) ===> -4.02431 (round -4.3) ===> -4.024322433 (floor 3.5) ===> 3.02434 (ceiling 3.5) ===> 4.02435 (truncate 3.5) ===> 3.02436 (round 3.5) ===> 4.0 ; inexact24372438 (round 7/2) ===> 4 ; exact2439 (round 7) ===> 724402441<procedure>(rationalize x y)</procedure><br>24422443Rationalize returns the simplest rational number differing from x by no2444more than y. A rational number r[1] is simpler than another rational2445number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)2446and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.2447Although not all rationals are comparable in this ordering (consider 2/24487 and 3/5) any interval contains a rational number that is simpler than2449every other rational number in that interval (the simpler 2/5 lies2450between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of2451all.24522453 (rationalize2454 (inexact->exact .3) 1/10) ===> 1/3 ; exact2455 (rationalize .3 1/10) ===> #i1/3 ; inexact24562457<procedure>(exp z)</procedure><br>2458<procedure>(log z [z2])</procedure><br>2459<procedure>(sin z)</procedure><br>2460<procedure>(cos z)</procedure><br>2461<procedure>(tan z)</procedure><br>2462<procedure>(asin z)</procedure><br>2463<procedure>(acos z)</procedure><br>2464<procedure>(atan z)</procedure><br>2465<procedure>(atan y x)</procedure><br>24662467These procedures are part of every implementation that supports general2468real numbers; they compute the usual transcendental functions. The Log2469procedure computes the natural logarithm of z (not the base ten logarithm)2470if a single argument is given, or the base-z2 logarithm of z1 if two arguments are2471given.2472Asin, acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and2473arctangent (tan^-1), respectively. The two-argument variant of atan2474computes (angle (make-rectangular x y)) (see below), even in2475implementations that don't support general complex numbers.24762477In general, the mathematical functions log, arcsine, arccosine, and2478arctangent are multiply defined. The value of log z is defined to be2479the one whose imaginary part lies in the range from -pi2480(exclusive) to pi (inclusive). log 0 is undefined. With log2481defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are2482according to the following formulae:24832484 sin^-1 z = - i log (i z + (1 - z^2)^1/2)24852486 cos^-1 z = pi / 2 - sin^-1 z24872488 tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)24892490The above specification follows [27], which in turn cites [19]; refer2491to these sources for more detailed discussion of branch cuts, boundary2492conditions, and implementation of these functions. When it is possible2493these procedures produce a real result from a real argument.24942495<procedure>(square z)</procedure>24962497Returns the square of z. This is equivalent to {{(* z z)}}-24982499 (square 42) ==> 17642500 (square 2.0) ==> 4.025012502<procedure>(exact-integer-sqrt k)</procedure>25032504Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.25052506 (exact-integer-sqrt 4) ==> 2 02507 (exact-integer-sqrt 5) ==> 2 125082509<procedure>(expt z[1] z[2])</procedure><br>25102511Returns z[1] raised to the power z[2]. For z[1] != 025122513 z[1]^z[2] = e^z[2] log z[1]251425150^z is 1 if z = 0 and 0 otherwise.25162517<procedure>(exact z)</procedure><br>2518<procedure>(inexact z)</procedure><br>25192520The procedure {{inexact}} returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the2521argument. For inexact arguments, the result is the same as the argument. For2522exact complex numbers, the result is a complex number whose real and imaginary2523parts are the result of applying inexact to the real and imaginary parts of the2524argument, respectively. If an exact argument has no reasonably close inexact2525equivalent (in the sense of =), then a violation of an implementation2526restriction may be reported.25272528The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the2529argument. For exact arguments, the result is the same as the argument. For2530inexact non-integral real arguments, the implementation may return a rational2531approximation, or may report an implementation violation. For inexact complex2532arguments, the result is a complex number whose real and imaginary parts are2533the result of applying exact to the real and imaginary parts of the argument,2534respectively. If an inexact argument has no reasonably close exact equivalent,2535(in the sense of =), then a violation of an implementation restriction may be2536reported.25372538==== Numerical input and output25392540<procedure>(number->string z [radix])</procedure>25412542Radix must be an exact integer. The R7RS standard only requires2543implementations to support 2, 8, 10, or 16, but CHICKEN allows any2544radix between 2 and 36, inclusive (note: due to a bug, flonums with2545fractional components always use radix 10, irrespective of the argument).2546If omitted, radix defaults to 10. The procedure number->string takes2547a number and a radix and returns as a string an external2548representation of the given number in the given radix such that25492550 (let ((number number)2551 (radix radix))2552 (eqv? number2553 (string->number (number->string number2554 radix)2555 radix)))25562557is true. It is an error if no possible result makes this expression2558true.25592560If z is inexact, the radix is 10, and the above expression can be2561satisfied by a result that contains a decimal point, then the result2562contains a decimal point and is expressed using the minimum number of2563digits (exclusive of exponent and trailing zeroes) needed to make the2564above expression true [3, 5]; otherwise the format of the result is2565unspecified.25662567The result returned by number->string never contains an explicit radix2568prefix.25692570Note: The error case can occur only when z is not a complex2571number or is a complex number with a non-rational real or imaginary2572part.25732574Rationale: If z is an inexact number represented using flonums,2575and the radix is 10, then the above expression is normally2576satisfied by a result containing a decimal point. The unspecified2577case allows for infinities, NaNs, and non-flonum representations.25782579As an extension to R7RS, CHICKEN supports reading and writing the2580special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',2581as well as negative zero.25822583<procedure>(string->number string)</procedure><br>2584<procedure>(string->number string radix)</procedure><br>25852586Returns a number of the maximally precise representation expressed by2587the given string. Radix must be an exact integer. The R7RS standard2588only requires implementations to support 2, 8, 10, or 16, but CHICKEN2589allows any radix between 2 and 36, inclusive. If supplied, radix is a2590default radix that may be overridden by an explicit radix prefix in2591string (e.g. "#o177"). If radix is not supplied, then the default2592radix is 10. If string is not a syntactically valid notation for a2593number, then string->number returns #f.25942595If the radix is higher than 18, the parser treats ambiguous syntax2596that might be a complex number, like {{{"+i"}}} and {{{"-i"}}} (and2597any prefixes like {{{"+1234i"}}}), as an integer. If you want this to2598be parsed as a complex number, explicitly write down {{{"0+i"}}} to2599disambiguate. Note that {{{number->string}}} will always emit complex2600numbers using the full notation, so it can always be read back by2601{{{string->number}}}.26022603 (string->number "100") ===> 1002604 (string->number "100" 16) ===> 2562605 (string->number "1e2") ===> 100.02606 (string->number "15##") ===> 1500.026072608Note: The domain of string->number may be restricted by2609implementations in the following ways. String->number is permitted2610to return #f whenever string contains an explicit radix prefix. If2611all numbers supported by an implementation are real, then string->2612number is permitted to return #f whenever string uses the polar or2613rectangular notations for complex numbers. If all numbers are2614integers, then string->number may return #f whenever the fractional2615notation is used. If all numbers are exact, then string->number may2616return #f whenever an exponent marker or explicit exactness prefix2617is used, or if a # appears in place of a digit. If all inexact2618numbers are integers, then string->number may return #f whenever a2619decimal point is used.26202621=== Other data types26222623This section describes operations on some of Scheme's non-numeric data2624types: booleans, pairs, lists, symbols, characters, strings and2625vectors.26262627==== Booleans26282629The standard boolean objects for true and false are written as #t and #f.2630What really matters, though, are the objects that the Scheme2631conditional expressions (if, cond, and, or, do) treat as true or false.2632The phrase "a true value" (or sometimes just "true") means any2633object treated as true by the conditional expressions, and the phrase2634"a false value" (or "false") means any object treated as false by2635the conditional expressions.26362637Of all the standard Scheme values, only #f counts as false in2638conditional expressions. Except for #f, all standard Scheme values,2639including #t, pairs, the empty list, symbols, numbers, strings,2640vectors, and procedures, count as true.26412642Note: Programmers accustomed to other dialects of Lisp should be2643aware that Scheme distinguishes both #f and the empty list from the2644symbol nil.26452646Boolean constants evaluate to themselves, so they do not need to be2647quoted in programs.26482649 #t ===> #t2650 #f ===> #f2651 '#f ===> #f26522653<procedure>(not obj)</procedure><br>26542655Not returns #t if obj is false, and returns #f otherwise.26562657 (not #t) ===> #f2658 (not 3) ===> #f2659 (not (list 3)) ===> #f2660 (not #f) ===> #t2661 (not '()) ===> #f2662 (not (list)) ===> #f2663 (not 'nil) ===> #f26642665<procedure>(boolean? obj)</procedure><br>26662667Boolean? returns #t if obj is either #t or #f and returns #f otherwise.26682669 (boolean? #f) ===> #t2670 (boolean? 0) ===> #f2671 (boolean? '()) ===> #f26722673<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>26742675Returns #t if all the arguments are #t or all are #f.26762677==== Pairs and lists26782679A pair (sometimes called a dotted pair) is a record structure with two2680fields called the car and cdr fields (for historical reasons). Pairs2681are created by the procedure cons. The car and cdr fields are accessed2682by the procedures car and cdr. The car and cdr fields are assigned by2683the procedures set-car! and set-cdr!.26842685Pairs are used primarily to represent lists. A list can be defined2686recursively as either the empty list or a pair whose cdr is a list.2687More precisely, the set of lists is defined as the smallest set X such2688that26892690* The empty list is in X.2691* If list is in X, then any pair whose cdr field contains list is2692 also in X.26932694The objects in the car fields of successive pairs of a list are the2695elements of the list. For example, a two-element list is a pair whose2696car is the first element and whose cdr is a pair whose car is the2697second element and whose cdr is the empty list. The length of a list is2698the number of elements, which is the same as the number of pairs.26992700The empty list is a special object of its own type (it is not a pair);2701it has no elements and its length is zero.27022703Note: The above definitions imply that all lists have finite2704length and are terminated by the empty list.27052706The most general notation (external representation) for Scheme pairs is2707the "dotted" notation (c[1] . c[2]) where c[1] is the value of the2708car field and c[2] is the value of the cdr field. For example (4 . 5)2709is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the2710external representation of a pair, not an expression that evaluates to2711a pair.27122713A more streamlined notation can be used for lists: the elements of the2714list are simply enclosed in parentheses and separated by spaces. The2715empty list is written () . For example,27162717 (a b c d e)27182719and27202721 (a . (b . (c . (d . (e . ())))))27222723are equivalent notations for a list of symbols.27242725A chain of pairs not ending in the empty list is called an improper2726list. Note that an improper list is not a list. The list and dotted2727notations can be combined to represent improper lists:27282729 (a b c . d)27302731is equivalent to27322733 (a . (b . (c . d)))27342735Whether a given pair is a list depends upon what is stored in the cdr2736field. When the set-cdr! procedure is used, an object can be a list one2737moment and not the next:27382739 (define x (list 'a 'b 'c))2740 (define y x)2741 y ===> (a b c)2742 (list? y) ===> #t2743 (set-cdr! x 4) ===> unspecified2744 x ===> (a . 4)2745 (eqv? x y) ===> #t2746 y ===> (a . 4)2747 (list? y) ===> #f2748 (set-cdr! x x) ===> unspecified2749 (list? x) ===> #f27502751Within literal expressions and representations of objects read by the2752read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>2753denote two-element lists whose first elements are the symbols quote,2754quasiquote, unquote, and unquote-splicing, respectively. The second2755element in each case is <datum>. This convention is supported so that2756arbitrary Scheme programs may be represented as lists. That is,2757according to Scheme's grammar, every <expression> is also a <datum>.2758Among other things, this permits the use of the read procedure to2759parse Scheme programs.27602761<procedure>(pair? obj)</procedure><br>27622763Pair? returns #t if obj is a pair, and otherwise returns #f.27642765 (pair? '(a . b)) ===> #t2766 (pair? '(a b c)) ===> #t2767 (pair? '()) ===> #f2768 (pair? '#(a b)) ===> #f27692770<procedure>(cons obj[1] obj[2])</procedure><br>27712772Returns a newly allocated pair whose car is obj[1] and whose cdr is2773obj[2]. The pair is guaranteed to be different (in the sense of eqv?)2774from every existing object.27752776 (cons 'a '()) ===> (a)2777 (cons '(a) '(b c d)) ===> ((a) b c d)2778 (cons "a" '(b c)) ===> ("a" b c)2779 (cons 'a 3) ===> (a . 3)2780 (cons '(a b) 'c) ===> ((a b) . c)27812782<procedure>(car pair)</procedure><br>27832784Returns the contents of the car field of pair. Note that it is an error2785to take the car of the empty list.27862787 (car '(a b c)) ===> a2788 (car '((a) b c d)) ===> (a)2789 (car '(1 . 2)) ===> 12790 (car '()) ===> error27912792<procedure>(cdr pair)</procedure><br>27932794Returns the contents of the cdr field of pair. Note that it is an error2795to take the cdr of the empty list.27962797 (cdr '((a) b c d)) ===> (b c d)2798 (cdr '(1 . 2)) ===> 22799 (cdr '()) ===> error28002801<procedure>(set-car! pair obj)</procedure><br>28022803Stores obj in the car field of pair. The value returned by set-car! is2804unspecified.28052806 (define (f) (list 'not-a-constant-list))2807 (define (g) '(constant-list))2808 (set-car! (f) 3) ===> unspecified2809 (set-car! (g) 3) ===> error28102811<procedure>(set-cdr! pair obj)</procedure><br>28122813Stores obj in the cdr field of pair. The value returned by set-cdr! is2814unspecified.28152816<procedure>(null? obj)</procedure><br>28172818Returns #t if obj is the empty list, otherwise returns #f.28192820<procedure>(list? obj)</procedure><br>28212822Returns #t if obj is a list, otherwise returns #f. By definition, all2823lists have finite length and are terminated by the empty list.28242825 (list? '(a b c)) ===> #t2826 (list? '()) ===> #t2827 (list? '(a . b)) ===> #f2828 (let ((x (list 'a)))2829 (set-cdr! x x)2830 (list? x)) ===> #f28312832<procedure>(make-list k [fill]}</procedure>28332834Returns 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.28352836 (make-list 2 3) ==> (3 3)28372838<procedure>(list obj ...)</procedure><br>28392840Returns a newly allocated list of its arguments.28412842 (list 'a (+ 3 4) 'c) ===> (a 7 c)2843 (list) ===> ()28442845<procedure>(length list)</procedure><br>28462847Returns the length of list.28482849 (length '(a b c)) ===> 32850 (length '(a (b) (c d e))) ===> 32851 (length '()) ===> 028522853<procedure>(append list ...)</procedure><br>28542855Returns a list consisting of the elements of the first list followed by2856the elements of the other lists.28572858 (append '(x) '(y)) ===> (x y)2859 (append '(a) '(b c d)) ===> (a b c d)2860 (append '(a (b)) '((c))) ===> (a (b) (c))28612862The resulting list is always newly allocated, except that it shares2863structure with the last list argument. The last argument may actually2864be any object; an improper list results if the last argument is not a2865proper list.28662867 (append '(a b) '(c . d)) ===> (a b c . d)2868 (append '() 'a) ===> a28692870<procedure>(reverse list)</procedure><br>28712872Returns a newly allocated list consisting of the elements of list in2873reverse order.28742875 (reverse '(a b c)) ===> (c b a)2876 (reverse '(a (b c) d (e (f))))2877 ===> ((e (f)) d (b c) a)28782879<procedure>(list-tail list k)</procedure><br>28802881Returns the sublist of list obtained by omitting the first k elements.2882It is an error if list has fewer than k elements. List-tail could be2883defined by28842885 (define list-tail2886 (lambda (x k)2887 (if (zero? k)2888 x2889 (list-tail (cdr x) (- k 1)))))28902891<procedure>(list-ref list k)</procedure><br>28922893Returns the kth element of list. (This is the same as the car of2894(list-tail list k).) It is an error if list has fewer than k elements.28952896 (list-ref '(a b c d) 2) ===> c2897 (list-ref '(a b c d)2898 (inexact->exact (round 1.8)))2899 ===> c29002901<procedure>(list-set! list k obj)</procedure>29022903It is an error if k is not a valid index of list.29042905The {{list-set!}} procedure stores obj in element k of list.29062907 (let ((ls (list 'one 'two 'five!)))2908 (list-set! ls 2 'three)2909 ls)2910 ==> (one two three)29112912 (list-set! '(0 1 2) 1 "oops")2913 ==> error ; constant list29142915<procedure>(memq obj list)</procedure><br>2916<procedure>(memv obj list)</procedure><br>2917<procedure>(member obj list [compare])</procedure><br>29182919These procedures return the first sublist of list whose car is obj,2920where the sublists of list are the non-empty lists returned by2921{{(list-tail list k)}} for k less than the length of list. If obj does not2922occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}2923to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and2924member {{compare}} if given, and {{equal?}} otherwise.29252926 (memq 'a '(a b c)) ===> (a b c)2927 (memq 'b '(a b c)) ===> (b c)2928 (memq 'a '(b c d)) ===> #f2929 (memq (list 'a) '(b (a) c)) ===> #f2930 (member (list 'a)2931 '(b (a) c)) ===> ((a) c)2932 (memq 101 '(100 101 102)) ===> unspecified2933 (memv 101 '(100 101 102)) ===> (101 102)29342935<procedure>(assq obj alist)</procedure><br>2936<procedure>(assv obj alist)</procedure><br>2937<procedure>(assoc obj alist [compare])</procedure><br>29382939Alist (for "association list") must be a list of pairs. These2940procedures find the first pair in alist whose car field is obj, and2941returns that pair. If no pair in alist has obj as its car, then #f (not2942the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car2943fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses2944{{compare}}, if given, otherwise {{equal?}}.29452946 (define e '((a 1) (b 2) (c 3)))2947 (assq 'a e) ===> (a 1)2948 (assq 'b e) ===> (b 2)2949 (assq 'd e) ===> #f2950 (assq (list 'a) '(((a)) ((b)) ((c))))2951 ===> #f2952 (assoc (list 'a) '(((a)) ((b)) ((c))))2953 ===> ((a))2954 (assq 5 '((2 3) (5 7) (11 13)))2955 ===> unspecified2956 (assv 5 '((2 3) (5 7) (11 13)))2957 ===> (5 7)29582959Rationale: Although they are ordinarily used as predicates, memq,2960memv, member, assq, assv, and assoc do not have question marks in2961their names because they return useful values rather than just #t2962or #f.29632964<procedure>(list-copy obj)</procedure>29652966Returns 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 in2967the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if2968obj is a circular list.29692970 (define a '(1 8 2 8)) ; a may be immutable2971 (define b (list-copy a))2972 (set-car! b 3) ; b is mutable2973 b ==> (3 8 2 8)2974 a ==> (1 8 2 8)29752976==== Symbols29772978Symbols are objects whose usefulness rests on the fact that two symbols2979are identical (in the sense of eqv?) if and only if their names are2980spelled the same way. This is exactly the property needed to represent2981identifiers in programs, and so most implementations of Scheme use them2982internally for that purpose. Symbols are useful for many other2983applications; for instance, they may be used the way enumerated values2984are used in Pascal.29852986The rules for writing a symbol are exactly the same as the rules for2987writing an identifier.29882989It is guaranteed that any symbol that has been returned as part of a2990literal expression, or read using the read procedure, and subsequently2991written out using the write procedure, will read back in as the2992identical symbol (in the sense of eqv?). The string->symbol procedure,2993however, can create symbols for which this write/read invariance may2994not hold because their names contain special characters or letters in2995the non-standard case.29962997Note: Some implementations of Scheme have a feature known as2998"slashification" in order to guarantee write/read invariance for2999all symbols, but historically the most important use of this3000feature has been to compensate for the lack of a string data type.30013002Some implementations also have "uninterned symbols", which defeat3003write/read invariance even in implementations with slashification,3004and also generate exceptions to the rule that two symbols are the3005same if and only if their names are spelled the same.30063007<procedure>(symbol? obj)</procedure><br>30083009Returns #t if obj is a symbol, otherwise returns #f.30103011 (symbol? 'foo) ===> #t3012 (symbol? (car '(a b))) ===> #t3013 (symbol? "bar") ===> #f3014 (symbol? 'nil) ===> #t3015 (symbol? '()) ===> #f3016 (symbol? #f) ===> #f30173018<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>30193020Returns #t if all the arguments all have the same names in the sense of {{string=?}}.30213022Note: The definition above assumes that none of the arguments are uninterned symbols.30233024<procedure>(symbol->string symbol)</procedure><br>30253026Returns the name of symbol as a string. If the symbol was part of an3027object returned as the value of a literal expression (see3028"[[#literal-expressions|literal expressions]]") or by a call to the3029read procedure, and its name contains alphabetic characters, then the3030string returned will contain characters in the implementation's3031preferred standard case -- some implementations will prefer upper3032case, others lower case. If the symbol was returned by string->symbol,3033the case of characters in the string returned will be the same as the3034case in the string that was passed to string->symbol. It is an error3035to apply mutation procedures like string-set! to strings returned by3036this procedure.30373038The following examples assume that the implementation's standard case3039is lower case:30403041 (symbol->string 'flying-fish)3042 ===> "flying-fish"3043 (symbol->string 'Martin) ===> "martin"3044 (symbol->string3045 (string->symbol "Malvina"))3046 ===> "Malvina"30473048<procedure>(string->symbol string)</procedure><br>30493050Returns the symbol whose name is string. This procedure can create3051symbols with names containing special characters or letters in the3052non-standard case, but it is usually a bad idea to create such symbols3053because in some implementations of Scheme they cannot be read as3054themselves. See symbol->string.30553056The following examples assume that the implementation's standard case3057is lower case:30583059 (eq? 'mISSISSIppi 'mississippi)3060 ===> #t3061 (string->symbol "mISSISSIppi")3062 ===> the symbol with name "mISSISSIppi"3063 (eq? 'bitBlt (string->symbol "bitBlt"))3064 ===> #f3065 (eq? 'JollyWog3066 (string->symbol3067 (symbol->string 'JollyWog)))3068 ===> #t3069 (string=? "K. Harper, M.D."3070 (symbol->string3071 (string->symbol "K. Harper, M.D.")))3072 ===> #t30733074==== Characters30753076Characters are objects that represent printed characters such as3077letters and digits. Characters are written using the notation #\3078<character> or #\<character name>. For example:30793080Characters are written using the notation {{#\<character>}} or {{#\<character name>}}3081or {{#\x<hex scalar value>}}.30823083The following character names must be supported by all implementations with the3084given values. Implementations may add other names provided they cannot be3085interpreted as hex scalar values preceded by x.30863087 #\alarm ; U+00073088 #\backspace ; U+00083089 #\delete ; U+007F3090 #\escape ; U+001B3091 #\newline ; the linefeed character, U+000A3092 #\null ; the null character, U+00003093 #\return ; the return character, U+000D3094 #\space ; the preferred way to write a space3095 #\tab ; the tab character, U+000930963097Here are some additional examples:30983099 #\a ; lower case letter3100 #\A ; upper case letter3101 #\( ; left parenthesis3102 #\ ; the space character3103 #\space ; the preferred way to write a space3104 #\newline ; the newline character31053106Case is significant in #\<character>, but not in #\<character name>. If3107<character> in #\<character> is alphabetic, then the character3108following <character> must be a delimiter character such as a space or3109parenthesis. This rule resolves the ambiguous case where, for example,3110the sequence of characters "#\space" could be taken to be either a3111representation of the space character or a representation of the3112character "#\s" followed by a representation of the symbol "pace."31133114Characters written in the #\ notation are self-evaluating. That is,3115they do not have to be quoted in programs. Some of the procedures that3116operate on characters ignore the difference between upper case and3117lower case. The procedures that ignore case have "-ci" (for "case3118insensitive") embedded in their names.31193120<procedure>(char? obj)</procedure><br>31213122Returns #t if obj is a character, otherwise returns #f.31233124<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>3125<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>3126<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>3127<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>3128<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>31293130These procedures impose a total ordering on the set of characters. It3131is guaranteed that under this ordering:31323133* The upper case characters are in order. For example, (char<? #\A #\3134 B) returns #t.3135* The lower case characters are in order. For example, (char<? #\a #\3136 b) returns #t.3137* The digits are in order. For example, (char<? #\0 #\9) returns #t.3138* Either all the digits precede all the upper case letters, or vice3139 versa.3140* Either all the digits precede all the lower case letters, or vice3141 versa.31423143Some implementations may generalize these procedures to take more than3144two arguments, as with the corresponding numerical predicates.31453146<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>3147<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>3148<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>3149<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>3150<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>31513152These procedures are similar to char=? et cetera, but they treat upper3153case and lower case letters as the same. For example, (char-ci=? #\A #\3154a) returns #t. Some implementations may generalize these procedures to3155take more than two arguments, as with the corresponding numerical3156predicates.31573158<procedure>(char-alphabetic? char)</procedure><br>3159<procedure>(char-numeric? char)</procedure><br>3160<procedure>(char-whitespace? char)</procedure><br>3161<procedure>(char-upper-case? letter)</procedure><br>3162<procedure>(char-lower-case? letter)</procedure><br>31633164These procedures return #t if their arguments are alphabetic, numeric,3165whitespace, upper case, or lower case characters, respectively,3166otherwise they return #f. The following remarks, which are specific to3167the ASCII character set, are intended only as a guide: The alphabetic3168characters are the 52 upper and lower case letters. The numeric3169characters are the ten decimal digits. The whitespace characters are3170space, tab, line feed, form feed, and carriage return.31713172<procedure>(char->integer char)</procedure><br>3173<procedure>(integer->char n)</procedure><br>31743175Given a character, char->integer returns an exact integer3176representation of the character. Given an exact integer that is the3177image of a character under char->integer, integer->char returns that3178character. These procedures implement order-preserving isomorphisms3179between the set of characters under the char<=? ordering and some3180subset of the integers under the <= ordering. That is, if31813182 (char<=? a b) ===> #t and (<= x y) ===> #t31833184and x and y are in the domain of integer->char, then31853186 (<= (char->integer a)3187 (char->integer b)) ===> #t31883189 (char<=? (integer->char x)3190 (integer->char y)) ===> #t31913192Note that {{integer->char}} does currently not detect3193a negative argument and will quietly convert {{-1}} to3194{{#x1ffff}} in CHICKEN.31953196==== Strings31973198Strings are sequences of characters. Strings are written as sequences of3199characters enclosed within quotation marks ("). Within a string literal,3200various escape sequences represent characters other than themselves. Escape3201sequences always start with a backslash (\):32023203* \a : alarm, U+000732043205* \b : backspace, U+000832063207* \t : character tabulation, U+000932083209* \n : linefeed, U+000A32103211* \r : return, U+000D32123213* \" : double quote, U+002232143215* \\ : backslash, U+005C32163217* \| : vertical line, U+007C32183219* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing32203221* \x<hex scalar value>; : specified character (note the terminating3222 semi-colon).32233224The result is unspecified if any other character in a string occurs after a3225backslash.32263227Except for a line ending, any character outside of an escape sequence stands3228for itself in the string literal. A line ending which is preceded by \3229<intraline whitespace> expands to nothing (along with any trailing intraline3230whitespace), and can be used to indent strings for improved legibility. Any3231other line ending has the same effect as inserting a \n character into the3232string.32333234Examples:32353236 "The word \"recursion\" has many meanings."3237 "Another example:\ntwo lines of text"3238 "Here's text \3239 containing just one line"3240 "\x03B1; is named GREEK SMALL LETTER ALPHA."32413242The length of a string is the3243number of characters that it contains. This number is an exact, non-negative3244integer that is fixed when the string is created. The valid indexes of a string3245are the exact non-negative integers less than the length of the string. The3246first character of a string has index 0, the second has index 1, and so on.32473248<procedure>(string? obj)</procedure><br>32493250Returns #t if obj is a string, otherwise returns #f.32513252<procedure>(make-string k)</procedure><br>3253<procedure>(make-string k char)</procedure><br>32543255Make-string returns a newly allocated string of length k. If char is3256given, then all elements of the string are initialized to char,3257otherwise the contents of the string are unspecified.32583259<procedure>(string char ...)</procedure><br>32603261Returns a newly allocated string composed of the arguments.32623263<procedure>(string-length string)</procedure><br>32643265Returns the number of characters in the given string.32663267<procedure>(string-ref string k)</procedure><br>32683269k must be a valid index of string. String-ref returns character k of3270string using zero-origin indexing.32713272<procedure>(string-set! string k char)</procedure><br>32733274k must be a valid index of string. String-set! stores char in element k3275of string and returns an unspecified value.32763277 (define (f) (make-string 3 #\*))3278 (define (g) "***")3279 (string-set! (f) 0 #\?) ===> unspecified3280 (string-set! (g) 0 #\?) ===> error3281 (string-set! (symbol->string 'immutable)3282 03283 #\?) ===> error32843285<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>32863287Returns #t if the two strings are the same length and contain the same3288characters in the same positions, otherwise returns #f.32893290<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>3291<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>3292<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>3293<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>32943295These procedures are the lexicographic extensions to strings of the3296corresponding orderings on characters. For example, string<? is the3297lexicographic ordering on strings induced by the ordering char<? on3298characters. If two strings differ in length but are the same up to the3299length of the shorter string, the shorter string is considered to be3300lexicographically less than the longer string.33013302<procedure>(substring string start [end])</procedure><br>33033304String must be a string, and start and end must be exact integers3305satisfying33063307 0 <= start <= end <= (string-length string)33083309Substring returns a newly allocated string formed from the characters3310of string beginning with index start (inclusive) and ending with index3311end (exclusive). The {{end}} argument is optional and defaults to the3312length of the string, this is a non-standard extension in CHICKEN.33133314<procedure>(string-append string ...)</procedure><br>33153316Returns a newly allocated string whose characters form the3317concatenation of the given strings.33183319<procedure>(string->list string [start [end]])</procedure><br>3320<procedure>(list->string list)</procedure><br>33213322String->list returns a newly allocated list of the characters that make3323up the given string between start and end. List->string returns a newly allocated string3324formed from the characters in the list list, which must be a list of3325characters. String->list and list->string are inverses so far as equal?3326is concerned.33273328<procedure>(string-copy string [start [end]])</procedure><br>33293330Returns a newly allocated copy of the given string.33313332<procedure>(string-copy! to at from [start [end]])</procedure>33333334It 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)}}.33353336Copies the characters of string from between start and end to string to, starting at3337at. The order in which characters are copied is unspecified, except that if the3338source and destination overlap, copying takes place as if the source is first3339copied into a temporary string and then into the destination. This can be3340achieved without allocating storage by making sure to copy in the correct3341direction in such circumstances.33423343 (define a "12345")3344 (define b (string-copy "abcde"))3345 (string-copy! b 1 a 0 2)3346 b ==> "a12de"33473348<procedure>(string-fill! string char +#!optional start end)</procedure><br>33493350Stores char in every element of the given string and returns an3351unspecified value. The optional start and end arguments specify3352the part of the string to be filled and default to the complete string.33533354==== Vectors33553356Vectors are heterogenous structures whose elements are indexed by3357integers. A vector typically occupies less space than a list of the3358same length, and the average time required to access a randomly chosen3359element is typically less for the vector than for the list.33603361The length of a vector is the number of elements that it contains. This3362number is a non-negative integer that is fixed when the vector is3363created. The valid indexes of a vector are the exact non-negative3364integers less than the length of the vector. The first element in a3365vector is indexed by zero, and the last element is indexed by one less3366than the length of the vector.33673368Vectors are written using the notation #(obj ...). For example, a3369vector of length 3 containing the number zero in element 0, the list (233702 2 2) in element 1, and the string "Anna" in element 2 can be written3371as following:33723373 #(0 (2 2 2 2) "Anna")33743375Vector constants are self-evaluating, so they do not need3376to be quoted in programs.33773378<procedure>(vector? obj)</procedure><br>33793380Returns #t if obj is a vector, otherwise returns #f.33813382<procedure>(make-vector k)</procedure><br>3383<procedure>(make-vector k fill)</procedure><br>33843385Returns a newly allocated vector of k elements. If a second argument is3386given, then each element is initialized to fill. Otherwise the initial3387contents of each element is unspecified.33883389<procedure>(vector obj ...)</procedure><br>33903391Returns a newly allocated vector whose elements contain the given3392arguments. Analogous to list.33933394 (vector 'a 'b 'c) ===> #(a b c)33953396<procedure>(vector-length vector)</procedure><br>33973398Returns the number of elements in vector as an exact integer.33993400<procedure>(vector-ref vector k)</procedure><br>34013402k must be a valid index of vector. Vector-ref returns the contents of3403element k of vector.34043405 (vector-ref '#(1 1 2 3 5 8 13 21)3406 5)3407 ===> 83408 (vector-ref '#(1 1 2 3 5 8 13 21)3409 (let ((i (round (* 2 (acos -1)))))3410 (if (inexact? i)3411 (inexact->exact i)3412 i)))3413 ===> 1334143415<procedure>(vector-set! vector k obj)</procedure><br>34163417k must be a valid index of vector. Vector-set! stores obj in element k3418of vector. The value returned by vector-set! is unspecified.34193420 (let ((vec (vector 0 '(2 2 2 2) "Anna")))3421 (vector-set! vec 1 '("Sue" "Sue"))3422 vec)3423 ===> #(0 ("Sue" "Sue") "Anna")34243425 (vector-set! '#(0 1 2) 1 "doe")3426 ===> error ; constant vector34273428<procedure>(vector->list vector [start [end]])</procedure><br>3429<procedure>(list->vector list)</procedure><br>34303431Vector->list returns a newly allocated list of the objects contained in3432the elements of vector. List->vector returns a newly created vector3433initialized to the elements of the list list.34343435 (vector->list '#(dah dah didah))3436 ===> (dah dah didah)3437 (list->vector '(dididit dah))3438 ===> #(dididit dah)34393440<procedure>(vector-fill! vector fill)</procedure><br>34413442Stores fill in every element of vector. The value returned by3443vector-fill! is unspecified.34443445<procedure>(vector->string vector [start [end]])</procedure><br>3446<procedure(string->vector string [start [end]])</procedure>34473448It is an error if any element of vector between start and end is not a character.34493450The vector->string procedure returns a newly allocated string of the objects3451contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to3452the elements of the string string between start and end.34533454In both procedures, order is preserved.34553456 (string->vector "ABC") ==> #(#\A #\B #\C)3457 (vector->string #(#\1 #\2 #\3) ==> "123"34583459<procedure>(vector-copy vector [start [end]])</procedure>34603461Returns a newly allocated copy of the elements of the given vector between3462start and end. The elements of the new vector are the same (in the sense of eqv?) as the3463elements of the old.34643465 (define a #(1 8 2 8)) ; a may be immutable3466 (define b (vector-copy a))3467 (vector-set! b 0 3) ; b is mutable3468 b ==> #(3 8 2 8)3469 (define c (vector-copy b 1 3))3470 c ==> #(8 2)34713472<procedure>(vector-copy! to at from [start [end]])</procedure>34733474It 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)}}.34753476Copies the elements of vector from between start and end to vector to, starting at3477at. The order in which elements are copied is unspecified, except that if the3478source and destination overlap, copying takes place as if the source is first3479copied into a temporary vector and then into the destination. This can be3480achieved without allocating storage by making sure to copy in the correct3481direction in such circumstances.34823483 (define a (vector 1 2 3 4 5))3484 (define b (vector 10 20 30 40 50))3485 (vector-copy! b 1 a 0 2)3486 b ==> #(10 1 2 40 50)34873488<procedure>(vector-append vector ....)</procedure>34893490Returns a newly allocated vector whose elements are the concatenation of the3491elements of the given vectors.34923493 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)34943495<procedure>(vector-fill! vector fill [start [end)]])</procedure>34963497The vector-fill! procedure stores fill in the elements of vector between start and3498end.34993500 (define a (vector 1 2 3 4 5))3501 (vector-fill! a 'smash 2 4)3502 a ==>#(1 2 smash smash 5)35033504==== Bytevectors35053506Bytevectors represent blocks of binary data. They are fixed-length sequences of3507bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A3508bytevector is typically more space-efficient than a vector containing the same3509values.35103511See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more3512information. {{(scheme base)}} re-exports all R7RS-specific procedures from3513that module.35143515=== Control features35163517This chapter describes various primitive procedures which control the3518flow of program execution in special ways. The procedure? predicate is3519also described here.35203521<procedure>(procedure? obj)</procedure><br>35223523Returns #t if obj is a procedure, otherwise returns #f.35243525 (procedure? car) ===> #t3526 (procedure? 'car) ===> #f3527 (procedure? (lambda (x) (* x x)))3528 ===> #t3529 (procedure? '(lambda (x) (* x x)))3530 ===> #f3531 (call-with-current-continuation procedure?)3532 ===> #t35333534<procedure>(apply proc arg[1] ... args)</procedure><br>35353536Proc must be a procedure and args must be a list. Calls proc with the3537elements of the list (append (list arg[1] ...) args) as the actual3538arguments.35393540 (apply + (list 3 4)) ===> 735413542 (define compose3543 (lambda (f g)3544 (lambda args3545 (f (apply g args)))))35463547 ((compose sqrt *) 12 75) ===> 3035483549<procedure>(map proc list[1] list[2] ...)</procedure><br>35503551The lists must be lists, and proc must be a procedure taking as many3552arguments as there are lists and returning a single value. Map applies3553proc element-wise to the elements of the lists and returns a list of3554the results, in order. The dynamic order in which proc is applied to3555the elements of the lists is unspecified.35563557Like in SRFI-1, this procedure allows the arguments to be of unequal3558length; it terminates when the shortest list runs out. This is a3559CHICKEN extension to R7RS.35603561 (map cadr '((a b) (d e) (g h)))3562 ===> (b e h)35633564 (map (lambda (n) (expt n n))3565 '(1 2 3 4 5))3566 ===> (1 4 27 256 3125)35673568 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)35693570 (let ((count 0))3571 (map (lambda (ignored)3572 (set! count (+ count 1))3573 count)3574 '(a b))) ===> (1 2) or (2 1)35753576<procedure>(string-map proc string[1] string[2] ...)</procedure>35773578It is an error if proc does not accept as many arguments as there are strings and return a single character.35793580The string-map procedure applies proc element-wise to the elements of the3581strings and returns a string of the results, in order. If more than one3582string is given and not all strings have the same length, string-map terminates3583when the shortest string runs out. The dynamic order in which3584proc is applied to the elements of the3585strings is unspecified. If multiple returns occur from string-map, the values3586returned by earlier returns are not mutated.35873588 (string-map char-foldcase "AbdEgH") ==> "abdegh"35893590 (string-map3591 (lambda (c)3592 (integer->char (+ 1 (char->integer c))))3593 "HAL") ==> "IBM"35943595 (string-map3596 (lambda (c k)3597 ((if (eqv? k #\u) char-upcase char-downcase)3598 c))3599 "studlycaps xxx"3600 "ululululul") ==> "StUdLyCaPs"36013602<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>36033604It is an error if proc does not accept as many arguments as there are vectors and return a single value.36053606The vector-map procedure applies proc element-wise to the elements of the3607vectors and returns a vector of the results, in order. If more than one3608vector is given and not all vectors have the same length, vector-map terminates3609when the shortest vector runs out. The dynamic order in which3610proc is applied to the elements of the3611vectors is unspecified. If multiple returns occur from vector-map, the values3612returned by earlier returns are not mutated.36133614 (vector-map cadr '#((a b) (d e) (g h)))3615 ==> #(b e h)36163617 (vector-map (lambda (n) (expt n n))3618 '#(1 2 3 4 5))3619 ==> #(1 4 27 256 3125)36203621 (vector-map + '#(1 2 3) '#(4 5 6 7))3622 ==> #(5 7 9)36233624 (let ((count 0))3625 (vector-map3626 (lambda (ignored)3627 (set! count (+ count 1))3628 count)3629 '#(a b))) ==> #(1 2) or #(2 1)36303631<procedure>(for-each proc list[1] list[2] ...)</procedure><br>36323633The arguments to for-each are like the arguments to map, but for-each3634calls proc for its side effects rather than for its values. Unlike map,3635for-each is guaranteed to call proc on the elements of the lists in3636order from the first element(s) to the last, and the value returned by3637for-each is unspecified.36383639 (let ((v (make-vector 5)))3640 (for-each (lambda (i)3641 (vector-set! v i (* i i)))3642 '(0 1 2 3 4))3643 v) ===> #(0 1 4 9 16)36443645Like in SRFI-1, this procedure allows the arguments to be of unequal3646length; it terminates when the shortest list runs out. This is a3647CHICKEN extension to R7RS.36483649<procedure>(string-for-each proc string[1] string[2] ...)</procedure>36503651It is an error if proc does not accept as many arguments as there are strings.3652The arguments to string-for-each are like the arguments to string-map, but3653string-for-each calls3654proc for its side effects rather than for its values. Unlike string-map,3655string-for-each is guaranteed to call3656proc on the elements of the3657strings in order from the first element(s) to the last, and the value returned3658by string-for-each is unspecified. If more than one3659string is given and not all strings have the same length, string-for-each3660terminates when the shortest string runs out. It is an error for3661proc to mutate any of the strings.36623663 (let ((v '()))3664 (string-for-each3665 (lambda (c) (set! v (cons (char->integer c) v)))3666 "abcde")3667 v) ==> (101 100 99 98 97)36683669<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>36703671It is an error if proc does not accept as many arguments as there are vectors.3672The arguments to vector-for-each are like the arguments to vector-map, but3673vector-for-each calls3674proc for its side effects rather than for its values. Unlike vector-map,3675vector-for-each is guaranteed to call3676proc on the elements of the3677vectors in order from the first element(s) to the last, and the value returned3678by vector-for-each is unspecified. If more than one3679vector is given and not all vectors have the same length, vector-for-each3680terminates when the shortest vector runs out. It is an error for3681proc to mutate any of the vectors.36823683 (let ((v (make-list 5)))3684 (vector-for-each3685 (lambda (i) (list-set! v i (* i i)))3686 '#(0 1 2 3 4))3687 v) ==> (0 1 4 9 16)36883689<procedure>(call-with-current-continuation proc)</procedure><br>3690<procedure>(call/cc proc)</procedure><br>36913692Proc must be a procedure of one argument. The procedure3693call-with-current-continuation packages up the current continuation3694(see the rationale below) as an "escape procedure" and passes it as3695an argument to proc. The escape procedure is a Scheme procedure that,3696if it is later called, will abandon whatever continuation is in effect3697at that later time and will instead use the continuation that was in3698effect when the escape procedure was created. Calling the escape3699procedure may cause the invocation of before and after thunks installed3700using dynamic-wind.37013702The escape procedure accepts the same number of arguments as the3703continuation to the original call to call-with-current-continuation.3704Except for continuations created by the call-with-values procedure, all3705continuations take exactly one value. The effect of passing no value or3706more than one value to continuations that were not created by3707call-with-values is unspecified.37083709The escape procedure that is passed to proc has unlimited extent just3710like any other procedure in Scheme. It may be stored in variables or3711data structures and may be called as many times as desired.37123713The following examples show only the most common ways in which3714call-with-current-continuation is used. If all real uses were as simple3715as these examples, there would be no need for a procedure with the3716power of call-with-current-continuation.37173718 (call-with-current-continuation3719 (lambda (exit)3720 (for-each (lambda (x)3721 (if (negative? x)3722 (exit x)))3723 '(54 0 37 -3 245 19))3724 #t)) ===> -337253726 (define list-length3727 (lambda (obj)3728 (call-with-current-continuation3729 (lambda (return)3730 (letrec ((r3731 (lambda (obj)3732 (cond ((null? obj) 0)3733 ((pair? obj)3734 (+ (r (cdr obj)) 1))3735 (else (return #f))))))3736 (r obj))))))37373738 (list-length '(1 2 3 4)) ===> 437393740 (list-length '(a b . c)) ===> #f37413742Rationale:37433744A common use of call-with-current-continuation is for structured,3745non-local exits from loops or procedure bodies, but in fact3746call-with-current-continuation is extremely useful for implementing3747a wide variety of advanced control structures.37483749Whenever a Scheme expression is evaluated there is a continuation3750wanting the result of the expression. The continuation represents3751an entire (default) future for the computation. If the expression3752is evaluated at top level, for example, then the continuation might3753take the result, print it on the screen, prompt for the next input,3754evaluate it, and so on forever. Most of the time the continuation3755includes actions specified by user code, as in a continuation that3756will take the result, multiply it by the value stored in a local3757variable, add seven, and give the answer to the top level3758continuation to be printed. Normally these ubiquitous continuations3759are hidden behind the scenes and programmers do not think much3760about them. On rare occasions, however, a programmer may need to3761deal with continuations explicitly. Call-with-current-continuation3762allows Scheme programmers to do that by creating a procedure that3763acts just like the current continuation.37643765Most programming languages incorporate one or more special-purpose3766escape constructs with names like exit, return, or even goto. In37671965, however, Peter Landin [16] invented a general purpose escape3768operator called the J-operator. John Reynolds [24] described a3769simpler but equally powerful construct in 1972. The catch special3770form described by Sussman and Steele in the 1975 report on Scheme3771is exactly the same as Reynolds's construct, though its name came3772from a less general construct in MacLisp. Several Scheme3773implementors noticed that the full power of the catch construct3774could be provided by a procedure instead of by a special syntactic3775construct, and the name call-with-current-continuation was coined3776in 1982. This name is descriptive, but opinions differ on the3777merits of such a long name, and some people use the name call/cc3778instead.37793780<procedure>(values obj ...)</procedure><br>37813782Delivers all of its arguments to its continuation. Except for3783continuations created by the call-with-values procedure, all3784continuations take exactly one value. Values might be defined as3785follows:37863787 (define (values . things)3788 (call-with-current-continuation3789 (lambda (cont) (apply cont things))))37903791<procedure>(call-with-values producer consumer)</procedure><br>37923793Calls its producer argument with no values and a continuation that,3794when passed some values, calls the consumer procedure with those values3795as arguments. The continuation for the call to consumer is the3796continuation of the call to call-with-values.37973798 (call-with-values (lambda () (values 4 5))3799 (lambda (a b) b))3800 ===> 538013802 (call-with-values * -) ===> -138033804<procedure>(dynamic-wind before thunk after)</procedure><br>38053806Calls thunk without arguments, returning the result(s) of this call.3807Before and after are called, also without arguments, as required by the3808following rules (note that in the absence of calls to continuations3809captured using call-with-current-continuation the three arguments are3810called once each, in order). Before is called whenever execution enters3811the dynamic extent of the call to thunk and after is called whenever it3812exits that dynamic extent. The dynamic extent of a procedure call is3813the period between when the call is initiated and when it returns. In3814Scheme, because of call-with-current-continuation, the dynamic extent3815of a call may not be a single, connected time period. It is defined as3816follows:38173818* The dynamic extent is entered when execution of the body of the3819 called procedure begins.38203821* The dynamic extent is also entered when execution is not within the3822 dynamic extent and a continuation is invoked that was captured3823 (using call-with-current-continuation) during the dynamic extent.38243825* It is exited when the called procedure returns.38263827* It is also exited when execution is within the dynamic extent and a3828 continuation is invoked that was captured while not within the3829 dynamic extent.38303831If a second call to dynamic-wind occurs within the dynamic extent of3832the call to thunk and then a continuation is invoked in such a way that3833the afters from these two invocations of dynamic-wind are both to be3834called, then the after associated with the second (inner) call to3835dynamic-wind is called first.38363837If a second call to dynamic-wind occurs within the dynamic extent of3838the call to thunk and then a continuation is invoked in such a way that3839the befores from these two invocations of dynamic-wind are both to be3840called, then the before associated with the first (outer) call to3841dynamic-wind is called first.38423843If invoking a continuation requires calling the before from one call to3844dynamic-wind and the after from another, then the after is called3845first.38463847The effect of using a captured continuation to enter or exit the3848dynamic extent of a call to before or after is undefined. However,3849in CHICKEN it is safe to do this, and they will execute in the outer3850dynamic context of the {{dynamic-wind}} form.38513852 (let ((path '())3853 (c #f))3854 (let ((add (lambda (s)3855 (set! path (cons s path)))))3856 (dynamic-wind3857 (lambda () (add 'connect))3858 (lambda ()3859 (add (call-with-current-continuation3860 (lambda (c0)3861 (set! c c0)3862 'talk1))))3863 (lambda () (add 'disconnect)))3864 (if (< (length path) 4)3865 (c 'talk2)3866 (reverse path))))38673868 ===> (connect talk1 disconnect3869 connect talk2 disconnect)38703871=== Exceptions38723873This section describes Scheme’s exception-handling and exception-raising3874procedures.38753876Exception handlers are one-argument procedures that determine the action the3877program takes when an exceptional situation is signaled. The system implicitly3878maintains a current exception handler in the dynamic environment.38793880The program raises an exception by invoking the current exception handler,3881passing it an object encapsulating information about the exception. Any3882procedure accepting one argument can serve as an exception handler and any3883object can be used to represent an exception.38843885<procedure>(with-exception-handler handler thunk)</procedure>38863887It is an error if handler does not accept one argument. It is also an error if3888thunk does not accept zero arguments.3889The with-exception-handler procedure returns the results of invoking3890thunk.3891Handler is installed as the current exception handler in the dynamic3892environment used for the invocation of3893thunk.38943895 (call-with-current-continuation3896 (lambda (k)3897 (with-exception-handler3898 (lambda (x)3899 (display "condition: ")3900 (write x)3901 (newline)3902 (k 'exception))3903 (lambda ()3904 (+ 1 (raise 'an-error))))))3905 ==> exception and prints "condition: an-error"39063907 (with-exception-handler3908 (lambda (x)3909 (display "something went wrong\n"))3910 (lambda ()3911 (+ 1 (raise 'an-error))))39123913prints "something went wrong"3914After printing, the second example then raises another exception.39153916<procedure>(raise obj)</procedure>39173918Raises an exception by invoking the current exception handler on3919obj. The handler is called with the same dynamic environment as that of the3920call to raise, except that the current exception handler is the one that was in3921place when the handler being called was installed. If the handler returns, a3922secondary exception is raised in the same dynamic environment as the handler.3923The relationship between3924obj and the object raised by the secondary exception is unspecified.39253926<procedure>(raise-continuable obj)</procedure>39273928Raises an exception by invoking the current exception handler on3929obj. The handler is called with the same dynamic environment as the call to3930raise-continuable, except that: (1) the current exception handler is the one3931that was in place when the handler being called was installed, and (2) if the3932handler being called returns, then it will again become the current exception3933handler. If the handler returns, the values it returns become the values3934returned by the call to raise-continuable.39353936 (with-exception-handler3937 (lambda (con)3938 (cond3939 ((string? con)3940 (display con))3941 (else3942 (display "a warning has been issued")))3943 42)3944 (lambda ()3945 (+ (raise-continuable "should be a number")3946 23)))3947 prints: "should be a number"3948 ==> 6539493950<procedure>(error [location] message obj ...)</procedure>39513952Message should be a string.3953Raises an exception as if by calling raise on a newly allocated3954implementation-defined object which encapsulates the information provided by3955message, as well as any3956objs, known as the irritants. The procedure error-object? must return #t on3957such objects.39583959 (define (null-list? l)3960 (cond ((pair? l) #f)3961 ((null? l) #t)3962 (else3963 (error3964 "null-list?: argument out of domain"3965 l))))39663967If location is given and a symbol, it indicates the name of the procedure where3968the error occurred.39693970<procedure>(error-object? obj)</procedure>39713972Returns #t if3973obj is an object created by error or one of an implementation-defined set of3974objects. Otherwise, it returns #f. The objects used to signal errors, including3975those which satisfy the predicates file-error? and read-error?, may or may not3976satisfy error-object?.39773978<procedure>(error-object-message error-object)</procedure>39793980Returns the message encapsulated by3981error-object.39823983<procedure>(error-object-irritants error-object)</procedure>39843985Returns a list of the irritants encapsulated by3986error-object.39873988<procedure>(read-error? obj)</procedure><br>3989<procedure>(file-error? obj)</procedure>39903991Error type predicates. Returns #t if3992obj is an object raised by the read procedure or by the inability to open an3993input or output port on a file, respectively. Otherwise, it returns #f.39943995=== Eval39963997<procedure>(eval expression [environment-specifier])</procedure><br>39983999Evaluates expression in the specified environment and returns its4000value. Expression must be a valid Scheme expression represented as4001data, and environment-specifier must be a value returned by one of the4002three procedures described below. Implementations may extend eval to4003allow non-expression programs (definitions) as the first argument and4004to allow other values as environments, with the restriction that eval4005is not allowed to create new bindings in the environments associated4006with null-environment or scheme-report-environment.40074008 (eval '(* 7 3) (scheme-report-environment 5))4009 ===> 2140104011 (let ((f (eval '(lambda (f x) (f x x))4012 (null-environment 5))))4013 (f + 10))4014 ===> 2040154016The {{environment-specifier}} is optional, and if not provided it4017defaults to the value of {{(interaction-environment)}}. This is a4018CHICKEN extension to R7RS, which, though strictly nonportable, is very4019common among Scheme implementations.40204021=== Input and output40224023==== Ports40244025Ports represent input and output devices. To Scheme, an input port is a Scheme4026object that can deliver data upon command, while an output port is a Scheme4027object that can accept data.40284029Different port types operate on different data. Scheme implementations are4030required to support textual ports and binary ports, but may also provide other4031port types.40324033A textual port supports reading or writing of individual characters from or to4034a backing store containing characters using read-char and write-char below, and4035it supports operations defined in terms of characters, such as read and write.40364037A binary port supports reading or writing of individual bytes from or to a4038backing store containing bytes using read-u8 and write-u8 below, as well as4039operations defined in terms of bytes. Whether the textual and binary port types4040are disjoint is implementation-dependent.40414042Ports can be used to access files, devices, and similar things on the host4043system on which the Scheme program is running.40444045<procedure>(call-with-port port proc)</procedure>40464047It is an error if4048proc does not accept one argument.4049The call-with-port procedure calls4050proc with4051port as an argument. If4052proc returns, then the port is closed automatically and the values yielded by4053the4054proc are returned. If40554056proc does not return, then the port must not be closed automatically unless it4057is possible to prove that the port will never again be used for a read or write4058operation.40594060 Rationale: Because Scheme’s escape procedures have unlimited extent, it is4061 possible to escape from the current continuation but later to resume it. If4062 implementations were permitted to close the port on any escape from the4063 current continuation, then it would be impossible to write portable code4064 using both call-with-current-continuation and call-with-port.40654066Ports represent input and output devices. To Scheme, an input port is a4067Scheme object that can deliver characters upon command, while an output4068port is a Scheme object that can accept characters.40694070<procedure>(input-port? obj)</procedure><br>4071<procedure>(output-port? obj)</procedure><br>4072<procedure>(textual-port? obj)</procedure><br>4073<procedure>(binary-port? obj)</procedure><br>4074<procedure>(port? obj)</procedure>40754076These procedures return #t if4077obj is an input port, output port, textual port, binary port, or any kind of4078port, respectively. Otherwise they return #f.40794080<procedure>(input-port-open? port)</procedure><br>4081<procedure>(output-port-open? port)</procedure>40824083Returns #t if4084port is still open and capable of performing input or output, respectively, and4085#f otherwise.40864087<procedure>(current-input-port [port])</procedure><br>4088<procedure>(current-output-port [port])</procedure><br>4089<procedure>(current-error-port [port])</procedure><br>40904091Returns the current default input, output or error port.40924093If the optional {{port}} argument is passed, the current input or4094output port is changed to the provided port. It can also be used with4095{{parameterize}} to temporarily bind the port to another value. This4096is a CHICKEN extension to the R7RS standard.40974098Note that the default output port is not buffered. Use4099[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]4100if you need a different behavior.41014102<procedure>(open-input-file filename [mode ...])</procedure><br>4103<procedure>(open-binary-input-file filename [mode ...])</procedure>41044105Takes a string naming an existing file and returns an input port4106capable of delivering textual or binary data from the file. If the file cannot be4107opened, an error is signalled.41084109Additional {{mode}} arguments can be passed in, which should be any of4110the keywords {{#:text}} or {{#:binary}}. These indicate the mode in4111which to open the file (this has an effect on non-UNIX platforms4112only). The extra {{mode}} arguments are CHICKEN extensions to the4113R7RS standard.41144115<procedure>(close-port port)</procedure><br>4116<procedure>(close-input-port port)</procedure><br>4117<procedure>(close-output-port port)</procedure><br>41184119Closes the resource associated with4120port, rendering the4121port incapable of delivering or accepting data. It is an error to apply the4122last two procedures to a port which is not an input or output port,4123respectively. Scheme implementations may provide ports which are simultaneously4124input and output ports, such as sockets; the close-input-port and4125close-output-port procedures can then be used to close the input and output4126sides of the port independently.41274128These routines have no effect if the port has already been closed.41294130<procedure>(open-input-string string)</procedure>41314132Takes a string and returns a textual input port that delivers characters from4133the string. If the string is modified, the effect is unspecified.41344135<procedure>(open-output-string)</procedure>41364137Returns a textual output port that will accumulate characters for retrieval by4138get-output-string.41394140<procedure>(get-output-string port)</procedure>41414142It is an error if4143port was not created with open-output-string.4144Returns a string consisting of the characters that have been output to the port4145so far in the order they were output. If the result string is modified, the4146effect is unspecified.41474148 (parameterize4149 ((current-output-port4150 (open-output-string)))4151 (display "piece")4152 (display " by piece ")4153 (display "by piece.")4154 (newline)4155 (get-output-string (current-output-port)))4156 ==> "piece by piece by piece.\n"41574158<procedure>(open-input-bytevector bytevector)</procedure>41594160Takes a bytevector and returns a binary input port that delivers bytes from the4161bytevector.41624163<procedure>(open-output-bytevector)</procedure>41644165Returns a binary output port that will accumulate bytes for retrieval by4166get-output-bytevector.41674168<procedure>(get-output-bytevector port)</procedure>41694170It is an error if4171port was not created with open-output-bytevector.4172Returns a bytevector consisting of the bytes that have been output to the port4173so far in the order they were output.41744175==== Input41764177If port is omitted from any input procedure, it defaults to the value returned by4178(current-input-port). It is an error to attempt an input operation on a closed4179port.41804181<procedure>(read-char [port])</procedure><br>41824183Returns the next character available from the input port, updating the4184port to point to the following character. If no more characters are4185available, an end of file object is returned. Port may be omitted, in4186which case it defaults to the value returned by current-input-port.41874188<procedure>(peek-char [port])</procedure><br>41894190Returns the next character available from the input port, without4191updating the port to point to the following character. If no more4192characters are available, an end of file object is returned. Port may4193be omitted, in which case it defaults to the value returned by4194current-input-port.41954196Note: The value returned by a call to peek-char is the same as4197the value that would have been returned by a call to read-char with4198the same port. The only difference is that the very next call to4199read-char or peek-char on that port will return the value returned4200by the preceding call to peek-char. In particular, a call to4201peek-char on an interactive port will hang waiting for input4202whenever a call to read-char would have hung.42034204<procedure>(read-line [port])</procedure>42054206Returns the next line of text available from the textual input4207port, updating the4208port to point to the following character. If an end of line is read, a string4209containing all of the text up to (but not including) the end of line is4210returned, and the port is updated to point just past the end of line. If an end4211of file is encountered before any end of line is read, but some characters have4212been read, a string containing those characters is returned. If an end of file4213is encountered before any characters are read, an end-of-file object is4214returned. For the purpose of this procedure, an end of line consists of either4215a linefeed character, a carriage return character, or a sequence of a carriage4216return character followed by a linefeed character. Implementations may also4217recognize other end of line characters or sequences.42184219<procedure>(eof-object? obj)</procedure><br>42204221Returns #t if obj is an end of file object, otherwise returns #f. The4222precise set of end of file objects will vary among implementations, but4223in any case no end of file object will ever be an object that can be4224read in using read.42254226<procedure>(eof-object)</procedure>42274228Returns an end-of-file object, not necessarily unique.42294230<procedure>(char-ready? [port])</procedure><br>42314232Returns #t if a character is ready on the input port and returns #f4233otherwise. If char-ready returns #t then the next read-char operation4234on the given port is guaranteed not to hang. If the port is at end of4235file then char-ready? returns #t. Port may be omitted, in which case it4236defaults to the value returned by current-input-port.42374238Rationale: Char-ready? exists to make it possible for a program4239to accept characters from interactive ports without getting stuck4240waiting for input. Any input editors associated with such ports4241must ensure that characters whose existence has been asserted by4242char-ready? cannot be rubbed out. If char-ready? were to return #f4243at end of file, a port at end of file would be indistinguishable4244from an interactive port that has no ready characters.42454246<procedure>(read-string k [port])</procedure>42474248See [[Module (chicken io)|(chicken io) module]] for more information.42494250<procedure>(read-u8 [port])</procedure>42514252Returns the next byte available from the binary input4253port, updating the4254port to point to the following byte. If no more bytes are available, an4255end-of-file object is returned.42564257<procedure>(peek-u8 [port])</procedure>42584259Returns the next byte available from the binary input4260port, but without updating the4261port to point to the following byte. If no more bytes are available, an4262end-of-file object is returned.42634264<procedure>(u8-ready? [port])</procedure>42654266Returns #t if a byte is ready on the binary input4267port and returns #f otherwise. If u8-ready? returns #t then the next read-u84268operation on the given4269port is guaranteed not to hang. If the4270port is at end of file then u8-ready? returns #t.42714272<procedure>(read-bytevector k [port])</procedure><br>4273<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>42744275See [[Module (chicken io)|(chicken io) module]] for more information.42764277==== Output42784279If port is omitted from any output procedure, it defaults to the value returned by4280(current-output-port). It is an error to attempt an output operation on a4281closed port.42824283<procedure>(newline)</procedure><br>4284<procedure>(newline port)</procedure><br>42854286Writes an end of line to port. Exactly how this is done differs from4287one operating system to another. Returns an unspecified value. The port4288argument may be omitted, in which case it defaults to the value4289returned by current-output-port.42904291<procedure>(write-char char)</procedure><br>4292<procedure>(write-char char port)</procedure><br>42934294Writes the character char (not an external representation of the4295character) to the given port and returns an unspecified value. The port4296argument may be omitted, in which case it defaults to the value4297returned by current-output-port.42984299<procedure>(write-string string [port [start [end]]])</procedurew>43004301Writes the characters of4302string from4303start to4304end in left-to-right order to the textual output4305port.43064307<procedure>(write-u8 byte [port])</procedure>43084309Writes the4310byte to the given binary output4311port and returns an unspecified value.43124313<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>43144315See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more4316information.43174318<procedure>(flush-output-port [port])</procedure>43194320Flushes any buffered output from the buffer of output-port to the underlying4321file or device and returns an unspecified value.43224323==== System interface43244325Questions of system interface generally fall outside of the domain of4326this report. However, the following operations are important enough to4327deserve description here.43284329<procedure>(features)</procedure>43304331Returns a list of the feature identifiers which cond-expand treats as true. It4332is an error to modify this list. Here is an example of what features might4333return:43344335 (features) ==>4336 (r7rs ratios exact-complex full-unicode4337 gnu-linux little-endian4338 fantastic-scheme4339 fantastic-scheme-1.04340 space-ship-control-system)43414342---4343Previous: [[Module scheme]]43444345Next: [[Module (scheme case-lambda)]]