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