~ chicken-core (master) /manual/Module (scheme base)


   1[[tags: manual]]
   2[[toc:]]
   3
   4== Module scheme
   5
   6This module provides all of CHICKEN's R7RS procedures and macros.
   7These descriptions are based directly on the ''Revised^7 Report on the
   8Algorithmic Language Scheme''.
   9
  10== Expressions
  11
  12Expression types are categorized as primitive or derived. Primitive
  13expression types include variables and procedure calls. Derived
  14expression types are not semantically primitive, but can instead be
  15defined as macros. The distinction which R7RS makes between primitive
  16and derived is unimportant and does not necessarily reflect how it is
  17implemented in CHICKEN itself.
  18
  19=== Primitive expression types
  20
  21==== Variable references
  22
  23<macro><variable></macro><br>
  24
  25An expression consisting of a variable is a variable reference. The
  26value of the variable reference is the value stored in the location to
  27which the variable is bound. It is an error to reference an unbound
  28variable.
  29
  30 (define x 28)
  31 x           ===>  28
  32
  33==== Literal expressions
  34
  35<macro>(quote <datum>)</macro><br>
  36<macro>'<datum></macro><br>
  37<macro><constant></macro><br>
  38
  39(quote <datum>) evaluates to <datum>. <Datum> may be any external
  40representation of a Scheme object. This notation is used to include
  41literal constants in Scheme code.
  42
  43 (quote a)                    ===>  a
  44 (quote #(a b c))             ===>  #(a b c)
  45 (quote (+ 1 2))              ===>  (+ 1 2)
  46
  47(quote <datum>) may be abbreviated as '<datum>. The two notations are
  48equivalent in all respects.
  49
  50 'a                           ===>  a
  51 '#(a b c)                    ===>  #(a b c)
  52 '()                          ===>  ()
  53 '(+ 1 2)                     ===>  (+ 1 2)
  54 '(quote a)                   ===>  (quote a)
  55 ''a                          ===>  (quote a)
  56
  57Numerical constants, string constants, character constants, and boolean
  58constants evaluate "to themselves"; they need not be quoted.
  59
  60 '"abc"             ===>  "abc"
  61 "abc"              ===>  "abc"
  62 '145932            ===>  145932
  63 145932             ===>  145932
  64 '#t                ===>  #t
  65 #t                 ===>  #t
  66 '#(a 10)           ===>  #(a 10)
  67 #(a 10)            ===>  #(a 10)
  68 '#u8(64 65)        ===>  #u8(64 65)
  69 #u8(64 65)         ===>  #u8(64 65)
  70
  71It is an error to alter a constant (i.e. the value of a literal
  72expression) using a mutation procedure like set-car! or string-set!.
  73In the current implementation of CHICKEN, identical constants don't
  74share memory and it is possible to mutate them, but this may change in
  75the future.
  76
  77==== Procedure calls
  78
  79<macro>(<operator> <operand[1]> ...)</macro><br>
  80
  81A procedure call is written by simply enclosing in parentheses
  82expressions for the procedure to be called and the arguments to be
  83passed to it. The operator and operand expressions are evaluated (in an
  84unspecified order) and the resulting procedure is passed the resulting
  85arguments.
  86
  87 (+ 3 4)                           ===>  7
  88 ((if #f + *) 3 4)                 ===>  12
  89
  90A number of procedures are available as the values of variables in the
  91initial environment; for example, the addition and multiplication
  92procedures in the above examples are the values of the variables + and
  93*.  New procedures are created by evaluating lambda
  94expressions. Procedure calls may return any number of values (see the
  95{{values}} procedure [[#control-features|below]]).
  96
  97Procedure calls are also called combinations.
  98
  99Note:   In contrast to other dialects of Lisp, the order of
 100evaluation is unspecified, and the operator expression and the
 101operand expressions are always evaluated with the same evaluation
 102rules.
 103
 104Note:   Although the order of evaluation is otherwise unspecified,
 105the effect of any concurrent evaluation of the operator and operand
 106expressions is constrained to be consistent with some sequential
 107order of evaluation. The order of evaluation may be chosen
 108differently for each procedure call.
 109
 110Note:   In many dialects of Lisp, the empty combination, (), is a
 111legitimate expression. In Scheme, combinations must have at least
 112one subexpression, so () is not a syntactically valid expression.
 113
 114==== Procedures
 115
 116<macro>(lambda <formals> <body>)</macro><br>
 117
 118Syntax: <Formals> should be a formal arguments list as described below,
 119and <body> should be a sequence of one or more expressions.
 120
 121Semantics: A lambda expression evaluates to a procedure. The
 122environment in effect when the lambda expression was evaluated is
 123remembered as part of the procedure. When the procedure is later called
 124with some actual arguments, the environment in which the lambda
 125expression was evaluated will be extended by binding the variables in
 126the formal argument list to fresh locations, the corresponding actual
 127argument values will be stored in those locations, and the expressions
 128in the body of the lambda expression will be evaluated sequentially in
 129the extended environment. The result(s) of the last expression in the
 130body will be returned as the result(s) of the procedure call.
 131
 132 (lambda (x) (+ x x))              ===>  a procedure
 133 ((lambda (x) (+ x x)) 4)          ===>  8
 134 
 135 (define reverse-subtract
 136   (lambda (x y) (- y x)))
 137 (reverse-subtract 7 10)           ===>  3
 138 
 139 (define add4
 140   (let ((x 4))
 141     (lambda (y) (+ x y))))
 142 (add4 6)                          ===>  10
 143
 144<Formals> should have one of the following forms:
 145
 146*   (<variable[1]> ...): The procedure takes a fixed number of
 147    arguments; when the procedure is called, the arguments will be
 148    stored in the bindings of the corresponding variables.
 149
 150*   <variable>: The procedure takes any number of arguments; when the
 151    procedure is called, the sequence of actual arguments is converted
 152    into a newly allocated list, and the list is stored in the binding
 153    of the <variable>.
 154
 155*   (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
 156    space-delimited period precedes the last variable, then the
 157    procedure takes n or more arguments, where n is the number of
 158    formal arguments before the period (there must be at least one).
 159    The value stored in the binding of the last variable will be a
 160    newly allocated list of the actual arguments left over after all
 161    the other actual arguments have been matched up against the other
 162    formal arguments.
 163
 164It is an error for a <variable> to appear more than once in <formals>.
 165
 166 ((lambda x x) 3 4 5 6)                  ===>  (3 4 5 6)
 167 ((lambda (x y . z) z)
 168  3 4 5 6)                               ===>  (5 6)
 169
 170Each procedure created as the result of evaluating a lambda expression
 171is (conceptually) tagged with a storage location, in order to make eqv?
 172and eq? work on procedures.
 173
 174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style
 175parameter lists, which allows embedded special keywords.  Such a
 176keyword gives a special meaning to the {{<formal>}} it precedes.
 177DSSSL parameter lists are defined by the following grammar:
 178
 179 <parameter-list> ==> <required-parameter>*
 180                      [#!optional <optional-parameter>*]
 181                      [#!rest <rest-parameter>]
 182                      [#!key <keyword-parameter>*]
 183 <required-parameter> ==> <ident>
 184 <optional-parameter> ==> <ident>
 185                          | (<ident> <initializer>)
 186 <rest-parameter> ==> <ident>
 187 <keyword-parameter> ==> <ident>
 188                         | (<ident> <initializer>)
 189 <initializer> ==> <expr>
 190
 191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
 192
 193* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.
 194* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
 195* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.
 196* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
 197
 198Needing a special mention is the close relationship between the
 199rest-parameter and possible keyword-parameters.  Declaring a
 200rest-parameter binds up all remaining arguments in a list, as
 201described above. These same remaining arguments are also used for
 202attempted matches with declared keyword-parameters, as described
 203above, in which case a matching keyword-parameter binds to the
 204corresponding value argument at the same time that both the keyword
 205and value arguments are added to the rest parameter list.  Note that
 206for efficiency reasons, the keyword-parameter matching does nothing
 207more than simply attempt to match with pairs that may exist in the
 208remaining arguments.  Extra arguments that don't match are simply
 209unused and forgotten if no rest-parameter has been declared.  Because
 210of this, the caller of a procedure containing one or more
 211keyword-parameters cannot rely on any kind of system error to report
 212wrong keywords being passed in.
 213
 214It shall be an error for an {{<ident>}} to appear more than once in a
 215parameter-list.
 216
 217If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.
 218
 219
 220Example:
 221
 222 ((lambda x x) 3 4 5 6)       => (3 4 5 6)
 223 ((lambda (x y #!rest z) z)
 224  3 4 5 6)                    => (5 6)
 225 ((lambda (x y #!optional z #!rest r #!key i (j 1))
 226     (list x y z i: i j: j))
 227  3 4 5 i: 6 i: 7)            => (3 4 5 i: 6 j: 1)
 228
 229
 230
 231==== Conditionals
 232
 233<macro>(if <test> <consequent> <alternate>)</macro><br>
 234<macro>(if <test> <consequent>)</macro><br>
 235
 236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
 237expressions.
 238
 239Semantics: An if expression is evaluated as follows: first, <test> is
 240evaluated. If it yields a true value (see [[#Booleans|the section
 241about booleans]] below), then <consequent> is evaluated and its
 242value(s) is(are) returned. Otherwise <alternate> is evaluated and its
 243value(s) is(are) returned. If <test> yields a false value and no
 244<alternate> is specified, then the result of the expression is
 245unspecified.
 246
 247 (if (> 3 2) 'yes 'no)                   ===>  yes
 248 (if (> 2 3) 'yes 'no)                   ===>  no
 249 (if (> 3 2)
 250     (- 3 2)
 251     (+ 3 2))                            ===>  1
 252
 253==== Assignments
 254
 255<macro>(set! <variable> <expression>)</macro><br>
 256
 257<Expression> is evaluated, and the resulting value is stored in the
 258location to which <variable> is bound. <Variable> must be bound either
 259in some region enclosing the set! expression or at top level. The
 260result of the set! expression is unspecified.
 261
 262 (define x 2)
 263 (+ x 1)                         ===>  3
 264 (set! x 4)                      ===>  unspecified
 265 (+ x 1)                         ===>  5
 266
 267As an extension to R7RS, {{set!}} for unbound toplevel variables is
 268allowed.  Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN
 269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].
 270
 271==== Inclusion
 272
 273<macro>(include STRING1 STRING2 ...)</macro>
 274<macro>(include-ci STRING1 STRING2 ...)</macro>
 275
 276Semantics: Both {{include}} and {{include-ci}} take one or
 277more filenames expressed as string literals, find the corresponding
 278files, read the contents of the files in the specified order
 279as if by repeated applications of {{read}}, and effectively replace the {{include}}
 280or {{include-ci}} expression with a {{begin}}
 281expression containing what was read from the files. The
 282difference between the two is that {{include-ci}} reads each
 283file as if it began with the {{#!fold-case}} directive, while
 284{{include}} does not.
 285
 286If the given filenames are relative paths, they are searched in the
 287directory containing the file where the {{include}} form appears,
 288then in the paths given in the list returned by {{include-path}}
 289(from the {{(chicken platform)}} module) or in the extension
 290repository directory.
 291
 292
 293=== Derived expression types
 294
 295The constructs in this section are hygienic.  For reference purposes,
 296these macro definitions will convert most of the constructs described
 297in this section into the primitive constructs described in the
 298previous section.  This does not necessarily mean that's exactly how
 299it's implemented in CHICKEN.
 300
 301==== Conditionals
 302
 303<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
 304
 305Syntax: Each <clause> should be of the form
 306
 307 (<test> <expression[1]> ...)
 308
 309where <test> is any expression. Alternatively, a <clause> may be of the
 310form
 311
 312 (<test> => <expression>)
 313
 314The last <clause> may be an "else clause," which has the form
 315
 316 (else <expression[1]> <expression[2]> ...).
 317
 318Semantics: A cond expression is evaluated by evaluating the <test>
 319expressions of successive <clause>s in order until one of them
 320evaluates to a true value (see [[#Booleans|the section about
 321booleans]] below). When a <test> evaluates to a true value, then the
 322remaining <expression>s in its <clause> are evaluated in order, and
 323the result(s) of the last <expression> in the <clause> is(are)
 324returned as the result(s) of the entire cond expression. If the
 325selected <clause> contains only the <test> and no <expression>s, then
 326the value of the <test> is returned as the result.  If the selected
 327<clause> uses the => alternate form, then the <expression> is
 328evaluated. Its value must be a procedure that accepts one argument;
 329this procedure is then called on the value of the <test> and the
 330value(s) returned by this procedure is(are) returned by the cond
 331expression. If all <test>s evaluate to false values, and there is no
 332else clause, then the result of the conditional expression is
 333unspecified; if there is an else clause, then its <expression>s are
 334evaluated, and the value(s) of the last one is(are) returned.
 335
 336 (cond ((> 3 2) 'greater)
 337       ((< 3 2) 'less))           ===>  greater
 338 (cond ((> 3 3) 'greater)
 339       ((< 3 3) 'less)
 340       (else 'equal))             ===>  equal
 341 (cond ((assv 'b '((a 1) (b 2))) => cadr)
 342       (else #f))                 ===>  2
 343
 344
 345As an extension to R7RS, CHICKEN also supports the
 346[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:
 347
 348 (<generator> <guard> => <expression>)
 349
 350In this situation, {{generator}} is ''always'' evaluated.  Its
 351resulting value(s) are used as argument(s) for the {{guard}}
 352procedure.  Finally, if {{guard}} returns a non-{{#f}} value, the
 353{{expression}} is evaluated by calling it with the result of
 354{{guard}}.  Otherwise, evaluation procedes to the next clause.
 355
 356<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
 357
 358Syntax: <Key> may be any expression. Each <clause> should have the form
 359
 360 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
 361
 362where each <datum> is an external representation of some object.
 363Alternatively, as per R7RS, a <clause> may be of the form
 364
 365 ((<datum[1]> ...) => <expression>).
 366
 367All the <datum>s must be distinct. The last <clause> may be an
 368"else clause," which has one of the following two forms:
 369
 370 (else <expression[1]> <expression[2]> ...)
 371 (else => <expression>).
 372
 373Semantics: A case expression is evaluated as follows. <Key> is
 374evaluated and its result is compared against each <datum>. If the
 375result of evaluating <key> is equivalent (in the sense of {{eqv?}};
 376see [[#equivalence-predicates|below]]) to a <datum>, then the
 377expressions in the corresponding <clause> are evaluated from left to
 378right and the result(s) of the last expression in the <clause> is(are)
 379returned as the result(s) of the case expression. If the selected
 380<clause> uses the => alternate form (an R7RS extension), then the
 381<expression> is evaluated. Its value must be a procedure that accepts
 382one argument; this procedure is then called on the value of the <key>
 383and the value(s) returned by this procedure is(are) returned by the
 384case expression.  If the result of evaluating <key> is different from
 385every <datum>, then if there is an else clause its expressions are
 386evaluated and the result(s) of the last is(are) the result(s) of the
 387case expression; otherwise the result of the case expression is
 388unspecified.
 389
 390 (case (* 2 3)
 391   ((2 3 5 7) 'prime)
 392   ((1 4 6 8 9) 'composite))             ===>  composite
 393 (case (car '(c d))
 394   ((a) 'a)
 395   ((b) 'b))                             ===>  unspecified
 396 (case (car '(c d))
 397   ((a e i o u) 'vowel)
 398   ((w y) 'semivowel)
 399   (else 'consonant))                    ===>  consonant
 400
 401<macro>(and <test[1]> ...)</macro><br>
 402
 403The <test> expressions are evaluated from left to right, and the value
 404of the first expression that evaluates to a false value (see
 405[[#Booleans|the section about booleans]]) is returned. Any remaining
 406expressions are not evaluated. If all the expressions evaluate to true
 407values, the value of the last expression is returned. If there are no
 408expressions then #t is returned.
 409
 410 (and (= 2 2) (> 2 1))                   ===>  #t
 411 (and (= 2 2) (< 2 1))                   ===>  #f
 412 (and 1 2 'c '(f g))                     ===>  (f g)
 413 (and)                                   ===>  #t
 414
 415<macro>(or <test[1]> ...)</macro><br>
 416
 417The <test> expressions are evaluated from left to right, and the value
 418of the first expression that evaluates to a true value (see
 419[[#Booleans|the section about booleans]]) is returned. Any remaining
 420expressions are not evaluated. If all expressions evaluate to false
 421values, the value of the last expression is returned. If there are no
 422expressions then #f is returned.
 423
 424 (or (= 2 2) (> 2 1))                    ===>  #t
 425 (or (= 2 2) (< 2 1))                    ===>  #t
 426 (or #f #f #f)         ===>  #f
 427 (or (memq 'b '(a b c))
 428     (/ 3 0))                            ===>  (b c)
 429
 430<macro>(unless TEST EXP1 EXP2 ...)</macro>
 431
 432Equivalent to:
 433
 434<enscript highlight=scheme>
 435(if (not TEST) (begin EXP1 EXP2 ...))
 436</enscript>
 437
 438<macro>(when TEST EXP1 EXP2 ...)</macro>
 439
 440Equivalent to:
 441
 442<enscript highlight=scheme>
 443(if TEST (begin EXP1 EXP2 ...))
 444</enscript>
 445
 446<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>
 447
 448The {{cond-expand}} expression type provides a way
 449to statically expand different expressions depending on the
 450implementation. A <ce-clause> takes the following form:
 451
 452{{
 453(<feature requirement> <expression> ...)
 454}}
 455
 456The last clause can be an "else clause," which has the form
 457
 458{{
 459(else <expression> ...)
 460}}]
 461
 462A feature requirement takes one of the following forms:
 463
 464<feature identifier>
 465
 466{{(library <library name>)}}
 467
 468{{(and <feature requirement> ...)}}
 469
 470{{(or <feature requirement> ...)}}
 471
 472{{(not <feature requirement>)}}
 473
 474Each implementation maintains a list of
 475feature identifiers which are present, as well as a list
 476of libraries which can be imported.
 477The value of a <feature requirement> is determined by replacing each
 478<feature identifier> and {{(library <library name>)}} on the
 479implementation's lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under
 480the normal interpretation of {{and}}, {{or}}, and {{not}}.
 481
 482A {{cond-expand}} is then expanded by evaluating the
 483<feature requirement>s of successive <ce-clause>s in order
 484until one of them returns {{#t}}. When a true clause is found,
 485the corresponding <expression>s are expanded to a {{begin}},
 486and the remaining clauses are ignored.
 487
 488If none of the
 489<feature requirement>s evaluate to {{#t}}, then if there is an
 490{{else}} clause, its <expression>s are included. Otherwise, the
 491behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},
 492{{cond-expand}} does not depend on the value of any variables.
 493
 494The following features are built-in and always available by default:
 495{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},
 496{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},
 497{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},
 498{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.
 499
 500There are also situation-specific feature identifiers: {{compiling}} during
 501compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}
 502when running within the compiler.
 503
 504The symbols returned by the following procedures from
 505[[Module (chicken platform)|(chicken platform)]] are also available
 506as feature-identifiers in all situations: {{(machine-byte-order)}},
 507{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For
 508example, the {{machine-type}} class of feature-identifiers include
 509{{arm}}, {{alpha}}, {{mips}}, etc.
 510
 511Platform endianness is indicated by the {{little-endian}} and {{big-endian}}
 512features.
 513
 514In addition the following feature-identifiers may exist: {{cross-chicken}},
 515{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.
 516
 517
 518==== Binding constructs
 519
 520The three binding constructs let, let*, and letrec give Scheme a block
 521structure, like Algol 60. The syntax of the three constructs is
 522identical, but they differ in the regions they establish for their
 523variable bindings. In a let expression, the initial values are computed
 524before any of the variables become bound; in a let* expression, the
 525bindings and evaluations are performed sequentially; while in a letrec
 526expression, all the bindings are in effect while their initial values
 527are being computed, thus allowing mutually recursive definitions.
 528
 529<macro>(let <bindings> <body>)</macro><br>
 530
 531Syntax: <Bindings> should have the form
 532
 533 ((<variable[1]> <init[1]>) ...),
 534
 535where each <init> is an expression, and <body> should be a sequence of
 536one or more expressions. It is an error for a <variable> to appear more
 537than once in the list of variables being bound.
 538
 539Semantics: The <init>s are evaluated in the current environment (in
 540some unspecified order), the <variable>s are bound to fresh locations
 541holding the results, the <body> is evaluated in the extended
 542environment, and the value(s) of the last expression of <body> is(are)
 543returned. Each binding of a <variable> has <body> as its region.
 544
 545 (let ((x 2) (y 3))
 546   (* x y))                              ===>  6
 547 
 548 (let ((x 2) (y 3))
 549   (let ((x 7)
 550         (z (+ x y)))
 551     (* z x)))                           ===>  35
 552
 553See also "named let", [[#iteration|below]].
 554
 555<macro>(let* <bindings> <body>)</macro><br>
 556
 557Syntax: <Bindings> should have the form
 558
 559 ((<variable[1]> <init[1]>) ...),
 560
 561and <body> should be a sequence of one or more expressions.
 562
 563Semantics: Let* is similar to let, but the bindings are performed
 564sequentially from left to right, and the region of a binding indicated
 565by (<variable> <init>) is that part of the let* expression to the right
 566of the binding. Thus the second binding is done in an environment in
 567which the first binding is visible, and so on.
 568
 569 (let ((x 2) (y 3))
 570   (let* ((x 7)
 571          (z (+ x y)))
 572     (* z x)))                     ===>  70
 573
 574<macro>(letrec <bindings> <body>)</macro><br>
 575
 576Syntax: <Bindings> should have the form
 577
 578 ((<variable[1]> <init[1]>) ...),
 579
 580and <body> should be a sequence of one or more expressions. It is an
 581error for a <variable> to appear more than once in the list of
 582variables being bound.
 583
 584Semantics: The <variable>s are bound to fresh locations holding
 585undefined values, the <init>s are evaluated in the resulting
 586environment (in some unspecified order), each <variable> is assigned to
 587the result of the corresponding <init>, the <body> is evaluated in the
 588resulting environment, and the value(s) of the last expression in
 589<body> is(are) returned. Each binding of a <variable> has the entire
 590letrec expression as its region, making it possible to define mutually
 591recursive procedures.
 592
 593 (letrec ((even?
 594           (lambda (n)
 595             (if (zero? n)
 596                 #t
 597                 (odd? (- n 1)))))
 598          (odd?
 599           (lambda (n)
 600             (if (zero? n)
 601                 #f
 602                 (even? (- n 1))))))
 603   (even? 88))
 604                         ===>  #t
 605
 606One restriction on letrec is very important: it must be possible to
 607evaluate each <init> without assigning or referring to the value of any
 608<variable>. If this restriction is violated, then it is an error. The
 609restriction is necessary because Scheme passes arguments by value
 610rather than by name. In the most common uses of letrec, all the <init>s
 611are lambda expressions and the restriction is satisfied automatically.
 612
 613<macro>(letrec* <bindings> <body>) </macro>
 614
 615Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}}, and
 616<body> is a sequence of zero or more
 617definitions followed by one or more expressions as described in section 4.1.4.
 618It is an error for a <variable> to appear more than once in the list of
 619variables being bound.
 620
 621Semantics: The <variable>s are bound to fresh locations, each <variable> is
 622assigned in left-to-right order to the result of evaluating the corresponding
 623<init> (interleaving evaluations and assignments), the <body> is evaluated in
 624the resulting environment, and the values of the last expression in <body> are
 625returned. Despite the left-to-right evaluation and assignment order, each
 626binding of a <variable> has the entire letrec* expression as its region, making
 627it possible to define mutually recursive procedures.
 628
 629If it is not possible to evaluate each <init> without assigning or referring to
 630the value of the corresponding <variable> or the <variable> of any of the
 631bindings that follow it in <bindings>, it is an error. Another restriction is
 632that it is an error to invoke the continuation of an <init> more than once.
 633
 634  ;; Returns the arithmetic, geometric, and
 635  ;; harmonic means of a nested list of numbers
 636  (define (means ton)
 637    (letrec*
 638       ((mean
 639          (lambda (f g)
 640            (f (/ (sum g ton) n))))
 641        (sum
 642          (lambda (g ton)
 643            (if (null? ton)
 644              (+)
 645              (if (number? ton)
 646                  (g ton)
 647                  (+ (sum g (car ton))
 648                     (sum g (cdr ton)))))))
 649        (n (sum (lambda (x) 1) ton)))
 650      (values (mean values values)
 651              (mean exp log)
 652              (mean / /))))
 653
 654Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666
 655(approximately), and 36/19.
 656
 657<macro>(let-values <mv binding spec> <body>)</macro>
 658
 659Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},
 660where each <init> is an expression, and <body> is
 661zero or more definitions followed by a sequence of one or more expressions as
 662described in section 4.1.4. It is an error for a variable to appear more than
 663once in the set of <formals>.
 664
 665Semantics: The <init>s are evaluated in the current environment (in some
 666unspecified order) as if by invoking call-with-values, and the variables
 667occurring in the <formals> are bound to fresh locations holding the values
 668returned by the <init>s, where the <formals> are matched to the return values
 669in the same way that the <formals> in a lambda expression are matched to the
 670arguments in a procedure call. Then, the <body> is evaluated in the extended
 671environment, and the values of the last expression of <body> are returned. Each
 672binding of a <variable> has <body> as its region.
 673
 674It is an error if the <formals> do not match the number of values returned by
 675the corresponding <init>.
 676
 677  (let-values (((root rem) (exact-integer-sqrt 32)))
 678    (* root rem))                 ==>  35
 679
 680<macro>(let*-values <mv binding spec> <body>)</macro>
 681
 682Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},
 683and <body> is a sequence of zero or more definitions
 684followed by one or more expressions as described in section 4.1.4. In each
 685<formals>, it is an error if any variable appears more than once.
 686
 687Semantics: The let*-values construct is similar to let-values, but the <init>s
 688are evaluated and bindings created sequentially from left to right, with the
 689region of the bindings of each <formals> including the <init>s to its right as
 690well as <body>. Thus the second <init> is evaluated in an environment in which
 691the first set of bindings is visible and initialized, and so on.
 692
 693  (let ((a 'a) (b 'b) (x 'x) (y 'y))
 694    (let*-values (((a b) (values x y))
 695                  ((x y) (values a b)))
 696      (list a b x y)))      ===>     (x y x y)
 697
 698==== Sequencing
 699
 700<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
 701
 702The <expression>s are evaluated sequentially from left to right, and
 703the value(s) of the last <expression> is(are) returned. This expression
 704type is used to sequence side effects such as input and output.
 705
 706 (define x 0)
 707 
 708 (begin (set! x 5)
 709        (+ x 1))                          ===>  6
 710 
 711 (begin (display "4 plus 1 equals ")
 712        (display (+ 4 1)))                ===>  unspecified
 713   and prints  4 plus 1 equals 5
 714
 715As an extension to R7RS, CHICKEN also allows {{(begin)}} without body
 716expressions in any context, not just at toplevel.  This simply
 717evaluates to the unspecified value.
 718
 719
 720==== Iteration
 721
 722<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
 723
 724Do is an iteration construct. It specifies a set of variables to be
 725bound, how they are to be initialized at the start, and how they are to
 726be updated on each iteration. When a termination condition is met, the
 727loop exits after evaluating the <expression>s.
 728
 729Do expressions are evaluated as follows: The <init> expressions are
 730evaluated (in some unspecified order), the <variable>s are bound to
 731fresh locations, the results of the <init> expressions are stored in
 732the bindings of the <variable>s, and then the iteration phase begins.
 733
 734Each iteration begins by evaluating <test>; if the result is false
 735(see [[#Booleans|the section about booleans]]), then the <command>
 736expressions are evaluated in order for effect, the <step> expressions
 737are evaluated in some unspecified order, the <variable>s are bound to
 738fresh locations, the results of the <step>s are stored in the bindings
 739of the <variable>s, and the next iteration begins.
 740
 741If <test> evaluates to a true value, then the <expression>s are
 742evaluated from left to right and the value(s) of the last <expression>
 743is(are) returned. If no <expression>s are present, then the value of
 744the do expression is unspecified.
 745
 746The region of the binding of a <variable> consists of the entire do
 747expression except for the <init>s. It is an error for a <variable> to
 748appear more than once in the list of do variables.
 749
 750A <step> may be omitted, in which case the effect is the same as if
 751(<variable> <init> <variable>) had been written instead of (<variable>
 752<init>).
 753
 754 (do ((vec (make-vector 5))
 755      (i 0 (+ i 1)))
 756     ((= i 5) vec)
 757   (vector-set! vec i i))                    ===>  #(0 1 2 3 4)
 758 
 759 (let ((x '(1 3 5 7 9)))
 760   (do ((x x (cdr x))
 761        (sum 0 (+ sum (car x))))
 762       ((null? x) sum)))                     ===>  25
 763
 764<macro>(let <variable> <bindings> <body>)</macro><br>
 765
 766"Named let" is a variant on the syntax of let which provides a more
 767general looping construct than do and may also be used to express
 768recursions. It has the same syntax and semantics as ordinary let except
 769that <variable> is bound within <body> to a procedure whose formal
 770arguments are the bound variables and whose body is <body>. Thus the
 771execution of <body> may be repeated by invoking the procedure named by
 772<variable>.
 773
 774 (let loop ((numbers '(3 -2 1 6 -5))
 775            (nonneg '())
 776            (neg '()))
 777   (cond ((null? numbers) (list nonneg neg))
 778         ((>= (car numbers) 0)
 779          (loop (cdr numbers)
 780                (cons (car numbers) nonneg)
 781                neg))
 782         ((< (car numbers) 0)
 783          (loop (cdr numbers)
 784                nonneg
 785                (cons (car numbers) neg)))))
 786                 ===>  ((6 1 3) (-5 -2))
 787
 788====  Dynamic bindings
 789
 790The dynamic extent of a procedure call is the time between when it is initiated
 791and when it returns. In Scheme, {{call-with-current-continuation}}
 792allows reentering a dynamic extent after its procedure call has returned. Thus,
 793the dynamic extent of a call might not be a single, continuous time period.
 794
 795This sections introduces parameter objects, which can be bound to new values
 796for the duration of a dynamic extent. The set of all parameter bindings at a
 797given time is called the dynamic environment.
 798
 799<procedure>(make-parameter init [converter])</procedure>
 800
 801Returns a newly allocated parameter object, which is a procedure that accepts
 802zero arguments and returns the value associated with the parameter object.
 803Initially, this value is the value of {{(converter init)}}, or of {{init}}
 804if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed
 805using {{parameterize}}, which is described below.
 806
 807The effect of passing arguments to a parameter object is
 808implementation-dependent.
 809
 810<syntax>(parameterize ((<param[1]> <value[1]>) ...) <body>)</syntax>
 811
 812Syntax: Both <param[1]> and <value[1]> are expressions.
 813
 814It is an error if the value of any <param> expression is not a parameter
 815object.
 816
 817Semantics: A parameterize expression is used to change the values returned by
 818specified parameter objects during the evaluation of the body.
 819
 820The <param> and <value> expressions are evaluated in an unspecified order. The
 821<body> is evaluated in a dynamic environment in which calls to the parameters
 822return the results of passing the corresponding values to the conversion
 823procedure specified when the parameters were created. Then the previous values
 824of the parameters are restored without passing them to the conversion
 825procedure. The results of the last expression in the <body> are returned as the
 826results of the entire parameterize expression.
 827
 828Note: If the conversion procedure is not idempotent, the results of
 829(parameterize ((x (x))) ...), which appears to bind the parameter
 830
 831x to its current value, might not be what the user expects.
 832
 833If an implementation supports multiple threads of execution, then parameterize
 834must not change the associated values of any parameters in any thread other
 835than the current thread and threads created inside <body>.
 836
 837Parameter objects can be used to specify configurable settings for a
 838computation without the need to pass the value to every procedure in the call
 839chain explicitly.
 840
 841  (define radix
 842    (make-parameter
 843     10
 844     (lambda (x)
 845       (if (and (exact-integer? x) (<= 2 x 16))
 846           x
 847           (error "invalid radix")))))
 848
 849  (define (f n) (number->string n (radix)))
 850
 851  (f 12)                                        ==> "12"
 852  (parameterize ((radix 2))
 853    (f 12))                                     ==> "1100"
 854  (f 12)                                        ==> "12"
 855
 856  (radix 16)                                    ==> unspecified
 857
 858  (parameterize ((radix 0))
 859    (f 12))                                     ==> error
 860
 861==== Exception handling
 862
 863<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>
 864
 865Syntax: Each <cond clause> is as in the specification of cond.
 866
 867Semantics: The <body> is evaluated with an exception handler that binds the
 868raised object (see {{raise}}) to <variable> and, within the scope
 869of that binding, evaluates the clauses as if they were the clauses of a cond
 870expression. That implicit cond expression is evaluated with the continuation
 871and dynamic environment of the guard expression. If every <cond clause>'s
 872<test> evaluates to #f and there is no else clause, then raise-continuable is
 873invoked on the raised object within the dynamic environment of the original
 874call to raise or raise-continuable, except that the current exception handler
 875is that of the guard expression.
 876
 877    (guard (condition
 878             ((assq 'a condition) => cdr)
 879             ((assq 'b condition)))
 880      (raise (list (cons 'a 42))))
 881    ==> 42
 882
 883    (guard (condition
 884             ((assq 'a condition) => cdr)
 885             ((assq 'b condition)))
 886      (raise (list (cons 'b 23))))
 887    ==> (b . 23)
 888
 889==== Quasiquotation
 890
 891<macro>(quasiquote <qq template>)</macro><br>
 892<macro>`<qq template></macro><br>
 893
 894"Backquote" or "quasiquote" expressions are useful for constructing
 895a list or vector structure when most but not all of the desired
 896structure is known in advance. If no commas appear within the <qq
 897template>, the result of evaluating `<qq template> is equivalent to the
 898result of evaluating '<qq template>. If a comma appears within the <qq
 899template>, however, the expression following the comma is evaluated
 900("unquoted") and its result is inserted into the structure instead of
 901the comma and the expression. If a comma appears followed immediately
 902by an at-sign (@), then the following expression must evaluate to a
 903list; the opening and closing parentheses of the list are then
 904"stripped away" and the elements of the list are inserted in place of
 905the comma at-sign expression sequence. A comma at-sign should only
 906appear within a list or vector <qq template>.
 907
 908 `(list ,(+ 1 2) 4)          ===>  (list 3 4)
 909 (let ((name 'a)) `(list ,name ',name))
 910                 ===>  (list a (quote a))
 911 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)
 912                 ===>  (a 3 4 5 6 b)
 913 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
 914                 ===>  ((foo 7) . cons)
 915 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
 916                 ===>  #(10 5 2 4 3 8)
 917
 918Quasiquote forms may be nested. Substitutions are made only for
 919unquoted components appearing at the same nesting level as the
 920outermost backquote. The nesting level increases by one inside each
 921successive quasiquotation, and decreases by one inside each
 922unquotation.
 923
 924 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
 925                 ===>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
 926 (let ((name1 'x)
 927       (name2 'y))
 928   `(a `(b ,,name1 ,',name2 d) e))
 929                 ===>  (a `(b ,x ,'y d) e)
 930
 931The two notations `<qq template> and (quasiquote <qq template>) are
 932identical in all respects. ,<expression> is identical to (unquote
 933<expression>), and ,@<expression> is identical to (unquote-splicing
 934<expression>). The external syntax generated by write for two-element
 935lists whose car is one of these symbols may vary between
 936implementations.
 937
 938 (quasiquote (list (unquote (+ 1 2)) 4))
 939                 ===>  (list 3 4)
 940 '(quasiquote (list (unquote (+ 1 2)) 4))
 941                 ===>  `(list ,(+ 1 2) 4)
 942      i.e., (quasiquote (list (unquote (+ 1 2)) 4))
 943
 944Unpredictable behavior can result if any of the symbols quasiquote,
 945unquote, or unquote-splicing appear in positions within a <qq template>
 946otherwise than as described above.
 947
 948=== Macros
 949
 950Scheme programs can define and use new derived expression types, called
 951macros. Program-defined expression types have the syntax
 952
 953 (<keyword> <datum> ...)
 954
 955where <keyword> is an identifier that uniquely determines the
 956expression type. This identifier is called the syntactic keyword, or
 957simply keyword, of the macro. The number of the <datum>s, and their
 958syntax, depends on the expression type.
 959
 960Each instance of a macro is called a use of the macro. The set of rules
 961that specifies how a use of a macro is transcribed into a more
 962primitive expression is called the transformer of the macro.
 963
 964The macro definition facility consists of two parts:
 965
 966*   A set of expressions used to establish that certain identifiers are
 967    macro keywords, associate them with macro transformers, and control
 968    the scope within which a macro is defined, and
 969
 970*   a pattern language for specifying macro transformers.
 971
 972The syntactic keyword of a macro may shadow variable bindings, and
 973local variable bindings may shadow keyword bindings. All macros defined
 974using the pattern language are "hygienic" and "referentially
 975transparent" and thus preserve Scheme's lexical scoping:
 976
 977*   If a macro transformer inserts a binding for an identifier
 978    (variable or keyword), the identifier will in effect be renamed
 979    throughout its scope to avoid conflicts with other identifiers.
 980    Note that a define at top level may or may not introduce a binding;
 981    this depends on whether the binding already existed before (in which
 982    case its value will be overridden).
 983
 984*   If a macro transformer inserts a free reference to an identifier,
 985    the reference refers to the binding that was visible where the
 986    transformer was specified, regardless of any local bindings that
 987    may surround the use of the macro.
 988
 989==== Binding constructs for syntactic keywords
 990
 991Let-syntax and letrec-syntax are analogous to let and letrec, but they
 992bind syntactic keywords to macro transformers instead of binding
 993variables to locations that contain values. Syntactic keywords may also
 994be bound at top level.
 995
 996<macro>(let-syntax <bindings> <body>)</macro><br>
 997
 998Syntax: <Bindings> should have the form
 999
 1000 ((<keyword> <transformer spec>) ...)
1001
1002Each <keyword> is an identifier, each <transformer spec> is an instance
1003of syntax-rules, and <body> should be a sequence of one or more
1004expressions. It is an error for a <keyword> to appear more than once in
1005the list of keywords being bound.
1006
1007Semantics: The <body> is expanded in the syntactic environment obtained
1008by extending the syntactic environment of the let-syntax expression
1009with macros whose keywords are the <keyword>s, bound to the specified
1010transformers. Each binding of a <keyword> has <body> as its region.
1011
1012 (let-syntax ((when (syntax-rules ()
1013                      ((when test stmt1 stmt2 ...)
1014                       (if test
1015                           (begin stmt1
1016                                  stmt2 ...))))))
1017   (let ((if #t))
1018     (when if (set! if 'now))
1019     if))                                   ===>  now
1020 
1021 (let ((x 'outer))
1022   (let-syntax ((m (syntax-rules () ((m) x))))
1023     (let ((x 'inner))
1024       (m))))                               ===>  outer
1025
1026<macro>(letrec-syntax <bindings> <body>)</macro><br>
1027
1028Syntax: Same as for let-syntax.
1029
1030Semantics: The <body> is expanded in the syntactic environment obtained
1031by extending the syntactic environment of the letrec-syntax expression
1032with macros whose keywords are the <keyword>s, bound to the specified
1033transformers. Each binding of a <keyword> has the <bindings> as well as
1034the <body> within its region, so the transformers can transcribe
1035expressions into uses of the macros introduced by the letrec-syntax
1036expression.
1037
1038 (letrec-syntax
1039   ((my-or (syntax-rules ()
1040             ((my-or) #f)
1041             ((my-or e) e)
1042             ((my-or e1 e2 ...)
1043              (let ((temp e1))
1044                (if temp
1045                    temp
1046                    (my-or e2 ...)))))))
1047   (let ((x #f)
1048         (y 7)
1049         (temp 8)
1050         (let odd?)
1051         (if even?))
1052     (my-or x
1053            (let temp)
1054            (if y)
1055            y)))                ===>  7
1056
1057==== Pattern language
1058
1059A <transformer spec> has the following form:
1060
1061 (syntax-rules <literals> <syntax rule> ...)
1062
1063Syntax: <Literals> is a list of identifiers and each <syntax rule>
1064should be of the form
1065
1066 (<pattern> <template>)
1067
1068The <pattern> in a <syntax rule> is a list <pattern> that begins with
1069the keyword for the macro.
1070
1071A <pattern> is either an identifier, a constant, or one of the
1072following
1073
1074 (<pattern> ...)
1075 (<pattern> <pattern> ... . <pattern>)
1076 (<pattern> ... <pattern> <ellipsis> <pattern> ...)
1077 #(<pattern> ...)
1078 #(<pattern> ... <pattern> <ellipsis>)
1079
1080and a template is either an identifier, a constant, or one of the
1081following
1082
1083 (<element> ...)
1084 (<element> <element> ... . <template>)
1085 (<ellipsis> <template>)
1086 #(<element> ...)
1087
1088where an <element> is a <template> optionally followed by an <ellipsis>
1089and an <ellipsis> is the identifier "...".
1090
1091Semantics: An instance of syntax-rules produces a new macro transformer
1092by specifying a sequence of hygienic rewrite rules. A use of a macro
1093whose keyword is associated with a transformer specified by
1094syntax-rules is matched against the patterns contained in the <syntax
1095rule>s, beginning with the leftmost <syntax rule>. When a match is
1096found, the macro use is transcribed hygienically according to the
1097template.
1098
1099An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal
1100identifier listed in the list of <pattern literal>s, or the <ellipsis>. All
1101other identifiers appearing within a <pattern> are pattern variables.
1102
1103The keyword at the beginning of the pattern in a <syntax rule> is not involved
1104in the matching and is considered neither a pattern variable nor a literal
1105identifier.
1106
1107Pattern variables match arbitrary input elements and are used to refer to
1108elements of the input in the template. It is an error for the same pattern
1109variable to appear more than once in a <pattern>.
1110
1111Underscores also match arbitrary input elements but are not pattern variables
1112and so cannot be used to refer to those elements. If an underscore appears in
1113the <pattern literal>s list, then that takes precedence and underscores in the
1114<pattern> match as literals. Multiple underscores can appear in a <pattern>.
1115
1116Identifiers that appear in (<pattern literal> ...) are interpreted as literal
1117identifiers to be matched against corresponding elements of the input. An
1118element in the input matches a literal identifier if and only if it is an
1119identifier and either both its occurrence in the macro expression and its
1120occurrence in the macro definition have the same lexical binding, or the two
1121identifiers are the same and both have no lexical binding.
1122
1123A subpattern followed by <ellipsis> can match zero or more elements of the
1124input, unless <ellipsis> appears in the <pattern literal>s, in which case it is
1125matched as a literal.
1126
1127More formally, an input form F matches a pattern P if and only if:
1128
1129*   P is an underscore (_).
1130
1131*   P is a non-literal identifier; or
1132
1133*   P is a literal identifier and F is an identifier with the same
1134    binding; or
1135
1136*   P is a list (P[1] ... P[n]) and F is a list of n forms that match P
1137    [1] through P[n], respectively; or
1138
1139*   P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
1140    or improper list of n or more forms that match P[1] through P[n],
1141    respectively, and whose nth "cdr" matches P[n+1]; or
1142
1143*   P is of the form (P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E
1144    is a list or improper list of n elements, the first k of which match P[1]
1145    through P[k], whose next m--k elements each match P[e], whose remaining n--m
1146    elements match P[m+1] through P[n], and whose nth and final cdr matches P[x
1147    ]; or
1148
1149*   P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
1150    forms that match P[1] through P[n]; or
1151
1152*   P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a
1153    vector of n elements the first k of which match P[1] through P[k], whose
1154    next m--k elements each match P[e], and whose remaining n--m elements match P
1155    [m+1] through P[n]; or
1156
1157*   P is a datum and F is equal to P in the sense of the equal?
1158    procedure.
1159
1160It is an error to use a macro keyword, within the scope of its binding,
1161in an expression that does not match any of the patterns.
1162
1163When a macro use is transcribed according to the template of the matching
1164<syntax rule>, pattern variables that occur in the template are replaced by the
1165elements they match in the input. Pattern variables that occur in subpatterns
1166followed by one or more instances of the identifier <ellipsis> are allowed only
1167in subtemplates that are followed by as many instances of <ellipsis>. They are
1168replaced in the output by all of the elements they match in the input,
1169distributed as indicated. It is an error if the output cannot be built up as
1170specified.
1171
1172Identifiers that appear in the template but are not pattern variables or the
1173identifier <ellipsis> are inserted into the output as literal identifiers. If a
1174literal identifier is inserted as a free identifier then it refers to the
1175binding of that identifier within whose scope the instance of syntax-rules
1176appears. If a literal identifier is inserted as a bound identifier then it is
1177in effect renamed to prevent inadvertent captures of free identifiers.
1178
1179A template of the form (<ellipsis> <template>) is identical to <template>,
1180except that ellipses within the template have no special meaning. That is, any
1181ellipses contained within <template> are treated as ordinary identifiers. In
1182particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.
1183This allows syntactic abstractions to expand into code containing ellipses.
1184
1185{{
1186(define-syntax be-like-begin
1187  (syntax-rules ()
1188    ((be-like-begin name)
1189     (define-syntax name
1190       (syntax-rules ()
1191         ((name expr (... ...))
1192          (begin expr (... ...))))))))
1193
1194(be-like-begin sequence)
1195
1196(sequence 1 2 3 4)  ==> 4
1197}}
1198
1199As an example, if {{let}} and {{cond}} have their standard meaning
1200then they are hygienic (as required) and the following is not an
1201error.
1202
1203 (let ((=> #f))
1204   (cond (#t => 'ok)))                   ===> ok
1205
1206The macro transformer for cond recognizes => as a local variable, and
1207hence an expression, and not as the top-level identifier =>, which the
1208macro transformer treats as a syntactic keyword. Thus the example
1209expands into
1210
1211 (let ((=> #f))
1212   (if #t (begin => 'ok)))
1213
1214instead of
1215
1216 (let ((=> #f))
1217   (let ((temp #t))
1218     (if temp ('ok temp))))
1219
1220which would result in an invalid procedure call.
1221
1222====  Signaling errors in macro transformers
1223
1224<macro>(syntax-error <message> <args> ...)</macro>
1225
1226{{syntax-error}} behaves similarly to {{error}} except that implementations with
1227an expansion pass separate from evaluation should signal an error as soon as
1228{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a
1229<pattern> that is an invalid use of the macro, which can provide more
1230descriptive error messages. <message> is a string literal, and <args> arbitrary
1231expressions providing additional information. Applications cannot count on
1232being able to catch syntax errors with exception handlers or guards.
1233
1234 (define-syntax simple-let
1235   (syntax-rules ()
1236     ((_ (head ... ((x . y) val) . tail)
1237         body1 body2 ...)
1238      (syntax-error
1239       "expected an identifier but got"
1240       (x . y)))
1241     ((_ ((name val) ...) body1 body2 ...)
1242      ((lambda (name ...) body1 body2 ...)
1243        val ...))))
1244
1245
1246== Program structure
1247
1248=== Programs
1249
1250A Scheme program consists of a sequence of expressions, definitions,
1251and syntax definitions. Expressions are described in chapter 4;
1252definitions and syntax definitions are the subject of the rest of the
1253present chapter.
1254
1255Programs are typically stored in files or entered interactively to a
1256running Scheme system, although other paradigms are possible;
1257questions of user interface lie outside the scope of this
1258report. (Indeed, Scheme would still be useful as a notation for
1259expressing computational methods even in the absence of a mechanical
1260implementation.)
1261
1262Definitions and syntax definitions occurring at the top level of a
1263program can be interpreted declaratively. They cause bindings to be
1264created in the top level environment or modify the value of existing
1265top-level bindings. Expressions occurring at the top level of a
1266program are interpreted imperatively; they are executed in order when
1267the program is invoked or loaded, and typically perform some kind of
1268initialization.
1269
1270At the top level of a program (begin <form1> ...) is equivalent to the
1271sequence of expressions, definitions, and syntax definitions that form
1272the body of the begin.
1273
1274===  Import declarations
1275
1276<macro>(import IMPORT-SET ...)</macro>
1277
1278An import declaration provides a way to import identifiers exported by a
1279library. Each <import set> names a set of bindings from a library and possibly
1280specifies local names for the imported bindings. It takes one of the following
1281forms:
1282
1283* <library name>
1284
1285* {{(only <import set> <identifier> ...)}}
1286
1287* {{(except <import set> <identifier> ...)}}
1288
1289* {{(prefix <import set> <identifier>)}}
1290
1291* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}
1292
1293In the first form, all of the identifiers in the named library's export clauses
1294are imported with the same names (or the exported names if exported with rename
1295). The additional <import set> forms modify this set as follows:
1296
1297*   only produces a subset of the given <import set> including only the listed
1298    identifiers (after any renaming). It is an error if any of the listed
1299    identifiers are not found in the original set.
1300
1301*   except produces a subset of the given <import set>, excluding the listed
1302    identifiers (after any renaming). It is an error if any of the listed
1303    identifiers are not found in the original set.
1304
1305*   rename modifies the given <import set>, replacing each instance of
1306    <identifier[1]> with <identifier[2]>. It is an error if any of the listed
1307    <identifier[1]>s are not found in the original set.
1308
1309*   prefix automatically renames all identifiers in the given <import set>,
1310    prefixing each with the specified <identifier>.
1311
1312=== Definitions
1313
1314Definitions are valid in some, but not all, contexts where expressions
1315are allowed. They are valid only at the top level of a <program> and
1316at the beginning of a <body>.
1317
1318A definition should have one of the following forms:
1319
1320<macro>(define <variable> <expression>)</macro><br>
1321<macro>(define (<variable> <formals>) <body>)</macro><br>
1322
1323<Formals> should be either a sequence of zero or more variables, or a
1324sequence of one or more variables followed by a space-delimited period
1325and another variable (as in a lambda expression). This form is
1326equivalent to
1327
1328 (define <variable>
1329   (lambda (<formals>) <body>)).
1330
1331<macro>(define <variable>)</macro>
1332
1333This form is a CHICKEN extension to R7RS, and is equivalent to
1334
1335 (define <variable> (void))
1336
1337<macro>(define (<variable> . <formal>) <body>)</macro><br>
1338
1339<Formal> should be a single variable. This form is equivalent to
1340
1341 (define <variable>
1342   (lambda <formal> <body>)).
1343
1344<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>
1345
1346As an extension to R7RS, CHICKEN allows ''curried'' definitions, where
1347the variable name may also be a list specifying a name and a nested
1348lambda list. For example,
1349
1350 (define ((make-adder x) y) (+ x y))
1351
1352is equivalent to
1353
1354 (define (make-adder x) (lambda (y) (+ x y))).
1355
1356This type of curried definition can be nested arbitrarily and combined
1357with dotted tail notation or DSSSL keywords.
1358
1359==== Top level definitions
1360
1361At the top level of a program, a definition
1362
1363 (define <variable> <expression>)
1364
1365has essentially the same effect as the assignment expression
1366
1367 (set! <variable> <expression>)
1368
1369if <variable> is bound. If <variable> is not bound, however, then the
1370definition will bind <variable> to a new location before performing
1371the assignment, whereas it would be an error to perform a set! on an
1372unbound variable in standard Scheme.  In CHICKEN, {{set!}} at toplevel
1373has the same effect as a definition, unless inside a module, in which
1374case it is an error.
1375
1376 (define add3
1377   (lambda (x) (+ x 3)))
1378 (add3 3)                         ===>  6
1379 (define first car)
1380 (first '(1 2))                   ===>  1
1381
1382Some implementations of Scheme use an initial environment in which all
1383possible variables are bound to locations, most of which contain
1384undefined values. Top level definitions in such an implementation are
1385truly equivalent to assignments.  In CHICKEN, attempting to evaluate
1386an unbound identifier will result in an error, but you ''can'' use
1387{{set!}} to bind an initial value to it.
1388
1389==== Internal definitions
1390
1391Definitions may occur at the beginning of a <body> (that is, the body
1392of a lambda, let, let*, letrec, let-syntax, or letrec-syntax
1393expression or that of a definition of an appropriate form). Such
1394definitions are known as internal definitions as opposed to the top
1395level definitions described above. The variable defined by an internal
1396definition is local to the <body>. That is, <variable> is bound rather
1397than assigned, and the region of the binding is the entire <body>. For
1398example,
1399
1400 (let ((x 5))
1401   (define foo (lambda (y) (bar x y)))
1402   (define bar (lambda (a b) (+ (* a b) a)))
1403   (foo (+ x 3)))                        ===>  45
1404
1405A <body> containing internal definitions can always be converted into
1406a completely equivalent letrec expression. For example, the let
1407expression in the above example is equivalent to
1408
1409 (let ((x 5))
1410   (letrec ((foo (lambda (y) (bar x y)))
1411            (bar (lambda (a b) (+ (* a b) a))))
1412     (foo (+ x 3))))
1413
1414Just as for the equivalent letrec expression, it must be possible to
1415evaluate each <expression> of every internal definition in a <body>
1416without assigning or referring to the value of any <variable> being
1417defined.
1418
1419Wherever an internal definition may occur (begin <definition1> ...) is
1420equivalent to the sequence of definitions that form the body of the
1421begin.
1422
1423CHICKEN extends the R7RS semantics by allowing internal definitions
1424everywhere, and not only at the beginning of a body. A set of internal
1425definitions is equivalent to a {{letrec}} form enclosing all following
1426expressions in the body:
1427
1428 (let ((foo 123))
1429   (bar)
1430   (define foo 456)
1431   (baz foo) )
1432
1433expands into
1434
1435 (let ((foo 123))
1436   (bar)
1437   (letrec ((foo 456))
1438     (baz foo) ) )
1439
1440Local sequences of {{define-syntax}} forms are translated into
1441equivalent {{letrec-syntax}} forms that enclose the following forms as
1442the body of the expression.
1443
1444===  Multiple-value definitions
1445
1446Another kind of definition is provided by define-values, which creates multiple
1447definitions from a single expression returning multiple values. It is allowed
1448wherever define is allowed.
1449
1450<macro>(define-values <formals> <expression>)</macro>
1451
1452It is an error if a variable appears more than once in the set of <formals>.
1453
1454Semantics: <Expression> is evaluated, and the <formals> are bound to the return
1455values in the same way that the <formals> in a lambda expression are matched to
1456the arguments in a procedure call.
1457
1458    (define-values (x y) (exact-integer-sqrt 17))
1459    (list x y)  ==> (4 1)
1460
1461    (let ()
1462      (define-values (x y) (values 1 2))
1463      (+ x y))      ==> 3
1464
1465=== Syntax definitions
1466
1467Syntax definitions are valid only at the top level of a
1468<program>. They have the following form:
1469
1470<macro>(define-syntax <keyword> <transformer spec>)</macro>
1471
1472{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should
1473be an instance of {{syntax-rules}}.  Note that CHICKEN also supports
1474{{er-macro-transformer}} and {{ir-macro-transformer}} here.  For more
1475information see [[Module (chicken syntax)|the (chicken syntax) module]].
1476
1477The top-level syntactic environment is extended by binding the
1478<keyword> to the specified transformer.
1479
1480In standard Scheme, there is no define-syntax analogue of internal
1481definitions in, but CHICKEN allows these as an extension to the
1482standard.  This means {{define-syntax}} may be used to define local
1483macros that are visible throughout the rest of the body in which the
1484definition occurred, i.e.
1485
1486  (let ()
1487    ...
1488    (define-syntax foo ...)
1489    (define-syntax bar ...)
1490    ...)
1491
1492is expanded into
1493
1494  (let ()
1495    ...
1496    (letrec-syntax ((foo ...) (bar ...))
1497      ...) )
1498
1499{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]
1500in allowing the ellipsis identifier to be user-defined by passing it as the first
1501argument to the {{syntax-rules}} form. Also, "tail" patterns of the form
1502
1503  (syntax-rules ()
1504    ((_ (a b ... c)
1505      ...
1506
1507are supported.
1508
1509The effect of destructively modifying the s-expression passed to a
1510transformer procedure is undefined.
1511
1512Although macros may expand into definitions and syntax definitions in
1513any context that permits them, it is an error for a definition or
1514syntax definition to shadow a syntactic keyword whose meaning is
1515needed to determine whether some form in the group of forms that
1516contains the shadowing definition is in fact a definition, or, for
1517internal definitions, is needed to determine the boundary between the
1518group and the expressions that follow the group. For example, the
1519following are errors:
1520
1521 (define define 3)
1522
1523 (begin (define begin list))
1524
1525 (let-syntax
1526   ((foo (syntax-rules ()
1527           ((foo (proc args ...) body ...)
1528            (define proc
1529              (lambda (args ...)
1530                body ...))))))
1531   (let ((x 3))
1532     (foo (plus x y) (+ x y))
1533     (define foo x)
1534     (plus foo x)))
1535
1536=== Record-type definitions
1537
1538Record-type definitions are used to introduce new data types, called record
1539types. Like other definitions, they can appear either at the outermost level or
1540in a body. The values of a record type are called records and are aggregations
1541of zero or more fields, each of which holds a single location. A predicate, a
1542constructor, and field accessors and mutators are defined for each record type.
1543
1544<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>
1545
1546Syntax: <name> and <pred> are identifiers. The <constructor> is of the form
1547{{(<constructor name> <field name> ...)}} and each <field> is either of the form
1548{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once
1549as a field name. It is also an error for the same identifier to occur more than
1550once as an accessor or mutator name.
1551
1552The define-record-type construct is generative: each use creates a new record
1553type that is distinct from all existing types, including Scheme's predefined
1554types and other record types — even record types of the same name or structure.
1555
1556An instance of define-record-type is equivalent to the following definitions:
1557
1558*   <name> is bound to a representation of the record type itself. This may be
1559    a run-time object or a purely syntactic representation. The representation
1560    is not utilized in this report, but it serves as a means to identify the
1561    record type for use by further language extensions.
1562
1563*   <constructor name> is bound to a procedure that takes as many arguments as
1564    there are <field name>s in the {{(<constructor name> ...)}} subexpression and
1565    returns a new record of type <name>. Fields whose names are listed with
1566    <constructor name> have the corresponding argument as their initial value.
1567    The initial values of all other fields are unspecified. It is an error for
1568    a field name to appear in <constructor> but not as a <field name>.
1569
1570*   <pred> is bound to a predicate that returns #t when given a value returned
1571    by the procedure bound to <constructor name> and #f for everything else.
1572
1573*   Each <accessor name> is bound to a procedure that takes a record of type
1574    <name> and returns the current value of the corresponding field. It is an
1575    error to pass an accessor a value which is not a record of the appropriate
1576    type.
1577
1578*   Each <modifier name> is bound to a procedure that takes a record of type
1579    <name> and a value which becomes the new value of the corresponding field;
1580    an unspecified value is returned. It is an error to pass a modifier a first
1581    argument which is not a record of the appropriate type.
1582
1583For instance, the following record-type definition
1584
1585    (define-record-type <pare>
1586      (kons x y)
1587      pare?
1588      (x kar set-kar!)
1589      (y kdr))
1590
1591defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a
1592modifier, and pare? to be a predicate for instances of <pare>.
1593
1594    (pare? (kons 1 2))         ===> #t
1595      (pare? (cons 1 2))         ===> #f
1596      (kar (kons 1 2))           ===> 1
1597      (kdr (kons 1 2))           ===> 2
1598      (let ((k (kons 1 2)))
1599        (set-kar! k 3)
1600        (kar k))                 ===> 3
1601
1602As an extension the <modifier name> may have the form
1603{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure
1604for the given {{PROCEDURE}} that sets the field value.
1605Usually {{PROCEDURE}} has the same name is <accessor name> (but it
1606doesn't have to).
1607
1608=== Libraries
1609
1610Libraries provide a way to organize Scheme programs into reusable parts with
1611explicitly defined interfaces to the rest of the program. This section defines
1612the notation and semantics for libraries.
1613
1614====  Library Syntax
1615
1616A library definition takes the following form:
1617
1618<macro>(define-library <library name> <library declaration> ...)</macro>
1619
1620<library name> is a list whose members are identifiers and exact non-negative
1621integers. It is used to identify the library uniquely when importing from other
1622programs or libraries. Libraries whose first identifier is scheme are reserved
1623for use by this report and future versions of this report. Libraries whose
1624first identifier is srfi are reserved for libraries implementing Scheme
1625Requests for Implementation. It is inadvisable, but not an error, for
1626identifiers in library names to contain any of the characters | \ ? * < " : > +
1627[ ] / or control characters after escapes are expanded.
1628
1629A <library declaration> is any of:
1630
1631*   {{(export <export spec> ...)}}
1632
1633*   {{(export-all)}}
1634
1635*   {{(import <import set> ...)}}
1636
1637*   {{(begin <command or definition> ...)}}
1638
1639*   {{(include <filename[1]> <filename[2]> ...)}}
1640
1641*   {{(include-ci <filename[1]> <filename[2]> ...)}}
1642
1643*   {{(include-library-declarations <filename[1]> <filename[2]> ...)}}
1644
1645*   {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}
1646
1647An export declaration specifies a list of identifiers which can be made visible
1648to other libraries or programs. An <export spec> takes one of the following
1649forms:
1650
1651* <identifier>
1652
1653* {{(rename <identifier[1]> <identifier[2]>)}}
1654
1655In an <export spec>, an <identifier> names a single binding defined within or
1656imported into the library, where the external name for the export is the same
1657as the name of the binding within the library. A {{rename}} spec exports the
1658binding defined within or imported into the library and named by <identifier
1659[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>
1660as the external name.
1661
1662As an extension to R7RS, CHICKEN allows the {{(export-all)}} specifier,
1663which exports all defined entities to be visible when importing the
1664library.
1665
1666An import declaration provides a way to import the identifiers exported by
1667another library.
1668
1669The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of
1670the library. They have the same syntax and semantics as the corresponding
1671expression types. This form of begin is analogous to, but not the same as, the
1672two types of begin defined in section 4.2.3.
1673
1674The {{include-library-declarations}} declaration is similar to {{include}} except that
1675the contents of the file are spliced directly into the current library
1676definition. This can be used, for example, to share the same export declaration
1677among multiple libraries as a simple form of library interface.
1678
1679The {{cond-expand}} declaration has the same syntax and semantics as the
1680{{cond-expand}} expression type, except that it expands to spliced-in library
1681declarations rather than expressions enclosed in begin.
1682
1683One possible implementation of libraries is as follows: After all {{cond-expand}}
1684library declarations are expanded, a new environment is constructed for the
1685library consisting of all imported bindings. The expressions from all begin,
1686{{include}} and {{include-ci}} library declarations are expanded in that environment in
1687the order in which they occur in the library. Alternatively, {{cond-expand}} and
1688{{import}} declarations may be processed in left to right order interspersed with
1689the processing of other declarations, with the environment growing as imported
1690bindings are added to it by each import declaration.
1691
1692When a library is loaded, its expressions are executed in textual order. If a
1693library's definitions are referenced in the expanded form of a program or
1694library body, then that library must be loaded before the expanded program or
1695library body is evaluated. This rule applies transitively. If a library is
1696imported by more than one program or library, it may possibly be loaded
1697additional times.
1698
1699Similarly, during the expansion of a library (foo), if any syntax keywords
1700imported from another library (bar) are needed to expand the library, then the
1701library (bar) must be expanded and its syntax definitions evaluated before the
1702expansion of (foo).
1703
1704
1705== Standard procedures
1706
1707This chapter describes Scheme's built-in procedures. The initial (or
1708"top level") Scheme environment starts out with a number of variables
1709bound to locations containing useful values, most of which are
1710primitive procedures that manipulate data. For example, the variable
1711abs is bound to (a location initially containing) a procedure of one
1712argument that computes the absolute value of a number, and the variable
1713+ is bound to a procedure that computes sums. Built-in procedures that
1714can easily be written in terms of other built-in procedures are
1715identified as "library procedures".
1716
1717A program may use a top-level definition to bind any variable. It may
1718subsequently alter any such binding by an assignment (see
1719[[#assignments|assignments]], above). These operations do
1720not modify the behavior of Scheme's built-in procedures. Altering any
1721top-level binding that has not been introduced by a definition has an
1722unspecified effect on the behavior of the built-in procedures.
1723
1724=== Equivalence predicates
1725
1726A predicate is a procedure that always returns a boolean value (#t or #f).
1727An equivalence predicate is the computational analogue of a
1728mathematical equivalence relation (it is symmetric, reflexive, and
1729transitive). Of the equivalence predicates described in this section,
1730eq? is the finest or most discriminating, and equal? is the coarsest.
1731eqv? is slightly less discriminating than eq?.
1732
1733<procedure>(eqv? obj[1] obj[2])</procedure><br>
1734
1735The eqv? procedure defines a useful equivalence relation on objects.
1736Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
1737as the same object. This relation is left slightly open to
1738interpretation, but the following partial specification of eqv? holds
1739for all implementations of Scheme.
1740
1741The eqv? procedure returns #t if:
1742
1743*   obj[1] and obj[2] are both #t or both #f.
1744
1745*   obj[1] and obj[2] are both symbols and
1746
1747    (string=? (symbol->string obj1)
1748              (symbol->string obj2))
1749                ===>  #t
1750
1751Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
1752symbol" as alluded to in the section on [[#symbols|symbols]]. This
1753report does not presume to specify the behavior of eqv? on
1754implementation-dependent extensions.
1755
1756*   obj[1] and obj[2] are both numbers, are numerically equal (see =,
1757    under [[#numerical-operations|numerical operations]]), and are
1758    either both exact or both inexact.
1759
1760*   obj[1] and obj[2] are both characters and are the same character
1761    according to the char=? procedure (see "[[#characters|characters]]").
1762
1763*   both obj[1] and obj[2] are the empty list.
1764
1765*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
1766    same locations in the store.
1767
1768*   obj[1] and obj[2] are procedures whose location tags are equal
1769    (see "[[#procedures|procedures]]").
1770
1771The eqv? procedure returns #f if:
1772
1773*   obj[1] and obj[2] are of different types.
1774
1775*   one of obj[1] and obj[2] is #t but the other is #f.
1776
1777*   obj[1] and obj[2] are symbols but
1778
1779    (string=? (symbol->string obj[1])
1780              (symbol->string obj[2]))
1781                ===>  #f
1782
1783*   one of obj[1] and obj[2] is an exact number but the other is an
1784    inexact number.
1785
1786*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
1787
1788*   obj[1] and obj[2] are characters for which the char=? procedure
1789    returns #f.
1790
1791*   one of obj[1] and obj[2] is the empty list but the other is not.
1792
1793*   obj[1] and obj[2] are pairs, vectors, or strings that denote
1794    distinct locations.
1795
1796*   obj[1] and obj[2] are procedures that would behave differently
1797    (return different value(s) or have different side effects) for some
1798    arguments.
1799
1800 (eqv? 'a 'a)                             ===>  #t
1801 (eqv? 'a 'b)                             ===>  #f
1802 (eqv? 2 2)                               ===>  #t
1803 (eqv? '() '())                           ===>  #t
1804 (eqv? 100000000 100000000)               ===>  #t
1805 (eqv? (cons 1 2) (cons 1 2))             ===>  #f
1806 (eqv? (lambda () 1)
1807       (lambda () 2))                     ===>  #f
1808 (eqv? #f 'nil)                           ===>  #f
1809 (let ((p (lambda (x) x)))
1810   (eqv? p p))                            ===>  #t
1811
1812The following examples illustrate cases in which the above rules do not
1813fully specify the behavior of eqv?. All that can be said about such
1814cases is that the value returned by eqv? must be a boolean.
1815
1816 (eqv? "" "")                     ===>  unspecified
1817 (eqv? '#() '#())                 ===>  unspecified
1818 (eqv? (lambda (x) x)
1819       (lambda (x) x))            ===>  unspecified
1820 (eqv? (lambda (x) x)
1821       (lambda (y) y))            ===>  unspecified
1822
1823The next set of examples shows the use of eqv? with procedures that
1824have local state. Gen-counter must return a distinct procedure every
1825time, since each procedure has its own internal counter. Gen-loser,
1826however, returns equivalent procedures each time, since the local state
1827does not affect the value or side effects of the procedures.
1828
1829 (define gen-counter
1830   (lambda ()
1831     (let ((n 0))
1832       (lambda () (set! n (+ n 1)) n))))
1833 (let ((g (gen-counter)))
1834   (eqv? g g))                   ===>  #t
1835 (eqv? (gen-counter) (gen-counter))
1836                                 ===>  #f
1837 (define gen-loser
1838   (lambda ()
1839     (let ((n 0))
1840       (lambda () (set! n (+ n 1)) 27))))
1841 (let ((g (gen-loser)))
1842   (eqv? g g))                   ===>  #t
1843 (eqv? (gen-loser) (gen-loser))
1844                                 ===>  unspecified
1845 
1846 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1847          (g (lambda () (if (eqv? f g) 'both 'g))))
1848   (eqv? f g))
1849                                 ===>  unspecified
1850 
1851 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1852          (g (lambda () (if (eqv? f g) 'g 'both))))
1853   (eqv? f g))
1854                                 ===>  #f
1855
1856Since it is an error to modify constant objects (those returned by
1857literal expressions), implementations are permitted, though not
1858required, to share structure between constants where appropriate. Thus
1859the value of eqv? on constants is sometimes implementation-dependent.
1860
1861 (eqv? '(a) '(a))                         ===>  unspecified
1862 (eqv? "a" "a")                           ===>  unspecified
1863 (eqv? '(b) (cdr '(a b)))                 ===>  unspecified
1864 (let ((x '(a)))
1865   (eqv? x x))                            ===>  #t
1866
1867Rationale:   The above definition of eqv? allows implementations
1868latitude in their treatment of procedures and literals:
1869implementations are free either to detect or to fail to detect that
1870two procedures or two literals are equivalent to each other, and
1871can decide whether or not to merge representations of equivalent
1872objects by using the same pointer or bit pattern to represent both.
1873
1874<procedure>(eq? obj[1] obj[2])</procedure><br>
1875
1876Eq? is similar to eqv? except that in some cases it is capable of
1877discerning distinctions finer than those detectable by eqv?.
1878
1879Eq? and eqv? are guaranteed to have the same behavior on symbols,
1880booleans, the empty list, pairs, procedures, and non-empty strings and
1881vectors. Eq?'s behavior on numbers and characters is
1882implementation-dependent, but it will always return either true or
1883false, and will return true only when eqv? would also return true. Eq?
1884may also behave differently from eqv? on empty vectors and empty
1885strings.
1886
1887 (eq? 'a 'a)                             ===>  #t
1888 (eq? '(a) '(a))                         ===>  unspecified
1889 (eq? (list 'a) (list 'a))               ===>  #f
1890 (eq? "a" "a")                           ===>  unspecified
1891 (eq? "" "")                             ===>  unspecified
1892 (eq? '() '())                           ===>  #t
1893 (eq? 2 2)                               ===>  unspecified
1894 (eq? #\A #\A)                           ===>  unspecified
1895 (eq? car car)                           ===>  #t
1896 (let ((n (+ 2 3)))
1897   (eq? n n))              ===>  unspecified
1898 (let ((x '(a)))
1899   (eq? x x))              ===>  #t
1900 (let ((x '#()))
1901   (eq? x x))              ===>  #t
1902 (let ((p (lambda (x) x)))
1903   (eq? p p))              ===>  #t
1904
1905Rationale:   It will usually be possible to implement eq? much more
1906efficiently than eqv?, for example, as a simple pointer comparison
1907instead of as some more complicated operation. One reason is that
1908it may not be possible to compute eqv? of two numbers in constant
1909time, whereas eq? implemented as pointer comparison will always
1910finish in constant time. Eq? may be used like eqv? in applications
1911using procedures to implement objects with state since it obeys the
1912same constraints as eqv?.
1913
1914<procedure>(equal? obj[1] obj[2])</procedure><br>
1915
1916Equal? recursively compares the contents of pairs, vectors, and
1917strings, applying eqv? on other objects such as numbers and symbols. A
1918rule of thumb is that objects are generally equal? if they print the
1919same. Equal? may fail to terminate if its arguments are circular data
1920structures.
1921
1922 (equal? 'a 'a)                          ===>  #t
1923 (equal? '(a) '(a))                      ===>  #t
1924 (equal? '(a (b) c)
1925         '(a (b) c))                     ===>  #t
1926 (equal? "abc" "abc")                    ===>  #t
1927 (equal? 2 2)                            ===>  #t
1928 (equal? (make-vector 5 'a)
1929         (make-vector 5 'a))             ===>  #t
1930 (equal? (lambda (x) x)
1931         (lambda (y) y))          ===>  unspecified
1932
1933=== Numbers
1934
1935Numerical computation has traditionally been neglected by the Lisp
1936community. Until Common Lisp there was no carefully thought out
1937strategy for organizing numerical computation, and with the exception
1938of the MacLisp system [20] little effort was made to execute numerical
1939code efficiently. This report recognizes the excellent work of the
1940Common Lisp committee and accepts many of their recommendations. In
1941some ways this report simplifies and generalizes their proposals in a
1942manner consistent with the purposes of Scheme.
1943
1944It is important to distinguish between the mathematical numbers, the
1945Scheme numbers that attempt to model them, the machine representations
1946used to implement the Scheme numbers, and notations used to write
1947numbers. This report uses the types number, complex, real, rational,
1948and integer to refer to both mathematical numbers and Scheme numbers.
1949Machine representations such as fixed point and floating point are
1950referred to by names such as fixnum and flonum.
1951
1952==== Numerical types
1953
1954Mathematically, numbers may be arranged into a tower of subtypes in
1955which each level is a subset of the level above it:
1956
1957    number
1958    complex
1959    real
1960    rational
1961    integer
1962
1963For example, 3 is an integer. Therefore 3 is also a rational, a real,
1964and a complex. The same is true of the Scheme numbers that model 3. For
1965Scheme numbers, these types are defined by the predicates number?,
1966complex?, real?, rational?, and integer?.
1967
1968There is no simple relationship between a number's type and its
1969representation inside a computer. Although most implementations of
1970Scheme will offer at least two different representations of 3, these
1971different representations denote the same integer.
1972
1973Scheme's numerical operations treat numbers as abstract data, as
1974independent of their representation as possible. Although an
1975implementation of Scheme may use fixnum, flonum, and perhaps other
1976representations for numbers, this should not be apparent to a casual
1977programmer writing simple programs.
1978
1979It is necessary, however, to distinguish between numbers that are
1980represented exactly and those that may not be. For example, indexes
1981into data structures must be known exactly, as must some polynomial
1982coefficients in a symbolic algebra system. On the other hand, the
1983results of measurements are inherently inexact, and irrational numbers
1984may be approximated by rational and therefore inexact approximations.
1985In order to catch uses of inexact numbers where exact numbers are
1986required, Scheme explicitly distinguishes exact from inexact numbers.
1987This distinction is orthogonal to the dimension of type.
1988
1989==== Exactness
1990
1991Scheme numbers are either exact or inexact. A number is exact if it was
1992written as an exact constant or was derived from exact numbers using
1993only exact operations. A number is inexact if it was written as an
1994inexact constant, if it was derived using inexact ingredients, or if it
1995was derived using inexact operations. Thus inexactness is a contagious
1996property of a number. If two implementations produce exact results for
1997a computation that did not involve inexact intermediate results, the
1998two ultimate results will be mathematically equivalent. This is
1999generally not true of computations involving inexact numbers since
2000approximate methods such as floating point arithmetic may be used, but
2001it is the duty of each implementation to make the result as close as
2002practical to the mathematically ideal result.
2003
2004Rational operations such as + should always produce exact results when
2005given exact arguments. If the operation is unable to produce an exact
2006result, then it may either report the violation of an implementation
2007restriction or it may silently coerce its result to an inexact value.
2008See [[#implementation-restrictions|the next section]].
2009
2010With the exception of inexact->exact, the operations described in this
2011section must generally return inexact results when given any inexact
2012arguments. An operation may, however, return an exact result if it can
2013prove that the value of the result is unaffected by the inexactness of
2014its arguments. For example, multiplication of any number by an exact
2015zero may produce an exact zero result, even if the other argument is
2016inexact.
2017
2018==== Implementation restrictions
2019
2020Implementations of Scheme are not required to implement the whole
2021tower of subtypes given under "[[#Numerical types|Numerical types]]",
2022but they must implement a coherent subset consistent with both the
2023purposes of the implementation and the spirit of the Scheme
2024language. For example, an implementation in which all numbers are real
2025may still be quite useful.
2026
2027Implementations may also support only a limited range of numbers of any
2028type, subject to the requirements of this section. The supported range
2029for exact numbers of any type may be different from the supported range
2030for inexact numbers of that type. For example, an implementation that
2031uses flonums to represent all its inexact real numbers may support a
2032practically unbounded range of exact integers and rationals while
2033limiting the range of inexact reals (and therefore the range of inexact
2034integers and rationals) to the dynamic range of the flonum format.
2035Furthermore the gaps between the representable inexact integers and
2036rationals are likely to be very large in such an implementation as the
2037limits of this range are approached.
2038
2039An implementation of Scheme must support exact integers throughout the
2040range of numbers that may be used for indexes of lists, vectors, and
2041strings or that may result from computing the length of a list, vector,
2042or string. The length, vector-length, and string-length procedures must
2043return an exact integer, and it is an error to use anything but an
2044exact integer as an index. Furthermore any integer constant within the
2045index range, if expressed by an exact integer syntax, will indeed be
2046read as an exact integer, regardless of any implementation restrictions
2047that may apply outside this range. Finally, the procedures listed below
2048will always return an exact integer result provided all their arguments
2049are exact integers and the mathematically expected result is
2050representable as an exact integer within the implementation:
2051
2052 -                     *
2053 +                     abs
2054 ceiling               denominator
2055 exact-integer-sqrt    expt
2056 floor                 floor/
2057 floor-quotient        floor-remainder
2058 gcd                   lcm
2059 max                   min
2060 modulo                numerator
2061 quotient              rationalize
2062 remainder             round
2063 square                truncate
2064 truncate/             truncate-quotient
2065 truncate-remainder
2066
2067CHICKEN follows the IEEE 32-bit and 64-bit floating point
2068standards on all supported platforms.
2069
2070It is the programmer's responsibility to avoid using inexact number objects
2071with magnitude or significand too large to be represented in the
2072implementation.
2073
2074In addition, implementations may distinguish special numbers called positive
2075infinity, negative infinity, NaN, and negative zero.
2076
2077Positive infinity is regarded as an inexact real (but not rational) number that
2078represents an indeterminate value greater than the numbers represented by all
2079rational numbers. Negative infinity is regarded as an inexact real (but not
2080rational) number that represents an indeterminate value less than the numbers
2081represented by all rational numbers.
2082
2083Adding or multiplying an infinite value by any finite real value results in an
2084appropriately signed infinity; however, the sum of positive and negative
2085infinities is a NaN. Positive infinity is the reciprocal of zero, and negative
2086infinity is the reciprocal of negative zero. The behavior of the transcendental
2087functions is sensitive to infinity in accordance with IEEE 754.
2088
2089A NaN is regarded as an inexact real (but not rational) number so indeterminate
2090that it might represent any real value, including positive or negative
2091infinity, and might even be greater than positive infinity or less than
2092negative infinity. An implementation that does not support non-real numbers may
2093use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).
2094
2095A NaN always compares false to any number, including a NaN. An arithmetic
2096operation where one operand is NaN returns NaN, unless the implementation can
2097prove that the result would be the same if the NaN were replaced by any
2098rational number. Dividing zero by zero results in NaN unless both zeros are
2099exact.
2100
2101Negative zero is an inexact real value written -0.0 and is distinct (in the
2102sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish
2103negative zero. If it does, however, the behavior of the transcendental
2104functions is sensitive to the distinction in accordance with IEEE 754.
2105Specifically, in a Scheme implementing both complex numbers and negative zero,
2106the branch cut of the complex logarithm function is such that (imag-part (log
2107-1.0-0.0i)) is --π rather than π.
2108
2109Furthermore, the negation of negative zero is ordinary zero and vice versa.
2110This implies that the sum of two or more negative zeros is negative, and the
2111result of subtracting (positive) zero from a negative zero is likewise
2112negative. However, numerical comparisons treat negative zero as equal to zero.
2113
2114Note that both the real and the imaginary parts of a complex number can be
2115infinities, NaNs, or negative zero.
2116
2117
2118==== Syntax of numerical constants
2119
2120For a complete formal description of the syntax of the written
2121representations for numbers, see the R7RS report. Note that case is
2122not significant in numerical constants.
2123
2124A number may be written in binary, octal, decimal, or hexadecimal by
2125the use of a radix prefix. The radix prefixes are #b (binary), #o
2126(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
2127number is assumed to be expressed in decimal.
2128
2129A numerical constant may be specified to be either exact or inexact by
2130a prefix. The prefixes are #e for exact, and #i for inexact. An
2131exactness prefix may appear before or after any radix prefix that is
2132used. If the written representation of a number has no exactness
2133prefix, the constant may be either inexact or exact. It is inexact if
2134it contains a decimal point, an exponent, or a "#" character in the
2135place of a digit, otherwise it is exact. In systems with inexact
2136numbers of varying precisions it may be useful to specify the precision
2137of a constant. For this purpose, numerical constants may be written
2138with an exponent marker that indicates the desired precision of the
2139inexact representation. The letters s, f, d, and l specify the use of
2140short, single, double, and long precision, respectively. (When fewer
2141than four internal inexact representations exist, the four size
2142specifications are mapped onto those available. For example, an
2143implementation with two internal representations may map short and
2144single together and long and double together.) In addition, the
2145exponent marker e specifies the default precision for the
2146implementation. The default precision has at least as much precision as
2147double, but implementations may wish to allow this default to be set by
2148the user.
2149
2150 3.14159265358979F0
2151         Round to single --- 3.141593
2152 0.6L0
2153         Extend to long --- .600000000000000
2154
2155==== Numerical operations
2156
2157The numerical routines described below have argument restrictions,
2158which are encoded in the naming conventions of the arguments as
2159given in the procedure's signature.  The conventions are as follows:
2160
2161; {{obj}} : any object
2162; {{list, list1, ... listj, ...	list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)
2163; {{z, z1, ... zj, ...}} : complex number
2164; {{x, x1, ... xj, ...}} : real number
2165; {{y, y1, ... yj, ...}} : real number
2166; {{q, q1, ... qj, ...}} : rational number
2167; {{n, n1, ... nj, ...}} : integer
2168; {{k, k1, ... kj, ...}} : exact non-negative integer
2169
2170The examples used in this section assume that any
2171numerical constant written using an exact notation is indeed
2172represented as an exact number. Some examples also assume that certain
2173numerical constants written using an inexact notation can be
2174represented without loss of accuracy; the inexact constants were chosen
2175so that this is likely to be true in implementations that use flonums
2176to represent inexact numbers.
2177
2178<procedure>(number? obj)</procedure><br>
2179<procedure>(complex? obj)</procedure><br>
2180<procedure>(real? obj)</procedure><br>
2181<procedure>(rational? obj)</procedure><br>
2182<procedure>(integer? obj)</procedure><br>
2183
2184These numerical type predicates can be applied to any kind of argument,
2185including non-numbers. They return #t if the object is of the named
2186type, and otherwise they return #f. In general, if a type predicate is
2187true of a number then all higher type predicates are also true of that
2188number. Consequently, if a type predicate is false of a number, then
2189all lower type predicates are also false of that number. If z is an
2190inexact complex number, then (real? z) is true if and only if (zero?
2191(imag-part z)) is true. If x is an inexact real number, then (integer?
2192x) is true if and only if (= x (round x)).
2193
2194 (complex? 3+4i)                 ===>  #t
2195 (complex? 3)                    ===>  #t
2196 (real? 3)                       ===>  #t
2197 (real? -2.5+0.0i)               ===>  #t
2198 (real? #e1e10)                  ===>  #t
2199 (rational? 6/10)                ===>  #t
2200 (rational? 6/3)                 ===>  #t
2201 (integer? 3+0i)                 ===>  #t
2202 (integer? 3.0)                  ===>  #t
2203 (integer? 8/4)                  ===>  #t
2204
2205Note:   The behavior of these type predicates on inexact numbers is
2206unreliable, since any inaccuracy may affect the result.
2207
2208Note:   In many implementations the rational? procedure will be the
2209same as real?, and the complex? procedure will be the same as
2210number?, but unusual implementations may be able to represent some
2211irrational numbers exactly or may extend the number system to
2212support some kind of non-complex numbers.
2213
2214<procedure>(exact? z)</procedure><br>
2215<procedure>(inexact? z)</procedure><br>
2216
2217These numerical predicates provide tests for the exactness of a
2218quantity. For any Scheme number, precisely one of these predicates is
2219true.
2220
2221<procedure>(exact-integer? z)</procedure>
2222
2223Returns #t if z is both exact and an integer; otherwise returns #f.
2224
2225 (exact-integer? 32)  ===> #t
2226 (exact-integer? 32.0)  ===> #f
2227 (exact-integer? 32/5)  ===> #f
2228
2229<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
2230<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
2231<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
2232<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
2233<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
2234
2235These procedures return #t if their arguments are (respectively):
2236equal, monotonically increasing, monotonically decreasing,
2237monotonically nondecreasing, or monotonically nonincreasing.
2238
2239These predicates are required to be transitive.
2240
2241Note:   The traditional implementations of these predicates in
2242Lisp-like languages are not transitive.
2243
2244Note:   While it is not an error to compare inexact numbers using
2245these predicates, the results may be unreliable because a small
2246inaccuracy may affect the result; this is especially true of = and
2247zero?. When in doubt, consult a numerical analyst.
2248
2249<procedure>(zero? z)</procedure><br>
2250<procedure>(positive? x)</procedure><br>
2251<procedure>(negative? x)</procedure><br>
2252<procedure>(odd? n)</procedure><br>
2253<procedure>(even? n)</procedure><br>
2254
2255These numerical predicates test a number for a particular property,
2256returning #t or #f. See note above.
2257
2258<procedure>(max x[1] x[2] ...)</procedure><br>
2259<procedure>(min x[1] x[2] ...)</procedure><br>
2260
2261These procedures return the maximum or minimum of their arguments.
2262
2263 (max 3 4)                      ===>  4    ; exact
2264 (max 3.9 4)                    ===>  4.0  ; inexact
2265
2266Note:   If any argument is inexact, then the result will also be
2267inexact (unless the procedure can prove that the inaccuracy is not
2268large enough to affect the result, which is possible only in
2269unusual implementations). If min or max is used to compare numbers
2270of mixed exactness, and the numerical value of the result cannot be
2271represented as an inexact number without loss of accuracy, then the
2272procedure may report a violation of an implementation restriction.
2273
2274<procedure>(+ z[1] ...)</procedure><br>
2275<procedure>(* z[1] ...)</procedure><br>
2276
2277These procedures return the sum or product of their arguments.
2278
2279 (+ 3 4)                         ===>  7
2280 (+ 3)                           ===>  3
2281 (+)                             ===>  0
2282 (* 4)                           ===>  4
2283 (*)                             ===>  1
2284
2285<procedure>(- z[1] z[2])</procedure><br>
2286<procedure>(- z)</procedure><br>
2287<procedure>(- z[1] z[2] ...)</procedure><br>
2288<procedure>(/ z[1] z[2])</procedure><br>
2289<procedure>(/ z)</procedure><br>
2290<procedure>(/ z[1] z[2] ...)</procedure><br>
2291
2292With two or more arguments, these procedures return the difference or
2293quotient of their arguments, associating to the left. With one
2294argument, however, they return the additive or multiplicative inverse
2295of their argument.
2296
2297 (- 3 4)                         ===>  -1
2298 (- 3 4 5)                       ===>  -6
2299 (- 3)                           ===>  -3
2300 (/ 3 4 5)                       ===>  3/20
2301 (/ 3)                           ===>  1/3
2302
2303<procedure>(abs x)</procedure><br>
2304
2305Abs returns the absolute value of its argument.
2306
2307 (abs -7)                        ===>  7
2308
2309<procedure>(floor/ n[1] n[2])</procedure><br>
2310<procedure>(floor-quotient n[1] n[2])</procedure><br>
2311<procedure>(floor-remainder n[1] n[2])</procedure><br>
2312<procedure>(truncate/ n[1] n[2])</procedure><br>
2313<procedure>(truncate-quotient n[1] n[2])</procedure><br>
2314<procedure>(truncate-remainder n[1] n[2])</procedure><br>
2315
2316These procedures implement number-theoretic (integer) division. It is an error
2317if n[2] is zero. The procedures ending in / return two integers; the other
2318procedures return an integer. All the procedures compute a quotient n[q] and remainder
2319n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as
2320follows:
2321
2322 (<operator>/ n[1] n[2]) ==> n[q] n[r]
2323 (<operator>-quotient n[1] n[2]) ==> n[q]
2324 (<operator>-remainder n[1] n[2]) ==> n[r]
2325
2326The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] -- n[2] * n[q]. Each set of operators uses a different choice of n[q]:
2327
2328 floor    n[q] = ⌊n[1] / n[2]⌋
2329 truncate n[q] = runcate(n[1] / n[2])
2330
2331For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,
2332
2333 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))
2334         (<operator>-remainder n[1] n[2])))
2335         ==> #t
2336
2337provided all numbers involved in that computation are exact.
2338
2339Examples:
2340
2341 (floor/ 5 2)          ==> 2 1
2342 (floor/ -5 2)         ==> -3 1
2343 (floor/ 5 -2)         ==> -3 -1
2344 (floor/ -5 -2)        ==> 2 -1
2345 (truncate/ 5 2)       ==> 2 1
2346 (truncate/ -5 2)      ==> -2 -1
2347 (truncate/ 5 -2)      ==> -2 1
2348 (truncate/ -5 -2)     ==> 2 -1
2349 (truncate/ -5.0 -2)   ==> 2.0 -1.0
2350
2351<procedure>(quotient n[1] n[2])</procedure><br>
2352<procedure>(remainder n[1] n[2])</procedure><br>
2353<procedure>(modulo n[1] n[2])</procedure><br>
2354
2355These procedures implement number-theoretic (integer) division. n[2]
2356should be non-zero. All three procedures return integers. If n[1]/n[2]
2357is an integer:
2358
2359    (quotient n[1] n[2])           ===> n[1]/n[2]
2360    (remainder n[1] n[2])          ===> 0
2361    (modulo n[1] n[2])             ===> 0
2362
2363If n[1]/n[2] is not an integer:
2364
2365    (quotient n[1] n[2])           ===> n[q]
2366    (remainder n[1] n[2])          ===> n[r]
2367    (modulo n[1] n[2])             ===> n[m]
2368
2369where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
2370|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
2371n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
2372
2373From this we can conclude that for integers n[1] and n[2] with n[2] not
2374equal to 0,
2375
2376     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
2377           (remainder n[1] n[2])))
2378                                         ===>  #t
2379
2380provided all numbers involved in that computation are exact.
2381
2382 (modulo 13 4)                   ===>  1
2383 (remainder 13 4)                ===>  1
2384 
2385 (modulo -13 4)                  ===>  3
2386 (remainder -13 4)               ===>  -1
2387 
2388 (modulo 13 -4)                  ===>  -3
2389 (remainder 13 -4)               ===>  1
2390 
2391 (modulo -13 -4)                 ===>  -1
2392 (remainder -13 -4)              ===>  -1
2393 
2394 (remainder -13 -4.0)            ===>  -1.0  ; inexact
2395
2396<procedure>(gcd n[1] ...)</procedure><br>
2397<procedure>(lcm n[1] ...)</procedure><br>
2398
2399These procedures return the greatest common divisor or least common
2400multiple of their arguments. The result is always non-negative.
2401
2402 (gcd 32 -36)                    ===>  4
2403 (gcd)                           ===>  0
2404 (lcm 32 -36)                    ===>  288
2405 (lcm 32.0 -36)                  ===>  288.0  ; inexact
2406 (lcm)                           ===>  1
2407
2408<procedure>(numerator q)</procedure><br>
2409<procedure>(denominator q)</procedure><br>
2410
2411These procedures return the numerator or denominator of their argument;
2412the result is computed as if the argument was represented as a fraction
2413in lowest terms. The denominator is always positive. The denominator of
24140 is defined to be 1.
2415
2416 (numerator (/ 6 4))            ===>  3
2417 (denominator (/ 6 4))          ===>  2
2418 (denominator
2419   (exact->inexact (/ 6 4)))    ===> 2.0
2420
2421<procedure>(floor x)</procedure><br>
2422<procedure>(ceiling x)</procedure><br>
2423<procedure>(truncate x)</procedure><br>
2424<procedure>(round x)</procedure><br>
2425
2426These procedures return integers. Floor returns the largest integer not
2427larger than x. Ceiling returns the smallest integer not smaller than x.
2428Truncate returns the integer closest to x whose absolute value is not
2429larger than the absolute value of x. Round returns the closest integer
2430to x, rounding to even when x is halfway between two integers.
2431
2432Rationale:   Round rounds to even for consistency with the default
2433rounding mode specified by the IEEE floating point standard.
2434
2435Note:   If the argument to one of these procedures is inexact, then
2436the result will also be inexact. If an exact value is needed, the
2437result should be passed to the inexact->exact procedure.
2438
2439 (floor -4.3)                  ===>  -5.0
2440 (ceiling -4.3)                ===>  -4.0
2441 (truncate -4.3)               ===>  -4.0
2442 (round -4.3)                  ===>  -4.0
2443 
2444 (floor 3.5)                   ===>  3.0
2445 (ceiling 3.5)                 ===>  4.0
2446 (truncate 3.5)                ===>  3.0
2447 (round 3.5)                   ===>  4.0  ; inexact
2448 
2449 (round 7/2)                   ===>  4    ; exact
2450 (round 7)                     ===>  7
2451
2452<procedure>(rationalize x y)</procedure><br>
2453
2454Rationalize returns the simplest rational number differing from x by no
2455more than y. A rational number r[1] is simpler than another rational
2456number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
2457and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
2458Although not all rationals are comparable in this ordering (consider 2/
24597 and 3/5) any interval contains a rational number that is simpler than
2460every other rational number in that interval (the simpler 2/5 lies
2461between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
2462all.
2463
2464 (rationalize
2465   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
2466 (rationalize .3 1/10)                ===> #i1/3  ; inexact
2467
2468<procedure>(square z)</procedure>
2469
2470Returns the square of z. This is equivalent to {{(* z z)}}-
2471
2472 (square 42)        ==> 1764
2473 (square 2.0)      ==> 4.0
2474
2475<procedure>(exact-integer-sqrt k)</procedure>
2476
2477Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.
2478
2479 (exact-integer-sqrt 4)  ==> 2 0
2480 (exact-integer-sqrt 5)  ==> 2 1
2481
2482<procedure>(expt z[1] z[2])</procedure><br>
2483
2484Returns z[1] raised to the power z[2]. For z[1] != 0
2485
2486 z[1]^z[2] = e^z[2] log z[1]
2487
24880^z is 1 if z = 0 and 0 otherwise.
2489
2490<procedure>(exact z)</procedure><br>
2491<procedure>(inexact z)</procedure><br>
2492
2493The procedure {{inexact}}  returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the
2494argument. For inexact arguments, the result is the same as the argument. For
2495exact complex numbers, the result is a complex number whose real and imaginary
2496parts are the result of applying inexact to the real and imaginary parts of the
2497argument, respectively. If an exact argument has no reasonably close inexact
2498equivalent (in the sense of =), then a violation of an implementation
2499restriction may be reported.
2500
2501The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the
2502argument. For exact arguments, the result is the same as the argument. For
2503inexact non-integral real arguments, the implementation may return a rational
2504approximation, or may report an implementation violation. For inexact complex
2505arguments, the result is a complex number whose real and imaginary parts are
2506the result of applying exact to the real and imaginary parts of the argument,
2507respectively. If an inexact argument has no reasonably close exact equivalent,
2508(in the sense of =), then a violation of an implementation restriction may be
2509reported.
2510
2511==== Numerical input and output
2512
2513<procedure>(number->string z [radix])</procedure>
2514
2515Radix must be an exact integer.  The R7RS standard only requires
2516implementations to support 2, 8, 10, or 16, but CHICKEN allows any
2517radix between 2 and 36, inclusive (note: due to a bug, flonums with
2518fractional components always use radix 10, irrespective of the argument).
2519If omitted, radix defaults to 10. The procedure number->string takes
2520a number and a radix and returns as a string an external
2521representation of the given number in the given radix such that
2522
2523 (let ((number number)
2524       (radix radix))
2525   (eqv? number
2526         (string->number (number->string number
2527                                         radix)
2528                         radix)))
2529
2530is true. It is an error if no possible result makes this expression
2531true.
2532
2533If z is inexact, the radix is 10, and the above expression can be
2534satisfied by a result that contains a decimal point, then the result
2535contains a decimal point and is expressed using the minimum number of
2536digits (exclusive of exponent and trailing zeroes) needed to make the
2537above expression true [3, 5]; otherwise the format of the result is
2538unspecified.
2539
2540The result returned by number->string never contains an explicit radix
2541prefix.
2542
2543Note:   The error case can occur only when z is not a complex
2544number or is a complex number with a non-rational real or imaginary
2545part.
2546
2547Rationale:   If z is an inexact number represented using flonums,
2548and the radix is 10, then the above expression is normally
2549satisfied by a result containing a decimal point. The unspecified
2550case allows for infinities, NaNs, and non-flonum representations.
2551
2552As an extension to R7RS, CHICKEN supports reading and writing the
2553special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
2554as well as negative zero.
2555
2556<procedure>(string->number string)</procedure><br>
2557<procedure>(string->number string radix)</procedure><br>
2558
2559Returns a number of the maximally precise representation expressed by
2560the given string.  Radix must be an exact integer.  The R7RS standard
2561only requires implementations to support 2, 8, 10, or 16, but CHICKEN
2562allows any radix between 2 and 36, inclusive.  If supplied, radix is a
2563default radix that may be overridden by an explicit radix prefix in
2564string (e.g. "#o177"). If radix is not supplied, then the default
2565radix is 10. If string is not a syntactically valid notation for a
2566number, then string->number returns #f.
2567
2568If the radix is higher than 18, the parser treats ambiguous syntax
2569that might be a complex number, like {{{"+i"}}} and {{{"-i"}}} (and
2570any prefixes like {{{"+1234i"}}}), as an integer.  If you want this to
2571be parsed as a complex number, explicitly write down {{{"0+i"}}} to
2572disambiguate.  Note that {{{number->string}}} will always emit complex
2573numbers using the full notation, so it can always be read back by
2574{{{string->number}}}.
2575
2576 (string->number "100")                ===>  100
2577 (string->number "100" 16)             ===>  256
2578 (string->number "1e2")                ===>  100.0
2579 (string->number "15##")               ===>  1500.0
2580
2581Note:   The domain of string->number may be restricted by
2582implementations in the following ways. String->number is permitted
2583to return #f whenever string contains an explicit radix prefix. If
2584all numbers supported by an implementation are real, then string->
2585number is permitted to return #f whenever string uses the polar or
2586rectangular notations for complex numbers. If all numbers are
2587integers, then string->number may return #f whenever the fractional
2588notation is used. If all numbers are exact, then string->number may
2589return #f whenever an exponent marker or explicit exactness prefix
2590is used, or if a # appears in place of a digit. If all inexact
2591numbers are integers, then string->number may return #f whenever a
2592decimal point is used.
2593
2594=== Other data types
2595
2596This section describes operations on some of Scheme's non-numeric data
2597types: booleans, pairs, lists, symbols, characters, strings and
2598vectors.
2599
2600==== Booleans
2601
2602The standard boolean objects for true and false are written as #t and #f.
2603What really matters, though, are the objects that the Scheme
2604conditional expressions (if, cond, and, or, do) treat as true or false.
2605The phrase "a true value" (or sometimes just "true") means any
2606object treated as true by the conditional expressions, and the phrase
2607"a false value" (or "false") means any object treated as false by
2608the conditional expressions.
2609
2610Of all the standard Scheme values, only #f counts as false in
2611conditional expressions. Except for #f, all standard Scheme values,
2612including #t, pairs, the empty list, symbols, numbers, strings,
2613vectors, and procedures, count as true.
2614
2615Note:   Programmers accustomed to other dialects of Lisp should be
2616aware that Scheme distinguishes both #f and the empty list from the
2617symbol nil.
2618
2619Boolean constants evaluate to themselves, so they do not need to be
2620quoted in programs.
2621
2622 #t                ===>  #t
2623 #f                ===>  #f
2624 '#f               ===>  #f
2625
2626<procedure>(not obj)</procedure><br>
2627
2628Not returns #t if obj is false, and returns #f otherwise.
2629
2630 (not #t)           ===>  #f
2631 (not 3)            ===>  #f
2632 (not (list 3))     ===>  #f
2633 (not #f)           ===>  #t
2634 (not '())          ===>  #f
2635 (not (list))       ===>  #f
2636 (not 'nil)         ===>  #f
2637
2638<procedure>(boolean? obj)</procedure><br>
2639
2640Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
2641
2642 (boolean? #f)                 ===>  #t
2643 (boolean? 0)                  ===>  #f
2644 (boolean? '())                ===>  #f
2645
2646<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>
2647
2648Returns #t if all the arguments are #t or all are #f.
2649
2650==== Pairs and lists
2651
2652A pair (sometimes called a dotted pair) is a record structure with two
2653fields called the car and cdr fields (for historical reasons). Pairs
2654are created by the procedure cons. The car and cdr fields are accessed
2655by the procedures car and cdr. The car and cdr fields are assigned by
2656the procedures set-car! and set-cdr!.
2657
2658Pairs are used primarily to represent lists. A list can be defined
2659recursively as either the empty list or a pair whose cdr is a list.
2660More precisely, the set of lists is defined as the smallest set X such
2661that
2662
2663*   The empty list is in X.
2664*   If list is in X, then any pair whose cdr field contains list is
2665    also in X.
2666
2667The objects in the car fields of successive pairs of a list are the
2668elements of the list. For example, a two-element list is a pair whose
2669car is the first element and whose cdr is a pair whose car is the
2670second element and whose cdr is the empty list. The length of a list is
2671the number of elements, which is the same as the number of pairs.
2672
2673The empty list is a special object of its own type (it is not a pair);
2674it has no elements and its length is zero.
2675
2676Note:   The above definitions imply that all lists have finite
2677length and are terminated by the empty list.
2678
2679The most general notation (external representation) for Scheme pairs is
2680the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
2681car field and c[2] is the value of the cdr field. For example (4 . 5)
2682is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
2683external representation of a pair, not an expression that evaluates to
2684a pair.
2685
2686A more streamlined notation can be used for lists: the elements of the
2687list are simply enclosed in parentheses and separated by spaces. The
2688empty list is written () . For example,
2689
2690 (a b c d e)
2691
2692and
2693
2694 (a . (b . (c . (d . (e . ())))))
2695
2696are equivalent notations for a list of symbols.
2697
2698A chain of pairs not ending in the empty list is called an improper
2699list. Note that an improper list is not a list. The list and dotted
2700notations can be combined to represent improper lists:
2701
2702 (a b c . d)
2703
2704is equivalent to
2705
2706 (a . (b . (c . d)))
2707
2708Whether a given pair is a list depends upon what is stored in the cdr
2709field. When the set-cdr! procedure is used, an object can be a list one
2710moment and not the next:
2711
2712 (define x (list 'a 'b 'c))
2713 (define y x)
2714 y                               ===>  (a b c)
2715 (list? y)                       ===>  #t
2716 (set-cdr! x 4)                  ===>  unspecified
2717 x                               ===>  (a . 4)
2718 (eqv? x y)                      ===>  #t
2719 y                               ===>  (a . 4)
2720 (list? y)                       ===>  #f
2721 (set-cdr! x x)                  ===>  unspecified
2722 (list? x)                       ===>  #f
2723
2724Within literal expressions and representations of objects read by the
2725read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2726denote two-element lists whose first elements are the symbols quote,
2727quasiquote, unquote, and unquote-splicing, respectively. The second
2728element in each case is <datum>. This convention is supported so that
2729arbitrary Scheme programs may be represented as lists. That is,
2730according to Scheme's grammar, every <expression> is also a <datum>.
2731Among other things, this permits the use of the read procedure to
2732parse Scheme programs.
2733
2734<procedure>(pair? obj)</procedure><br>
2735
2736Pair? returns #t if obj is a pair, and otherwise returns #f.
2737
2738 (pair? '(a . b))                ===>  #t
2739 (pair? '(a b c))                ===>  #t
2740 (pair? '())                     ===>  #f
2741 (pair? '#(a b))                 ===>  #f
2742
2743<procedure>(cons obj[1] obj[2])</procedure><br>
2744
2745Returns a newly allocated pair whose car is obj[1] and whose cdr is
2746obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2747from every existing object.
2748
2749 (cons 'a '())                   ===>  (a)
2750 (cons '(a) '(b c d))            ===>  ((a) b c d)
2751 (cons "a" '(b c))               ===>  ("a" b c)
2752 (cons 'a 3)                     ===>  (a . 3)
2753 (cons '(a b) 'c)                ===>  ((a b) . c)
2754
2755<procedure>(car pair)</procedure><br>
2756
2757Returns the contents of the car field of pair. Note that it is an error
2758to take the car of the empty list.
2759
2760 (car '(a b c))                  ===>  a
2761 (car '((a) b c d))              ===>  (a)
2762 (car '(1 . 2))                  ===>  1
2763 (car '())                       ===>  error
2764
2765<procedure>(cdr pair)</procedure><br>
2766
2767Returns the contents of the cdr field of pair. Note that it is an error
2768to take the cdr of the empty list.
2769
2770 (cdr '((a) b c d))              ===>  (b c d)
2771 (cdr '(1 . 2))                  ===>  2
2772 (cdr '())                       ===>  error
2773
2774<procedure>(set-car! pair obj)</procedure><br>
2775
2776Stores obj in the car field of pair. The value returned by set-car! is
2777unspecified.
2778
2779 (define (f) (list 'not-a-constant-list))
2780 (define (g) '(constant-list))
2781 (set-car! (f) 3)                     ===>  unspecified
2782 (set-car! (g) 3)                     ===>  error
2783
2784<procedure>(set-cdr! pair obj)</procedure><br>
2785
2786Stores obj in the cdr field of pair. The value returned by set-cdr! is
2787unspecified.
2788
2789<procedure>(null? obj)</procedure><br>
2790
2791Returns #t if obj is the empty list, otherwise returns #f.
2792
2793<procedure>(list? obj)</procedure><br>
2794
2795Returns #t if obj is a list, otherwise returns #f. By definition, all
2796lists have finite length and are terminated by the empty list.
2797
2798 (list? '(a b c))             ===>  #t
2799 (list? '())                  ===>  #t
2800 (list? '(a . b))             ===>  #f
2801 (let ((x (list 'a)))
2802   (set-cdr! x x)
2803   (list? x))                 ===>  #f
2804
2805<procedure>(make-list k [fill])</procedure>
2806
2807Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.
2808
2809 (make-list 2 3)    ==>   (3 3)
2810
2811<procedure>(list obj ...)</procedure><br>
2812
2813Returns a newly allocated list of its arguments.
2814
2815 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
2816 (list)                                  ===>  ()
2817
2818<procedure>(length list)</procedure><br>
2819
2820Returns the length of list.
2821
2822 (length '(a b c))                       ===>  3
2823 (length '(a (b) (c d e)))               ===>  3
2824 (length '())                            ===>  0
2825
2826<procedure>(append list ...)</procedure><br>
2827
2828Returns a list consisting of the elements of the first list followed by
2829the elements of the other lists.
2830
2831 (append '(x) '(y))                      ===>  (x y)
2832 (append '(a) '(b c d))                  ===>  (a b c d)
2833 (append '(a (b)) '((c)))                ===>  (a (b) (c))
2834
2835The resulting list is always newly allocated, except that it shares
2836structure with the last list argument. The last argument may actually
2837be any object; an improper list results if the last argument is not a
2838proper list.
2839
2840 (append '(a b) '(c . d))                ===>  (a b c . d)
2841 (append '() 'a)                         ===>  a
2842
2843<procedure>(reverse list)</procedure><br>
2844
2845Returns a newly allocated list consisting of the elements of list in
2846reverse order.
2847
2848 (reverse '(a b c))                      ===>  (c b a)
2849 (reverse '(a (b c) d (e (f))))
2850                 ===>  ((e (f)) d (b c) a)
2851
2852<procedure>(list-tail list k)</procedure><br>
2853
2854Returns the sublist of list obtained by omitting the first k elements.
2855It is an error if list has fewer than k elements. List-tail could be
2856defined by
2857
2858 (define list-tail
2859   (lambda (x k)
2860     (if (zero? k)
2861         x
2862         (list-tail (cdr x) (- k 1)))))
2863
2864<procedure>(list-ref list k)</procedure><br>
2865
2866Returns the kth element of list. (This is the same as the car of
2867(list-tail list k).) It is an error if list has fewer than k elements.
2868
2869 (list-ref '(a b c d) 2)                ===>  c
2870 (list-ref '(a b c d)
2871           (inexact->exact (round 1.8)))
2872                 ===>  c
2873
2874<procedure>(list-set! list k obj)</procedure>
2875
2876It is an error if k is not a valid index of list.
2877
2878The {{list-set!}} procedure stores obj in element k of list.
2879
2880 (let ((ls (list 'one 'two 'five!)))
2881   (list-set! ls 2 'three)
2882   ls)
2883 ==>  (one two three)
2884
2885 (list-set! '(0 1 2) 1 "oops")
2886 ==> error  ; constant list
2887
2888<procedure>(memq obj list)</procedure><br>
2889<procedure>(memv obj list)</procedure><br>
2890<procedure>(member obj list [compare])</procedure><br>
2891
2892These procedures return the first sublist of list whose car is obj,
2893where the sublists of list are the non-empty lists returned by
2894{{(list-tail list k)}} for k less than the length of list. If obj does not
2895occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}
2896to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and
2897member {{compare}} if given, and {{equal?}} otherwise.
2898
2899 (memq 'a '(a b c))                      ===>  (a b c)
2900 (memq 'b '(a b c))                      ===>  (b c)
2901 (memq 'a '(b c d))                      ===>  #f
2902 (memq (list 'a) '(b (a) c))             ===>  #f
2903 (member (list 'a)
2904         '(b (a) c))                     ===>  ((a) c)
2905 (memq 101 '(100 101 102))               ===>  unspecified
2906 (memv 101 '(100 101 102))               ===>  (101 102)
2907
2908<procedure>(assq obj alist)</procedure><br>
2909<procedure>(assv obj alist)</procedure><br>
2910<procedure>(assoc obj alist [compare])</procedure><br>
2911
2912Alist (for "association list") must be a list of pairs. These
2913procedures find the first pair in alist whose car field is obj, and
2914returns that pair. If no pair in alist has obj as its car, then #f (not
2915the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car
2916fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses
2917{{compare}}, if given, otherwise {{equal?}}.
2918
2919 (define e '((a 1) (b 2) (c 3)))
2920 (assq 'a e)             ===>  (a 1)
2921 (assq 'b e)             ===>  (b 2)
2922 (assq 'd e)             ===>  #f
2923 (assq (list 'a) '(((a)) ((b)) ((c))))
2924                         ===>  #f
2925 (assoc (list 'a) '(((a)) ((b)) ((c))))
2926                                    ===>  ((a))
2927 (assq 5 '((2 3) (5 7) (11 13)))
2928                                    ===>  unspecified
2929 (assv 5 '((2 3) (5 7) (11 13)))
2930                                    ===>  (5 7)
2931
2932Rationale:   Although they are ordinarily used as predicates, memq,
2933memv, member, assq, assv, and assoc do not have question marks in
2934their names because they return useful values rather than just #t
2935or #f.
2936
2937<procedure>(list-copy obj)</procedure>
2938
2939Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in
2940the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if
2941obj is a circular list.
2942
2943 (define a '(1 8 2 8)) ; a may be immutable
2944 (define b (list-copy a))
2945 (set-car! b 3)        ; b is mutable
2946 b  ==> (3 8 2 8)
2947 a  ==> (1 8 2 8)
2948
2949==== Symbols
2950
2951Symbols are objects whose usefulness rests on the fact that two symbols
2952are identical (in the sense of eqv?) if and only if their names are
2953spelled the same way. This is exactly the property needed to represent
2954identifiers in programs, and so most implementations of Scheme use them
2955internally for that purpose. Symbols are useful for many other
2956applications; for instance, they may be used the way enumerated values
2957are used in Pascal.
2958
2959The rules for writing a symbol are exactly the same as the rules for
2960writing an identifier.
2961
2962It is guaranteed that any symbol that has been returned as part of a
2963literal expression, or read using the read procedure, and subsequently
2964written out using the write procedure, will read back in as the
2965identical symbol (in the sense of eqv?). The string->symbol procedure,
2966however, can create symbols for which this write/read invariance may
2967not hold because their names contain special characters or letters in
2968the non-standard case.
2969
2970Note:   Some implementations of Scheme have a feature known as
2971"slashification" in order to guarantee write/read invariance for
2972all symbols, but historically the most important use of this
2973feature has been to compensate for the lack of a string data type.
2974
2975Some implementations also have "uninterned symbols", which defeat
2976write/read invariance even in implementations with slashification,
2977and also generate exceptions to the rule that two symbols are the
2978same if and only if their names are spelled the same.
2979
2980<procedure>(symbol? obj)</procedure><br>
2981
2982Returns #t if obj is a symbol, otherwise returns #f.
2983
2984 (symbol? 'foo)                  ===>  #t
2985 (symbol? (car '(a b)))          ===>  #t
2986 (symbol? "bar")                 ===>  #f
2987 (symbol? 'nil)                  ===>  #t
2988 (symbol? '())                   ===>  #f
2989 (symbol? #f)                    ===>  #f
2990
2991<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>
2992
2993Returns #t if all the arguments all have the same names in the sense of {{string=?}}.
2994
2995Note: The definition above assumes that none of the arguments are uninterned symbols.
2996
2997<procedure>(symbol->string symbol)</procedure><br>
2998
2999Returns the name of symbol as a string. If the symbol was part of an
3000object returned as the value of a literal expression (see
3001"[[#literal-expressions|literal expressions]]") or by a call to the
3002read procedure, and its name contains alphabetic characters, then the
3003string returned will contain characters in the implementation's
3004preferred standard case -- some implementations will prefer upper
3005case, others lower case. If the symbol was returned by string->symbol,
3006the case of characters in the string returned will be the same as the
3007case in the string that was passed to string->symbol.  It is an error
3008to apply mutation procedures like string-set! to strings returned by
3009this procedure.
3010
3011The following examples assume that the implementation's standard case
3012is lower case:
3013
3014 (symbol->string 'flying-fish)
3015                                           ===>  "flying-fish"
3016 (symbol->string 'Martin)                  ===>  "martin"
3017 (symbol->string
3018    (string->symbol "Malvina"))
3019                                           ===>  "Malvina"
3020
3021<procedure>(string->symbol string)</procedure><br>
3022
3023Returns the symbol whose name is string. This procedure can create
3024symbols with names containing special characters or letters in the
3025non-standard case, but it is usually a bad idea to create such symbols
3026because in some implementations of Scheme they cannot be read as
3027themselves. See symbol->string.
3028
3029The following examples assume that the implementation's standard case
3030is lower case:
3031
3032 (eq? 'mISSISSIppi 'mississippi)
3033                 ===>  #t
3034 (string->symbol "mISSISSIppi")
3035                 ===>  the symbol with name "mISSISSIppi"
3036 (eq? 'bitBlt (string->symbol "bitBlt"))
3037                 ===>  #f
3038 (eq? 'JollyWog
3039      (string->symbol
3040        (symbol->string 'JollyWog)))
3041                 ===>  #t
3042 (string=? "K. Harper, M.D."
3043           (symbol->string
3044             (string->symbol "K. Harper, M.D.")))
3045                 ===>  #t
3046
3047==== Characters
3048
3049Characters are objects that represent printed characters such as
3050letters and digits. Characters are written using the notation #\
3051<character> or #\<character name>. For example:
3052
3053Characters are written using the notation {{#\<character>}} or {{#\<character name>}}
3054or {{#\x<hex scalar value>}}.
3055
3056The following character names must be supported by all implementations with the
3057given values. Implementations may add other names provided they cannot be
3058interpreted as hex scalar values preceded by x.
3059
3060   #\alarm     ; U+0007
3061   #\backspace ; U+0008
3062   #\delete    ; U+007F
3063   #\escape    ; U+001B
3064   #\newline   ; the linefeed character, U+000A
3065   #\null      ; the null character, U+0000
3066   #\return    ; the return character, U+000D
3067   #\space     ; the preferred way to write a space
3068   #\tab       ; the tab character, U+0009
3069
3070Here are some additional examples:
3071
3072 #\a       ; lower case letter
3073 #\A       ; upper case letter
3074 #\(       ; left parenthesis
3075 #\        ; the space character
3076 #\space   ; the preferred way to write a space
3077 #\newline ; the newline character
3078
3079Case is significant in #\<character>, but not in #\<character name>. If
3080<character> in #\<character> is alphabetic, then the character
3081following <character> must be a delimiter character such as a space or
3082parenthesis. This rule resolves the ambiguous case where, for example,
3083the sequence of characters "#\space" could be taken to be either a
3084representation of the space character or a representation of the
3085character "#\s" followed by a representation of the symbol "pace."
3086
3087Characters written in the #\ notation are self-evaluating. That is,
3088they do not have to be quoted in programs. Some of the procedures that
3089operate on characters ignore the difference between upper case and
3090lower case. The procedures that ignore case have "-ci" (for "case
3091insensitive") embedded in their names.
3092
3093<procedure>(char? obj)</procedure><br>
3094
3095Returns #t if obj is a character, otherwise returns #f.
3096
3097<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>
3098<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>
3099<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>
3100<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>
3101<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>
3102
3103These procedures impose a total ordering on the set of characters. It
3104is guaranteed that under this ordering:
3105
3106*   The upper case characters are in order. For example, (char<? #\A #\
3107    B) returns #t.
3108*   The lower case characters are in order. For example, (char<? #\a #\
3109    b) returns #t.
3110*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
3111*   Either all the digits precede all the upper case letters, or vice
3112    versa.
3113*   Either all the digits precede all the lower case letters, or vice
3114    versa.
3115
3116Some implementations may generalize these procedures to take more than
3117two arguments, as with the corresponding numerical predicates.
3118
3119<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>
3120<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>
3121<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>
3122<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>
3123<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>
3124
3125These procedures are similar to char=? et cetera, but they treat upper
3126case and lower case letters as the same. For example, (char-ci=? #\A #\
3127a) returns #t. Some implementations may generalize these procedures to
3128take more than two arguments, as with the corresponding numerical
3129predicates.
3130
3131<procedure>(char-alphabetic? char)</procedure><br>
3132<procedure>(char-numeric? char)</procedure><br>
3133<procedure>(char-whitespace? char)</procedure><br>
3134<procedure>(char-upper-case? letter)</procedure><br>
3135<procedure>(char-lower-case? letter)</procedure><br>
3136
3137These procedures return #t if their arguments are alphabetic, numeric,
3138whitespace, upper case, or lower case characters, respectively,
3139otherwise they return #f. The following remarks, which are specific to
3140the ASCII character set, are intended only as a guide: The alphabetic
3141characters are the 52 upper and lower case letters. The numeric
3142characters are the ten decimal digits. The whitespace characters are
3143space, tab, line feed, form feed, and carriage return.
3144
3145<procedure>(char->integer char)</procedure><br>
3146<procedure>(integer->char n)</procedure><br>
3147
3148Given a character, char->integer returns an exact integer
3149representation of the character. Given an exact integer that is the
3150image of a character under char->integer, integer->char returns that
3151character. These procedures implement order-preserving isomorphisms
3152between the set of characters under the char<=? ordering and some
3153subset of the integers under the <= ordering. That is, if
3154
3155 (char<=? a b) ===> #t  and  (<= x y) ===> #t
3156
3157and x and y are in the domain of integer->char, then
3158
3159 (<= (char->integer a)
3160     (char->integer b))                  ===>  #t
3161 
3162 (char<=? (integer->char x)
3163          (integer->char y))             ===>  #t
3164
3165Note that {{integer->char}} does currently not detect
3166a negative argument and will quietly convert {{-1}} to
3167{{#x1ffff}} in CHICKEN.
3168
3169==== Strings
3170
3171Strings are sequences of characters. Strings are written as sequences of
3172characters enclosed within quotation marks ("). Within a string literal,
3173various escape sequences represent characters other than themselves. Escape
3174sequences always start with a backslash (\):
3175
3176* \a : alarm, U+0007
3177
3178* \b : backspace, U+0008
3179
3180* \t : character tabulation, U+0009
3181
3182* \n : linefeed, U+000A
3183
3184* \r : return, U+000D
3185
3186* \" : double quote, U+0022
3187
3188* \\ : backslash, U+005C
3189
3190* \| : vertical line, U+007C
3191
3192* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing
3193
3194* \x<hex scalar value>; : specified character (note the terminating
3195    semi-colon).
3196
3197The result is unspecified if any other character in a string occurs after a
3198backslash.
3199
3200Except for a line ending, any character outside of an escape sequence stands
3201for itself in the string literal. A line ending which is preceded by \
3202<intraline whitespace> expands to nothing (along with any trailing intraline
3203whitespace), and can be used to indent strings for improved legibility. Any
3204other line ending has the same effect as inserting a \n character into the
3205string.
3206
3207Examples:
3208
3209 "The word \"recursion\" has many meanings."
3210 "Another example:\ntwo lines of text"
3211 "Here's text \
3212    containing just one line"
3213 "\x03B1; is named GREEK SMALL LETTER ALPHA."
3214
3215The length of a string is the
3216number of characters that it contains. This number is an exact, non-negative
3217integer that is fixed when the string is created. The valid indexes of a string
3218are the exact non-negative integers less than the length of the string. The
3219first character of a string has index 0, the second has index 1, and so on.
3220
3221<procedure>(string? obj)</procedure><br>
3222
3223Returns #t if obj is a string, otherwise returns #f.
3224
3225<procedure>(make-string k)</procedure><br>
3226<procedure>(make-string k char)</procedure><br>
3227
3228Make-string returns a newly allocated string of length k. If char is
3229given, then all elements of the string are initialized to char,
3230otherwise the contents of the string are unspecified.
3231
3232<procedure>(string char ...)</procedure><br>
3233
3234Returns a newly allocated string composed of the arguments.
3235
3236<procedure>(string-length string)</procedure><br>
3237
3238Returns the number of characters in the given string.
3239
3240<procedure>(string-ref string k)</procedure><br>
3241
3242k must be a valid index of string. String-ref returns character k of
3243string using zero-origin indexing.
3244
3245<procedure>(string-set! string k char)</procedure><br>
3246
3247k must be a valid index of string. String-set! stores char in element k
3248of string and returns an unspecified value.
3249
3250 (define (f) (make-string 3 #\*))
3251 (define (g) "***")
3252 (string-set! (f) 0 #\?)          ===>  unspecified
3253 (string-set! (g) 0 #\?)          ===>  error
3254 (string-set! (symbol->string 'immutable)
3255              0
3256              #\?)          ===>  error
3257
3258<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>
3259
3260Returns #t if the two strings are the same length and contain the same
3261characters in the same positions, otherwise returns #f.
3262
3263<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>
3264<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>
3265<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>
3266<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>
3267
3268These procedures are the lexicographic extensions to strings of the
3269corresponding orderings on characters. For example, string<? is the
3270lexicographic ordering on strings induced by the ordering char<? on
3271characters. If two strings differ in length but are the same up to the
3272length of the shorter string, the shorter string is considered to be
3273lexicographically less than the longer string.
3274
3275<procedure>(substring string start [end])</procedure><br>
3276
3277String must be a string, and start and end must be exact integers
3278satisfying
3279
3280 0 <= start <= end <= (string-length string)
3281
3282Substring returns a newly allocated string formed from the characters
3283of string beginning with index start (inclusive) and ending with index
3284end (exclusive). The {{end}} argument is optional and defaults to the
3285length of the string, this is a non-standard extension in CHICKEN.
3286
3287<procedure>(string-append string ...)</procedure><br>
3288
3289Returns a newly allocated string whose characters form the
3290concatenation of the given strings.
3291
3292<procedure>(string->list string [start [end]])</procedure><br>
3293<procedure>(list->string list)</procedure><br>
3294
3295String->list returns a newly allocated list of the characters that make
3296up the given string between start and end. List->string returns a newly allocated string
3297formed from the characters in the list list, which must be a list of
3298characters. String->list and list->string are inverses so far as equal?
3299is concerned.
3300
3301<procedure>(string-copy string [start [end]])</procedure><br>
3302
3303Returns a newly allocated copy of the given string.
3304
3305<procedure>(string-copy! to at from [start [end]])</procedure>
3306
3307It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.
3308
3309Copies the characters of string from between start and end to string to, starting at
3310at. The order in which characters are copied is unspecified, except that if the
3311source and destination overlap, copying takes place as if the source is first
3312copied into a temporary string and then into the destination. This can be
3313achieved without allocating storage by making sure to copy in the correct
3314direction in such circumstances.
3315
3316 (define a "12345")
3317 (define b (string-copy "abcde"))
3318 (string-copy! b 1 a 0 2)
3319 b  ==> "a12de"
3320
3321<procedure>(string-fill! string char +#!optional start end)</procedure><br>
3322
3323Stores char in every element of the given string and returns an
3324unspecified value. The optional start and end arguments specify
3325the part of the string to be filled and default to the complete string.
3326
3327==== Vectors
3328
3329Vectors are heterogenous structures whose elements are indexed by
3330integers. A vector typically occupies less space than a list of the
3331same length, and the average time required to access a randomly chosen
3332element is typically less for the vector than for the list.
3333
3334The length of a vector is the number of elements that it contains. This
3335number is a non-negative integer that is fixed when the vector is
3336created. The valid indexes of a vector are the exact non-negative
3337integers less than the length of the vector. The first element in a
3338vector is indexed by zero, and the last element is indexed by one less
3339than the length of the vector.
3340
3341Vectors are written using the notation #(obj ...). For example, a
3342vector of length 3 containing the number zero in element 0, the list (2
33432 2 2) in element 1, and the string "Anna" in element 2 can be written
3344as following:
3345
3346 #(0 (2 2 2 2) "Anna")
3347
3348Vector constants are self-evaluating, so they do not need
3349to be quoted in programs.
3350
3351<procedure>(vector? obj)</procedure><br>
3352
3353Returns #t if obj is a vector, otherwise returns #f.
3354
3355<procedure>(make-vector k)</procedure><br>
3356<procedure>(make-vector k fill)</procedure><br>
3357
3358Returns a newly allocated vector of k elements. If a second argument is
3359given, then each element is initialized to fill. Otherwise the initial
3360contents of each element is unspecified.
3361
3362<procedure>(vector obj ...)</procedure><br>
3363
3364Returns a newly allocated vector whose elements contain the given
3365arguments. Analogous to list.
3366
3367 (vector 'a 'b 'c)                       ===>  #(a b c)
3368
3369<procedure>(vector-length vector)</procedure><br>
3370
3371Returns the number of elements in vector as an exact integer.
3372
3373<procedure>(vector-ref vector k)</procedure><br>
3374
3375k must be a valid index of vector. Vector-ref returns the contents of
3376element k of vector.
3377
3378 (vector-ref '#(1 1 2 3 5 8 13 21)
3379             5)
3380                 ===>  8
3381 (vector-ref '#(1 1 2 3 5 8 13 21)
3382             (let ((i (round (* 2 (acos -1)))))
3383               (if (inexact? i)
3384                   (inexact->exact i)
3385                   i)))
3386                 ===> 13
3387
3388<procedure>(vector-set! vector k obj)</procedure><br>
3389
3390k must be a valid index of vector. Vector-set! stores obj in element k
3391of vector. The value returned by vector-set! is unspecified.
3392
3393 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
3394   (vector-set! vec 1 '("Sue" "Sue"))
3395   vec)
3396                 ===>  #(0 ("Sue" "Sue") "Anna")
3397
3398 (vector-set! '#(0 1 2) 1 "doe")
3399                 ===>  error  ; constant vector
3400
3401<procedure>(vector->list vector [start [end]])</procedure><br>
3402<procedure>(list->vector list)</procedure><br>
3403
3404Vector->list returns a newly allocated list of the objects contained in
3405the elements of vector. List->vector returns a newly created vector
3406initialized to the elements of the list list.
3407
3408 (vector->list '#(dah dah didah))
3409                 ===>  (dah dah didah)
3410 (list->vector '(dididit dah))
3411                 ===>  #(dididit dah)
3412
3413<procedure>(vector->string vector [start [end]])</procedure><br>
3414<procedure>(string->vector string [start [end]])</procedure>
3415
3416It is an error if any element of vector between start and end is not a character.
3417
3418The vector->string procedure returns a newly allocated string of the objects
3419contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to
3420the elements of the string string between start and end.
3421
3422In both procedures, order is preserved.
3423
3424 (string->vector "ABC")   ==>   #(#\A #\B #\C)
3425 (vector->string #(#\1 #\2 #\3))  ==> "123"
3426
3427<procedure>(vector-copy vector [start [end]])</procedure>
3428
3429Returns a newly allocated copy of the elements of the given vector between
3430start and end. The elements of the new vector are the same (in the sense of eqv?) as the
3431elements of the old.
3432
3433 (define a #(1 8 2 8)) ; a may be immutable
3434 (define b (vector-copy a))
3435 (vector-set! b 0 3)   ; b is mutable
3436 b  ==> #(3 8 2 8)
3437 (define c (vector-copy b 1 3))
3438 c  ==> #(8 2)
3439
3440<procedure>(vector-copy! to at from [start [end]])</procedure>
3441
3442It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.
3443
3444Copies the elements of vector from between start and end to vector to, starting at
3445at. The order in which elements are copied is unspecified, except that if the
3446source and destination overlap, copying takes place as if the source is first
3447copied into a temporary vector and then into the destination. This can be
3448achieved without allocating storage by making sure to copy in the correct
3449direction in such circumstances.
3450
3451 (define a (vector 1 2 3 4 5))
3452 (define b (vector 10 20 30 40 50))
3453 (vector-copy! b 1 a 0 2)
3454 b  ==> #(10 1 2 40 50)
3455
3456<procedure>(vector-append vector ....)</procedure>
3457
3458Returns a newly allocated vector whose elements are the concatenation of the
3459elements of the given vectors.
3460
3461 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)
3462
3463<procedure>(vector-fill! vector fill [start [end]])</procedure>
3464
3465The vector-fill! procedure stores fill in the elements of vector between start and
3466end.
3467
3468 (define a (vector 1 2 3 4 5))
3469 (vector-fill! a 'smash 2 4)
3470 a ==>#(1 2 smash smash 5)
3471
3472====  Bytevectors
3473
3474Bytevectors represent blocks of binary data. They are fixed-length sequences of
3475bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A
3476bytevector is typically more space-efficient than a vector containing the same
3477values.
3478
3479See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
3480information. {{(scheme base)}} re-exports all R7RS-specific procedures from
3481that module.
3482
3483=== Control features
3484
3485This chapter describes various primitive procedures which control the
3486flow of program execution in special ways. The procedure? predicate is
3487also described here.
3488
3489<procedure>(procedure? obj)</procedure><br>
3490
3491Returns #t if obj is a procedure, otherwise returns #f.
3492
3493 (procedure? car)                    ===>  #t
3494 (procedure? 'car)                   ===>  #f
3495 (procedure? (lambda (x) (* x x)))
3496                                     ===>  #t
3497 (procedure? '(lambda (x) (* x x)))
3498                                     ===>  #f
3499 (call-with-current-continuation procedure?)
3500                                     ===>  #t
3501
3502<procedure>(apply proc arg[1] ... args)</procedure><br>
3503
3504Proc must be a procedure and args must be a list. Calls proc with the
3505elements of the list (append (list arg[1] ...) args) as the actual
3506arguments.
3507
3508 (apply + (list 3 4))                      ===>  7
3509 
3510 (define compose
3511   (lambda (f g)
3512     (lambda args
3513       (f (apply g args)))))
3514 
3515 ((compose sqrt *) 12 75)                      ===>  30
3516
3517<procedure>(map proc list[1] list[2] ...)</procedure><br>
3518
3519The lists must be lists, and proc must be a procedure taking as many
3520arguments as there are lists and returning a single value. Map applies
3521proc element-wise to the elements of the lists and returns a list of
3522the results, in order. The dynamic order in which proc is applied to
3523the elements of the lists is unspecified.
3524
3525Like in SRFI-1, this procedure allows the arguments to be of unequal
3526length; it terminates when the shortest list runs out.  This is a
3527CHICKEN extension to R7RS.
3528
3529 (map cadr '((a b) (d e) (g h)))
3530                 ===>  (b e h)
3531 
3532 (map (lambda (n) (expt n n))
3533      '(1 2 3 4 5))
3534                 ===>  (1 4 27 256 3125)
3535 
3536 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
3537 
3538 (let ((count 0))
3539   (map (lambda (ignored)
3540          (set! count (+ count 1))
3541          count)
3542        '(a b)))                         ===>  (1 2) or (2 1)
3543
3544<procedure>(string-map proc string[1] string[2] ...)</procedure>
3545
3546It is an error if proc does not accept as many arguments as there are strings and return a single character.
3547
3548The string-map procedure applies proc element-wise to the elements of the
3549strings and returns a string of the results, in order. If more than one
3550string is given and not all strings have the same length, string-map terminates
3551when the shortest string runs out. The dynamic order in which
3552proc is applied to the elements of the
3553strings is unspecified. If multiple returns occur from string-map, the values
3554returned by earlier returns are not mutated.
3555
3556 (string-map char-foldcase "AbdEgH") ==> "abdegh"
3557
3558 (string-map
3559  (lambda (c)
3560    (integer->char (+ 1 (char->integer c))))
3561  "HAL")                ==> "IBM"
3562
3563 (string-map
3564  (lambda (c k)
3565    ((if (eqv? k #\u) char-upcase char-downcase)
3566     c))
3567  "studlycaps xxx"
3568  "ululululul")         ==> "StUdLyCaPs"
3569
3570<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>
3571
3572It is an error if proc does not accept as many arguments as there are vectors and return a single value.
3573
3574The vector-map procedure applies proc element-wise to the elements of the
3575vectors and returns a vector of the results, in order. If more than one
3576vector is given and not all vectors have the same length, vector-map terminates
3577when the shortest vector runs out. The dynamic order in which
3578proc is applied to the elements of the
3579vectors is unspecified. If multiple returns occur from vector-map, the values
3580returned by earlier returns are not mutated.
3581
3582 (vector-map cadr '#((a b) (d e) (g h)))
3583 ==> #(b e h)
3584
3585 (vector-map (lambda (n) (expt n n))
3586             '#(1 2 3 4 5))
3587 ==> #(1 4 27 256 3125)
3588
3589 (vector-map + '#(1 2 3) '#(4 5 6 7))
3590 ==>  #(5 7 9)
3591
3592 (let ((count 0))
3593   (vector-map
3594    (lambda (ignored)
3595      (set! count (+ count 1))
3596      count)
3597    '#(a b)))                      ==>  #(1 2) or #(2 1)
3598
3599<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
3600
3601The arguments to for-each are like the arguments to map, but for-each
3602calls proc for its side effects rather than for its values. Unlike map,
3603for-each is guaranteed to call proc on the elements of the lists in
3604order from the first element(s) to the last, and the value returned by
3605for-each is unspecified.
3606
3607 (let ((v (make-vector 5)))
3608   (for-each (lambda (i)
3609               (vector-set! v i (* i i)))
3610             '(0 1 2 3 4))
3611   v)                                        ===>  #(0 1 4 9 16)
3612
3613Like in SRFI-1, this procedure allows the arguments to be of unequal
3614length; it terminates when the shortest list runs out.  This is a
3615CHICKEN extension to R7RS.
3616
3617<procedure>(string-for-each proc string[1] string[2] ...)</procedure>
3618
3619It is an error if proc does not accept as many arguments as there are strings.
3620The arguments to string-for-each are like the arguments to string-map, but
3621string-for-each calls
3622proc for its side effects rather than for its values. Unlike string-map,
3623string-for-each is guaranteed to call
3624proc on the elements of the
3625strings in order from the first element(s) to the last, and the value returned
3626by string-for-each is unspecified. If more than one
3627string is given and not all strings have the same length, string-for-each
3628terminates when the shortest string runs out. It is an error for
3629proc to mutate any of the strings.
3630
3631 (let ((v '()))
3632   (string-for-each
3633    (lambda (c) (set! v (cons (char->integer c) v)))
3634    "abcde")
3635   v)                          ==>  (101 100 99 98 97)
3636
3637<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>
3638
3639It is an error if proc does not accept as many arguments as there are vectors.
3640The arguments to vector-for-each are like the arguments to vector-map, but
3641vector-for-each calls
3642proc for its side effects rather than for its values. Unlike vector-map,
3643vector-for-each is guaranteed to call
3644proc on the elements of the
3645vectors in order from the first element(s) to the last, and the value returned
3646by vector-for-each is unspecified. If more than one
3647vector is given and not all vectors have the same length, vector-for-each
3648terminates when the shortest vector runs out. It is an error for
3649proc to mutate any of the vectors.
3650
3651 (let ((v (make-list 5)))
3652   (vector-for-each
3653    (lambda (i) (list-set! v i (* i i)))
3654    '#(0 1 2 3 4))
3655   v)                                 ==>  (0 1 4 9 16)
3656
3657<procedure>(call-with-current-continuation proc)</procedure><br>
3658<procedure>(call/cc proc)</procedure><br>
3659
3660Proc must be a procedure of one argument. The procedure
3661call-with-current-continuation packages up the current continuation
3662(see the rationale below) as an "escape procedure" and passes it as
3663an argument to proc. The escape procedure is a Scheme procedure that,
3664if it is later called, will abandon whatever continuation is in effect
3665at that later time and will instead use the continuation that was in
3666effect when the escape procedure was created. Calling the escape
3667procedure may cause the invocation of before and after thunks installed
3668using dynamic-wind.
3669
3670The escape procedure accepts the same number of arguments as the
3671continuation to the original call to call-with-current-continuation.
3672Except for continuations created by the call-with-values procedure, all
3673continuations take exactly one value. The effect of passing no value or
3674more than one value to continuations that were not created by
3675call-with-values is unspecified.
3676
3677The escape procedure that is passed to proc has unlimited extent just
3678like any other procedure in Scheme. It may be stored in variables or
3679data structures and may be called as many times as desired.
3680
3681The following examples show only the most common ways in which
3682call-with-current-continuation is used. If all real uses were as simple
3683as these examples, there would be no need for a procedure with the
3684power of call-with-current-continuation.
3685
3686 (call-with-current-continuation
3687   (lambda (exit)
3688     (for-each (lambda (x)
3689                 (if (negative? x)
3690                     (exit x)))
3691               '(54 0 37 -3 245 19))
3692     #t))                                ===>  -3
3693 
3694 (define list-length
3695   (lambda (obj)
3696     (call-with-current-continuation
3697       (lambda (return)
3698         (letrec ((r
3699                   (lambda (obj)
3700                     (cond ((null? obj) 0)
3701                           ((pair? obj)
3702                            (+ (r (cdr obj)) 1))
3703                           (else (return #f))))))
3704           (r obj))))))
3705 
3706 (list-length '(1 2 3 4))                    ===>  4
3707 
3708 (list-length '(a b . c))                    ===>  #f
3709
3710Rationale:
3711
3712A common use of call-with-current-continuation is for structured,
3713non-local exits from loops or procedure bodies, but in fact
3714call-with-current-continuation is extremely useful for implementing
3715a wide variety of advanced control structures.
3716
3717Whenever a Scheme expression is evaluated there is a continuation
3718wanting the result of the expression. The continuation represents
3719an entire (default) future for the computation. If the expression
3720is evaluated at top level, for example, then the continuation might
3721take the result, print it on the screen, prompt for the next input,
3722evaluate it, and so on forever. Most of the time the continuation
3723includes actions specified by user code, as in a continuation that
3724will take the result, multiply it by the value stored in a local
3725variable, add seven, and give the answer to the top level
3726continuation to be printed. Normally these ubiquitous continuations
3727are hidden behind the scenes and programmers do not think much
3728about them. On rare occasions, however, a programmer may need to
3729deal with continuations explicitly. Call-with-current-continuation
3730allows Scheme programmers to do that by creating a procedure that
3731acts just like the current continuation.
3732
3733Most programming languages incorporate one or more special-purpose
3734escape constructs with names like exit, return, or even goto. In
37351965, however, Peter Landin [16] invented a general purpose escape
3736operator called the J-operator. John Reynolds [24] described a
3737simpler but equally powerful construct in 1972. The catch special
3738form described by Sussman and Steele in the 1975 report on Scheme
3739is exactly the same as Reynolds's construct, though its name came
3740from a less general construct in MacLisp. Several Scheme
3741implementors noticed that the full power of the catch construct
3742could be provided by a procedure instead of by a special syntactic
3743construct, and the name call-with-current-continuation was coined
3744in 1982. This name is descriptive, but opinions differ on the
3745merits of such a long name, and some people use the name call/cc
3746instead.
3747
3748<procedure>(values obj ...)</procedure><br>
3749
3750Delivers all of its arguments to its continuation. Except for
3751continuations created by the call-with-values procedure, all
3752continuations take exactly one value. Values might be defined as
3753follows:
3754
3755 (define (values . things)
3756   (call-with-current-continuation
3757     (lambda (cont) (apply cont things))))
3758
3759<procedure>(call-with-values producer consumer)</procedure><br>
3760
3761Calls its producer argument with no values and a continuation that,
3762when passed some values, calls the consumer procedure with those values
3763as arguments. The continuation for the call to consumer is the
3764continuation of the call to call-with-values.
3765
3766 (call-with-values (lambda () (values 4 5))
3767                   (lambda (a b) b))
3768                                                            ===>  5
3769 
3770 (call-with-values * -)                                     ===>  -1
3771
3772<procedure>(dynamic-wind before thunk after)</procedure><br>
3773
3774Calls thunk without arguments, returning the result(s) of this call.
3775Before and after are called, also without arguments, as required by the
3776following rules (note that in the absence of calls to continuations
3777captured using call-with-current-continuation the three arguments are
3778called once each, in order). Before is called whenever execution enters
3779the dynamic extent of the call to thunk and after is called whenever it
3780exits that dynamic extent. The dynamic extent of a procedure call is
3781the period between when the call is initiated and when it returns. In
3782Scheme, because of call-with-current-continuation, the dynamic extent
3783of a call may not be a single, connected time period. It is defined as
3784follows:
3785
3786*   The dynamic extent is entered when execution of the body of the
3787    called procedure begins.
3788
3789*   The dynamic extent is also entered when execution is not within the
3790    dynamic extent and a continuation is invoked that was captured
3791    (using call-with-current-continuation) during the dynamic extent.
3792
3793*   It is exited when the called procedure returns.
3794
3795*   It is also exited when execution is within the dynamic extent and a
3796    continuation is invoked that was captured while not within the
3797    dynamic extent.
3798
3799If a second call to dynamic-wind occurs within the dynamic extent of
3800the call to thunk and then a continuation is invoked in such a way that
3801the afters from these two invocations of dynamic-wind are both to be
3802called, then the after associated with the second (inner) call to
3803dynamic-wind is called first.
3804
3805If a second call to dynamic-wind occurs within the dynamic extent of
3806the call to thunk and then a continuation is invoked in such a way that
3807the befores from these two invocations of dynamic-wind are both to be
3808called, then the before associated with the first (outer) call to
3809dynamic-wind is called first.
3810
3811If invoking a continuation requires calling the before from one call to
3812dynamic-wind and the after from another, then the after is called
3813first.
3814
3815The effect of using a captured continuation to enter or exit the
3816dynamic extent of a call to before or after is undefined.  However,
3817in CHICKEN it is safe to do this, and they will execute in the outer
3818dynamic context of the {{dynamic-wind}} form.
3819
3820 (let ((path '())
3821       (c #f))
3822   (let ((add (lambda (s)
3823                (set! path (cons s path)))))
3824     (dynamic-wind
3825       (lambda () (add 'connect))
3826       (lambda ()
3827         (add (call-with-current-continuation
3828                (lambda (c0)
3829                  (set! c c0)
3830                  'talk1))))
3831       (lambda () (add 'disconnect)))
3832     (if (< (length path) 4)
3833         (c 'talk2)
3834         (reverse path))))
3835 
3836                 ===> (connect talk1 disconnect
3837                       connect talk2 disconnect)
3838
3839=== Exceptions
3840
3841This section describes Scheme's exception-handling and exception-raising
3842procedures.
3843
3844Exception handlers are one-argument procedures that determine the action the
3845program takes when an exceptional situation is signaled. The system implicitly
3846maintains a current exception handler in the dynamic environment.
3847
3848The program raises an exception by invoking the current exception handler,
3849passing it an object encapsulating information about the exception. Any
3850procedure accepting one argument can serve as an exception handler and any
3851object can be used to represent an exception.
3852
3853<procedure>(with-exception-handler handler thunk)</procedure>
3854
3855It is an error if handler does not accept one argument. It is also an error if
3856thunk does not accept zero arguments.
3857The with-exception-handler procedure returns the results of invoking
3858thunk.
3859Handler is installed as the current exception handler in the dynamic
3860environment used for the invocation of
3861thunk.
3862
3863 (call-with-current-continuation
3864  (lambda (k)
3865   (with-exception-handler
3866    (lambda (x)
3867     (display "condition: ")
3868     (write x)
3869     (newline)
3870     (k 'exception))
3871    (lambda ()
3872     (+ 1 (raise 'an-error))))))
3873          ==> exception and prints "condition: an-error"
3874
3875 (with-exception-handler
3876  (lambda (x)
3877   (display "something went wrong\n"))
3878  (lambda ()
3879   (+ 1 (raise 'an-error))))
3880
3881prints  "something went wrong"
3882After printing, the second example then raises another exception.
3883
3884<procedure>(raise obj)</procedure>
3885
3886Raises an exception by invoking the current exception handler on
3887obj. The handler is called with the same dynamic environment as that of the
3888call to raise, except that the current exception handler is the one that was in
3889place when the handler being called was installed. If the handler returns, a
3890secondary exception is raised in the same dynamic environment as the handler.
3891The relationship between
3892obj and the object raised by the secondary exception is unspecified.
3893
3894<procedure>(raise-continuable obj)</procedure>
3895
3896Raises an exception by invoking the current exception handler on
3897obj. The handler is called with the same dynamic environment as the call to
3898raise-continuable, except that: (1) the current exception handler is the one
3899that was in place when the handler being called was installed, and (2) if the
3900handler being called returns, then it will again become the current exception
3901handler. If the handler returns, the values it returns become the values
3902returned by the call to raise-continuable.
3903
3904 (with-exception-handler
3905   (lambda (con)
3906     (cond
3907       ((string? con)
3908        (display con))
3909       (else
3910        (display "a warning has been issued")))
3911     42)
3912   (lambda ()
3913     (+ (raise-continuable "should be a number")
3914        23)))
3915     prints: "should be a number"
3916     ==> 65
3917
3918<procedure>(error [location] message obj ...)</procedure>
3919
3920Message should be a string.
3921Raises an exception as if by calling raise on a newly allocated
3922implementation-defined object which encapsulates the information provided by
3923message, as well as any
3924objs, known as the irritants. The procedure error-object? must return #t on
3925such objects.
3926
3927 (define (null-list? l)
3928   (cond ((pair? l) #f)
3929         ((null? l) #t)
3930         (else
3931           (error
3932             "null-list?: argument out of domain"
3933             l))))
3934
3935If location is given and a symbol, it indicates the name of the procedure where
3936the error occurred.
3937
3938<procedure>(error-object? obj)</procedure>
3939
3940Returns #t if
3941obj is an object created by error or one of an implementation-defined set of
3942objects. Otherwise, it returns #f. The objects used to signal errors, including
3943those which satisfy the predicates file-error? and read-error?, may or may not
3944satisfy error-object?.
3945
3946<procedure>(error-object-message error-object)</procedure>
3947
3948Returns the message encapsulated by
3949error-object.
3950
3951<procedure>(error-object-irritants error-object)</procedure>
3952
3953Returns a list of the irritants encapsulated by
3954error-object.
3955
3956<procedure>(read-error? obj)</procedure><br>
3957<procedure>(file-error? obj)</procedure>
3958
3959Error type predicates. Returns #t if
3960obj is an object raised by the read procedure or by the inability to open an
3961input or output port on a file, respectively. Otherwise, it returns #f.
3962
3963=== Eval
3964
3965<procedure>(eval expression [environment-specifier])</procedure><br>
3966
3967Evaluates expression in the specified environment and returns its
3968value. Expression must be a valid Scheme expression represented as
3969data, and environment-specifier must be a value returned by one of the
3970three procedures described below. Implementations may extend eval to
3971allow non-expression programs (definitions) as the first argument and
3972to allow other values as environments, with the restriction that eval
3973is not allowed to create new bindings in the environments associated
3974with null-environment or scheme-report-environment.
3975
3976 (eval '(* 7 3) (scheme-report-environment 5))
3977                                                            ===>  21
3978 
3979 (let ((f (eval '(lambda (f x) (f x x))
3980                (null-environment 5))))
3981   (f + 10))
3982                                                            ===>  20
3983
3984The {{environment-specifier}} is optional, and if not provided it
3985defaults to the value of {{(interaction-environment)}}.  This is a
3986CHICKEN extension to R7RS, which, though strictly nonportable, is very
3987common among Scheme implementations.
3988
3989=== Input and output
3990
3991==== Ports
3992
3993Ports represent input and output devices. To Scheme, an input port is a Scheme
3994object that can deliver data upon command, while an output port is a Scheme
3995object that can accept data.
3996
3997Different port types operate on different data. Scheme implementations are
3998required to support textual ports and binary ports, but may also provide other
3999port types.
4000
4001A textual port supports reading or writing of individual characters from or to
4002a backing store containing characters using read-char and write-char below, and
4003it supports operations defined in terms of characters, such as read and write.
4004
4005A binary port supports reading or writing of individual bytes from or to a
4006backing store containing bytes using read-u8 and write-u8 below, as well as
4007operations defined in terms of bytes. Whether the textual and binary port types
4008are disjoint is implementation-dependent.
4009
4010Ports can be used to access files, devices, and similar things on the host
4011system on which the Scheme program is running.
4012
4013<procedure>(call-with-port port proc)</procedure>
4014
4015It is an error if
4016proc does not accept one argument.
4017The call-with-port procedure calls
4018proc with
4019port as an argument. If
4020proc returns, then the port is closed automatically and the values yielded by
4021the
4022proc are returned. If
4023
4024proc does not return, then the port must not be closed automatically unless it
4025is possible to prove that the port will never again be used for a read or write
4026operation.
4027
4028    Rationale: Because Scheme's escape procedures have unlimited extent, it is
4029    possible to escape from the current continuation but later to resume it. If
4030    implementations were permitted to close the port on any escape from the
4031    current continuation, then it would be impossible to write portable code
4032    using both call-with-current-continuation and call-with-port.
4033
4034Ports represent input and output devices. To Scheme, an input port is a
4035Scheme object that can deliver characters upon command, while an output
4036port is a Scheme object that can accept characters.
4037
4038<procedure>(input-port? obj)</procedure><br>
4039<procedure>(output-port? obj)</procedure><br>
4040<procedure>(textual-port? obj)</procedure><br>
4041<procedure>(binary-port? obj)</procedure><br>
4042<procedure>(port? obj)</procedure>
4043
4044These procedures return #t if
4045obj is an input port, output port, textual port, binary port, or any kind of
4046port, respectively. Otherwise they return #f.
4047
4048<procedure>(input-port-open? port)</procedure><br>
4049<procedure>(output-port-open? port)</procedure>
4050
4051Returns #t if
4052port is still open and capable of performing input or output, respectively, and
4053#f otherwise.
4054
4055<procedure>(current-input-port [port])</procedure><br>
4056<procedure>(current-output-port [port])</procedure><br>
4057<procedure>(current-error-port [port])</procedure><br>
4058
4059Returns the current default input, output or error port.
4060
4061If the optional {{port}} argument is passed, the current input or
4062output port is changed to the provided port.  It can also be used with
4063{{parameterize}} to temporarily bind the port to another value.  This
4064is a CHICKEN extension to the R7RS standard.
4065
4066Note that the default output port is not buffered. Use
4067[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]
4068if you need a different behavior.
4069
4070<procedure>(open-input-file filename [mode ...])</procedure><br>
4071<procedure>(open-binary-input-file filename [mode ...])</procedure>
4072
4073Takes a string naming an existing file and returns an input port
4074capable of delivering textual or binary data from the file. If the file cannot be
4075opened, an error is signalled.
4076
4077Additional {{mode}} arguments can be passed in, which should be any of
4078the keywords {{#:text}} or {{#:binary}}.  These indicate the mode in
4079which to open the file (this has an effect on non-UNIX platforms
4080only).  The extra {{mode}} arguments are CHICKEN extensions to the
4081R7RS standard.
4082
4083<procedure>(close-port port)</procedure><br>
4084<procedure>(close-input-port port)</procedure><br>
4085<procedure>(close-output-port port)</procedure><br>
4086
4087Closes the resource associated with
4088port, rendering the
4089port incapable of delivering or accepting data. It is an error to apply the
4090last two procedures to a port which is not an input or output port,
4091respectively. Scheme implementations may provide ports which are simultaneously
4092input and output ports, such as sockets; the close-input-port and
4093close-output-port procedures can then be used to close the input and output
4094sides of the port independently.
4095
4096These routines have no effect if the port has already been closed.
4097
4098<procedure>(open-input-string string)</procedure>
4099
4100Takes a string and returns a textual input port that delivers characters from
4101the string. If the string is modified, the effect is unspecified.
4102
4103<procedure>(open-output-string)</procedure>
4104
4105Returns a textual output port that will accumulate characters for retrieval by
4106get-output-string.
4107
4108<procedure>(get-output-string port)</procedure>
4109
4110It is an error if
4111port was not created with open-output-string.
4112Returns a string consisting of the characters that have been output to the port
4113so far in the order they were output. If the result string is modified, the
4114effect is unspecified.
4115
4116 (parameterize
4117     ((current-output-port
4118       (open-output-string)))
4119     (display "piece")
4120     (display " by piece ")
4121     (display "by piece.")
4122     (newline)
4123     (get-output-string (current-output-port)))
4124   ==> "piece by piece by piece.\n"
4125
4126<procedure>(open-input-bytevector bytevector)</procedure>
4127
4128Takes a bytevector and returns a binary input port that delivers bytes from the
4129bytevector.
4130
4131<procedure>(open-output-bytevector)</procedure>
4132
4133Returns a binary output port that will accumulate bytes for retrieval by
4134get-output-bytevector.
4135
4136<procedure>(get-output-bytevector port)</procedure>
4137
4138It is an error if
4139port was not created with open-output-bytevector.
4140Returns a bytevector consisting of the bytes that have been output to the port
4141so far in the order they were output.
4142
4143==== Input
4144
4145If port is omitted from any input procedure, it defaults to the value returned by
4146(current-input-port). It is an error to attempt an input operation on a closed
4147port.
4148
4149<procedure>(read-char [port])</procedure><br>
4150
4151Returns the next character available from the input port, updating the
4152port to point to the following character. If no more characters are
4153available, an end of file object is returned. Port may be omitted, in
4154which case it defaults to the value returned by current-input-port.
4155
4156<procedure>(peek-char [port])</procedure><br>
4157
4158Returns the next character available from the input port, without
4159updating the port to point to the following character. If no more
4160characters are available, an end of file object is returned. Port may
4161be omitted, in which case it defaults to the value returned by
4162current-input-port.
4163
4164Note:   The value returned by a call to peek-char is the same as
4165the value that would have been returned by a call to read-char with
4166the same port. The only difference is that the very next call to
4167read-char or peek-char on that port will return the value returned
4168by the preceding call to peek-char. In particular, a call to
4169peek-char on an interactive port will hang waiting for input
4170whenever a call to read-char would have hung.
4171
4172<procedure>(read-line [port])</procedure>
4173
4174Returns the next line of text available from the textual input
4175port, updating the
4176port to point to the following character. If an end of line is read, a string
4177containing all of the text up to (but not including) the end of line is
4178returned, and the port is updated to point just past the end of line. If an end
4179of file is encountered before any end of line is read, but some characters have
4180been read, a string containing those characters is returned. If an end of file
4181is encountered before any characters are read, an end-of-file object is
4182returned. For the purpose of this procedure, an end of line consists of either
4183a linefeed character, a carriage return character, or a sequence of a carriage
4184return character followed by a linefeed character. Implementations may also
4185recognize other end of line characters or sequences.
4186
4187<procedure>(eof-object? obj)</procedure><br>
4188
4189Returns #t if obj is an end of file object, otherwise returns #f. The
4190precise set of end of file objects will vary among implementations, but
4191in any case no end of file object will ever be an object that can be
4192read in using read.
4193
4194<procedure>(eof-object)</procedure>
4195
4196Returns an end-of-file object, not necessarily unique.
4197
4198<procedure>(char-ready? [port])</procedure><br>
4199
4200Returns #t if a character is ready on the input port and returns #f
4201otherwise. If char-ready returns #t then the next read-char operation
4202on the given port is guaranteed not to hang. If the port is at end of
4203file then char-ready? returns #t. Port may be omitted, in which case it
4204defaults to the value returned by current-input-port.
4205
4206Rationale:   Char-ready? exists to make it possible for a program
4207to accept characters from interactive ports without getting stuck
4208waiting for input. Any input editors associated with such ports
4209must ensure that characters whose existence has been asserted by
4210char-ready? cannot be rubbed out. If char-ready? were to return #f
4211at end of file, a port at end of file would be indistinguishable
4212from an interactive port that has no ready characters.
4213
4214<procedure>(read-string k [port])</procedure>
4215
4216See [[Module (chicken io)|(chicken io) module]] for more information.
4217
4218<procedure>(read-u8 [port])</procedure>
4219
4220Returns the next byte available from the binary input
4221port, updating the
4222port to point to the following byte. If no more bytes are available, an
4223end-of-file object is returned.
4224
4225<procedure>(peek-u8 [port])</procedure>
4226
4227Returns the next byte available from the binary input
4228port, but without updating the
4229port to point to the following byte. If no more bytes are available, an
4230end-of-file object is returned.
4231
4232<procedure>(u8-ready? [port])</procedure>
4233
4234Returns #t if a byte is ready on the binary input
4235port and returns #f otherwise. If u8-ready? returns #t then the next read-u8
4236operation on the given
4237port is guaranteed not to hang. If the
4238port is at end of file then u8-ready?​ ​returns #t.
4239
4240<procedure>(read-bytevector k [port])</procedure><br>
4241<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>
4242
4243See [[Module (chicken io)|(chicken io) module]] for more information.
4244
4245==== Output
4246
4247If port is omitted from any output procedure, it defaults to the value returned by
4248(current-output-port). It is an error to attempt an output operation on a
4249closed port.
4250
4251<procedure>(newline)</procedure><br>
4252<procedure>(newline port)</procedure><br>
4253
4254Writes an end of line to port. Exactly how this is done differs from
4255one operating system to another. Returns an unspecified value. The port
4256argument may be omitted, in which case it defaults to the value
4257returned by current-output-port.
4258
4259<procedure>(write-char char)</procedure><br>
4260<procedure>(write-char char port)</procedure><br>
4261
4262Writes the character char (not an external representation of the
4263character) to the given port and returns an unspecified value. The port
4264argument may be omitted, in which case it defaults to the value
4265returned by current-output-port.
4266
4267<procedure>(write-string string [port [start [end]]])</procedurew>
4268
4269Writes the characters of
4270string from
4271start to
4272end in left-to-right order to the textual output
4273port.
4274
4275<procedure>(write-u8 byte [port])</procedure>
4276
4277Writes the
4278byte to the given binary output
4279port and returns an unspecified value.
4280
4281<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>
4282
4283See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
4284information.
4285
4286<procedure>(flush-output-port [port])</procedure>
4287
4288Flushes any buffered output from the buffer of output-port to the underlying
4289file or device and returns an unspecified value.
4290
4291==== System interface
4292
4293Questions of system interface generally fall outside of the domain of
4294this report. However, the following operations are important enough to
4295deserve description here.
4296
4297<procedure>(features)</procedure>
4298
4299Returns a list of the feature identifiers which cond-expand treats as true. It
4300is an error to modify this list. Here is an example of what features might
4301return:
4302
4303 (features)  ==>
4304   (r7rs ratios exact-complex full-unicode
4305    gnu-linux little-endian
4306    fantastic-scheme
4307    fantastic-scheme-1.0
4308    space-ship-control-system)
4309
4310---
4311Previous: [[Module scheme]]
4312
4313Next: [[Module (scheme case-lambda)]]
Trap