Module scheme
This module provides all of CHICKEN's R7RS procedures and macros. These descriptions are based directly on the Revised^7 Report on the Algorithmic Language Scheme.
Expressions
Expression types are categorized as primitive or derived. Primitive expression types include variables and procedure calls. Derived expression types are not semantically primitive, but can instead be defined as macros. The distinction which R7RS makes between primitive and derived is unimportant and does not necessarily reflect how it is implemented in CHICKEN itself.
Primitive expression types
Variable references
[syntax] <variable>An expression consisting of a variable is a variable reference. The value of the variable reference is the value stored in the location to which the variable is bound. It is an error to reference an unbound variable.
(define x 28) x ===> 28
Literal expressions
[syntax] (quote <datum>)[syntax] '<datum>
[syntax] <constant>
(quote <datum>) evaluates to <datum>. <Datum> may be any external representation of a Scheme object. This notation is used to include literal constants in Scheme code.
(quote a) ===> a (quote #(a b c)) ===> #(a b c) (quote (+ 1 2)) ===> (+ 1 2)
(quote <datum>) may be abbreviated as '<datum>. The two notations are equivalent in all respects.
'a ===> a '#(a b c) ===> #(a b c) '() ===> () '(+ 1 2) ===> (+ 1 2) '(quote a) ===> (quote a) ''a ===> (quote a)
Numerical constants, string constants, character constants, and boolean constants evaluate "to themselves"; they need not be quoted.
'"abc" ===> "abc" "abc" ===> "abc" '145932 ===> 145932 145932 ===> 145932 '#t ===> #t #t ===> #t '#(a 10) ===> #(a 10) #(a 10) ===> #(a 10) '#u8(64 65) ===> #u8(64 65) #u8(64 65) ===> #u8(64 65)
It is an error to alter a constant (i.e. the value of a literal expression) using a mutation procedure like set-car! or string-set!. In the current implementation of CHICKEN, identical constants don't share memory and it is possible to mutate them, but this may change in the future.
Procedure calls
[syntax] (<operator> <operand[1]> ...)A procedure call is written by simply enclosing in parentheses expressions for the procedure to be called and the arguments to be passed to it. The operator and operand expressions are evaluated (in an unspecified order) and the resulting procedure is passed the resulting arguments.
(+ 3 4) ===> 7 ((if #f + *) 3 4) ===> 12
A number of procedures are available as the values of variables in the initial environment; for example, the addition and multiplication procedures in the above examples are the values of the variables + and *. New procedures are created by evaluating lambda expressions. Procedure calls may return any number of values (see the values procedure below).
Procedure calls are also called combinations.
Note: In contrast to other dialects of Lisp, the order of evaluation is unspecified, and the operator expression and the operand expressions are always evaluated with the same evaluation rules.
Note: Although the order of evaluation is otherwise unspecified, the effect of any concurrent evaluation of the operator and operand expressions is constrained to be consistent with some sequential order of evaluation. The order of evaluation may be chosen differently for each procedure call.
Note: In many dialects of Lisp, the empty combination, (), is a legitimate expression. In Scheme, combinations must have at least one subexpression, so () is not a syntactically valid expression.
Procedures
[syntax] (lambda <formals> <body>)Syntax: <Formals> should be a formal arguments list as described below, and <body> should be a sequence of one or more expressions.
Semantics: A lambda expression evaluates to a procedure. The environment in effect when the lambda expression was evaluated is remembered as part of the procedure. When the procedure is later called with some actual arguments, the environment in which the lambda expression was evaluated will be extended by binding the variables in the formal argument list to fresh locations, the corresponding actual argument values will be stored in those locations, and the expressions in the body of the lambda expression will be evaluated sequentially in the extended environment. The result(s) of the last expression in the body will be returned as the result(s) of the procedure call.
(lambda (x) (+ x x)) ===> a procedure ((lambda (x) (+ x x)) 4) ===> 8 (define reverse-subtract (lambda (x y) (- y x))) (reverse-subtract 7 10) ===> 3 (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (add4 6) ===> 10
<Formals> should have one of the following forms:
- (<variable[1]> ...): The procedure takes a fixed number of arguments; when the procedure is called, the arguments will be stored in the bindings of the corresponding variables.
- <variable>: The procedure takes any number of arguments; when the procedure is called, the sequence of actual arguments is converted into a newly allocated list, and the list is stored in the binding of the <variable>.
- (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a space-delimited period precedes the last variable, then the procedure takes n or more arguments, where n is the number of formal arguments before the period (there must be at least one). The value stored in the binding of the last variable will be a newly allocated list of the actual arguments left over after all the other actual arguments have been matched up against the other formal arguments.
It is an error for a <variable> to appear more than once in <formals>.
((lambda x x) 3 4 5 6) ===> (3 4 5 6) ((lambda (x y . z) z) 3 4 5 6) ===> (5 6)
Each procedure created as the result of evaluating a lambda expression is (conceptually) tagged with a storage location, in order to make eqv? and eq? work on procedures.
As an extension to R7RS, CHICKEN also supports "extended" DSSSL style parameter lists, which allows embedded special keywords. Such a keyword gives a special meaning to the <formal> it precedes. DSSSL parameter lists are defined by the following grammar:
<parameter-list> ==> <required-parameter>* [#!optional <optional-parameter>*] [#!rest <rest-parameter>] [#!key <keyword-parameter>*] <required-parameter> ==> <ident> <optional-parameter> ==> <ident> | (<ident> <initializer>) <rest-parameter> ==> <ident> <keyword-parameter> ==> <ident> | (<ident> <initializer>) <initializer> ==> <expr>
When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
- 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.
- 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.
- 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.
- 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.
Needing a special mention is the close relationship between the rest-parameter and possible keyword-parameters. Declaring a rest-parameter binds up all remaining arguments in a list, as described above. These same remaining arguments are also used for attempted matches with declared keyword-parameters, as described above, in which case a matching keyword-parameter binds to the corresponding value argument at the same time that both the keyword and value arguments are added to the rest parameter list. Note that for efficiency reasons, the keyword-parameter matching does nothing more than simply attempt to match with pairs that may exist in the remaining arguments. Extra arguments that don't match are simply unused and forgotten if no rest-parameter has been declared. Because of this, the caller of a procedure containing one or more keyword-parameters cannot rely on any kind of system error to report wrong keywords being passed in.
It shall be an error for an <ident> to appear more than once in a parameter-list.
If 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.
Example:
((lambda x x) 3 4 5 6) => (3 4 5 6) ((lambda (x y #!rest z) z) 3 4 5 6) => (5 6) ((lambda (x y #!optional z #!rest r #!key i (j 1)) (list x y z i: i j: j)) 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)
Conditionals
[syntax] (if <test> <consequent> <alternate>)[syntax] (if <test> <consequent>)
Syntax: <Test>, <consequent>, and <alternate> may be arbitrary expressions.
Semantics: An if expression is evaluated as follows: first, <test> is evaluated. If it yields a true value (see the section about booleans below), then <consequent> is evaluated and its value(s) is(are) returned. Otherwise <alternate> is evaluated and its value(s) is(are) returned. If <test> yields a false value and no <alternate> is specified, then the result of the expression is unspecified.
(if (> 3 2) 'yes 'no) ===> yes (if (> 2 3) 'yes 'no) ===> no (if (> 3 2) (- 3 2) (+ 3 2)) ===> 1
Assignments
[syntax] (set! <variable> <expression>)<Expression> is evaluated, and the resulting value is stored in the location to which <variable> is bound. <Variable> must be bound either in some region enclosing the set! expression or at top level. The result of the set! expression is unspecified.
(define x 2) (+ x 1) ===> 3 (set! x 4) ===> unspecified (+ x 1) ===> 5
As an extension to R7RS, set! for unbound toplevel variables is allowed. Also, (set! (PROCEDURE ...) ...) is supported, as CHICKEN implements SRFI-17.
Inclusion
[syntax] (include STRING1 STRING2 ...)[syntax] (include-ci STRING1 STRING2 ...)
Semantics: Both include and include-ci take one or more filenames expressed as string literals, apply an implementation-specific algorithm to find corresponding files, read the contents of the files in the specified order as if by repeated applications of read, and effectively replace the include or include-ci expression with a begin expression containing what was read from the files. The difference between the two is that include-ci reads each file as if it began with the #!fold-case directive, while include does not.
Derived expression types
The constructs in this section are hygienic. For reference purposes, these macro definitions will convert most of the constructs described in this section into the primitive constructs described in the previous section. This does not necessarily mean that's exactly how it's implemented in CHICKEN.
Conditionals
[syntax] (cond <clause[1]> <clause[2]> ...)Syntax: Each <clause> should be of the form
(<test> <expression[1]> ...)
where <test> is any expression. Alternatively, a <clause> may be of the form
(<test> => <expression>)
The last <clause> may be an "else clause," which has the form
(else <expression[1]> <expression[2]> ...).
Semantics: A cond expression is evaluated by evaluating the <test> expressions of successive <clause>s in order until one of them evaluates to a true value (see the section about booleans below). When a <test> evaluates to a true value, then the remaining <expression>s in its <clause> are evaluated in order, and the result(s) of the last <expression> in the <clause> is(are) returned as the result(s) of the entire cond expression. If the selected <clause> contains only the <test> and no <expression>s, then the value of the <test> is returned as the result. If the selected <clause> uses the => alternate form, then the <expression> is evaluated. Its value must be a procedure that accepts one argument; this procedure is then called on the value of the <test> and the value(s) returned by this procedure is(are) returned by the cond expression. If all <test>s evaluate to false values, and there is no else clause, then the result of the conditional expression is unspecified; if there is an else clause, then its <expression>s are evaluated, and the value(s) of the last one is(are) returned.
(cond ((> 3 2) 'greater) ((< 3 2) 'less)) ===> greater (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal)) ===> equal (cond ((assv 'b '((a 1) (b 2))) => cadr) (else #f)) ===> 2
As an extension to R7RS, CHICKEN also supports the SRFI-61 syntax:
(<generator> <guard> => <expression>)
In this situation, generator is always evaluated. Its resulting value(s) are used as argument(s) for the guard procedure. Finally, if guard returns a non-#f value, the expression is evaluated by calling it with the result of guard. Otherwise, evaluation procedes to the next clause.
[syntax] (case <key> <clause[1]> <clause[2]> ...)Syntax: <Key> may be any expression. Each <clause> should have the form
((<datum[1]> ...) <expression[1]> <expression[2]> ...),
where each <datum> is an external representation of some object. Alternatively, as per R7RS, a <clause> may be of the form
((<datum[1]> ...) => <expression>).
All the <datum>s must be distinct. The last <clause> may be an "else clause," which has one of the following two forms:
(else <expression[1]> <expression[2]> ...) (else => <expression>).
Semantics: A case expression is evaluated as follows. <Key> is evaluated and its result is compared against each <datum>. If the result of evaluating <key> is equivalent (in the sense of eqv?; see below) to a <datum>, then the expressions in the corresponding <clause> are evaluated from left to right and the result(s) of the last expression in the <clause> is(are) returned as the result(s) of the case expression. If the selected <clause> uses the => alternate form (an R7RS extension), then the <expression> is evaluated. Its value must be a procedure that accepts one argument; this procedure is then called on the value of the <key> and the value(s) returned by this procedure is(are) returned by the case expression. If the result of evaluating <key> is different from every <datum>, then if there is an else clause its expressions are evaluated and the result(s) of the last is(are) the result(s) of the case expression; otherwise the result of the case expression is unspecified.
(case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite)) ===> composite (case (car '(c d)) ((a) 'a) ((b) 'b)) ===> unspecified (case (car '(c d)) ((a e i o u) 'vowel) ((w y) 'semivowel) (else 'consonant)) ===> consonant[syntax] (and <test[1]> ...)
The <test> expressions are evaluated from left to right, and the value of the first expression that evaluates to a false value (see the section about booleans) is returned. Any remaining expressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then #t is returned.
(and (= 2 2) (> 2 1)) ===> #t (and (= 2 2) (< 2 1)) ===> #f (and 1 2 'c '(f g)) ===> (f g) (and) ===> #t[syntax] (or <test[1]> ...)
The <test> expressions are evaluated from left to right, and the value of the first expression that evaluates to a true value (see the section about booleans) is returned. Any remaining expressions are not evaluated. If all expressions evaluate to false values, the value of the last expression is returned. If there are no expressions then #f is returned.
(or (= 2 2) (> 2 1)) ===> #t (or (= 2 2) (< 2 1)) ===> #t (or #f #f #f) ===> #f (or (memq 'b '(a b c)) (/ 3 0)) ===> (b c)[syntax] (unless TEST EXP1 EXP2 ...)
Equivalent to:
(if (not TEST) (begin EXP1 EXP2 ...))
[syntax] (when TEST EXP1 EXP2 ...)
Equivalent to:
(if TEST (begin EXP1 EXP2 ...))
[syntax] (cond-expand <ce-clause1> <ce-clause2> ...)
The cond-expand expression type provides a way to statically expand different expressions depending on the implementation. A <ce-clause> takes the following form:
(<feature requirement> <expression> ...)
The last clause can be an "else clause," which has the form
(else <expression> ...) ]
A ⟨feature requirement⟩ takes one of the following forms:
<feature identifier>
(library <library name>)
(and <feature requirement> ...)
(or <feature requirement> ...)
(not <feature requirement>)
Each implementation maintains a list of feature identifiers which are present, as well as a list of libraries which can be imported. The value of a <feature requirement> is determined by replacing each <feature identifier> and (library <library name>) on the implementation’s lists with #t, and all other feature identifiers and library names with #f, then evaluating the resulting expression as a Scheme boolean expression under the normal interpretation of and, or, and not.
A cond-expand is then expanded by evaluating the <feature requirement>s of successive <ce-clause>s in order until one of them returns #t. When a true clause is found, the corresponding <expression>s are expanded to a begin, and the remaining clauses are ignored.
If none of the <feature requirement>s evaluate to #t, then if there is an else clause, its <expression>s are included. Otherwise, the behavior of the cond-expand is unspecified. Unlike cond, cond-expand does not depend on the value of any variables.
The following features are built-in and always available by default: chicken, srfi-0, srfi-2, srfi-6, srfi-8, srfi-9, srfi-11, srfi-12, srfi-15, srfi-16, srfi-17, srfi-23, srfi-26, srfi-28, srfi-30, srfi-31, srfi-39, srfi-46, srfi-55, srfi-61, srfi-62, srfi-87, srfi-88.
There are also situation-specific feature identifiers: compiling during compilation, csi when running in the interpreter, and compiler-extension when running within the compiler.
The symbols returned by the following procedures from (chicken platform) are also available as feature-identifiers in all situations: (machine-byte-order), (machine-type), (software-type), (software-version). For example, the machine-type class of feature-identifiers include arm, alpha, mips, etc.
Platform endianness is indicated by the little-endian and big-endian features.
In addition the following feature-identifiers may exist: cross-chicken, dload, gchooks, ptables, case-insensitive.
Binding constructs
The three binding constructs let, let*, and letrec give Scheme a block structure, like Algol 60. The syntax of the three constructs is identical, but they differ in the regions they establish for their variable bindings. In a let expression, the initial values are computed before any of the variables become bound; in a let* expression, the bindings and evaluations are performed sequentially; while in a letrec expression, all the bindings are in effect while their initial values are being computed, thus allowing mutually recursive definitions.
[syntax] (let <bindings> <body>)Syntax: <Bindings> should have the form
((<variable[1]> <init[1]>) ...),
where each <init> is an expression, and <body> should be a sequence of one or more expressions. It is an error for a <variable> to appear more than once in the list of variables being bound.
Semantics: The <init>s are evaluated in the current environment (in some unspecified order), the <variable>s are bound to fresh locations holding the results, the <body> is evaluated in the extended environment, and the value(s) of the last expression of <body> is(are) returned. Each binding of a <variable> has <body> as its region.
(let ((x 2) (y 3)) (* x y)) ===> 6 (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))) ===> 35
See also "named let", below.
[syntax] (let* <bindings> <body>)Syntax: <Bindings> should have the form
((<variable[1]> <init[1]>) ...),
and <body> should be a sequence of one or more expressions.
Semantics: Let* is similar to let, but the bindings are performed sequentially from left to right, and the region of a binding indicated by (<variable> <init>) is that part of the let* expression to the right of the binding. Thus the second binding is done in an environment in which the first binding is visible, and so on.
(let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))) ===> 70[syntax] (letrec <bindings> <body>)
Syntax: <Bindings> should have the form
((<variable[1]> <init[1]>) ...),
and <body> should be a sequence of one or more expressions. It is an error for a <variable> to appear more than once in the list of variables being bound.
Semantics: The <variable>s are bound to fresh locations holding undefined values, the <init>s are evaluated in the resulting environment (in some unspecified order), each <variable> is assigned to the result of the corresponding <init>, the <body> is evaluated in the resulting environment, and the value(s) of the last expression in <body> is(are) returned. Each binding of a <variable> has the entire letrec expression as its region, making it possible to define mutually recursive procedures.
(letrec ((even? (lambda (n) (if (zero? n) #t (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) #f (even? (- n 1)))))) (even? 88)) ===> #t
One restriction on letrec is very important: it must be possible to evaluate each <init> without assigning or referring to the value of any <variable>. If this restriction is violated, then it is an error. The restriction is necessary because Scheme passes arguments by value rather than by name. In the most common uses of letrec, all the <init>s are lambda expressions and the restriction is satisfied automatically.
[syntax] (letrec* <bindings> <body>)Syntax: <Bindings> has the form ((<variable[1]> <init[1]>) ...),and <body>is a sequence of zero or more definitions followed by one or more expressions as described in section 4.1.4. It is an error for a <variable> to appear more than once in the list of variables being bound.
Semantics: The <variable>s are bound to fresh locations, each <variable> is assigned in left-to-right order to the result of evaluating the corresponding <init> (interleaving evaluations and assignments), the <body> is evaluated in the resulting environment, and the values of the last expression in <body> are returned. Despite the left-to-right evaluation and assignment order, each binding of a <variable> has the entire letrec* expression as its region, making it possible to define mutually recursive procedures.
If it is not possible to evaluate each <init> without assigning or referring to the value of the corresponding <variable> or the <variable> of any of the bindings that follow it in <bindings>, it is an error. Another restriction is that it is an error to invoke the continuation of an <init> more than once.
{{
- ; Returns the arithmetic, geometric, and
- ; harmonic means of a nested list of numbers
(define (means ton)
(letrec* ((mean (lambda (f g) (f (/ (sum g ton) n)))) (sum (lambda (g ton) (if (null? ton) (+) (if (number? ton) (g ton) (+ (sum g (car ton)) (sum g (cdr ton))))))) (n (sum (lambda (x) 1) ton))) (values (mean values values) (mean exp log) (mean / /))))
}}
Evaluating (means '(3 (1 4))) returns three values: 8/3, 2.28942848510666 (approximately), and 36/19.
[syntax] (let-values <mv binding spec> <body>)Syntax: <Mv binding spec> has the form ((<formals[1]> <init[1]>) ...), where each <init> is an expression, and <body> is zero or more definitions followed by a sequence of one or more expressions as described in section 4.1.4. It is an error for a variable to appear more than once in the set of <formals>.
Semantics: The <init>s are evaluated in the current environment (in some unspecified order) as if by invoking call-with-values, and the variables occurring in the <formals> are bound to fresh locations holding the values returned by the <init>s, where the <formals> are matched to the return values in the same way that the <formals> in a lambda expression are matched to the arguments in a procedure call. Then, the <body> is evaluated in the extended environment, and the values of the last expression of <body> are returned. Each binding of a <variable> has <body> as its region.
It is an error if the <formals> do not match the number of values returned by the corresponding <init>.
{{ (let-values (((root rem) (exact-integer-sqrt 32)))
(* root rem)) ==> 35
}}
[syntax] (let*-values <mv binding spec> <body>)Syntax: <Mv binding spec> has the form ((<formals> <init>) ...), and <body> is a sequence of zero or more definitions followed by one or more expressions as described in section 4.1.4. In each <formals>, it is an error if any variable appears more than once.
Semantics: The let*-values construct is similar to let-values, but the <init>s are evaluated and bindings created sequentially from left to right, with the region of the bindings of each <formals> including the <init>s to its right as well as <body>. Thus the second <init> is evaluated in an environment in which the first set of bindings is visible and initialized, and so on.
{{ (let ((a 'a) (b 'b) (x 'x) (y 'y))
(let*-values (((a b) (values x y)) ((x y) (values a b))) (list a b x y))) ⟹ (x y x y)
}}
Sequencing
[syntax] (begin <expression[1]> <expression[2]> ...)The <expression>s are evaluated sequentially from left to right, and the value(s) of the last <expression> is(are) returned. This expression type is used to sequence side effects such as input and output.
(define x 0) (begin (set! x 5) (+ x 1)) ===> 6 (begin (display "4 plus 1 equals ") (display (+ 4 1))) ===> unspecified and prints 4 plus 1 equals 5
As an extension to R7RS, CHICKEN also allows (begin) without body expressions in any context, not just at toplevel. This simply evaluates to the unspecified value.
Iteration
[syntax] (do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)Do is an iteration construct. It specifies a set of variables to be bound, how they are to be initialized at the start, and how they are to be updated on each iteration. When a termination condition is met, the loop exits after evaluating the <expression>s.
Do expressions are evaluated as follows: The <init> expressions are evaluated (in some unspecified order), the <variable>s are bound to fresh locations, the results of the <init> expressions are stored in the bindings of the <variable>s, and then the iteration phase begins.
Each iteration begins by evaluating <test>; if the result is false (see the section about booleans), then the <command> expressions are evaluated in order for effect, the <step> expressions are evaluated in some unspecified order, the <variable>s are bound to fresh locations, the results of the <step>s are stored in the bindings of the <variable>s, and the next iteration begins.
If <test> evaluates to a true value, then the <expression>s are evaluated from left to right and the value(s) of the last <expression> is(are) returned. If no <expression>s are present, then the value of the do expression is unspecified.
The region of the binding of a <variable> consists of the entire do expression except for the <init>s. It is an error for a <variable> to appear more than once in the list of do variables.
A <step> may be omitted, in which case the effect is the same as if (<variable> <init> <variable>) had been written instead of (<variable> <init>).
(do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) ===> #(0 1 2 3 4) (let ((x '(1 3 5 7 9))) (do ((x x (cdr x)) (sum 0 (+ sum (car x)))) ((null? x) sum))) ===> 25[syntax] (let <variable> <bindings> <body>)
"Named let" is a variant on the syntax of let which provides a more general looping construct than do and may also be used to express recursions. It has the same syntax and semantics as ordinary let except that <variable> is bound within <body> to a procedure whose formal arguments are the bound variables and whose body is <body>. Thus the execution of <body> may be repeated by invoking the procedure named by <variable>.
(let loop ((numbers '(3 -2 1 6 -5)) (nonneg '()) (neg '())) (cond ((null? numbers) (list nonneg neg)) ((>= (car numbers) 0) (loop (cdr numbers) (cons (car numbers) nonneg) neg)) ((< (car numbers) 0) (loop (cdr numbers) nonneg (cons (car numbers) neg))))) ===> ((6 1 3) (-5 -2))
Dynamic bindings
The dynamic extent of a procedure call is the time between when it is initiated and when it returns. In Scheme, call-with-current-continuation allows reentering a dynamic extent after its procedure call has returned. Thus, the dynamic extent of a call might not be a single, continuous time period.
This sections introduces parameter objects, which can be bound to new values for the duration of a dynamic extent. The set of all parameter bindings at a given time is called the dynamic environment.
[procedure] (make-parameter init [converter])Returns a newly allocated parameter object, which is a procedure that accepts zero arguments and returns the value associated with the parameter object. Initially, this value is the value of (converter init), or of init if the conversion procedure converter is not specified. The associated value can be temporarily changed using parameterize, which is described below.
The effect of passing arguments to a parameter object is implementation-dependent.
<macro>(parameterize ((<param[1]> <value[1]>) ...) <body>)</procedure>
Syntax: Both <param[1]> and <value[1]> are expressions.
It is an error if the value of any <param> expression is not a parameter object.
Semantics: A parameterize expression is used to change the values returned by specified parameter objects during the evaluation of the body.
The <param> and <value> expressions are evaluated in an unspecified order. The <body> is evaluated in a dynamic environment in which calls to the parameters return the results of passing the corresponding values to the conversion procedure specified when the parameters were created. Then the previous values of the parameters are restored without passing them to the conversion procedure. The results of the last expression in the <body> are returned as the results of the entire parameterize expression.
Note: If the conversion procedure is not idempotent, the results of (parameterize ((x (x))) ...), which appears to bind the parameter x to its current value, might not be what the user expects.
If an implementation supports multiple threads of execution, then parameterize must not change the associated values of any parameters in any thread other than the current thread and threads created inside <body>.
Parameter objects can be used to specify configurable settings for a computation without the need to pass the value to every procedure in the call chain explicitly.
{{ (define radix
(make-parameter 10 (lambda (x) (if (and (exact-integer? x) (<= 2 x 16)) x (error "invalid radix")))))
(define (f n) (number->string n (radix)))
(f 12) ==> "12" (parameterize ((radix 2))
(f 12)) ==> "1100"
(f 12) ==> "12"
(radix 16) ==> unspecified
(parameterize ((radix 0))
(f 12)) ==> error
}}
Exception handling
[syntax] (guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)Syntax: Each <cond clause> is as in the specification of cond.
Semantics: The <body> is evaluated with an exception handler that binds the raised object (see raise) to <variable> and, within the scope of that binding, evaluates the clauses as if they were the clauses of a cond expression. That implicit cond expression is evaluated with the continuation and dynamic environment of the guard expression. If every <cond clause>'s <test> evaluates to #f and there is no else clause, then raise-continuable is invoked on the raised object within the dynamic environment of the original call to raise or raise-continuable, except that the current exception handler is that of the guard expression.
{{ (guard (condition
((assq 'a condition) => cdr) ((assq 'b condition))) (raise (list (cons 'a 42))))
==> 42
(guard (condition
((assq 'a condition) => cdr) ((assq 'b condition))) (raise (list (cons 'b 23))))
==> (b . 23) }}
Quasiquotation
[syntax] (quasiquote <qq template>)[syntax] `<qq template>
"Backquote" or "quasiquote" expressions are useful for constructing a list or vector structure when most but not all of the desired structure is known in advance. If no commas appear within the <qq template>, the result of evaluating `<qq template> is equivalent to the result of evaluating '<qq template>. If a comma appears within the <qq template>, however, the expression following the comma is evaluated ("unquoted") and its result is inserted into the structure instead of the comma and the expression. If a comma appears followed immediately by an at-sign (@), then the following expression must evaluate to a list; the opening and closing parentheses of the list are then "stripped away" and the elements of the list are inserted in place of the comma at-sign expression sequence. A comma at-sign should only appear within a list or vector <qq template>.
`(list ,(+ 1 2) 4) ===> (list 3 4) (let ((name 'a)) `(list ,name ',name)) ===> (list a (quote a)) `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) ===> (a 3 4 5 6 b) `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))) ===> ((foo 7) . cons) `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8) ===> #(10 5 2 4 3 8)
Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost backquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation.
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f) (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)) ===> (a `(b ,x ,'y d) e)
The two notations `<qq template> and (quasiquote <qq template>) are identical in all respects. ,<expression> is identical to (unquote <expression>), and ,@<expression> is identical to (unquote-splicing <expression>). The external syntax generated by write for two-element lists whose car is one of these symbols may vary between implementations.
(quasiquote (list (unquote (+ 1 2)) 4)) ===> (list 3 4) '(quasiquote (list (unquote (+ 1 2)) 4)) ===> `(list ,(+ 1 2) 4) i.e., (quasiquote (list (unquote (+ 1 2)) 4))
Unpredictable behavior can result if any of the symbols quasiquote, unquote, or unquote-splicing appear in positions within a <qq template> otherwise than as described above.
Macros
Scheme programs can define and use new derived expression types, called macros. Program-defined expression types have the syntax
(<keyword> <datum> ...)
where <keyword> is an identifier that uniquely determines the expression type. This identifier is called the syntactic keyword, or simply keyword, of the macro. The number of the <datum>s, and their syntax, depends on the expression type.
Each instance of a macro is called a use of the macro. The set of rules that specifies how a use of a macro is transcribed into a more primitive expression is called the transformer of the macro.
The macro definition facility consists of two parts:
- A set of expressions used to establish that certain identifiers are macro keywords, associate them with macro transformers, and control the scope within which a macro is defined, and
- a pattern language for specifying macro transformers.
The syntactic keyword of a macro may shadow variable bindings, and local variable bindings may shadow keyword bindings. All macros defined using the pattern language are "hygienic" and "referentially transparent" and thus preserve Scheme's lexical scoping:
- If a macro transformer inserts a binding for an identifier (variable or keyword), the identifier will in effect be renamed throughout its scope to avoid conflicts with other identifiers. Note that a define at top level may or may not introduce a binding; this depends on whether the binding already existed before (in which case its value will be overridden).
- If a macro transformer inserts a free reference to an identifier, the reference refers to the binding that was visible where the transformer was specified, regardless of any local bindings that may surround the use of the macro.
Binding constructs for syntactic keywords
Let-syntax and letrec-syntax are analogous to let and letrec, but they bind syntactic keywords to macro transformers instead of binding variables to locations that contain values. Syntactic keywords may also be bound at top level.
[syntax] (let-syntax <bindings> <body>)Syntax: <Bindings> should have the form
((<keyword> <transformer spec>) ...)
Each <keyword> is an identifier, each <transformer spec> is an instance of syntax-rules, and <body> should be a sequence of one or more expressions. It is an error for a <keyword> to appear more than once in the list of keywords being bound.
Semantics: The <body> is expanded in the syntactic environment obtained by extending the syntactic environment of the let-syntax expression with macros whose keywords are the <keyword>s, bound to the specified transformers. Each binding of a <keyword> has <body> as its region.
(let-syntax ((when (syntax-rules () ((when test stmt1 stmt2 ...) (if test (begin stmt1 stmt2 ...)))))) (let ((if #t)) (when if (set! if 'now)) if)) ===> now (let ((x 'outer)) (let-syntax ((m (syntax-rules () ((m) x)))) (let ((x 'inner)) (m)))) ===> outer[syntax] (letrec-syntax <bindings> <body>)
Syntax: Same as for let-syntax.
Semantics: The <body> is expanded in the syntactic environment obtained by extending the syntactic environment of the letrec-syntax expression with macros whose keywords are the <keyword>s, bound to the specified transformers. Each binding of a <keyword> has the <bindings> as well as the <body> within its region, so the transformers can transcribe expressions into uses of the macros introduced by the letrec-syntax expression.
(letrec-syntax ((my-or (syntax-rules () ((my-or) #f) ((my-or e) e) ((my-or e1 e2 ...) (let ((temp e1)) (if temp temp (my-or e2 ...))))))) (let ((x #f) (y 7) (temp 8) (let odd?) (if even?)) (my-or x (let temp) (if y) y))) ===> 7
Pattern language
A <transformer spec> has the following form:
(syntax-rules <literals> <syntax rule> ...)
Syntax: <Literals> is a list of identifiers and each <syntax rule> should be of the form
(<pattern> <template>)
The <pattern> in a <syntax rule> is a list <pattern> that begins with the keyword for the macro.
A <pattern> is either an identifier, a constant, or one of the following
(<pattern> ...) (<pattern> <pattern> ... . <pattern>) (<pattern> ... <pattern> <ellipsis> <pattern> ...) #(<pattern> ...) #(<pattern> ... <pattern> <ellipsis>)
and a template is either an identifier, a constant, or one of the following
(<element> ...) (<element> <element> ... . <template>) (<ellipsis> <template>) #(<element> ...)
where an <element> is a <template> optionally followed by an <ellipsis> and an <ellipsis> is the identifier "...".
Semantics: An instance of syntax-rules produces a new macro transformer by specifying a sequence of hygienic rewrite rules. A use of a macro whose keyword is associated with a transformer specified by syntax-rules is matched against the patterns contained in the <syntax rule>s, beginning with the leftmost <syntax rule>. When a match is found, the macro use is transcribed hygienically according to the template.
An identifier appearing within a <pattern> can be an underscore (_), a literal identifier listed in the list of <pattern literal>s, or the <ellipsis>. All other identifiers appearing within a <pattern> are pattern variables.
The keyword at the beginning of the pattern in a <syntax rule> is not involved in the matching and is considered neither a pattern variable nor a literal identifier.
Pattern variables match arbitrary input elements and are used to refer to elements of the input in the template. It is an error for the same pattern variable to appear more than once in a <pattern>.
Underscores also match arbitrary input elements but are not pattern variables and so cannot be used to refer to those elements. If an underscore appears in the <pattern literal>s list, then that takes precedence and underscores in the <pattern> match as literals. Multiple underscores can appear in a <pattern>.
Identifiers that appear in (<pattern literal> …) are interpreted as literal identifiers to be matched against corresponding elements of the input. An element in the input matches a literal identifier if and only if it is an identifier and either both its occurrence in the macro expression and its occurrence in the macro definition have the same lexical binding, or the two identifiers are the same and both have no lexical binding.
A subpattern followed by <ellipsis> can match zero or more elements of the input, unless <ellipsis> appears in the <pattern literal>s, in which case it is matched as a literal.
More formally, an input form F matches a pattern P if and only if:
- P is an underscore (_).
- P is a non-literal identifier; or
- P is a literal identifier and F is an identifier with the same binding; or
- P is a list (P[1] ... P[n]) and F is a list of n forms that match P [1] through P[n], respectively; or
- P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list or improper list of n or more forms that match P[1] through P[n], respectively, and whose nth "cdr" matches P[n+1]; or
- P is of the form (P[1] … P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E is a list or improper list of n elements, the first k of which match P[1] through P[k], whose next m−k elements each match P[e], whose remaining n−m elements match P[m+1] through P[n], and whose nth and final cdr matches P[x ]; or
- P is a vector of the form #(P[1] ... P[n]) and F is a vector of n forms that match P[1] through P[n]; or
• P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a vector of n elements the first k of which match P[1] through P[k], whose next m−k elements each match P[e], and whose remaining n−m elements match P [m+1] through P[n]; or
- P is a datum and F is equal to P in the sense of the equal? procedure.
It is an error to use a macro keyword, within the scope of its binding, in an expression that does not match any of the patterns.
When a macro use is transcribed according to the template of the matching <syntax rule>, pattern variables that occur in the template are replaced by the elements they match in the input. Pattern variables that occur in subpatterns followed by one or more instances of the identifier <ellipsis> are allowed only in subtemplates that are followed by as many instances of <ellipsis>. They are replaced in the output by all of the elements they match in the input, distributed as indicated. It is an error if the output cannot be built up as specified.
Identifiers that appear in the template but are not pattern variables or the identifier <ellipsis> are inserted into the output as literal identifiers. If a literal identifier is inserted as a free identifier then it refers to the binding of that identifier within whose scope the instance of syntax-rules appears. If a literal identifier is inserted as a bound identifier then it is in effect renamed to prevent inadvertent captures of free identifiers.
A template of the form (<ellipsis> <template>) is identical to <template>, except that ellipses within the template have no special meaning. That is, any ellipses contained within <template> are treated as ordinary identifiers. In particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>. This allows syntactic abstractions to expand into code containing ellipses.
{{ (define-syntax be-like-begin
(syntax-rules () ((be-like-begin name) (define-syntax name (syntax-rules () ((name expr (... ...)) (begin expr (... ...))))))))
(be-like-begin sequence)
(sequence 1 2 3 4) ==> 4 }}
As an example, if let and cond have their standard meaning then they are hygienic (as required) and the following is not an error.
(let ((=> #f)) (cond (#t => 'ok))) ===> ok
The macro transformer for cond recognizes => as a local variable, and hence an expression, and not as the top-level identifier =>, which the macro transformer treats as a syntactic keyword. Thus the example expands into
(let ((=> #f)) (if #t (begin => 'ok)))
instead of
(let ((=> #f)) (let ((temp #t)) (if temp ('ok temp))))
which would result in an invalid procedure call.
Signaling errors in macro transformers
[syntax] (syntax-error <message> <args> ...)syntax-error behaves similarly to error except that implementations with an expansion pass separate from evaluation should signal an error as soon as syntax-error is expanded. This can be used as a syntax-rules <template> for a <pattern> that is an invalid use of the macro, which can provide more descriptive error messages. <message> is a string literal, and <args> arbitrary expressions providing additional information. Applications cannot count on being able to catch syntax errors with exception handlers or guards.
(define-syntax simple-let (syntax-rules () ((_ (head ... ((x . y) val) . tail) body1 body2 ...) (syntax-error "expected an identifier but got" (x . y))) ((_ ((name val) ...) body1 body2 ...) ((lambda (name ...) body1 body2 ...) val ...))))
Program structure
Programs
A Scheme program consists of a sequence of expressions, definitions, and syntax definitions. Expressions are described in chapter 4; definitions and syntax definitions are the subject of the rest of the present chapter.
Programs are typically stored in files or entered interactively to a running Scheme system, although other paradigms are possible; questions of user interface lie outside the scope of this report. (Indeed, Scheme would still be useful as a notation for expressing computational methods even in the absence of a mechanical implementation.)
Definitions and syntax definitions occurring at the top level of a program can be interpreted declaratively. They cause bindings to be created in the top level environment or modify the value of existing top-level bindings. Expressions occurring at the top level of a program are interpreted imperatively; they are executed in order when the program is invoked or loaded, and typically perform some kind of initialization.
At the top level of a program (begin <form1> ...) is equivalent to the sequence of expressions, definitions, and syntax definitions that form the body of the begin.
Import declarations
[syntax] (import IMPORT-SET ...)An import declaration provides a way to import identifiers exported by a library. Each <import set> names a set of bindings from a library and possibly specifies local names for the imported bindings. It takes one of the following forms:
- <library name>
- (only <import set> <identifier> ...)
- (except <import set> <identifier> ...)
- (prefix <import set> <identifier>)
- (rename <import set> (<identifier[1]> <identifier[2]>) ...)
In the first form, all of the identifiers in the named library’s export clauses are imported with the same names (or the exported names if exported with rename ). The additional <import set> forms modify this set as follows:
- only produces a subset of the given <import set> including only the listed identifiers (after any renaming). It is an error if any of the listed identifiers are not found in the original set.
- except produces a subset of the given <import set>, excluding the listed identifiers (after any renaming). It is an error if any of the listed identifiers are not found in the original set.
- rename modifies the given <import set>, replacing each instance of <identifier[1]> with <identifier[2]>. It is an error if any of the listed <identifier[1]>s are not found in the original set.
- prefix automatically renames all identifiers in the given <import set>, prefixing each with the specified <identifier>.
Definitions
Definitions are valid in some, but not all, contexts where expressions are allowed. They are valid only at the top level of a <program> and at the beginning of a <body>.
A definition should have one of the following forms:
[syntax] (define <variable> <expression>)[syntax] (define (<variable> <formals>) <body>)
<Formals> should be either a sequence of zero or more variables, or a sequence of one or more variables followed by a space-delimited period and another variable (as in a lambda expression). This form is equivalent to
(define <variable> (lambda (<formals>) <body>)).[syntax] (define <variable>)
This form is a CHICKEN extension to R7RS, and is equivalent to
(define <variable> (void))[syntax] (define (<variable> . <formal>) <body>)
<Formal> should be a single variable. This form is equivalent to
(define <variable> (lambda <formal> <body>)).[syntax] (define ((<variable> <formal> ...) ...) <body>)
As an extension to R7RS, CHICKEN allows curried definitions, where the variable name may also be a list specifying a name and a nested lambda list. For example,
(define ((make-adder x) y) (+ x y))
is equivalent to
(define (make-adder x) (lambda (y) (+ x y))).
This type of curried definition can be nested arbitrarily and combined with dotted tail notation or DSSSL keywords.
Top level definitions
At the top level of a program, a definition
(define <variable> <expression>)
has essentially the same effect as the assignment expression
(set! <variable> <expression>)
if <variable> is bound. If <variable> is not bound, however, then the definition will bind <variable> to a new location before performing the assignment, whereas it would be an error to perform a set! on an unbound variable in standard Scheme. In CHICKEN, set! at toplevel has the same effect as a definition, unless inside a module, in which case it is an error.
(define add3 (lambda (x) (+ x 3))) (add3 3) ===> 6 (define first car) (first '(1 2)) ===> 1
Some implementations of Scheme use an initial environment in which all possible variables are bound to locations, most of which contain undefined values. Top level definitions in such an implementation are truly equivalent to assignments. In CHICKEN, attempting to evaluate an unbound identifier will result in an error, but you can use set! to bind an initial value to it.
Internal definitions
Definitions may occur at the beginning of a <body> (that is, the body of a lambda, let, let*, letrec, let-syntax, or letrec-syntax expression or that of a definition of an appropriate form). Such definitions are known as internal definitions as opposed to the top level definitions described above. The variable defined by an internal definition is local to the <body>. That is, <variable> is bound rather than assigned, and the region of the binding is the entire <body>. For example,
(let ((x 5)) (define foo (lambda (y) (bar x y))) (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3))) ===> 45
A <body> containing internal definitions can always be converted into a completely equivalent letrec expression. For example, the let expression in the above example is equivalent to
(let ((x 5)) (letrec ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3))))
Just as for the equivalent letrec expression, it must be possible to evaluate each <expression> of every internal definition in a <body> without assigning or referring to the value of any <variable> being defined.
Wherever an internal definition may occur (begin <definition1> ...) is equivalent to the sequence of definitions that form the body of the begin.
CHICKEN extends the R7RS semantics by allowing internal definitions everywhere, and not only at the beginning of a body. A set of internal definitions is equivalent to a letrec form enclosing all following expressions in the body:
(let ((foo 123)) (bar) (define foo 456) (baz foo) )
expands into
(let ((foo 123)) (bar) (letrec ((foo 456)) (baz foo) ) )
Local sequences of define-syntax forms are translated into equivalent letrec-syntax forms that enclose the following forms as the body of the expression.
Multiple-value definitions
Another kind of definition is provided by define-values, which creates multiple definitions from a single expression returning multiple values. It is allowed wherever define is allowed.
[syntax] (define-values <formals> <expression>)It is an error if a variable appears more than once in the set of <formals>.
Semantics: <Expression> is evaluated, and the <formals> are bound to the return values in the same way that the <formals> in a lambda expression are matched to the arguments in a procedure call.
{{ (define-values (x y) (exact-integer-sqrt 17)) (list x y) ==> (4 1)
(let ()
(define-values (x y) (values 1 2)) (+ x y)) ==> 3
}}
Syntax definitions
Syntax definitions are valid only at the top level of a <program>. They have the following form:
[syntax] (define-syntax <keyword> <transformer spec>)<Keyword> is an identifier, and the <transformer spec> should be an instance of syntax-rules. Note that CHICKEN also supports er-macro-transformer and ir-macro-transformer here. For more information see the (chicken syntax) module.
The top-level syntactic environment is extended by binding the <keyword> to the specified transformer.
In standard Scheme, there is no define-syntax analogue of internal definitions in, but CHICKEN allows these as an extension to the standard. This means define-syntax may be used to define local macros that are visible throughout the rest of the body in which the definition occurred, i.e.
(let () ... (define-syntax foo ...) (define-syntax bar ...) ...)
is expanded into
(let () ... (letrec-syntax ((foo ...) (bar ...)) ...) )
syntax-rules supports SRFI-46 in allowing the ellipsis identifier to be user-defined by passing it as the first argument to the syntax-rules form. Also, "tail" patterns of the form
(syntax-rules () ((_ (a b ... c) ...
are supported.
The effect of destructively modifying the s-expression passed to a transformer procedure is undefined.
Although macros may expand into definitions and syntax definitions in any context that permits them, it is an error for a definition or syntax definition to shadow a syntactic keyword whose meaning is needed to determine whether some form in the group of forms that contains the shadowing definition is in fact a definition, or, for internal definitions, is needed to determine the boundary between the group and the expressions that follow the group. For example, the following are errors:
(define define 3) (begin (define begin list)) (let-syntax ((foo (syntax-rules () ((foo (proc args ...) body ...) (define proc (lambda (args ...) body ...)))))) (let ((x 3)) (foo (plus x y) (+ x y)) (define foo x) (plus foo x)))
Record-type definitions
Record-type definitions are used to introduce new data types, called record types. Like other definitions, they can appear either at the outermost level or in a body. The values of a record type are called records and are aggregations of zero or more fields, each of which holds a single location. A predicate, a constructor, and field accessors and mutators are defined for each record type.
[syntax] (define-record-type <name> <constructor> <pred> <field> ...)Syntax: <name> and <pred> are identifiers. The <constructor> is of the form (<constructor name> <field name> ...) and each <field> is either of the form (<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 once as a field name. It is also an error for the same identifier to occur more than once as an accessor or mutator name.
The define-record-type construct is generative: each use creates a new record type that is distinct from all existing types, including Scheme’s predefined types and other record types — even record types of the same name or structure.
An instance of define-record-type is equivalent to the following definitions:
- <name> is bound to a representation of the record type itself. This may be a run-time object or a purely syntactic representation. The representation is not utilized in this report, but it serves as a means to identify the record type for use by further language extensions.
- <constructor name> is bound to a procedure that takes as many arguments as there are <field name>s in the (<constructor name> ...) subexpression and returns a new record of type <name>. Fields whose names are listed with <constructor name> have the corresponding argument as their initial value. The initial values of all other fields are unspecified. It is an error for a field name to appear in <constructor> but not as a <field name>.
- <pred> is bound to a predicate that returns #t when given a value returned by the procedure bound to <constructor name> and #f for everything else.
- Each <accessor name> is bound to a procedure that takes a record of type <name> and returns the current value of the corresponding field. It is an error to pass an accessor a value which is not a record of the appropriate type.
- Each <modifier name> is bound to a procedure that takes a record of type <name> and a value which becomes the new value of the corresponding field; an unspecified value is returned. It is an error to pass a modifier a first argument which is not a record of the appropriate type.
For instance, the following record-type definition
{{ (define-record-type <pare>
(kons x y) pare? (x kar set-kar!) (y kdr))
}}
defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a modifier, and pare? to be a predicate for instances of <pare>.
{{ (pare? (kons 1 2)) ⟹ #t
(pare? (cons 1 2)) ⟹ #f (kar (kons 1 2)) ⟹ 1 (kdr (kons 1 2)) ⟹ 2 (let ((k (kons 1 2))) (set-kar! k 3) (kar k)) ⟹ 3
}}
Libraries
Libraries provide a way to organize Scheme programs into reusable parts with explicitly defined interfaces to the rest of the program. This section defines the notation and semantics for libraries.
Library Syntax
A library definition takes the following form:
[syntax] (define-library <library name> <library declaration> ...)<library name> is a list whose members are identifiers and exact non-negative integers. It is used to identify the library uniquely when importing from other programs or libraries. Libraries whose first identifier is scheme are reserved for use by this report and future versions of this report. Libraries whose first identifier is srfi are reserved for libraries implementing Scheme Requests for Implementation. It is inadvisable, but not an error, for identifiers in library names to contain any of the characters | \ ? * < " : > + [ ] / or control characters after escapes are expanded.
A <library declaration> is any of:
- (export <export spec> ...)
- (import <import set> ...)
- (begin <command or definition> ...)
- (include <filename[1]> <filename[2]> ...)
- (include-ci <filename[1]> <filename[2]> ...)
- (include-library-declarations <filename[1]> <filename[2]> ...)
- (cond-expand <ce-clause[1]> <ce-clause[2]> ...
An export declaration specifies a list of identifiers which can be made visible to other libraries or programs. An <export spec> takes one of the following forms:
- <identifier>
- (rename <identifier[1]> <identifier[2]>)
In an <export spec>, an <identifier> names a single binding defined within or imported into the library, where the external name for the export is the same as the name of the binding within the library. A rename spec exports the binding defined within or imported into the library and named by <identifier [1]> in each (<identifier[1]> <identifier[2]>) pairing, using <identifier[2]> as the external name.
An import declaration provides a way to import the identifiers exported by another library.
The begin, include, and include-ci declarations are used to specify the body of the library. They have the same syntax and semantics as the corresponding expression types. This form of begin is analogous to, but not the same as, the two types of begin defined in section 4.2.3.
The include-library-declarations declaration is similar to include except that the contents of the file are spliced directly into the current library definition. This can be used, for example, to share the same export declaration among multiple libraries as a simple form of library interface.
The cond-expand declaration has the same syntax and semantics as the cond-expand expression type, except that it expands to spliced-in library declarations rather than expressions enclosed in begin.
One possible implementation of libraries is as follows: After all cond-expand library declarations are expanded, a new environment is constructed for the library consisting of all imported bindings. The expressions from all begin, include and include-ci library declarations are expanded in that environment in the order in which they occur in the library. Alternatively, cond-expand and import declarations may be processed in left to right order interspersed with the processing of other declarations, with the environment growing as imported bindings are added to it by each import declaration.
When a library is loaded, its expressions are executed in textual order. If a library’s definitions are referenced in the expanded form of a program or library body, then that library must be loaded before the expanded program or library body is evaluated. This rule applies transitively. If a library is imported by more than one program or library, it may possibly be loaded additional times.
Similarly, during the expansion of a library (foo), if any syntax keywords imported from another library (bar) are needed to expand the library, then the library (bar) must be expanded and its syntax definitions evaluated before the expansion of (foo).
Standard procedures
This chapter describes Scheme's built-in procedures. The initial (or "top level") Scheme environment starts out with a number of variables bound to locations containing useful values, most of which are primitive procedures that manipulate data. For example, the variable abs is bound to (a location initially containing) a procedure of one argument that computes the absolute value of a number, and the variable + is bound to a procedure that computes sums. Built-in procedures that can easily be written in terms of other built-in procedures are identified as "library procedures".
A program may use a top-level definition to bind any variable. It may subsequently alter any such binding by an assignment (see assignments, above). These operations do not modify the behavior of Scheme's built-in procedures. Altering any top-level binding that has not been introduced by a definition has an unspecified effect on the behavior of the built-in procedures.
Equivalence predicates
A predicate is a procedure that always returns a boolean value (#t or #f). An equivalence predicate is the computational analogue of a mathematical equivalence relation (it is symmetric, reflexive, and transitive). Of the equivalence predicates described in this section, eq? is the finest or most discriminating, and equal? is the coarsest. eqv? is slightly less discriminating than eq?.
[procedure] (eqv? obj[1] obj[2])The eqv? procedure defines a useful equivalence relation on objects. Briefly, it returns #t if obj[1] and obj[2] should normally be regarded as the same object. This relation is left slightly open to interpretation, but the following partial specification of eqv? holds for all implementations of Scheme.
The eqv? procedure returns #t if:
- obj[1] and obj[2] are both #t or both #f.
- obj[1] and obj[2] are both symbols and
(string=? (symbol->string obj1) (symbol->string obj2)) ===> #t
Note: This assumes that neither obj[1] nor obj[2] is an "uninterned symbol" as alluded to in the section on symbols. This report does not presume to specify the behavior of eqv? on implementation-dependent extensions.
- obj[1] and obj[2] are both numbers, are numerically equal (see =, under numerical operations), and are either both exact or both inexact.
- obj[1] and obj[2] are both characters and are the same character according to the char=? procedure (see "characters").
- both obj[1] and obj[2] are the empty list.
- obj[1] and obj[2] are pairs, vectors, or strings that denote the same locations in the store.
- obj[1] and obj[2] are procedures whose location tags are equal (see "procedures").
The eqv? procedure returns #f if:
- obj[1] and obj[2] are of different types.
- one of obj[1] and obj[2] is #t but the other is #f.
- obj[1] and obj[2] are symbols but
(string=? (symbol->string obj[1]) (symbol->string obj[2])) ===> #f
- one of obj[1] and obj[2] is an exact number but the other is an inexact number.
- obj[1] and obj[2] are numbers for which the = procedure returns #f.
- obj[1] and obj[2] are characters for which the char=? procedure returns #f.
- one of obj[1] and obj[2] is the empty list but the other is not.
- obj[1] and obj[2] are pairs, vectors, or strings that denote distinct locations.
- obj[1] and obj[2] are procedures that would behave differently (return different value(s) or have different side effects) for some arguments.
(eqv? 'a 'a) ===> #t (eqv? 'a 'b) ===> #f (eqv? 2 2) ===> #t (eqv? '() '()) ===> #t (eqv? 100000000 100000000) ===> #t (eqv? (cons 1 2) (cons 1 2)) ===> #f (eqv? (lambda () 1) (lambda () 2)) ===> #f (eqv? #f 'nil) ===> #f (let ((p (lambda (x) x))) (eqv? p p)) ===> #t
The following examples illustrate cases in which the above rules do not fully specify the behavior of eqv?. All that can be said about such cases is that the value returned by eqv? must be a boolean.
(eqv? "" "") ===> unspecified (eqv? '#() '#()) ===> unspecified (eqv? (lambda (x) x) (lambda (x) x)) ===> unspecified (eqv? (lambda (x) x) (lambda (y) y)) ===> unspecified
The next set of examples shows the use of eqv? with procedures that have local state. Gen-counter must return a distinct procedure every time, since each procedure has its own internal counter. Gen-loser, however, returns equivalent procedures each time, since the local state does not affect the value or side effects of the procedures.
(define gen-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (let ((g (gen-counter))) (eqv? g g)) ===> #t (eqv? (gen-counter) (gen-counter)) ===> #f (define gen-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (let ((g (gen-loser))) (eqv? g g)) ===> #t (eqv? (gen-loser) (gen-loser)) ===> unspecified (letrec ((f (lambda () (if (eqv? f g) 'both 'f))) (g (lambda () (if (eqv? f g) 'both 'g)))) (eqv? f g)) ===> unspecified (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (eqv? f g)) ===> #f
Since it is an error to modify constant objects (those returned by literal expressions), implementations are permitted, though not required, to share structure between constants where appropriate. Thus the value of eqv? on constants is sometimes implementation-dependent.
(eqv? '(a) '(a)) ===> unspecified (eqv? "a" "a") ===> unspecified (eqv? '(b) (cdr '(a b))) ===> unspecified (let ((x '(a))) (eqv? x x)) ===> #t
Rationale: The above definition of eqv? allows implementations latitude in their treatment of procedures and literals: implementations are free either to detect or to fail to detect that two procedures or two literals are equivalent to each other, and can decide whether or not to merge representations of equivalent objects by using the same pointer or bit pattern to represent both.
[procedure] (eq? obj[1] obj[2])Eq? is similar to eqv? except that in some cases it is capable of discerning distinctions finer than those detectable by eqv?.
Eq? and eqv? are guaranteed to have the same behavior on symbols, booleans, the empty list, pairs, procedures, and non-empty strings and vectors. Eq?'s behavior on numbers and characters is implementation-dependent, but it will always return either true or false, and will return true only when eqv? would also return true. Eq? may also behave differently from eqv? on empty vectors and empty strings.
(eq? 'a 'a) ===> #t (eq? '(a) '(a)) ===> unspecified (eq? (list 'a) (list 'a)) ===> #f (eq? "a" "a") ===> unspecified (eq? "" "") ===> unspecified (eq? '() '()) ===> #t (eq? 2 2) ===> unspecified (eq? #\A #\A) ===> unspecified (eq? car car) ===> #t (let ((n (+ 2 3))) (eq? n n)) ===> unspecified (let ((x '(a))) (eq? x x)) ===> #t (let ((x '#())) (eq? x x)) ===> #t (let ((p (lambda (x) x))) (eq? p p)) ===> #t
Rationale: It will usually be possible to implement eq? much more efficiently than eqv?, for example, as a simple pointer comparison instead of as some more complicated operation. One reason is that it may not be possible to compute eqv? of two numbers in constant time, whereas eq? implemented as pointer comparison will always finish in constant time. Eq? may be used like eqv? in applications using procedures to implement objects with state since it obeys the same constraints as eqv?.
[procedure] (equal? obj[1] obj[2])Equal? recursively compares the contents of pairs, vectors, and strings, applying eqv? on other objects such as numbers and symbols. A rule of thumb is that objects are generally equal? if they print the same. Equal? may fail to terminate if its arguments are circular data structures.
(equal? 'a 'a) ===> #t (equal? '(a) '(a)) ===> #t (equal? '(a (b) c) '(a (b) c)) ===> #t (equal? "abc" "abc") ===> #t (equal? 2 2) ===> #t (equal? (make-vector 5 'a) (make-vector 5 'a)) ===> #t (equal? (lambda (x) x) (lambda (y) y)) ===> unspecified
Numbers
Numerical computation has traditionally been neglected by the Lisp community. Until Common Lisp there was no carefully thought out strategy for organizing numerical computation, and with the exception of the MacLisp system [20] little effort was made to execute numerical code efficiently. This report recognizes the excellent work of the Common Lisp committee and accepts many of their recommendations. In some ways this report simplifies and generalizes their proposals in a manner consistent with the purposes of Scheme.
It is important to distinguish between the mathematical numbers, the Scheme numbers that attempt to model them, the machine representations used to implement the Scheme numbers, and notations used to write numbers. This report uses the types number, complex, real, rational, and integer to refer to both mathematical numbers and Scheme numbers. Machine representations such as fixed point and floating point are referred to by names such as fixnum and flonum.
Numerical types
Mathematically, numbers may be arranged into a tower of subtypes in which each level is a subset of the level above it:
number complex real rational integer
For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex. The same is true of the Scheme numbers that model 3. For Scheme numbers, these types are defined by the predicates number?, complex?, real?, rational?, and integer?.
There is no simple relationship between a number's type and its representation inside a computer. Although most implementations of Scheme will offer at least two different representations of 3, these different representations denote the same integer.
Scheme's numerical operations treat numbers as abstract data, as independent of their representation as possible. Although an implementation of Scheme may use fixnum, flonum, and perhaps other representations for numbers, this should not be apparent to a casual programmer writing simple programs.
It is necessary, however, to distinguish between numbers that are represented exactly and those that may not be. For example, indexes into data structures must be known exactly, as must some polynomial coefficients in a symbolic algebra system. On the other hand, the results of measurements are inherently inexact, and irrational numbers may be approximated by rational and therefore inexact approximations. In order to catch uses of inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact from inexact numbers. This distinction is orthogonal to the dimension of type.
Exactness
Scheme numbers are either exact or inexact. A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations. A number is inexact if it was written as an inexact constant, if it was derived using inexact ingredients, or if it was derived using inexact operations. Thus inexactness is a contagious property of a number. If two implementations produce exact results for a computation that did not involve inexact intermediate results, the two ultimate results will be mathematically equivalent. This is generally not true of computations involving inexact numbers since approximate methods such as floating point arithmetic may be used, but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result.
Rational operations such as + should always produce exact results when given exact arguments. If the operation is unable to produce an exact result, then it may either report the violation of an implementation restriction or it may silently coerce its result to an inexact value. See the next section.
With the exception of inexact->exact, the operations described in this section must generally return inexact results when given any inexact arguments. An operation may, however, return an exact result if it can prove that the value of the result is unaffected by the inexactness of its arguments. For example, multiplication of any number by an exact zero may produce an exact zero result, even if the other argument is inexact.
Implementation restrictions
Implementations of Scheme are not required to implement the whole tower of subtypes given under "Numerical types", but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, an implementation in which all numbers are real may still be quite useful.
Implementations may also support only a limited range of numbers of any type, subject to the requirements of this section. The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type. For example, an implementation that uses flonums to represent all its inexact real numbers may support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the flonum format. Furthermore the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached.
An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists, vectors, and strings or that may result from computing the length of a list, vector, or string. The length, vector-length, and string-length procedures must return an exact integer, and it is an error to use anything but an exact integer as an index. Furthermore any integer constant within the index range, if expressed by an exact integer syntax, will indeed be read as an exact integer, regardless of any implementation restrictions that may apply outside this range. Finally, the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation:
- * + abs ceiling denominator exact-integer-sqrt expt floor floor/ floor-quotient floor-remainder gcd lcm max min modulo numerator quotient rationalize remainder round square truncate truncate/ truncate-quotient truncate-remainder
CHICKEN follows the IEEE 32-bit and 64-bit floating point standards on all supported platforms.
It is the programmer’s responsibility to avoid using inexact number objects with magnitude or significand too large to be represented in the implementation.
In addition, implementations may distinguish special numbers called positive infinity, negative infinity, NaN, and negative zero.
Positive infinity is regarded as an inexact real (but not rational) number that represents an indeterminate value greater than the numbers represented by all rational numbers. Negative infinity is regarded as an inexact real (but not rational) number that represents an indeterminate value less than the numbers represented by all rational numbers.
Adding or multiplying an infinite value by any finite real value results in an appropriately signed infinity; however, the sum of positive and negative infinities is a NaN. Positive infinity is the reciprocal of zero, and negative infinity is the reciprocal of negative zero. The behavior of the transcendental functions is sensitive to infinity in accordance with IEEE 754.
A NaN is regarded as an inexact real (but not rational) number so indeterminate that it might represent any real value, including positive or negative infinity, and might even be greater than positive infinity or less than negative infinity. An implementation that does not support non-real numbers may use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).
A NaN always compares false to any number, including a NaN. An arithmetic operation where one operand is NaN returns NaN, unless the implementation can prove that the result would be the same if the NaN were replaced by any rational number. Dividing zero by zero results in NaN unless both zeros are exact.
Negative zero is an inexact real value written -0.0 and is distinct (in the sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish negative zero. If it does, however, the behavior of the transcendental functions is sensitive to the distinction in accordance with IEEE 754. Specifically, in a Scheme implementing both complex numbers and negative zero, the branch cut of the complex logarithm function is such that (imag-part (log -1.0-0.0i)) is −π rather than π.
Furthermore, the negation of negative zero is ordinary zero and vice versa. This implies that the sum of two or more negative zeros is negative, and the result of subtracting (positive) zero from a negative zero is likewise negative. However, numerical comparisons treat negative zero as equal to zero.
Note that both the real and the imaginary parts of a complex number can be infinities, NaNs, or negative zero.
Syntax of numerical constants
For a complete formal description of the syntax of the written representations for numbers, see the R7RS report. Note that case is not significant in numerical constants.
A number may be written in binary, octal, decimal, or hexadecimal by the use of a radix prefix. The radix prefixes are #b (binary), #o (octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a number is assumed to be expressed in decimal.
A numerical constant may be specified to be either exact or inexact by a prefix. The prefixes are #e for exact, and #i for inexact. An exactness prefix may appear before or after any radix prefix that is used. If the written representation of a number has no exactness prefix, the constant may be either inexact or exact. It is inexact if it contains a decimal point, an exponent, or a "#" character in the place of a digit, otherwise it is exact. In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant. For this purpose, numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation. The letters s, f, d, and l specify the use of short, single, double, and long precision, respectively. (When fewer than four internal inexact representations exist, the four size specifications are mapped onto those available. For example, an implementation with two internal representations may map short and single together and long and double together.) In addition, the exponent marker e specifies the default precision for the implementation. The default precision has at least as much precision as double, but implementations may wish to allow this default to be set by the user.
3.14159265358979F0 Round to single --- 3.141593 0.6L0 Extend to long --- .600000000000000
Numerical operations
The numerical routines described below have argument restrictions, which are encoded in the naming conventions of the arguments as given in the procedure's signature. The conventions are as follows:
- obj
- any object
- {{list, list1, ... listj, ... list
- (see "Pairs and lists" below)
- z, z1, ... zj, ...
- complex number
- x, x1, ... xj, ...
- real number
- y, y1, ... yj, ...
- real number
- q, q1, ... qj, ...
- rational number
- n, n1, ... nj, ...
- integer
- k, k1, ... kj, ...
- exact non-negative integer
The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number. Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy; the inexact constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers.
[procedure] (number? obj)[procedure] (complex? obj)
[procedure] (real? obj)
[procedure] (rational? obj)
[procedure] (integer? obj)
These numerical type predicates can be applied to any kind of argument, including non-numbers. They return #t if the object is of the named type, and otherwise they return #f. In general, if a type predicate is true of a number then all higher type predicates are also true of that number. Consequently, if a type predicate is false of a number, then all lower type predicates are also false of that number. If z is an inexact complex number, then (real? z) is true if and only if (zero? (imag-part z)) is true. If x is an inexact real number, then (integer? x) is true if and only if (= x (round x)).
(complex? 3+4i) ===> #t (complex? 3) ===> #t (real? 3) ===> #t (real? -2.5+0.0i) ===> #t (real? #e1e10) ===> #t (rational? 6/10) ===> #t (rational? 6/3) ===> #t (integer? 3+0i) ===> #t (integer? 3.0) ===> #t (integer? 8/4) ===> #t
Note: The behavior of these type predicates on inexact numbers is unreliable, since any inaccuracy may affect the result.
Note: In many implementations the rational? procedure will be the same as real?, and the complex? procedure will be the same as number?, but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non-complex numbers.
[procedure] (exact? z)[procedure] (inexact? z)
These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of these predicates is true.
[procedure] (exact-integer? z)Returns #t if z is both exact and an integer; otherwise returns #f.
(exact-integer? 32) ===> #t (exact-integer? 32.0) ===> #f (exact-integer? 32/5) ===> #f[procedure] (= z[1] z[2] z[3] ...)
[procedure] (< x[1] x[2] x[3] ...)
[procedure] (> x[1] x[2] x[3] ...)
[procedure] (<= x[1] x[2] x[3] ...)
[procedure] (>= x[1] x[2] x[3] ...)
These procedures return #t if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing.
These predicates are required to be transitive.
Note: The traditional implementations of these predicates in Lisp-like languages are not transitive.
Note: While it is not an error to compare inexact numbers using these predicates, the results may be unreliable because a small inaccuracy may affect the result; this is especially true of = and zero?. When in doubt, consult a numerical analyst.
[procedure] (zero? z)[procedure] (positive? x)
[procedure] (negative? x)
[procedure] (odd? n)
[procedure] (even? n)
These numerical predicates test a number for a particular property, returning #t or #f. See note above.
[procedure] (max x[1] x[2] ...)[procedure] (min x[1] x[2] ...)
These procedures return the maximum or minimum of their arguments.
(max 3 4) ===> 4 ; exact (max 3.9 4) ===> 4.0 ; inexact
Note: If any argument is inexact, then the result will also be inexact (unless the procedure can prove that the inaccuracy is not large enough to affect the result, which is possible only in unusual implementations). If min or max is used to compare numbers of mixed exactness, and the numerical value of the result cannot be represented as an inexact number without loss of accuracy, then the procedure may report a violation of an implementation restriction.
[procedure] (+ z[1] ...)[procedure] (* z[1] ...)
These procedures return the sum or product of their arguments.
(+ 3 4) ===> 7 (+ 3) ===> 3 (+) ===> 0 (* 4) ===> 4 (*) ===> 1[procedure] (- z[1] z[2])
[procedure] (- z)
[procedure] (- z[1] z[2] ...)
[procedure] (/ z[1] z[2])
[procedure] (/ z)
[procedure] (/ z[1] z[2] ...)
With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument.
(- 3 4) ===> -1 (- 3 4 5) ===> -6 (- 3) ===> -3 (/ 3 4 5) ===> 3/20 (/ 3) ===> 1/3[procedure] (abs x)
Abs returns the absolute value of its argument.
(abs -7) ===> 7[procedure] (floor/ n[1] n[2])
[procedure] (floor-quotient n[1] n[2])
[procedure] (floor-remainder n[1] n[2])
[procedure] (truncate/ n[1] n[2])
[procedure] (truncate-quotient n[1] n[2])
[procedure] (truncate-remainder n[1] n[2])
These procedures implement number-theoretic (integer) division. It is an error if n[2] is zero. The procedures ending in / return two integers; the other procedures return an integer. All the procedures compute a quotient n[q] and remainder n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as follows:
(<operator>/ n[1] n[2]) ==> n[q] n[r] (<operator>-quotient n[1] n[2]) ==> n[q] (<operator>-remainder n[1] n[2]) ==> n[r]
The 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]:
floor n[q] = ⌊n[1] / n[2]⌋ truncate n[q] = runcate(n[1] / n[2])
For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,
(= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2])) (<operator>-remainder n[1] n[2]))) ==> #t
provided all numbers involved in that computation are exact.
Examples:
(floor/ 5 2) ==> 2 1 (floor/ -5 2) ==> -3 1 (floor/ 5 -2) ==> -3 -1 (floor/ -5 -2) ==> 2 -1 (truncate/ 5 2) ==> 2 1 (truncate/ -5 2) ==> -2 -1 (truncate/ 5 -2) ==> -2 1 (truncate/ -5 -2) ==> 2 -1 (truncate/ -5.0 -2) ==> 2.0 -1.0[procedure] (quotient n[1] n[2])
[procedure] (remainder n[1] n[2])
[procedure] (modulo n[1] n[2])
These procedures implement number-theoretic (integer) division. n[2] should be non-zero. All three procedures return integers. If n[1]/n[2] is an integer:
(quotient n[1] n[2]) ===> n[1]/n[2] (remainder n[1] n[2]) ===> 0 (modulo n[1] n[2]) ===> 0
If n[1]/n[2] is not an integer:
(quotient n[1] n[2]) ===> n[q] (remainder n[1] n[2]) ===> n[r] (modulo n[1] n[2]) ===> n[m]
where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 < |n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2], n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
From this we can conclude that for integers n[1] and n[2] with n[2] not equal to 0,
(= n[1] (+ (* n[2] (quotient n[1] n[2])) (remainder n[1] n[2]))) ===> #t
provided all numbers involved in that computation are exact.
(modulo 13 4) ===> 1 (remainder 13 4) ===> 1 (modulo -13 4) ===> 3 (remainder -13 4) ===> -1 (modulo 13 -4) ===> -3 (remainder 13 -4) ===> 1 (modulo -13 -4) ===> -1 (remainder -13 -4) ===> -1 (remainder -13 -4.0) ===> -1.0 ; inexact[procedure] (gcd n[1] ...)
[procedure] (lcm n[1] ...)
These procedures return the greatest common divisor or least common multiple of their arguments. The result is always non-negative.
(gcd 32 -36) ===> 4 (gcd) ===> 0 (lcm 32 -36) ===> 288 (lcm 32.0 -36) ===> 288.0 ; inexact (lcm) ===> 1[procedure] (numerator q)
[procedure] (denominator q)
These procedures return the numerator or denominator of their argument; the result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1.
(numerator (/ 6 4)) ===> 3 (denominator (/ 6 4)) ===> 2 (denominator (exact->inexact (/ 6 4))) ===> 2.0[procedure] (floor x)
[procedure] (ceiling x)
[procedure] (truncate x)
[procedure] (round x)
These procedures return integers. Floor returns the largest integer not larger than x. Ceiling returns the smallest integer not smaller than x. Truncate returns the integer closest to x whose absolute value is not larger than the absolute value of x. Round returns the closest integer to x, rounding to even when x is halfway between two integers.
Rationale: Round rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard.
Note: If the argument to one of these procedures is inexact, then the result will also be inexact. If an exact value is needed, the result should be passed to the inexact->exact procedure.
(floor -4.3) ===> -5.0 (ceiling -4.3) ===> -4.0 (truncate -4.3) ===> -4.0 (round -4.3) ===> -4.0 (floor 3.5) ===> 3.0 (ceiling 3.5) ===> 4.0 (truncate 3.5) ===> 3.0 (round 3.5) ===> 4.0 ; inexact (round 7/2) ===> 4 ; exact (round 7) ===> 7[procedure] (rationalize x y)
Rationalize returns the simplest rational number differing from x by no more than y. A rational number r[1] is simpler than another rational number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms) and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7. Although not all rationals are comparable in this ordering (consider 2/ 7 and 3/5) any interval contains a rational number that is simpler than every other rational number in that interval (the simpler 2/5 lies between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of all.
(rationalize (inexact->exact .3) 1/10) ===> 1/3 ; exact (rationalize .3 1/10) ===> #i1/3 ; inexact[procedure] (exp z)
[procedure] (log z [z2])
[procedure] (sin z)
[procedure] (cos z)
[procedure] (tan z)
[procedure] (asin z)
[procedure] (acos z)
[procedure] (atan z)
[procedure] (atan y x)
These procedures are part of every implementation that supports general real numbers; they compute the usual transcendental functions. The Log procedure computes the natural logarithm of z (not the base ten logarithm) if a single argument is given, or the base-z2 logarithm of z1 if two arguments are given. Asin, acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and arctangent (tan^-1), respectively. The two-argument variant of atan computes (angle (make-rectangular x y)) (see below), even in implementations that don't support general complex numbers.
In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. The value of log z is defined to be the one whose imaginary part lies in the range from -pi (exclusive) to pi (inclusive). log 0 is undefined. With log defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are according to the following formulae:
sin^-1 z = - i log (i z + (1 - z^2)^1/2) cos^-1 z = pi / 2 - sin^-1 z tan^-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)
The above specification follows [27], which in turn cites [19]; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions. When it is possible these procedures produce a real result from a real argument.
[procedure] (square z)Returns the square of z. This is equivalent to (* z z)-
(square 42) ==> 1764 (square 2.0) ==> 4.0[procedure] (exact-integer-sqrt k)
Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.
(exact-integer-sqrt 4) ==> 2 0 (exact-integer-sqrt 5) ==> 2 1[procedure] (expt z[1] z[2])
Returns z[1] raised to the power z[2]. For z[1] != 0
z[1]^z[2] = e^z[2] log z[1]
0^z is 1 if z = 0 and 0 otherwise.
[procedure] (exact z)[procedure] (inexact z)
The procedure inexact returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the argument. For inexact arguments, the result is the same as the argument. For exact complex numbers, the result is a complex number whose real and imaginary parts are the result of applying inexact to the real and imaginary parts of the argument, respectively. If an exact argument has no reasonably close inexact equivalent (in the sense of =), then a violation of an implementation restriction may be reported.
The procedure exact returns an exact representation of z. The value returned is the exact number that is numerically closest to the argument. For exact arguments, the result is the same as the argument. For inexact non-integral real arguments, the implementation may return a rational approximation, or may report an implementation violation. For inexact complex arguments, the result is a complex number whose real and imaginary parts are the result of applying exact to the real and imaginary parts of the argument, respectively. If an inexact argument has no reasonably close exact equivalent, (in the sense of =), then a violation of an implementation restriction may be reported.
Numerical input and output
[procedure] (number->string z [radix])Radix must be an exact integer. The R7RS standard only requires implementations to support 2, 8, 10, or 16, but CHICKEN allows any radix between 2 and 36, inclusive (note: a bug in CHICKEN 5 currently limits the upper bound to 16). If omitted, radix defaults to 10. The procedure number->string takes a number and a radix and returns as a string an external representation of the given number in the given radix such that
(let ((number number) (radix radix)) (eqv? number (string->number (number->string number radix) radix)))
is true. It is an error if no possible result makes this expression true.
If z is inexact, the radix is 10, and the above expression can be satisfied by a result that contains a decimal point, then the result contains a decimal point and is expressed using the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the above expression true [3, 5]; otherwise the format of the result is unspecified.
The result returned by number->string never contains an explicit radix prefix.
Note: The error case can occur only when z is not a complex number or is a complex number with a non-rational real or imaginary part.
Rationale: If z is an inexact number represented using flonums, and the radix is 10, then the above expression is normally satisfied by a result containing a decimal point. The unspecified case allows for infinities, NaNs, and non-flonum representations.
As an extension to R7RS, CHICKEN supports reading and writing the special IEEE floating-point numbers +nan, +inf and -inf, as well as negative zero.
[procedure] (string->number string)[procedure] (string->number string radix)
Returns a number of the maximally precise representation expressed by the given string. Radix must be an exact integer. The R7RS standard only requires implementations to support 2, 8, 10, or 16, but CHICKEN allows any radix between 2 and 36, inclusive. If supplied, radix is a default radix that may be overridden by an explicit radix prefix in string (e.g. "#o177"). If radix is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number, then string->number returns #f.
(string->number "100") ===> 100 (string->number "100" 16) ===> 256 (string->number "1e2") ===> 100.0 (string->number "15##") ===> 1500.0
Note: The domain of string->number may be restricted by implementations in the following ways. String->number is permitted to return #f whenever string contains an explicit radix prefix. If all numbers supported by an implementation are real, then string-> number is permitted to return #f whenever string uses the polar or rectangular notations for complex numbers. If all numbers are integers, then string->number may return #f whenever the fractional notation is used. If all numbers are exact, then string->number may return #f whenever an exponent marker or explicit exactness prefix is used, or if a # appears in place of a digit. If all inexact numbers are integers, then string->number may return #f whenever a decimal point is used.
Other data types
This section describes operations on some of Scheme's non-numeric data types: booleans, pairs, lists, symbols, characters, strings and vectors.
Booleans
The standard boolean objects for true and false are written as #t and #f. What really matters, though, are the objects that the Scheme conditional expressions (if, cond, and, or, do) treat as true or false. The phrase "a true value" (or sometimes just "true") means any object treated as true by the conditional expressions, and the phrase "a false value" (or "false") means any object treated as false by the conditional expressions.
Of all the standard Scheme values, only #f counts as false in conditional expressions. Except for #f, all standard Scheme values, including #t, pairs, the empty list, symbols, numbers, strings, vectors, and procedures, count as true.
Note: Programmers accustomed to other dialects of Lisp should be aware that Scheme distinguishes both #f and the empty list from the symbol nil.
Boolean constants evaluate to themselves, so they do not need to be quoted in programs.
#t ===> #t #f ===> #f '#f ===> #f[procedure] (not obj)
Not returns #t if obj is false, and returns #f otherwise.
(not #t) ===> #f (not 3) ===> #f (not (list 3)) ===> #f (not #f) ===> #t (not '()) ===> #f (not (list)) ===> #f (not 'nil) ===> #f[procedure] (boolean? obj)
Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
(boolean? #f) ===> #t (boolean? 0) ===> #f (boolean? '()) ===> #f[procedure] (boolean=? boolean[1] boolean[2] boolean[3] ...)
Returns #t if all the arguments are #t or all are #f.
Pairs and lists
A pair (sometimes called a dotted pair) is a record structure with two fields called the car and cdr fields (for historical reasons). Pairs are created by the procedure cons. The car and cdr fields are accessed by the procedures car and cdr. The car and cdr fields are assigned by the procedures set-car! and set-cdr!.
Pairs are used primarily to represent lists. A list can be defined recursively as either the empty list or a pair whose cdr is a list. More precisely, the set of lists is defined as the smallest set X such that
- The empty list is in X.
- If list is in X, then any pair whose cdr field contains list is also in X.
The objects in the car fields of successive pairs of a list are the elements of the list. For example, a two-element list is a pair whose car is the first element and whose cdr is a pair whose car is the second element and whose cdr is the empty list. The length of a list is the number of elements, which is the same as the number of pairs.
The empty list is a special object of its own type (it is not a pair); it has no elements and its length is zero.
Note: The above definitions imply that all lists have finite length and are terminated by the empty list.
The most general notation (external representation) for Scheme pairs is the "dotted" notation (c[1] . c[2]) where c[1] is the value of the car field and c[2] is the value of the cdr field. For example (4 . 5) is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the external representation of a pair, not an expression that evaluates to a pair.
A more streamlined notation can be used for lists: the elements of the list are simply enclosed in parentheses and separated by spaces. The empty list is written () . For example,
(a b c d e)
and
(a . (b . (c . (d . (e . ())))))
are equivalent notations for a list of symbols.
A chain of pairs not ending in the empty list is called an improper list. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists:
(a b c . d)
is equivalent to
(a . (b . (c . d)))
Whether a given pair is a list depends upon what is stored in the cdr field. When the set-cdr! procedure is used, an object can be a list one moment and not the next:
(define x (list 'a 'b 'c)) (define y x) y ===> (a b c) (list? y) ===> #t (set-cdr! x 4) ===> unspecified x ===> (a . 4) (eqv? x y) ===> #t y ===> (a . 4) (list? y) ===> #f (set-cdr! x x) ===> unspecified (list? x) ===> #f
Within literal expressions and representations of objects read by the read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum> denote two-element lists whose first elements are the symbols quote, quasiquote, unquote, and unquote-splicing, respectively. The second element in each case is <datum>. This convention is supported so that arbitrary Scheme programs may be represented as lists. That is, according to Scheme's grammar, every <expression> is also a <datum>. Among other things, this permits the use of the read procedure to parse Scheme programs.
[procedure] (pair? obj)Pair? returns #t if obj is a pair, and otherwise returns #f.
(pair? '(a . b)) ===> #t (pair? '(a b c)) ===> #t (pair? '()) ===> #f (pair? '#(a b)) ===> #f[procedure] (cons obj[1] obj[2])
Returns a newly allocated pair whose car is obj[1] and whose cdr is obj[2]. The pair is guaranteed to be different (in the sense of eqv?) from every existing object.
(cons 'a '()) ===> (a) (cons '(a) '(b c d)) ===> ((a) b c d) (cons "a" '(b c)) ===> ("a" b c) (cons 'a 3) ===> (a . 3) (cons '(a b) 'c) ===> ((a b) . c)[procedure] (car pair)
Returns the contents of the car field of pair. Note that it is an error to take the car of the empty list.
(car '(a b c)) ===> a (car '((a) b c d)) ===> (a) (car '(1 . 2)) ===> 1 (car '()) ===> error[procedure] (cdr pair)
Returns the contents of the cdr field of pair. Note that it is an error to take the cdr of the empty list.
(cdr '((a) b c d)) ===> (b c d) (cdr '(1 . 2)) ===> 2 (cdr '()) ===> error[procedure] (set-car! pair obj)
Stores obj in the car field of pair. The value returned by set-car! is unspecified.
(define (f) (list 'not-a-constant-list)) (define (g) '(constant-list)) (set-car! (f) 3) ===> unspecified (set-car! (g) 3) ===> error[procedure] (set-cdr! pair obj)
Stores obj in the cdr field of pair. The value returned by set-cdr! is unspecified.
[procedure] (null? obj)Returns #t if obj is the empty list, otherwise returns #f.
[procedure] (list? obj)Returns #t if obj is a list, otherwise returns #f. By definition, all lists have finite length and are terminated by the empty list.
(list? '(a b c)) ===> #t (list? '()) ===> #t (list? '(a . b)) ===> #f (let ((x (list 'a))) (set-cdr! x x) (list? x)) ===> #f[procedure] (make-list k [fill]}
Returns 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.
(make-list 2 3) ==> (3 3)[procedure] (list obj ...)
Returns a newly allocated list of its arguments.
(list 'a (+ 3 4) 'c) ===> (a 7 c) (list) ===> ()[procedure] (length list)
Returns the length of list.
(length '(a b c)) ===> 3 (length '(a (b) (c d e))) ===> 3 (length '()) ===> 0[procedure] (append list ...)
Returns a list consisting of the elements of the first list followed by the elements of the other lists.
(append '(x) '(y)) ===> (x y) (append '(a) '(b c d)) ===> (a b c d) (append '(a (b)) '((c))) ===> (a (b) (c))
The resulting list is always newly allocated, except that it shares structure with the last list argument. The last argument may actually be any object; an improper list results if the last argument is not a proper list.
(append '(a b) '(c . d)) ===> (a b c . d) (append '() 'a) ===> a[procedure] (reverse list)
Returns a newly allocated list consisting of the elements of list in reverse order.
(reverse '(a b c)) ===> (c b a) (reverse '(a (b c) d (e (f)))) ===> ((e (f)) d (b c) a)[procedure] (list-tail list k)
Returns the sublist of list obtained by omitting the first k elements. It is an error if list has fewer than k elements. List-tail could be defined by
(define list-tail (lambda (x k) (if (zero? k) x (list-tail (cdr x) (- k 1)))))[procedure] (list-ref list k)
Returns the kth element of list. (This is the same as the car of (list-tail list k).) It is an error if list has fewer than k elements.
(list-ref '(a b c d) 2) ===> c (list-ref '(a b c d) (inexact->exact (round 1.8))) ===> c[procedure] (list-set! list k obj)
It is an error if k is not a valid index of list.
The list-set! procedure stores obj in element k of list.
(let ((ls (list 'one 'two 'five!))) (list-set! ls 2 'three) ls) ==> (one two three) (list-set! '(0 1 2) 1 "oops") ==> error ; constant list[procedure] (memq obj list)
[procedure] (memv obj list)
[procedure] (member obj list [compare])
These procedures return the first sublist of list whose car is obj, where the sublists of list are the non-empty lists returned by (list-tail list k) for k less than the length of list. If obj does not occur in list, then #f (not the empty list) is returned. memq uses eq? to compare obj with the elements of list, while memv uses eqv? and member compare if given, and equal? otherwise.
(memq 'a '(a b c)) ===> (a b c) (memq 'b '(a b c)) ===> (b c) (memq 'a '(b c d)) ===> #f (memq (list 'a) '(b (a) c)) ===> #f (member (list 'a) '(b (a) c)) ===> ((a) c) (memq 101 '(100 101 102)) ===> unspecified (memv 101 '(100 101 102)) ===> (101 102)[procedure] (assq obj alist)
[procedure] (assv obj alist)
[procedure] (assoc obj alist [compare])
Alist (for "association list") must be a list of pairs. These procedures find the first pair in alist whose car field is obj, and returns that pair. If no pair in alist has obj as its car, then #f (not the empty list) is returned. assq uses eq? to compare obj with the car fields of the pairs in alist, while assv uses eqv? and assoc uses compare, if given, otherwise equal?.
(define e '((a 1) (b 2) (c 3))) (assq 'a e) ===> (a 1) (assq 'b e) ===> (b 2) (assq 'd e) ===> #f (assq (list 'a) '(((a)) ((b)) ((c)))) ===> #f (assoc (list 'a) '(((a)) ((b)) ((c)))) ===> ((a)) (assq 5 '((2 3) (5 7) (11 13))) ===> unspecified (assv 5 '((2 3) (5 7) (11 13))) ===> (5 7)
Rationale: Although they are ordinarily used as predicates, memq, memv, member, assq, assv, and assoc do not have question marks in their names because they return useful values rather than just #t or #f.
[procedure] (list-copy obj)Returns 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 in the sense of eqv?. An obj which is not a list is returned unchanged. It is an error if obj is a circular list.
(define a '(1 8 2 8)) ; a may be immutable (define b (list-copy a)) (set-car! b 3) ; b is mutable b ==> (3 8 2 8) a ==> (1 8 2 8)
Symbols
Symbols are objects whose usefulness rests on the fact that two symbols are identical (in the sense of eqv?) if and only if their names are spelled the same way. This is exactly the property needed to represent identifiers in programs, and so most implementations of Scheme use them internally for that purpose. Symbols are useful for many other applications; for instance, they may be used the way enumerated values are used in Pascal.
The rules for writing a symbol are exactly the same as the rules for writing an identifier.
It is guaranteed that any symbol that has been returned as part of a literal expression, or read using the read procedure, and subsequently written out using the write procedure, will read back in as the identical symbol (in the sense of eqv?). The string->symbol procedure, however, can create symbols for which this write/read invariance may not hold because their names contain special characters or letters in the non-standard case.
Note: Some implementations of Scheme have a feature known as "slashification" in order to guarantee write/read invariance for all symbols, but historically the most important use of this feature has been to compensate for the lack of a string data type.
Some implementations also have "uninterned symbols", which defeat write/read invariance even in implementations with slashification, and also generate exceptions to the rule that two symbols are the same if and only if their names are spelled the same.
[procedure] (symbol? obj)Returns #t if obj is a symbol, otherwise returns #f.
(symbol? 'foo) ===> #t (symbol? (car '(a b))) ===> #t (symbol? "bar") ===> #f (symbol? 'nil) ===> #t (symbol? '()) ===> #f (symbol? #f) ===> #f[procedure] (symbol=? symbol[1] symbol[2] symbol[3] ...)
Returns #t if all the arguments all have the same names in the sense of string=?.
Note: The definition above assumes that none of the arguments are uninterned symbols.
[procedure] (symbol->string symbol)Returns the name of symbol as a string. If the symbol was part of an object returned as the value of a literal expression (see "literal expressions") or by a call to the read procedure, and its name contains alphabetic characters, then the string returned will contain characters in the implementation's preferred standard case -- some implementations will prefer upper case, others lower case. If the symbol was returned by string->symbol, the case of characters in the string returned will be the same as the case in the string that was passed to string->symbol. It is an error to apply mutation procedures like string-set! to strings returned by this procedure.
The following examples assume that the implementation's standard case is lower case:
(symbol->string 'flying-fish) ===> "flying-fish" (symbol->string 'Martin) ===> "martin" (symbol->string (string->symbol "Malvina")) ===> "Malvina"[procedure] (string->symbol string)
Returns the symbol whose name is string. This procedure can create symbols with names containing special characters or letters in the non-standard case, but it is usually a bad idea to create such symbols because in some implementations of Scheme they cannot be read as themselves. See symbol->string.
The following examples assume that the implementation's standard case is lower case:
(eq? 'mISSISSIppi 'mississippi) ===> #t (string->symbol "mISSISSIppi") ===> the symbol with name "mISSISSIppi" (eq? 'bitBlt (string->symbol "bitBlt")) ===> #f (eq? 'JollyWog (string->symbol (symbol->string 'JollyWog))) ===> #t (string=? "K. Harper, M.D." (symbol->string (string->symbol "K. Harper, M.D."))) ===> #t
Characters
Characters are objects that represent printed characters such as letters and digits. Characters are written using the notation #\ <character> or #\<character name>. For example:
Characters are written using the notation #\<character> or #\<character name> or #\x<hex scalar value>.
The following character names must be supported by all implementations with the given values. Implementations may add other names provided they cannot be interpreted as hex scalar values preceded by x.
#\alarm ; U+0007 #\backspace ; U+0008 #\delete ; U+007F #\escape ; U+001B #\newline ; the linefeed character, U+000A #\null ; the null character, U+0000 #\return ; the return character, U+000D #\space ; the preferred way to write a space #\tab ; the tab character, U+0009
Here are some additional examples:
#\a ; lower case letter #\A ; upper case letter #\( ; left parenthesis #\ ; the space character #\space ; the preferred way to write a space #\newline ; the newline character
Case is significant in #\<character>, but not in #\<character name>. If <character> in #\<character> is alphabetic, then the character following <character> must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of characters "#\space" could be taken to be either a representation of the space character or a representation of the character "#\s" followed by a representation of the symbol "pace."
Characters written in the #\ notation are self-evaluating. That is, they do not have to be quoted in programs. Some of the procedures that operate on characters ignore the difference between upper case and lower case. The procedures that ignore case have "-ci" (for "case insensitive") embedded in their names.
[procedure] (char? obj)Returns #t if obj is a character, otherwise returns #f.
[procedure] (char=? char[1] char[2] char[3] ...)[procedure] (char<? char[1] char[2] char[3] ...)
[procedure] (char>? char[1] char[2] char[3] ...)
[procedure] (char<=? char[1] char[2] char[3] ...)
[procedure] (char>=? char[1] char[2] char[3] ...)
These procedures impose a total ordering on the set of characters. It is guaranteed that under this ordering:
- The upper case characters are in order. For example, (char<? #\A #\ B) returns #t.
- The lower case characters are in order. For example, (char<? #\a #\ b) returns #t.
- The digits are in order. For example, (char<? #\0 #\9) returns #t.
- Either all the digits precede all the upper case letters, or vice versa.
- Either all the digits precede all the lower case letters, or vice versa.
Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numerical predicates.
[procedure] (char-ci=? char[1] char[2] char[3] ...)[procedure] (char-ci<? char[1] char[2] char[3] ...)
[procedure] (char-ci>? char[1] char[2] char[3] ...)
[procedure] (char-ci<=? char[1] char[2] char[3] ...)
[procedure] (char-ci>=? char[1] char[2] char[3] ...)
These procedures are similar to char=? et cetera, but they treat upper case and lower case letters as the same. For example, (char-ci=? #\A #\ a) returns #t. Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numerical predicates.
[procedure] (char-alphabetic? char)[procedure] (char-numeric? char)
[procedure] (char-whitespace? char)
[procedure] (char-upper-case? letter)
[procedure] (char-lower-case? letter)
These procedures return #t if their arguments are alphabetic, numeric, whitespace, upper case, or lower case characters, respectively, otherwise they return #f. The following remarks, which are specific to the ASCII character set, are intended only as a guide: The alphabetic characters are the 52 upper and lower case letters. The numeric characters are the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and carriage return.
[procedure] (char->integer char)[procedure] (integer->char n)
Given a character, char->integer returns an exact integer representation of the character. Given an exact integer that is the image of a character under char->integer, integer->char returns that character. These procedures implement order-preserving isomorphisms between the set of characters under the char<=? ordering and some subset of the integers under the <= ordering. That is, if
(char<=? a b) ===> #t and (<= x y) ===> #t
and x and y are in the domain of integer->char, then
(<= (char->integer a) (char->integer b)) ===> #t (char<=? (integer->char x) (integer->char y)) ===> #t
Note that integer->char does currently not detect a negative argument and will quietly convert -1 to #x1ffff in CHICKEN.
Strings
Strings are sequences of characters. Strings are written as sequences of characters enclosed within quotation marks ("). Within a string literal, various escape sequences represent characters other than themselves. Escape sequences always start with a backslash (\):
- \a : alarm, U+0007
- \b : backspace, U+0008
- \t : character tabulation, U+0009
- \n : linefeed, U+000A
- \r : return, U+000D
- \" : double quote, U+0022
- \\ : backslash, U+005C
- \| : vertical line, U+007C
- \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing
- \x<hex scalar value>; : specified character (note the terminating semi-colon).
The result is unspecified if any other character in a string occurs after a backslash.
Except for a line ending, any character outside of an escape sequence stands for itself in the string literal. A line ending which is preceded by \ <intraline whitespace> expands to nothing (along with any trailing intraline whitespace), and can be used to indent strings for improved legibility. Any other line ending has the same effect as inserting a \n character into the string.
Examples:
"The word \"recursion\" has many meanings." "Another example:\ntwo lines of text" "Here's text \ containing just one line" "\x03B1; is named GREEK SMALL LETTER ALPHA."
The length of a string is the number of characters that it contains. This number is an exact, non-negative integer that is fixed when the string is created. The valid indexes of a string are the exact non-negative integers less than the length of the string. The first character of a string has index 0, the second has index 1, and so on.
[procedure] (string? obj)Returns #t if obj is a string, otherwise returns #f.
[procedure] (make-string k)[procedure] (make-string k char)
Make-string returns a newly allocated string of length k. If char is given, then all elements of the string are initialized to char, otherwise the contents of the string are unspecified.
[procedure] (string char ...)Returns a newly allocated string composed of the arguments.
[procedure] (string-length string)Returns the number of characters in the given string.
[procedure] (string-ref string k)k must be a valid index of string. String-ref returns character k of string using zero-origin indexing.
[procedure] (string-set! string k char)k must be a valid index of string. String-set! stores char in element k of string and returns an unspecified value.
(define (f) (make-string 3 #\*)) (define (g) "***") (string-set! (f) 0 #\?) ===> unspecified (string-set! (g) 0 #\?) ===> error (string-set! (symbol->string 'immutable) 0 #\?) ===> error[procedure] (string=? string[1] string[2] string[3] ...)
Returns #t if the two strings are the same length and contain the same characters in the same positions, otherwise returns #f.
[procedure] (string<? string[1] string[2] string[3] ...)[procedure] (string>? string[1] string[2] string[3] ...)
[procedure] (string<=? string[1] string[2] string[3] ...)
[procedure] (string>=? string[1] string[2] string[3] ...)
These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, string<? is the lexicographic ordering on strings induced by the ordering char<? on characters. If two strings differ in length but are the same up to the length of the shorter string, the shorter string is considered to be lexicographically less than the longer string.
[procedure] (substring string start [end])String must be a string, and start and end must be exact integers satisfying
0 <= start <= end <= (string-length string)
Substring returns a newly allocated string formed from the characters of string beginning with index start (inclusive) and ending with index end (exclusive). The end argument is optional and defaults to the length of the string, this is a non-standard extension in CHICKEN.
[procedure] (string-append string ...)Returns a newly allocated string whose characters form the concatenation of the given strings.
[procedure] (string->list string [start [end]])[procedure] (list->string list)
String->list returns a newly allocated list of the characters that make up the given string between start and end. List->string returns a newly allocated string formed from the characters in the list list, which must be a list of characters. String->list and list->string are inverses so far as equal? is concerned.
[procedure] (string-copy string [start [end]])Returns a newly allocated copy of the given string.
[procedure] (string-copy! to at from [start [end]])It 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).
Copies the characters of string from between start and end to string to, starting at at. The order in which characters are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary string and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
(define a "12345") (define b (string-copy "abcde")) (string-copy! b 1 a 0 2) b ==> "a12de"[procedure] (string-fill! string char +#!optional start end)
Stores char in every element of the given string and returns an unspecified value. The optional start and end arguments specify the part of the string to be filled and default to the complete string.
Vectors
Vectors are heterogenous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time required to access a randomly chosen element is typically less for the vector than for the list.
The length of a vector is the number of elements that it contains. This number is a non-negative integer that is fixed when the vector is created. The valid indexes of a vector are the exact non-negative integers less than the length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than the length of the vector.
Vectors are written using the notation #(obj ...). For example, a vector of length 3 containing the number zero in element 0, the list (2 2 2 2) in element 1, and the string "Anna" in element 2 can be written as following:
#(0 (2 2 2 2) "Anna")
Vector constants are self-evaluating, so they do not need to be quoted in programs.
[procedure] (vector? obj)Returns #t if obj is a vector, otherwise returns #f.
[procedure] (make-vector k)[procedure] (make-vector k fill)
Returns a newly allocated vector 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.
[procedure] (vector obj ...)Returns a newly allocated vector whose elements contain the given arguments. Analogous to list.
(vector 'a 'b 'c) ===> #(a b c)[procedure] (vector-length vector)
Returns the number of elements in vector as an exact integer.
[procedure] (vector-ref vector k)k must be a valid index of vector. Vector-ref returns the contents of element k of vector.
(vector-ref '#(1 1 2 3 5 8 13 21) 5) ===> 8 (vector-ref '#(1 1 2 3 5 8 13 21) (let ((i (round (* 2 (acos -1))))) (if (inexact? i) (inexact->exact i) i))) ===> 13[procedure] (vector-set! vector k obj)
k must be a valid index of vector. Vector-set! stores obj in element k of vector. The value returned by vector-set! is unspecified.
(let ((vec (vector 0 '(2 2 2 2) "Anna"))) (vector-set! vec 1 '("Sue" "Sue")) vec) ===> #(0 ("Sue" "Sue") "Anna") (vector-set! '#(0 1 2) 1 "doe") ===> error ; constant vector[procedure] (vector->list vector [start [end]])
[procedure] (list->vector list)
Vector->list returns a newly allocated list of the objects contained in the elements of vector. List->vector returns a newly created vector initialized to the elements of the list list.
(vector->list '#(dah dah didah)) ===> (dah dah didah) (list->vector '(dididit dah)) ===> #(dididit dah)[procedure] (vector-fill! vector fill)
Stores fill in every element of vector. The value returned by vector-fill! is unspecified.
[procedure] (vector->string vector [start [end]])<procedure(string->vector string [start [end]])</procedure>
It is an error if any element of vector between start and end is not a character.
The vector->string procedure returns a newly allocated string of the objects contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to the elements of the string string between start and end.
In both procedures, order is preserved.
(string->vector "ABC") ==> #(#\A #\B #\C) (vector->string #(#\1 #\2 #\3) ==> "123"[procedure] (vector-copy vector [start [end]])
Returns a newly allocated copy of the elements of the given vector between start and end. The elements of the new vector are the same (in the sense of eqv?) as the elements of the old.
(define a #(1 8 2 8)) ; a may be immutable (define b (vector-copy a)) (vector-set! b 0 3) ; b is mutable b ==> #(3 8 2 8) (define c (vector-copy b 1 3)) c ==> #(8 2)[procedure] (vector-copy! to at from [start [end]])
It 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).
Copies the elements of vector from between start and end to vector to, starting at at. The order in which elements are copied is unspecified, except that if the source and destination overlap, copying takes place as if the source is first copied into a temporary vector and then into the destination. This can be achieved without allocating storage by making sure to copy in the correct direction in such circumstances.
(define a (vector 1 2 3 4 5)) (define b (vector 10 20 30 40 50)) (vector-copy! b 1 a 0 2) b ==> #(10 1 2 40 50)[procedure] (vector-append vector ....)
Returns a newly allocated vector whose elements are the concatenation of the elements of the given vectors.
(vector-append #(a b c) #(d e f)) ==> #(a b c d e f)[procedure] (vector-fill! vector fill [start [end)]])
The vector-fill! procedure stores fill in the elements of vector between start and end.
(define a (vector 1 2 3 4 5)) (vector-fill! a 'smash 2 4) a ==>#(1 2 smash smash 5)
Bytevectors
Bytevectors represent blocks of binary data. They are fixed-length sequences of bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A bytevector is typically more space-efficient than a vector containing the same values.
See The (chicken bytevector) module for more information. (scheme base) re-exports all R7RS-specific procedures from that module.
Control features
This chapter describes various primitive procedures which control the flow of program execution in special ways. The procedure? predicate is also described here.
[procedure] (procedure? obj)Returns #t if obj is a procedure, otherwise returns #f.
(procedure? car) ===> #t (procedure? 'car) ===> #f (procedure? (lambda (x) (* x x))) ===> #t (procedure? '(lambda (x) (* x x))) ===> #f (call-with-current-continuation procedure?) ===> #t[procedure] (apply proc arg[1] ... args)
Proc must be a procedure and args must be a list. Calls proc with the elements of the list (append (list arg[1] ...) args) as the actual arguments.
(apply + (list 3 4)) ===> 7 (define compose (lambda (f g) (lambda args (f (apply g args))))) ((compose sqrt *) 12 75) ===> 30[procedure] (map proc list[1] list[2] ...)
The lists must be lists, and proc must be a procedure taking as many arguments as there are lists and returning a single value. Map applies proc element-wise to the elements of the lists and returns a list of the results, in order. The dynamic order in which proc is applied to the elements of the lists is unspecified.
Like in SRFI-1, this procedure allows the arguments to be of unequal length; it terminates when the shortest list runs out. This is a CHICKEN extension to R7RS.
(map cadr '((a b) (d e) (g h))) ===> (b e h) (map (lambda (n) (expt n n)) '(1 2 3 4 5)) ===> (1 4 27 256 3125) (map + '(1 2 3) '(4 5 6)) ===> (5 7 9) (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) '(a b))) ===> (1 2) or (2 1)[procedure] (string-map proc string[1] string[2] ...)
It is an error if proc does not accept as many arguments as there are strings and return a single character.
The string-map procedure applies proc element-wise to the elements of the strings and returns a string of the results, in order. If more than one string is given and not all strings have the same length, string-map terminates when the shortest string runs out. The dynamic order in which proc is applied to the elements of the strings is unspecified. If multiple returns occur from string-map, the values returned by earlier returns are not mutated.
(string-map char-foldcase "AbdEgH") ==> "abdegh" (string-map (lambda (c) (integer->char (+ 1 (char->integer c)))) "HAL") ==> "IBM" (string-map (lambda (c k) ((if (eqv? k #\u) char-upcase char-downcase) c)) "studlycaps xxx" "ululululul") ==> "StUdLyCaPs"[procedure] (vector-map proc vector[1] vector[2] ...)
It is an error if proc does not accept as many arguments as there are vectors and return a single value.
The vector-map procedure applies proc element-wise to the elements of the vectors and returns a vector of the results, in order. If more than one vector is given and not all vectors have the same length, vector-map terminates when the shortest vector runs out. The dynamic order in which proc is applied to the elements of the vectors is unspecified. If multiple returns occur from vector-map, the values returned by earlier returns are not mutated.
(vector-map cadr '#((a b) (d e) (g h))) ==> #(b e h) (vector-map (lambda (n) (expt n n)) '#(1 2 3 4 5)) ==> #(1 4 27 256 3125) (vector-map + '#(1 2 3) '#(4 5 6 7)) ==> #(5 7 9) (let ((count 0)) (vector-map (lambda (ignored) (set! count (+ count 1)) count) '#(a b))) ==> #(1 2) or #(2 1)[procedure] (for-each proc list[1] list[2] ...)
The arguments to for-each are like the arguments to map, but for-each calls proc for its side effects rather than for its values. Unlike map, for-each is guaranteed to call proc on the elements of the lists in order from the first element(s) to the last, and the value returned by for-each is unspecified.
(let ((v (make-vector 5))) (for-each (lambda (i) (vector-set! v i (* i i))) '(0 1 2 3 4)) v) ===> #(0 1 4 9 16)
Like in SRFI-1, this procedure allows the arguments to be of unequal length; it terminates when the shortest list runs out. This is a CHICKEN extension to R7RS.
[procedure] (string-for-each proc string[1] string[2] ...)It is an error if proc does not accept as many arguments as there are strings. The arguments to string-for-each are like the arguments to string-map, but string-for-each calls proc for its side effects rather than for its values. Unlike string-map, string-for-each is guaranteed to call proc on the elements of the strings in order from the first element(s) to the last, and the value returned by string-for-each is unspecified. If more than one string is given and not all strings have the same length, string-for-each terminates when the shortest string runs out. It is an error for proc to mutate any of the strings.
(let ((v '())) (string-for-each (lambda (c) (set! v (cons (char->integer c) v))) "abcde") v) ==> (101 100 99 98 97)[procedure] (vector-for-each proc vector[1] vector[2] ...)
It is an error if proc does not accept as many arguments as there are vectors. The arguments to vector-for-each are like the arguments to vector-map, but vector-for-each calls proc for its side effects rather than for its values. Unlike vector-map, vector-for-each is guaranteed to call proc on the elements of the vectors in order from the first element(s) to the last, and the value returned by vector-for-each is unspecified. If more than one vector is given and not all vectors have the same length, vector-for-each terminates when the shortest vector runs out. It is an error for proc to mutate any of the vectors.
(let ((v (make-list 5))) (vector-for-each (lambda (i) (list-set! v i (* i i))) '#(0 1 2 3 4)) v) ==> (0 1 4 9 16)[procedure] (call-with-current-continuation proc)
[procedure] (call/cc proc)
Proc must be a procedure of one argument. The procedure call-with-current-continuation packages up the current continuation (see the rationale below) as an "escape procedure" and passes it as an argument to proc. The escape procedure is a Scheme procedure that, if it is later called, will abandon whatever continuation is in effect at that later time and will instead use the continuation that was in effect when the escape procedure was created. Calling the escape procedure may cause the invocation of before and after thunks installed using dynamic-wind.
The escape procedure accepts the same number of arguments as the continuation to the original call to call-with-current-continuation. Except for continuations created by the call-with-values procedure, all continuations take exactly one value. The effect of passing no value or more than one value to continuations that were not created by call-with-values is unspecified.
The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired.
The following examples show only the most common ways in which call-with-current-continuation is used. If all real uses were as simple as these examples, there would be no need for a procedure with the power of call-with-current-continuation.
(call-with-current-continuation (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) '(54 0 37 -3 245 19)) #t)) ===> -3 (define list-length (lambda (obj) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (obj) (cond ((null? obj) 0) ((pair? obj) (+ (r (cdr obj)) 1)) (else (return #f)))))) (r obj)))))) (list-length '(1 2 3 4)) ===> 4 (list-length '(a b . c)) ===> #f
Rationale:
A common use of call-with-current-continuation is for structured, non-local exits from loops or procedure bodies, but in fact call-with-current-continuation is extremely useful for implementing a wide variety of advanced control structures.
Whenever a Scheme expression is evaluated there is a continuation wanting the result of the expression. The continuation represents an entire (default) future for the computation. If the expression is evaluated at top level, for example, then the continuation might take the result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions specified by user code, as in a continuation that will take the result, multiply it by the value stored in a local variable, add seven, and give the answer to the top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and programmers do not think much about them. On rare occasions, however, a programmer may need to deal with continuations explicitly. Call-with-current-continuation allows Scheme programmers to do that by creating a procedure that acts just like the current continuation.
Most programming languages incorporate one or more special-purpose escape constructs with names like exit, return, or even goto. In 1965, however, Peter Landin [16] invented a general purpose escape operator called the J-operator. John Reynolds [24] described a simpler but equally powerful construct in 1972. The catch special form described by Sussman and Steele in the 1975 report on Scheme is exactly the same as Reynolds's construct, though its name came from a less general construct in MacLisp. Several Scheme implementors noticed that the full power of the catch construct could be provided by a procedure instead of by a special syntactic construct, and the name call-with-current-continuation was coined in 1982. This name is descriptive, but opinions differ on the merits of such a long name, and some people use the name call/cc instead.
[procedure] (values obj ...)Delivers all of its arguments to its continuation. Except for continuations created by the call-with-values procedure, all continuations take exactly one value. Values might be defined as follows:
(define (values . things) (call-with-current-continuation (lambda (cont) (apply cont things))))[procedure] (call-with-values producer consumer)
Calls its producer argument with no values and a continuation that, when passed some values, calls the consumer procedure with those values as arguments. The continuation for the call to consumer is the continuation of the call to call-with-values.
(call-with-values (lambda () (values 4 5)) (lambda (a b) b)) ===> 5 (call-with-values * -) ===> -1[procedure] (dynamic-wind before thunk after)
Calls thunk without arguments, returning the result(s) of this call. Before and after are called, also without arguments, as required by the following rules (note that in the absence of calls to continuations captured using call-with-current-continuation the three arguments are called once each, in order). Before is called whenever execution enters the dynamic extent of the call to thunk and after is called whenever it exits that dynamic extent. The dynamic extent of a procedure call is the period between when the call is initiated and when it returns. In Scheme, because of call-with-current-continuation, the dynamic extent of a call may not be a single, connected time period. It is defined as follows:
- The dynamic extent is entered when execution of the body of the called procedure begins.
- The dynamic extent is also entered when execution is not within the dynamic extent and a continuation is invoked that was captured (using call-with-current-continuation) during the dynamic extent.
- It is exited when the called procedure returns.
- It is also exited when execution is within the dynamic extent and a continuation is invoked that was captured while not within the dynamic extent.
If a second call to dynamic-wind occurs within the dynamic extent of the call to thunk and then a continuation is invoked in such a way that the afters from these two invocations of dynamic-wind are both to be called, then the after associated with the second (inner) call to dynamic-wind is called first.
If a second call to dynamic-wind occurs within the dynamic extent of the call to thunk and then a continuation is invoked in such a way that the befores from these two invocations of dynamic-wind are both to be called, then the before associated with the first (outer) call to dynamic-wind is called first.
If invoking a continuation requires calling the before from one call to dynamic-wind and the after from another, then the after is called first.
The effect of using a captured continuation to enter or exit the dynamic extent of a call to before or after is undefined. However, in CHICKEN it is safe to do this, and they will execute in the outer dynamic context of the dynamic-wind form.
(let ((path '()) (c #f)) (let ((add (lambda (s) (set! path (cons s path))))) (dynamic-wind (lambda () (add 'connect)) (lambda () (add (call-with-current-continuation (lambda (c0) (set! c c0) 'talk1)))) (lambda () (add 'disconnect))) (if (< (length path) 4) (c 'talk2) (reverse path)))) ===> (connect talk1 disconnect connect talk2 disconnect)
Exceptions
This section describes Scheme’s exception-handling and exception-raising procedures.
Exception handlers are one-argument procedures that determine the action the program takes when an exceptional situation is signaled. The system implicitly maintains a current exception handler in the dynamic environment.
The program raises an exception by invoking the current exception handler, passing it an object encapsulating information about the exception. Any procedure accepting one argument can serve as an exception handler and any object can be used to represent an exception.
[procedure] (with-exception-handler handler thunk)It is an error if handler does not accept one argument. It is also an error if thunk does not accept zero arguments. The with-exception-handler procedure returns the results of invoking thunk. Handler is installed as the current exception handler in the dynamic environment used for the invocation of thunk.
(call-with-current-continuation (lambda (k) (with-exception-handler (lambda (x) (display "condition: ") (write x) (newline) (k 'exception)) (lambda () (+ 1 (raise 'an-error)))))) ==> exception and prints "condition: an-error" (with-exception-handler (lambda (x) (display "something went wrong\n")) (lambda () (+ 1 (raise 'an-error))))
prints "something went wrong" After printing, the second example then raises another exception.
[procedure] (raise obj)Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as that of the call to raise, except that the current exception handler is the one that was in place when the handler being called was installed. If the handler returns, a secondary exception is raised in the same dynamic environment as the handler. The relationship between obj and the object raised by the secondary exception is unspecified.
[procedure] (raise-continuable obj)Raises an exception by invoking the current exception handler on obj. The handler is called with the same dynamic environment as the call to raise-continuable, except that: (1) the current exception handler is the one that was in place when the handler being called was installed, and (2) if the handler being called returns, then it will again become the current exception handler. If the handler returns, the values it returns become the values returned by the call to raise-continuable.
(with-exception-handler (lambda (con) (cond ((string? con) (display con)) (else (display "a warning has been issued"))) 42) (lambda () (+ (raise-continuable "should be a number") 23))) prints: "should be a number" ==> 65[procedure] (error [location] message obj ...)
Message should be a string. Raises an exception as if by calling raise on a newly allocated implementation-defined object which encapsulates the information provided by message, as well as any objs, known as the irritants. The procedure error-object? must return #t on such objects.
(define (null-list? l) (cond ((pair? l) #f) ((null? l) #t) (else (error "null-list?: argument out of domain" l))))
If location is given and a symbol, it indicates the name of the procedure where the error occurred.
[procedure] (error-object? obj)Returns #t if obj is an object created by error or one of an implementation-defined set of objects. Otherwise, it returns #f. The objects used to signal errors, including those which satisfy the predicates file-error? and read-error?, may or may not satisfy error-object?.
[procedure] (error-object-message error-object)Returns the message encapsulated by error-object.
[procedure] (error-object-irritants error-object)Returns a list of the irritants encapsulated by error-object.
[procedure] (read-error? obj)[procedure] (file-error? obj)
Error type predicates. Returns #t if obj is an object raised by the read procedure or by the inability to open an input or output port on a file, respectively. Otherwise, it returns #f.
Eval
[procedure] (eval expression [environment-specifier])Evaluates expression in the specified environment and returns its value. Expression must be a valid Scheme expression represented as data, and environment-specifier must be a value returned by one of the three procedures described below. Implementations may extend eval to allow non-expression programs (definitions) as the first argument and to allow other values as environments, with the restriction that eval is not allowed to create new bindings in the environments associated with null-environment or scheme-report-environment.
(eval '(* 7 3) (scheme-report-environment 5)) ===> 21 (let ((f (eval '(lambda (f x) (f x x)) (null-environment 5)))) (f + 10)) ===> 20
The environment-specifier is optional, and if not provided it defaults to the value of (interaction-environment). This is a CHICKEN extension to R7RS, which, though strictly nonportable, is very common among Scheme implementations.
Input and output
Ports
Ports represent input and output devices. To Scheme, an input port is a Scheme object that can deliver data upon command, while an output port is a Scheme object that can accept data.
Different port types operate on different data. Scheme implementations are required to support textual ports and binary ports, but may also provide other port types.
A textual port supports reading or writing of individual characters from or to a backing store containing characters using read-char and write-char below, and it supports operations defined in terms of characters, such as read and write.
A binary port supports reading or writing of individual bytes from or to a backing store containing bytes using read-u8 and write-u8 below, as well as operations defined in terms of bytes. Whether the textual and binary port types are disjoint is implementation-dependent.
Ports can be used to access files, devices, and similar things on the host system on which the Scheme program is running.
[procedure] (call-with-port port proc)It is an error if proc does not accept one argument. The call-with-port procedure calls proc with port as an argument. If proc returns, then the port is closed automatically and the values yielded by the proc are returned. If
proc does not return, then the port must not be closed automatically unless it is possible to prove that the port will never again be used for a read or write operation.
Rationale: Because Scheme’s escape procedures have unlimited extent, it is possible to escape from the current continuation but later to resume it. If implementations were permitted to close the port on any escape from the current continuation, then it would be impossible to write portable code using both call-with-current-continuation and call-with-port.
Ports represent input and output devices. To Scheme, an input port is a Scheme object that can deliver characters upon command, while an output port is a Scheme object that can accept characters.
[procedure] (input-port? obj)[procedure] (output-port? obj)
[procedure] (textual-port? obj)
[procedure] (binary-port? obj)
[procedure] (port? obj)
These procedures return #t if obj is an input port, output port, textual port, binary port, or any kind of port, respectively. Otherwise they return #f.
[procedure] (input-port-open? port)[procedure] (output-port-open? port)
Returns #t if port is still open and capable of performing input or output, respectively, and #f otherwise.
[procedure] (current-input-port [port])[procedure] (current-output-port [port])
[procedure] (current-error-port [port])
Returns the current default input, output or error port.
If the optional port argument is passed, the current input or output port is changed to the provided port. It can also be used with parameterize to temporarily bind the port to another value. This is a CHICKEN extension to the R7RS standard.
Note that the default output port is not buffered. Use set-buffering-mode! if you need a different behavior.
[procedure] (open-input-file filename [mode ...])[procedure] (open-binary-input-file filename [mode ...])
Takes a string naming an existing file and returns an input port capable of delivering textual or binary data from the file. If the file cannot be opened, an error is signalled.
Additional mode arguments can be passed in, which should be any of the keywords #:text or #:binary. These indicate the mode in which to open the file (this has an effect on non-UNIX platforms only). The extra mode arguments are CHICKEN extensions to the R7RS standard.
[procedure] (close-port port)[procedure] (close-input-port port)
[procedure] (close-output-port port)
Closes the resource associated with port, rendering the port incapable of delivering or accepting data. It is an error to apply the last two procedures to a port which is not an input or output port, respectively. Scheme implementations may provide ports which are simultaneously input and output ports, such as sockets; the close-input-port and close-output-port procedures can then be used to close the input and output sides of the port independently.
These routines have no effect if the port has already been closed.
[procedure] (open-input-string string)Takes a string and returns a textual input port that delivers characters from the string. If the string is modified, the effect is unspecified.
[procedure] (open-output-string)Returns a textual output port that will accumulate characters for retrieval by get-output-string.
[procedure] (get-output-string port)It is an error if port was not created with open-output-string. Returns a string consisting of the characters that have been output to the port so far in the order they were output. If the result string is modified, the effect is unspecified.
(parameterize ((current-output-port (open-output-string))) (display "piece") (display " by piece ") (display "by piece.") (newline) (get-output-string (current-output-port))) ==> "piece by piece by piece.\n"[procedure] (open-input-bytevector bytevector)
Takes a bytevector and returns a binary input port that delivers bytes from the bytevector.
[procedure] (open-output-bytevector)Returns a binary output port that will accumulate bytes for retrieval by get-output-bytevector.
[procedure] (get-output-bytevector port)It is an error if port was not created with open-output-bytevector. Returns a bytevector consisting of the bytes that have been output to the port so far in the order they were output.
Input
If port is omitted from any input procedure, it defaults to the value returned by (current-input-port). It is an error to attempt an input operation on a closed port.
[procedure] (read-char [port])Returns the next character available from the input port, updating the port to point to the following character. If no more characters are available, an end of file object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port.
[procedure] (peek-char [port])Returns the next character available from the input port, without updating the port to point to the following character. If no more characters are available, an end of file object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port.
Note: The value returned by a call to peek-char is the same as the value that would have been returned by a call to read-char with the same port. The only difference is that the very next call to read-char or peek-char on that port will return the value returned by the preceding call to peek-char. In particular, a call to peek-char on an interactive port will hang waiting for input whenever a call to read-char would have hung.
[procedure] (read-line [port])Returns the next line of text available from the textual input port, updating the port to point to the following character. If an end of line is read, a string containing all of the text up to (but not including) the end of line is returned, and the port is updated to point just past the end of line. If an end of file is encountered before any end of line is read, but some characters have been read, a string containing those characters is returned. If an end of file is encountered before any characters are read, an end-of-file object is returned. For the purpose of this procedure, an end of line consists of either a linefeed character, a carriage return character, or a sequence of a carriage return character followed by a linefeed character. Implementations may also recognize other end of line characters or sequences.
[procedure] (eof-object? obj)Returns #t if obj is an end of file object, otherwise returns #f. The precise set of end of file objects will vary among implementations, but in any case no end of file object will ever be an object that can be read in using read.
[procedure] (eof-object)Returns an end-of-file object, not necessarily unique.
[procedure] (char-ready? [port])Returns #t if a character is ready on the input port and returns #f otherwise. If char-ready returns #t then the next read-char operation on the given port is guaranteed not to hang. If the port is at end of file then char-ready? returns #t. Port may be omitted, in which case it defaults to the value returned by current-input-port.
Rationale: Char-ready? exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input. Any input editors associated with such ports must ensure that characters whose existence has been asserted by char-ready? cannot be rubbed out. If char-ready? were to return #f at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters.
[procedure] (read-string k [port])See (chicken io) module for more information.
[procedure] (read-u8 [port])Returns the next byte available from the binary input port, updating the port to point to the following byte. If no more bytes are available, an end-of-file object is returned.
[procedure] (peek-u8 [port])Returns the next byte available from the binary input port, but without updating the port to point to the following byte. If no more bytes are available, an end-of-file object is returned.
[procedure] (u8-ready? [port])Returns #t if a byte is ready on the binary input port and returns #f otherwise. If u8-ready? returns #t then the next read-u8 operation on the given port is guaranteed not to hang. If the port is at end of file then u8-ready? returns #t.
[procedure] (read-bytevector k [port])[procedure] (read-bytevector! bytevector [port [start [end]]])
See (chicken io) module for more information.
Output
If port is omitted from any output procedure, it defaults to the value returned by (current-output-port). It is an error to attempt an output operation on a closed port.
[procedure] (newline)[procedure] (newline port)
Writes an end of line to port. Exactly how this is done differs from one operating system to another. Returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.
[procedure] (write-char char)[procedure] (write-char char port)
Writes the character char (not an external representation of the character) to the given port and returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.
<procedure>(write-string string [port [start [end]]])</procedurew>
Writes the characters of string from start to end in left-to-right order to the textual output port.
[procedure] (write-u8 byte [port])Writes the byte to the given binary output port and returns an unspecified value.
[procedure] (write-bytevector bytevector [port [start [end]]])See The (chicken bytevector) module for more information.
[procedure] (flush-output-port [port])Flushes any buffered output from the buffer of output-port to the underlying file or device and returns an unspecified value.
System interface
Questions of system interface generally fall outside of the domain of this report. However, the following operations are important enough to deserve description here.
[procedure] (features)Returns a list of the feature identifiers which cond-expand treats as true. It is an error to modify this list. Here is an example of what features might return:
(features) ==> (r7rs ratios exact-complex full-unicode gnu-linux little-endian fantastic-scheme fantastic-scheme-1.0 space-ship-control-system)
Previous: Module scheme