Go to the first, previous, next, last section, table of contents.


Standard procedures

This chapter describes Scheme's built-in procedures. The initial (or "top level") Scheme environment starts out with a number of variables bound to locations containing useful values, most of which are primitive procedures that manipulate data. For example, the variable abs is bound to (a location initially containing) a procedure of one argument that computes the absolute value of a number, and the variable + is bound to a procedure that computes sums.

Booleans

The standard boolean objects for true and false are written as #t and #f. What really matters, though, are the objects that the Scheme conditional expressions (if, cond, and, or, do) treat as true or false. The phrase "a true value" (or sometimes just "true") means any object treated as true by the conditional expressions, and the phrase "a false value" (or "false") means any object treated as false by the conditional expressions.

Of all the standard Scheme values, only #f and the empty list count as false in conditional expressions. Everything else, including #t, pairs, symbols, numbers, strings, vectors, and procedures, counts as true.

The empty list counts as false for compatibility with existing programs and implementations that assume this to be the case.

Programmers accustomed to other dialects of Lisp should beware that Scheme distinguishes false and the empty list from the symbol nil.

Boolean constants evaluate to themselves, so they don't need to be quoted in programs.


#t                                     ==>  #t
#f                                     ==>  #f
'#f                                    ==>  #f

essential procedure: not obj

Not returns #t if obj is false, and returns #f otherwise.

(not #t)                               ==>  #f
(not 3)                                ==>  #f
(not (list 3))                         ==>  #f
(not #f)                               ==>  #t
(not '())                              ==>  #t
(not (list))                           ==>  #t

essential procedure: boolean? obj

Boolean? returns #t if obj is either #t or #f and returns #f otherwise.

(boolean? #f)                          ==>  #t
(boolean? 0)                           ==>  #f

variable: nil
variable: t

Some implementations provide variables nil and t whose values in the initial environment are #f and #t respectively.

t                                      ==>  #t
nil                                    ==>  #f
'nil                                   ==>  nil

Equivalence predicates

A predicate is a procedure that always returns a boolean value (#t or #f). An equivalence predicate is the computational analogue of a mathematical equivalence relation (it is symmetric, reflexive, and transitive). Of the equivalence predicates described in this section, eq? is the finest or most discriminating, and equal? is the coarsest. Eqv? is slightly less discriminating than eq?.

Two objects are operationally equivalent if and only if there is no way that they can be distinguished, using Scheme primitives other than eqv? or eq? or those like memq and assv whose meaning is defined explicitly in terms of eqv? or eq?. It is guaranteed that objects maintain their operational identity despite being named by variables or fetched from or stored into data structures.

This definition can be interpreted in the following ways for various kinds of objects:

essential procedure: eqv? obj1 obj2

The eqv? procedure implements an approximation to the relation of operational equivalence. It returns #t if it can prove that obj1 and obj2 are operationally equivalent. If it can't, it always errs on the conservative side and returns #f.

The only situation in which it might fail to prove is when obj1 and obj2 are operationally equivalent procedures that were created at different times. In general, operational equivalence of procedures is uncomputable, but it is guaranteed that eqv? can recognize a procedure created at a given time by a given lambda expression as "being itself." This is useful for applications in which procedures are being used to implement objects with local state.

(eqv? 'a 'a)                           ==>  #t
(eqv? 'a 'b)                           ==>  #f
(eqv? 2 2)                             ==>  #t
(eqv? '() '())                         ==>  #t
(eqv? "" "")                           ==>  #t
(eqv? 100000000 100000000)             ==>  #t
(eqv? (cons 1 2) (cons 1 2))           ==>  #f
(eqv? (lambda () 1)
      (lambda () 2))                   ==>  #f
(eqv? #f 'nil)                         ==>  #f
(let ((p (lambda (x) x)))
  (eqv? p p))                          ==>  #t

The following examples illustrate cases in which eqv? is permitted to fail to prove operational equivalence, depending on the implementation. (In every case, it will return either #t or #f, but which one it returns is implementation-dependent.) Compare with the last example in the previous set.

(eqv? (lambda (x) x)
      (lambda (x) x))                  ==>  unspecified
(eqv? (lambda (x) x)
      (lambda (y) y))                  ==>  unspecified

The next set of examples shows the use of eqv? with procedures that have local state. Gen-counter must return a distinct procedure every time, since each procedure has its own internal counter. Gen-loser, however, returns equivalent procedures each time, since the local state does not affect the value or side effects of the procedures.

(define gen-counter
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) n))))
(let ((g (gen-counter)))
  (eqv? g g))                          ==>  #t
(eqv? (gen-counter) (gen-counter))
                                       ==>  #f
(define gen-loser
  (lambda ()
    (let ((n 0))
      (lambda () (set! n (+ n 1)) 27))))
(let ((g (gen-loser)))
  (eqv? g g))                          ==>  #t
(eqv? (gen-loser) (gen-loser))
                                       ==>  unspecified

Objects of distinct types are never operationally equivalent, except that false and the empty list are permitted to be identical, and the character type need not be disjoint from other types.

(eqv? '() #f)                          ==>  unspecified
(eqv? 57 #\A)                          ==>  unspecified

Since it is an error to modify constant objects (those returned by literal expressions), implementations are permitted, though not required, to share structure between constants where appropriate. Thus the value of eqv? on constants is sometimes implementation-dependent.

(let ((x '(a)))
  (eqv? x x))                          ==>  #t
(eqv? '(a) '(a))                       ==>  unspecified
(eqv? "a" "a")                         ==>  unspecified
(eqv? '(b) (cdr '(a b)))               ==>  unspecified

Note: The above definition of eqv? allows implementations latitude in their treatment of procedures and literals: implementations are free to either detect or fail to detect that two procedures or two literals are operationally equivalent to each other, and can decide whether or not to merge representations of equivalent objects by using the same pointer or bit pattern to represent both.

essential procedure: eq? obj1 obj2

Eq? is similar to eqv? except that in some cases it is capable of discerning distinctions finer than those detectable by eqv?.

Eq? and eqv? are guaranteed to have the same behavior on symbols, booleans, the empty list, pairs, and non-empty strings and vectors. Eq?'s behavior on numbers and characters is implementation-dependent, but it will always return either true or false, and will return true only when eqv? would also return true. Eq? may also behave differently from eqv? on empty vectors and empty strings.

(eq? 'a 'a)                            ==>  #t
(eq? '(a) '(a))                        ==>  unspecified
(eq? (list 'a) (list 'a))              ==>  #f
(eq? "a" "a")                          ==>  unspecified
(eq? "" "")                            ==>  unspecified
(eq? '() '())                          ==>  #t
(eq? 2 2)                              ==>  unspecified
(eq? #\A #\A)                          ==>  unspecified
(eq? car car)                          ==>  #t
(let ((n (+ 2 3)))
  (eq? n n))                           ==>  unspecified
(let ((x '(a)))
  (eq? x x))                           ==>  #t
(let ((x '#()))
  (eq? x x))                           ==>  #t
(let ((p (lambda (x) x)))
  (eq? p p))                           ==>  #t

Note: It will usually be possible to implement eq? much more efficiently than eqv?, for example, as a simple pointer comparison instead of as some more complicated operation. One reason is that it may not be possible to compute eqv? of two numbers in constant time, whereas eq? implemented as pointer comparison will always finish in constant time. Eq? may be used like eqv? in applications using procedures to implement objects with state since it obeys the same constraints as eqv?. @end quotation

essential procedure: equal? obj1 obj2

Equal? recursively compares the contents of pairs, vectors, and strings, applying eqv? on other objects such as numbers and symbols. A rule of thumb is that objects are generally equal? if they print the same. Equal? may fail to terminate if its arguments are circular data structures.

(equal? 'a 'a)                         ==>  #t
(equal? '(a) '(a))                     ==>  #t
(equal? '(a (b) c)
        '(a (b) c))                    ==>  #t
(equal? "abc" "abc")                   ==>  #t
(equal? 2 2)                           ==>  #t
(equal? (make-vector 5 'a)
        (make-vector 5 'a))            ==>  #t
(equal? (lambda (x) x)
        (lambda (y) y))                ==>  unspecified

Pairs and lists

A pair (sometimes called a dotted pair) is a record structure with two fields called the car and cdr fields (for historical reasons). Pairs are created by the procedure cons. The car and cdr fields are accessed by the procedures car and cdr. The car and cdr fields are assigned by the procedures set-car! and set-cdr!.

Pairs are used primarily to represent lists. A list can be defined recursively as either the empty list or a pair whose cdr is a list. The objects in the car fields of successive pairs of a list are the elements of the list. For example, a two-element list is a pair whose car is the first element and whose cdr is a pair whose car is the second element and whose cdr is the empty list. The length of a list is the number of elements, which is the same as the number of pairs.

The empty list is a special object of its own type (it is not a pair); it has no elements and its length is zero.

The most general notation (external representation) for Scheme pairs is the "dotted" notation `(c1 . c2)' where c1 is the value of the car field and c2 is the value of the cdr field. For example `(4 . 5)' is a pair whose car is 4 and whose cdr is 5. Note that `(4 . 5)' is the external representation of a pair, not an expression that evaluates to a pair.

A more streamlined notation can be used for lists: the elements of the list are simply enclosed in parentheses and separated by spaces. The empty list is written () . For example,


(a b c d e)

and


(a . (b . (c . (d . (e . ())))))

are both representations of the same list of symbols.

A chain of pairs not ending in the empty list is called an improper list. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists:


(a b c . d)

is equivalent to


(a . (b . (c . d)))

Whether a given pair is a list depends upon what is stored in the cdr field. When the set-cdr! procedure is used, an object can be a list one moment and not the next:


(define x (list 'a 'b 'c))
(define y x)
y                                      ==>  (a b c)
(set-cdr! x 4)                         ==>  unspecified
x                                      ==>  (a . 4)
(eqv? x y)                             ==>  #t
y                                      ==>  (a . 4)

It is often convenient to speak of a homogeneous list of objects of some particular data type, as for example `(1 2 3)' is a list of integers. To be more precise, suppose D is some data type. (Any predicate defines a data type consisting of those objects of which the predicate is true.) Then

Within literal expressions and representations of objects read by the read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum> denote two-element lists whose first elements are the symbols quote, quasiquote, unquote, and unquote-splicing, respectively. The second element in each case is <datum>. This convention is supported so that arbitrary Scheme programs may be represented as lists. That is, according to Scheme's grammar, every <expression> is also a <datum> (see section see section External representations). Among other things, this permits the use of the read procedure to parse Scheme programs. See section section External representations.

essential procedure: pair? obj

Pair? returns #t if obj is a pair, and otherwise returns #f.

(pair? '(a . b))                       ==>  #t
(pair? '(a b c))                       ==>  #t
(pair? '())                            ==>  #f
(pair? '#(a b))                        ==>  #f

essential procedure: cons obj1 obj2

Returns a newly allocated pair whose car is obj1 and whose cdr is obj2. The pair is guaranteed to be different (in the sense of eqv?) from every existing object.

(cons 'a '())                          ==>  (a)
(cons '(a) '(b c d))                   ==>  ((a) b c d)
(cons "a" '(b c))                      ==>  ("a" b c)
(cons 'a 3)                            ==>  (a . 3)
(cons '(a b) 'c)                       ==>  ((a b) . c)

essential procedure: car pair

Returns the contents of the car field of pair. Note that it is an error to take the car of the empty list.

(car '(a b c))                         ==>  a
(car '((a) b c d))                     ==>  (a)
(car '(1 . 2))                         ==>  1
(car '())                              ==>  error

essential procedure: cdr pair

Returns the contents of the cdr field of pair. Note that it is an error to take the cdr of the empty list.

(cdr '((a) b c d))                     ==>  (b c d)
(cdr '(1 . 2))                         ==>  2
(cdr '())                              ==>  error

essential procedure: set-car! pair obj

Stores obj in the car field of pair. The value returned by set-car! is unspecified.

essential procedure: set-cdr! pair obj

Stores obj in the cdr field of pair. The value returned by set-cdr! is unspecified.

essential procedure: caar pair
essential procedure: cadr pair

...: ...

essential procedure: cdddar pair
essential procedure: cddddr pair

These procedures are compositions of car and cdr, where for example caddr could be defined by

(define caddr (lambda (x) (car (cdr (cdr x))))).

Arbitrary compositions, up to four deep, are provided. There are twenty-eight of these procedures in all.

essential procedure: null? obj

Returns #t if obj is the empty list, otherwise returns #f. (In implementations in which the empty list is the same as #f, null? will return #t if obj is #f.)

essential procedure: list obj ...,

Returns a list of its arguments.

(list 'a (+ 3 4) 'c)                   ==>  (a 7 c)
(list)                                 ==>  ()

essential procedure: length list

Returns the length of list.

(length '(a b c))                      ==>  3
(length '(a (b) (c d e)))              ==>  3
(length '())                           ==>  0

essential procedure: append list1 list2
procedure: append list ...,

Returns a list consisting of the elements of the first list followed by the elements of the other lists.

(append '(x) '(y))                     ==>  (x y)
(append '(a) '(b c d))                 ==>  (a b c d)
(append '(a (b)) '((c)))               ==>  (a (b) (c))

The resulting list is always newly allocated, except that it shares structure with the last list argument. The last argument may actually be any object; an improper list results if it is not a proper list.

(append '(a b) '(c . d))               ==>  (a b c . d)
(append '() 'a)                        ==>  a

procedure: reverse list

Returns a newly allocated list consisting of the elements of list in reverse order.

(reverse '(a b c))                     ==>  (c b a)
(reverse '(a (b c) d (e (f))))  
          ==>  ((e (f)) d (b c) a)

procedure: list-tail list k

Returns the sublist of list obtained by omitting the first k elements. List-tail could be defined by

(define list-tail
  (lambda (x k)
    (if (zero? k)
        x
        (list-tail (cdr x) (- k 1)))))

procedure: list-ref list k

Returns the kth element of list. (This is the same as the car of (list-tail list k).)

(list-ref '(a b c d) 2)                ==>  c

procedure: last-pair list

Returns the last pair in the nonempty, possibly improper, list list. Last-pair could be defined by

(define last-pair
  (lambda (x)
    (if (pair? (cdr x))
        (last-pair (cdr x))
        x)))

essential procedure: memq obj list
essential procedure: memv obj list
essential procedure: member obj list

These procedures return the first sublist of list whose car is obj. If obj does not occur in list, #f (n.b.: not the empty list) is returned. Memq uses eq? to compare obj with the elements of list, while memv uses eqv? and member uses equal?.

(memq 'a '(a b c))                     ==>  (a b c)
(memq 'b '(a b c))                     ==>  (b c)
(memq 'a '(b c d))                     ==>  #f
(memq (list 'a) '(b (a) c))            ==>  #f
(member (list 'a)
        '(b (a) c))                    ==>  ((a) c)
(memq 101 '(100 101 102))              ==>  unspecified
(memv 101 '(100 101 102))              ==>  (101 102)

essential procedure: assq obj alist
essential procedure: assv obj alist
essential procedure: assoc obj alist

Alist (for "association list") must be a list of pairs. These procedures find the first pair in alist whose car field is obj, and returns that pair. If no pair in alist has obj as its car, #f is returned. Assq uses eq? to compare obj with the car fields of the pairs in alist, while assv uses eqv? and assoc uses equal?.

(define e '((a 1) (b 2) (c 3)))
(assq 'a e)                            ==>  (a 1)
(assq 'b e)                            ==>  (b 2)
(assq 'd e)                            ==>  #f
(assq (list 'a) '(((a)) ((b)) ((c))))
                                       ==>  #f
(assoc (list 'a) '(((a)) ((b)) ((c))))   
                                       ==>  ((a))
(assq 5 '((2 3) (5 7) (11 13)))    
                                       ==>  unspecified
(assv 5 '((2 3) (5 7) (11 13)))    
                                       ==>  (5 7)

Note: Although they are ordinarily used as predicates, memq, memv, member, assq, assv, and assoc do not have question marks in their names because they return useful values rather than just #t or #f.

Symbols

Symbols are objects whose usefulness rests on the fact that two symbols are identical (in the sense of eqv?) if and only if their names are spelled the same way. This is exactly the property needed to represent identifiers in programs, and so most implementations of Scheme use them internally for that purpose. Symbols are useful for many other applications; for instance, they may be used the way enumerated values are used in Pascal.

The rules for writing a symbol are exactly the same as the rules for writing an identifier; see sections section Identifiers and section Lexical structure.

It is guaranteed that any symbol that has been returned as part of a literal expression, or read using the read procedure, and subsequently written out using the write procedure, will read back in as the identical symbol (in the sense of eqv?). The string->symbol procedure, however, can create symbols for which this write/read invariance may not hold because their names contain special characters or letters in the non-standard case.

Note: Some implementations of Scheme have a feature known as "slashification" in order to guarantee write/read invariance for all symbols, but historically the most important use of this feature has been to compensate for the lack of a string data type.

Some implementations also have "uninterned symbols", which defeat write/read invariance even in implementations with slashification, and also generate exceptions to the rule that two symbols are the same if and only if their names are spelled the same.

essential procedure: symbol? obj

Returns #t if obj is a symbol, otherwise returns #f.

(symbol? 'foo)                         ==>  #t
(symbol? (car '(a b)))                 ==>  #t
(symbol? "bar")                        ==>  #f

essential procedure: symbol->string symbol

Returns the name of symbol as a string. If the symbol was part of an object returned as the value of a literal expression (section see section Literal expressions) or by a call to the read procedure, and its name contains alphabetic characters, then the string returned will contain characters in the implementation's preferred standard case--some implementations will prefer upper case, others lower case. If the symbol was returned by string->symbol, the case of characters in the string returned will be the same as the case in the string that was passed to string->symbol. It is an error to apply mutation procedures like string-set! to strings returned by this procedure.

The following examples assume that the implementation's standard case is lower case:

(symbol->string 'flying-fish)     
                                       ==>  "flying-fish"
(symbol->string 'Martin)               ==>  "martin"
(symbol->string
   (string->symbol "Malvina"))     
                                       ==>  "Malvina"

essential procedure: string->symbol string

Returns the symbol whose name is string. This procedure can create symbols with names containing special characters or letters in the non-standard case, but it is usually a bad idea to create such symbols because in some implementations of Scheme they cannot be read as themselves. See symbol->string.

The following examples assume that the implementation's standard case is lower case:

(eq? 'mISSISSIppi 'mississippi)  
          ==>  #t
(string->symbol "mISSISSIppi")  
          ==>
  the symbol with name "mISSISSIppi"
(eq? 'bitBlt (string->symbol "bitBlt"))     
          ==>  #f
(eq? 'JollyWog
     (string->symbol
       (symbol->string 'JollyWog)))  
          ==>  #t
(string=? "K. Harper, M.D."
          (symbol->string
            (string->symbol "K. Harper, M.D.")))  
          ==>  #t

Numbers

Numerical computation has traditionally been neglected by the Lisp community. Until Common Lisp there has been no carefully thought out strategy for organizing numerical computation, and with the exception of the MacLisp system [Pitman83] there has been little effort to execute numerical code efficiently. We applaud the excellent work of the Common Lisp committee and we accept many of their recommendations. In some ways we simplify and generalize their proposals in a manner consistent with the purposes of Scheme.

Scheme's numerical operations treat numbers as abstract data, as independent of their representation as is possible. Thus, the casual user should be able to write simple programs without having to know that the implementation may use fixed-point, floating-point, and perhaps other representations for his data. Unfortunately, this illusion of uniformity can be sustained only approximately--the implementation of numbers will leak out of its abstraction whenever the user must be in control of precision, or accuracy, or when he must construct especially efficient computations. Thus the language must also provide escape mechanisms so that a sophisticated programmer can exercise more control over the execution of his code and the representation of his data when necessary.

It is important to distinguish between the abstract numbers, their machine representations, and their written representations. We will use mathematical terms number, complex, real, rational, and integer for properties of the abstract numbers, the names fixnum, bignum, ratnum, and flonum for machine representations, and the names int, fix, flo, sci, rat, polar, and rect for input/output formats.

Numbers

A Scheme system provides data of type number, which is the most general numerical type supported by that system. Number is likely to be a complicated union type implemented in terms of fixnums, bignums, flonums, and so forth, but this should not be apparent to a naive user. What the user should see is that the usual operations on numbers produce the mathematically expected results, within the limits of the implementation. Thus if the user divides the exact number 3 by the exact number 2, he should get something like 1.5 (or the exact fraction 3/2). If he adds that result to itself, and the implementation is good enough, he should get an exact 3.

Mathematically, numbers may be arranged into a tower of subtypes with projections and injections relating adjacent levels of the tower:

number
complex
real
rational
integer

We impose a uniform rule of downward coercion--a number of one type is also of a lower type if the injection (up) of the projection (down) of a number leaves the number unchanged. Since this tower is a genuine mathematical structure, Scheme provides predicates and procedures to access the tower.

Not all implementations of Scheme must provide the whole tower, but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language.

Exactness

Numbers are either exact or inexact. A number is exact if it was derived from exact numbers using only exact operations. A number is inexact if it models a quantity (e.g., a measurement) known only approximately, if it was derived using inexact ingredients, or if it was derived using inexact operations. Thus inexactness is a contagious property of a number. Some operations, such as the square root (of non-square numbers), must be inexact because of the finite precision of our representations.

Other operations are inexact because of implementation requirements. We emphasize that exactness is independent of the position of the number on the tower. It is perfectly possible to have an inexact integer or an exact real; 355/113 may be an exact rational or it may be an inexact rational approximation to pi, depending on the application.

Operationally, it is the system's responsibility to combine exact numbers using exact methods, such as infinite precision integer and rational arithmetic, where possible. An implementation may not be able to do this (if it does not use infinite precision integers and rationals), but if a number becomes inexact for implementation reasons there is likely to be an important error condition, such as integer overflow, to be reported. Arithmetic on inexact numbers is not so constrained. The system may use floating point and other ill-behaved representation strategies for inexact numbers. This is not to say that implementors need not use the best known algorithms for inexact computations--only that approximate methods of high quality are allowed. In a system that cannot explicitly distinguish exact from inexact numbers the system must do its best to maintain precision. Scheme systems must not burden users with numerical operations described in terms of hardware and operating-system dependent representations such as fixnum and flonum, however, because these representation issues are hardly ever germane to the user's problems.

We highly recommend that the IEEE 32-bit and 64-bit floating-point standards be adopted for implementations that use floating-point representations internally. To minimize loss of precision we adopt the following rules: If an implementation uses several different sizes of floating-point formats, the results of any operation with a floating-point result must be expressed in the largest format used to express any of the floating-point arguments to that operation. It is desirable (but not required) for potentially irrational operations such as sqrt, when applied to exact arguments, to produce exact answers whenever possible (for example the square root of an exact 4 ought to be an exact 2). If an exact number (or an inexact number represented as a fixnum, a bignum, or a ratnum) is operated upon so as to produce an inexact result (as by sqrt), and if the result is represented as a flonum, then the largest available flonum format must be used; but if the result is expressed as a ratnum then the rational approximation must have at least as much precision as the largest available flonum.

Number syntax

Scheme allows the traditional ways of writing numerical constants, though any particular implementation may support only some of them. These syntaxes are intended to be purely notational; any kind of number may be written in any form that the user deems convenient. Of course, writing 1/7 as a limited-precision decimal fraction will not express the number exactly, but this approximate form of expression may be just what the user wants to see.

The syntax of numbers is described formally in section section Lexical structure. See section section Formats for many examples of representations of numbers.

A numerical constant may be represented in binary, octal, decimal, or hex by the use of a radix prefix. The radix prefixes are `#b' (binary), `#o' (octal), `#d' (decimal), and `#x' (hex). With no radix prefix, a number is assumed to be expressed in decimal.

A numerical constant may be specified to be either exact or inexact by a prefix. The prefixes are `#e' for exact, and `#i' for inexact. An exactness prefix may appear before or after any radix prefix that is used. If the representation of a numerical constant has no exactness prefix, the constant may be assumed to be exact or inexact at the discretion of the implementation, except that integers expressed without decimal points and without use of exponential notation are assumed exact.

In systems with both single and double precision flonums we may want to specify which size we want to use to represent a constant internally. For example, we may want a constant that has the value of pi rounded to the single precision length, or we might want a long number that has the value 6/10. In either case, we are specifying an explicit way to represent an inexact number. For this purpose, we may express a number with a prefix that indicates short or long flonum representation:


#S3.14159265358979
       Round to short --- 3.141593
#L.6
       Extend to long --- .600000000000000

Numerical operations

The reader is referred to section section Entry format for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines.

essential procedure: number? obj
essential procedure: complex? obj
essential procedure: real? obj
essential procedure: rational? obj
essential procedure: integer? obj

These numerical type predicates can be applied to any kind of argument, including non-numbers. They return true if the object is of the named type. In general, if a type predicate is true of a number then all higher type predicates are also true of that number. Not every system supports all of these types; for example, it is entirely possible to have a Scheme system that has only integers. Nonetheless every implementation of Scheme must have all of these predicates.

essential procedure: zero? z
essential procedure: positive? x
essential procedure: negative? x
essential procedure: odd? n
essential procedure: even? n
essential procedure: exact? z
essential procedure: inexact? z

These numerical predicates test a number for a particular property, returning #t or #f.

essential procedure: = z1 z2
essential procedure: < x1 x2
essential procedure: > x1 x2
essential procedure: <= x1 x2
essential procedure: >= x1 x2

Some implementations allow these procedures to take many arguments, to facilitate range checks. These procedures return #t if their arguments are (respectively): numerically equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing. Warning: on inexact numbers the equality tests will give unreliable results, and the other numerical comparisons will be useful only heuristically; when in doubt, consult a numerical analyst.

essential procedure: max x1 x2
procedure: max x1 x2 ...,
essential procedure: min x1 x2
procedure: min x1 x2 ...,

These procedures return the maximum or minimum of their arguments.

essential procedure: + z1 z2
procedure: + z1 ...,
essential procedure: * z1 z2
procedure: * z1 ...,

These procedures return the sum or product of their arguments.

(+ 3 4)                                ==>  7
(+ 3)                                  ==>  3
(+)                                    ==>  0
(* 4)                                  ==>  4
(*)                                    ==>  1

essential procedure: - z1 z2
procedure: - z1 z2 ...,
essential procedure: / z1 z2
procedure: / z1 z2 ...,

With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument.

(- 3 4)                                ==>  -1
(- 3 4 5)                              ==>  -6
(- 3)                                  ==>  -3
(/ 3 4 5)                              ==>  3/20
(/ 3)                                  ==>  1/3

essential procedure: abs z

Abs returns the magnitude of its argument.

(abs -7)                               ==>  7
(abs -3+4i)                            ==>  5

essential procedure: quotient n1 n2
essential procedure: remainder n1 n2
procedure: modulo n1 n2

These are intended to implement number-theoretic (integer) division: For positive integers n1 and n2, if n3 and n4 are integers such that n1=n2n3+n4 and 0<= n4<n2, then

(quotient n1 n2)                       ==>  n3
(remainder n1 n2)                      ==>  n4
(modulo n1 n2)                         ==>  n4

For all integers n1 and n2 with n2 not equal to 0,

(= n1 (+ (* n2 (quotient n1 n2))
              (remainder n1 n2)))
                                       ==>  #t

The value returned by quotient always has the sign of the product of its arguments. Remainder and modulo differ on negative arguments--the remainder always has the sign of the dividend, the modulo always has the sign of the divisor:

(modulo 13 4)                          ==>  1
(remainder 13 4)                       ==>  1

(modulo -13 4)                         ==>  3
(remainder -13 4)                      ==>  -1

(modulo 13 -4)                         ==>  -3
(remainder 13 -4)                      ==>  1

(modulo -13 -4)                        ==>  -1
(remainder -13 -4)                     ==>  -1

procedure: numerator q
procedure: denominator q

These procedures return the numerator or denominator of their argument.

(numerator (/ 6 4))                    ==>  3
(denominator (/ 6 4))                  ==>  2

procedure: gcd n1 ...,
procedure: lcm n1 ...,

These procedures return the greatest common divisor or least common multiple of their arguments. The result is always non-negative.

(gcd 32 -36)                           ==>  4
(gcd)                                  ==>  0
(lcm 32 -36)                           ==>  288
(lcm)                                  ==>  1

procedure: floor x
procedure: ceiling x
procedure: truncate x
procedure: round x
procedure: rationalize x y
procedure: rationalize x

These procedures create integers and rationals. Their results are exact if and only if their arguments are exact.

Floor returns the largest integer not larger than x. Ceiling returns the smallest integer not smaller than x. Truncate returns the integer of maximal absolute value not larger than the absolute value of x. Round returns the closest integer to x, rounding to even when x is halfway between two integers. With two arguments, rationalize produces the rational number with smallest denominator differing from x by no more than y. With one argument, rationalize produces the best rational approximation to x, preserving all of the precision in its representation.

Note: Round rounds to even for consistency with the rounding modes required by the IEEE floating point standard.

procedure: exp z
procedure: log z
procedure: sin z
procedure: cos z
procedure: tan z
procedure: asin z
procedure: acos z
procedure: atan z
procedure: atan y x

These procedures are part of every implementation that supports real numbers; they compute the usual transcendental functions. Log computes the natural logarithm of z (not the base 10 logarithm). Asin, acos, and atan compute arcsine (sin^-1), arccosine (cos^-1), and arctangent (tan^-1), respectively. The two-argument variant of atan computes (angle (make-rectangular x y)) (see below), even in implementations that don't support complex numbers.

In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. For nonzero real x, the value of log x is defined to be the one whose imaginary part lies in the range -pi (exclusive) to pi (inclusive). log 0 is undefined. The value of log z when z is complex is defined according to the formula

log z = log magnitude(z) + i --> angle (z)

With log defined this way, the values of sin^-1 z, cos^-1 z, and tan^-1 z are according to the following formulae:

sin^-1 z = -i log (i z + sqrt1 - z^2)

cos^-1 z = -i log (z + i sqrt1 - z^2)

tan^-1 z = -i log ( (1 + i z) sqrt1/(1 + z^2) )

The above specification follows [CLtL], which in turn follows [Penfield81]; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions.

procedure: sqrt z

Returns the principal square root of z. The result will have either positive real part, or zero real part and non-negative imaginary part.

procedure: expt z1 z2

Returns z1 raised to the power z2:

z_1^z_2 = e^z_2 log z_1

0^0 is defined to be equal to 1.

procedure: make-rectangular x1 x2
procedure: make-polar x3 x4
procedure: real-part z
procedure: imag-part z
procedure: magnitude z
procedure: angle z

These procedures are part of every implementation that supports complex numbers. Suppose x1, x2, x3, and x4 are real numbers and z is a complex number such that

z = x1 + x2i = x3 . e^i x4

Then make-rectangular and make-polar return z, real-part returns x1, imag-part returns x2, magnitude returns x3, and angle returns x4. In the case of angle, whose value is not uniquely determined by the preceding rule, the value returned will be the one in the range -pi (exclusive) to pi (inclusive).

Note: Magnitude is the same as abs, but abs must be present in all implementations, whereas magnitude will only be present in implementations that support complex numbers.

procedure: exact->inexact z
procedure: inexact->exact z

Exact->inexact returns an inexact representation of z, which is a fairly harmless thing to do. Inexact->exact returns an exact representation of z. Since the law of "garbage in, garbage out" remains in force, inexact->exact should not be used casually.

Numerical input and output

procedure: number->string number format

The conventions used to produce the printed representation of a number can be specified by a format, as described in section section Formats. The procedure number->string takes a number and a format and returns as a string the printed representation of the given number in the given format. This procedure will mostly be used by sophisticated users and in system programs. In general, a naive user will need to know nothing about the formats because the system printer will have reasonable default formats for all types of numbers.

procedure: string->number string exactness radix

The system reader will construct reasonable default numerical types for numbers expressed in each of the formats it recognizes. A user who needs control of the coercion from strings to numbers will use string->number. Exactness must be a symbol, either `E' (for exact) or `I' (for inexact). Radix must also be a symbol: `B' for binary, `O' for octal, `D' for decimal, and `X' for hexadecimal. Returns a number of the maximally precise representation expressed by the given string. It is an error if string does not express a number according to the grammar in section section Lexical structure.

Formats

A format is a list beginning with a format descriptor, which is a symbol such as `sci'. Following the descriptor are parameters used by that descriptor, such as the number of significant digits to be used. Default values are supplied for any parameters that are omitted. Modifiers may appear after the parameters, such as the `radix' and `exactness' formats described below, which themselves take parameters.

Details of particular formats such as sci and fix are given in section section Details of formats.

For example, the format `(sci 5 2 (exactness s))' specifies that a number is to be expressed in Fortran scientific format with 5 significant places and two places after the radix point, and that its exactness prefix is to be suppressed.

In the following examples, the comment shows the format that was used to produce the output shown:


123  +123  -123              ; (int)
123456789012345678901234567  ; (int)
355/113  +355/113  -355/113  ; (rat)
+123.45  -123.45             ; (fix 2)
3.14159265358979             ; (fix 14)
3.14159265358979             ; (flo 15)
123.450                      ; (flo 6)
-123.45e-1                   ; (sci 5 2)
123e3  123e-3  -123e-3       ; (sci 3 0)
-1+2i                        ; (rect (int) (int))
1.2@1.570796                 ; (polar (fix 1)
                             ;        (flo 7))

A format may specify that a number should be expressed in a particular radix. The radix prefix may also be suppressed. For example, one may express a complex number in polar form with the magnitude in octal and the angle in decimal as follows:


#o1.2@#d1.570796327 ; (polar (flo 2 (radix o))
                    ;        (flo (radix d)))
#o1.2@1.570796327   ; (polar (flo 2 (radix o))
                    ;        (flo (radix d s)))

A format may specify that a number should be expressed with an explicit exactness prefix ((exactness e)), or it may force the exactness to be suppressed ((exactness s)). For example, the following are ways to express an inexact value for pi:


#i355/113           ; (rat (exactness e))
355/113             ; (rat (exactness s))
#i3.1416            ; (fix 4 (exactness e))

An attempt to produce more digits than are available in the internal machine representation of a number will be marked with a "#" filling the extra digits. This is not a statement that the implementation knows or keeps track of the significance of a number, just that the machine will flag attempts to produce 20 digits of a number that has only 15 digits of machine representation:


3.14158265358979#####   ; (flo 20 (exactness s))

Details of formats

The format descriptors are:

format: int

Express as an integer. The radix point is implicit. If there are not enough significant places then insignificant digits will be flagged. For example, an inexact integer 6.0238.10^23 (represented internally as a 7 digit flonum) would be printed as

6023800#################

format: rat n

Express as a rational fraction. n specifies the largest denominator to be used in constructing a rational approximation to the number being expressed. If n is omitted it defaults to infinity.

format: fix n

Express with a fixed radix point. n specifies the number of places to the right of the radix point. n defaults to the size of a single-precision flonum. If there are not enough significant places, then insignificant digits will be flagged. For example, an inexact 6.0238.10^23 (represented internally as a 7 digit flonum) would be printed with a (fix 2) format as

6023800#################.##

format: flo n

Express with a floating radix point. n specifies the total number of places to be displayed. n defaults to the size of a single-precision flonum. If the number is out of range, it is converted to (sci). (flo h) expresses n in floating point format heuristically for human consumption.

format: sci n m

Express in exponential notation. n specifies the total number of places to be displayed. n defaults to the size of a single-precision flonum. m specifies the number of places to the right of the radix point. m defaults to n-1. (sci h) does heuristic expression.

format: rect r i

Express as a rectangular form complex number. r and i are formats for the real and imaginary parts respectively. They default to (heur).

format: polar m a

Express as a polar form complex number. m and a are formats for the magnitude and angle respectively. m and a default to (heur).

format: heur

Express heuristically using the minimum number of digits required to get an expression that when coerced back to a number produces the original machine representation. Exact numbers are expressed as (int) or (rat). Inexact numbers are expressed as (flo h) or (sci h) depending on their range. Complex numbers are expressed in (rect). This is the normal default of the system printer.

The following modifiers may be added to a numerical format specification:

format: exactness s

This controls the expression of the exactness prefix of a number. s must be a symbol, either E or S, indicating whether the exactness is to be expressed or suppressed, respectively. If no exactness modifier is specified for a format then the exactness is by default suppressed.

format: radix r s

This forces a number to be expressed in the radix r. r may be the symbol B (binary), O (octal), D (decimal), or X (hex). s must be a symbol, either E or S, indicating whether the radix prefix is to be expressed or suppressed, respectively. s defaults to E (expressed). If no radix modifier is specified then the default is decimal and the prefix is suppressed.

Characters

Characters are objects that represent printed characters such as letters and digits. There is no requirement that the data type of characters be disjoint from other data types; implementations are encouraged to have a separate character data type, but may choose to represent characters as integers, strings, or some other type.

Characters are written using the notation #\<character> or #\<character name>. For example:

#\a
; lower case letter
#\A
; upper case letter
#\(
; left parenthesis
#\
; the space character
#\space
; the preferred way to write a space
#\newline
; the newline character

Case is significant in #\<character>, but not in #\<character name>. If <character> in #\<character> is alphabetic, then the character following <character> must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of characters "#\ space" could be taken to be either a representation of the space character or a representation of the character "#\ s" followed by a representation of the symbol "pace."

Characters written in the #\ notation are self-evaluating. That is, they do not have to be quoted in programs. The #\ notation is not an essential part of Scheme, however. Even implementations that support the #\ notation for input do not have to support it for output.

Some of the procedures that operate on characters ignore the difference between upper case and lower case. The procedures that ignore case have the suffix "-ci" (for "case insensitive"). If the operation is a predicate, then the "-ci" suffix precedes the "?" at the end of the name.

essential procedure: char? obj

Returns #t if obj is a character, otherwise returns #f.

essential procedure: char=? char1 char2
essential procedure: char<? char1 char2
essential procedure: char>? char1 char2
essential procedure: char<=? char1 char2
essential procedure: char>=? char1 char2

These procedures impose a total ordering on the set of characters. It is guaranteed that under this ordering:

Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numeric predicates.

procedure: char-ci=? char1 char2
procedure: char-ci<? char1 char2
procedure: char-ci>? char1 char2
procedure: char-ci<=? char1 char2
procedure: char-ci>=? char1 char2

These procedures are similar to char=? et cetera, but they treat upper case and lower case letters as the same. For example, `(char-ci=? #\A #\a)' returns #t. Some implementations may generalize these procedures to take more than two arguments, as with the corresponding numeric predicates.

procedure: char-alphabetic? char
procedure: char-numeric? char
procedure: char-whitespace? char

These procedures return #t if their arguments are alphabetic, numeric, or whitespace characters, respectively, otherwise they return #f. The following remarks, which are specific to the ASCII character set, are intended only as a guide: The alphabetic characters are the 52 upper and lower case letters. The numeric characters are the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and carriage return.

procedure: char-upper-case? letter
procedure: char-lower-case? letter

Letter must be an alphabetic character. These procedures return #t if their arguments are upper case or lower case characters, respectively, otherwise they return #f.

essential procedure: char->integer char
essential procedure: integer->char n

Given a character, char->integer returns an integer representation of the character. Given an integer that is the image of a character under char->integer, integer->char returns a character. These procedures implement order isomorphisms between the set of characters under the char<=? ordering and some subset of the integers under the <= ordering. That is, if

(char<=? a b) => #t  and  (<= x y) => #t

and x and y are in the range of char->integer, then

(<= (char->integer a)
    (char->integer b))                 ==>  #t

(char<=? (integer->char x)
         (integer->char y))            ==>  #t

procedure: char-upcase char
procedure: char-downcase char

These procedures return a character char2 such that `(char-ci=? char char2)'. In addition, if char is alphabetic, then the result of char-upcase is upper case and the result of char-downcase is lower case.

Strings

Strings are sequences of characters. In some implementations of Scheme they are immutable; other implementations provide destructive procedures such as string-set! that alter string objects.

Strings are written as sequences of characters enclosed within doublequotes (`"'). A doublequote can be written inside a string only by escaping it with a backslash (\), as in


"The word \"recursion\" has many meanings."

A backslash can be written inside a string only by escaping it with another backslash. Scheme does not specify the effect of a backslash within a string that is not followed by a doublequote or backslash.

A string may continue from one line to the next, but this is usually a bad idea because the exact effect may vary from one computer system to another.

The length of a string is the number of characters that it contains. This number is a non-negative integer that is fixed when the string is created. The valid indexes of a string are the exact non-negative integers less than the length of the string. The first character of a string has index 0, the second has index 1, and so on.

In phrases such as "the characters of string beginning with index start and ending with index end," it is understood that the index start is inclusive and the index end is exclusive. Thus if start and end are the same index, a null substring is referred to, and if start is zero and end is the length of string, then the entire string is referred to.

Some of the procedures that operate on strings ignore the difference between upper and lower case. The versions that ignore case have the suffix "`-ci'" (for "case insensitive"). If the operation is a predicate, then the "`-ci'" suffix precedes the "`?'" at the end of the name.

essential procedure: string? obj

Returns #t if obj is a string, otherwise returns #f.

procedure: make-string k
procedure: make-string k char

k must be a non-negative integer, and char must be a character. Make-string returns a newly allocated string of length k. If char is given, then all elements of the string are initialized to char, otherwise the contents of the string are unspecified.

essential procedure: string-length string

Returns the number of characters in the given string.

essential procedure: string-ref string k

k must be a valid index of string. String-ref returns character k of string using zero-origin indexing.

procedure: string-set! string k char

k must be a valid index of string . String-set! stores char in element k of string and returns an unspecified value.

essential procedure: string=? string1 string2
procedure: string-ci=? string1 string2

Returns #t if the two strings are the same length and contain the same characters in the same positions, otherwise returns #f. String-ci=? treats upper and lower case letters as though they were the same character, but string=? treats upper and lower case as distinct characters.

essential procedure: string<? string1 string2
essential procedure: string>? string1 string2
essential procedure: string<=? string1 string2
essential procedure: string>=? string1 string2
procedure: string-ci<? string1 string2
procedure: string-ci>? string1 string2
procedure: string-ci<=? string1 string2
procedure: string-ci>=? string1 string2

These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, string<? is the lexicographic ordering on strings induced by the ordering char<? on characters. If two strings differ in length but are the same up to the length of the shorter string, the shorter string is considered to be lexicographically less than the longer string.

Implementations may generalize these and the string=? and string-ci=? procedures to take more than two arguments, as with the corresponding numeric predicates.

essential procedure: substring string start end

String must be a string, and start and end must be exact integers satisfying

0 <= start <= end <= (string-length string).

Substring returns a newly allocated string formed from the characters of string beginning with index start (inclusive) and ending with index end (exclusive).

essential procedure: string-append string1 string2
procedure: string-append string ...,

Returns a new string whose characters form the concatenation of the given strings.

essential procedure: string->list string
essential procedure: list->string chars

String->list returns a newly allocated list of the characters that make up the given string. List->string returns a string formed from the characters in the list chars. String->list and list->string are inverses so far as equal? is concerned. Implementations that provide destructive operations on strings should ensure that the result of list->string is newly allocated.

procedure: string-copy string

Returns a newly allocated copy of the given string.

procedure: string-fill! string char

Stores char in every element of the given string and returns an unspecified value.

Vectors

Vectors are heterogenous mutable structures whose elements are indexed by integers.

The length of a vector is the number of elements that it contains. This number is a non-negative integer that is fixed when the vector is created. The valid indexes of a vector are the exact non-negative integers less than the length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than the length of the vector.

Vectors are written using the notation #(obj ...,). For example, a vector of length 3 containing the number zero in element 0, the list `(2 2 2 2)' in element 1, and the string `"Anna"' in element 2 can be written as following:


#(0 (2 2 2 2) "Anna")

Note that this is the external representation of a vector, not an expression evaluating to a vector. Like list constants, vector constants must be quoted:


'#(0 (2 2 2 2) "Anna")  
          ==>  #(0 (2 2 2 2) "Anna")

essential procedure: vector? obj
Returns #t if obj is a vector, otherwise returns #f.

essential procedure: make-vector k
procedure: make-vector k fill

Returns a newly allocated vector of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified.

essential procedure: vector obj ...,

Returns a newly allocated vector whose elements contain the given arguments. Analogous to list.

(vector 'a 'b 'c)                      ==>  #(a b c)

essential procedure: vector-length vector

Returns the number of elements in vector.

essential procedure: vector-ref vector k

k must be a valid index of vector. Vector-ref returns the contents of element k of vector.

(vector-ref '#(1 1 2 3 5 8 13 21) 5)  =>  8

essential procedure: vector-set! vector k obj

k must be a valid index of vector. Vector-set! stores obj in element k of vector. The value returned by vector-set! is unspecified.

(let ((vec (vector 0 '(2 2 2 2) "Anna")))
  (vector-set! vec 1 '("Sue" "Sue"))
  vec)      
          ==>  #(0 ("Sue" "Sue") "Anna")

essential procedure: vector->list vector
essential procedure: list->vector list

Vector->list returns a newly created list of the objects contained in the elements of vector. List->vector returns a newly created vector initialized to the elements of the list list.

(vector->list '#(dah dah didah))  
          ==>  (dah dah didah)
(list->vector '(dididit dah))   
          ==>  #(dididit dah)

procedure: vector-fill! vector fill

Stores fill in every element of vector. The value returned by vector-fill! is unspecified.

Control features

This chapter describes various primitive procedures which control the flow of program execution in special ways. The procedure? predicate is also described here.

essential procedure: procedure? obj

Returns #t if obj is a procedure, otherwise returns #f.

(procedure? car)                       ==>  #t
(procedure? 'car)                      ==>  #f
(procedure? (lambda (x) (* x x)))   
                                       ==>  #t
(procedure? '(lambda (x) (* x x)))  
                                       ==>  #f
(call-with-current-continuation procedure?)
                                       ==>  #t

essential procedure: apply proc args
procedure: apply proc arg1 ... args

Proc must be a procedure and args must be a list. The first (essential) form calls proc with the elements of args as the actual arguments. The second form is a generalization of the first that calls proc with the elements of the list `(append (list arg1 ...,) args)' as the actual arguments.

(apply + (list 3 4))                   ==>  7

(define compose
  (lambda (f g)
    (lambda args
      (f (apply g args)))))

((compose sqrt *) 12 75)               ==>  30

essential procedure: map proc list
procedure: map proc list1 list2 ...,

The lists must be lists, and proc must be a procedure taking as many arguments as there are lists. If more than one list is given, then they must all be the same length. Map applies proc element-wise to the elements of the lists and returns a list of the results. The order in which proc is applied to the elements of the lists is unspecified.

(map cadr '((a b) (d e) (g h)))   
          ==>  (b e h)

(map (lambda (n) (expt n n))
     '(1 2 3 4 5))                
          ==>  (1 4 27 256 3125)

(map + '(1 2 3) '(4 5 6))              ==>  (5 7 9)

(let ((count 0))
  (map (lambda (ignored)
         (set! count (+ count 1))
         count)
       '(a b c)))                      ==>  unspecified

essential procedure: for-each proc list
procedure: for-each proc list1 list2 ...,

The arguments to for-each are like the arguments to map, but for-each calls proc for its side effects rather than for its values. Unlike map, for-each is guaranteed to call proc on the elements of the lists in order from the first element to the last, and the value returned by for-each is unspecified.

(let ((v (make-vector 5)))
  (for-each (lambda (i)
              (vector-set! v i (* i i)))
            '(0 1 2 3 4))
  v)                                   ==>  #(0 1 4 9 16)

procedure: force promise

Forces the value of promise (see delay, section see section Delayed evaluation). If no value has been computed for the promise, then a value is computed and returned. The value of the promise is cached (or "memoized") so that if it is forced a second time, the previously computed value is returned without any recomputation.

(force (delay (+ 1 2)))                ==>  3
(let ((p (delay (+ 1 2))))
  (list (force p) (force p)))  
                                       ==>  (3 3)

(define a-stream
  (letrec ((next
            (lambda (n)
              (cons n (delay (next (+ n 1)))))))
    (next 0)))
(define head car)
(define tail
  (lambda (stream) (force (cdr stream))))

(head (tail (tail a-stream)))  
                                       ==>  2

Force and delay are mainly intended for programs written in functional style. The following examples should not be considered to illustrate good programming style, but they illustrate the property that the value of a promise is computed at most once.

(define count 0)
(define p (delay (begin (set! count (+ count 1))
                        (* x 3))))
(define x 5)
count                                  ==>  0
p                                      ==>  a promise
(force p)                              ==>  15
p                                      ==>  a promise, still
count                                  ==>  1
(force p)                              ==>  15
count                                  ==>  1

Here is a possible implementation of delay and force. We define the expression

(delay <expression>)

to have the same meaning as the procedure call

(make-promise (lambda () <expression>)),

where make-promise is defined as follows:

(define make-promise
  (lambda (proc)
    (let ((already-run? #f) (result #f))
      (lambda ()
        (cond ((not already-run?)
               (set! result (proc))
               (set! already-run? #t)))
        result))))

Promises are implemented here as procedures of no arguments, and force simply calls its argument.

(define force
  (lambda (object)
    (object)))

Various extensions to this semantics of delay and force are supported in some implementations:

essential procedure: call-with-current-continuation proc

Proc must be a procedure of one argument. The procedure call-with-current-continuation packages up the current continuation (see the rationale below) as an "escape procedure" and passes it as an argument to proc. The escape procedure is a Scheme procedure of one argument that, if it is later passed a value, will ignore whatever continuation is in effect at that later time and will give the value instead to the continuation that was in effect when the escape procedure was created.

The escape procedure created by call-with-current-continuation has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired.

The following examples show only the most common uses of call-with-current-continuation. If all real programs were as simple as these examples, there would be no need for a procedure with the power of call-with-current-continuation.

(call-with-current-continuation
  (lambda (exit)
    (for-each (lambda (x)
                (if (negative? x)
                    (exit x)))
              '(54 0 37 -3 245 19))
    #t))                               ==>  -3

(define list-length
  (lambda (obj)
    (call-with-current-continuation
      (lambda (return)
        (letrec ((r
                  (lambda (obj)
                    (cond ((null? obj) 0)
                          ((pair? obj)
                           (+ (r (cdr obj)) 1))
                          (else (return #f))))))
          (r obj))))))

(list-length '(1 2 3 4))               ==>  4

(list-length '(a b . c))               ==>  #f

Rationale: A common use of call-with-current-continuation is for structured, non-local exits from loops or procedure bodies, but in fact call-with-current-continuation is extremely useful for implementing a wide variety of advanced control structures.

Whenever a Scheme expression is evaluated there is a continuation wanting the result of the expression. The continuation represents an entire (default) future for the computation. If the expression is evaluated at top level, for example, then the continuation will take the result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions specified by user code, as in a continuation that will take the result, multiply it by the value stored in a local variable, add seven, and give the answer to the top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and programmers don't think much about them. On rare occasions, however, a programmer may need to deal with continuations explicitly. Call-with-current-continuation allows Scheme programmers to do that by creating a procedure that acts just like the current continuation.

Most programming languages incorporate one or more special-purpose escape constructs with names like exit, return, or even goto. In 1965, however, Peter Landin [Landin65] invented a general purpose escape operator called the J-operator. John Reynolds [Reynolds72] described a simpler but equally powerful construct in 1972. The catch special form described by Sussman and Steele in the 1975 report on Scheme is exactly the same as Reynolds's construct, though its name came from a less general construct in MacLisp. Several Scheme implementors noticed that the full power of the catch construct could be provided by a procedure instead of by a special syntactic construct, and the name call-with-current-continuation was coined in 1982. This name is descriptive, but opinions differ on the merits of such a long name, and some people use the name call/cc instead.

Input and output

Ports

Ports represent input and output devices. To Scheme, an input device is a Scheme object that can deliver characters upon command, while an output device is a Scheme object that can accept characters.

essential procedure: call-with-input-file string proc
essential procedure: call-with-output-file string proc

Proc should be a procedure of one argument, and string should be a string naming a file. For call-with-input-file, the file must already exist; for call-with-output-file, the effect is unspecified if the file already exists. These procedures call proc with one argument: the port obtained by opening the named file for input or output. If the file cannot be opened, an error is signalled. If the procedure returns, then the port is closed automatically and the value yielded by the procedure is returned. If the procedure does not return, then Scheme will not close the port unless it can prove that the port will never again be used for a read or write operation.

Rationale: Because Scheme's escape procedures have unlimited extent, it is possible to escape from the current continuation but later to escape back in. If implementations were permitted to close the port on any escape from the current continuation, then it would be impossible to write portable code using both call-with-current-continuation and call-with-input-file or call-with-output-file.

essential procedure: input-port? obj
essential procedure: output-port? obj

Returns #t if obj is an input port or output port respectively, otherwise returns #f.

essential procedure: current-input-port
essential procedure: current-output-port
Returns the current default input or output port.

procedure: with-input-from-file string thunk
procedure: with-output-to-file string thunk

Thunk must be a procedure of no arguments, and string must be a string naming a file. For with-input-from-file, the file must already exist; for with-output-to-file, the effect is unspecified if the file already exists. The file is opened for input or output, an input or output port connected to it is made the default value returned by current-input-port or current-output-port, and the thunk is called with no arguments. When the thunk returns, the port is closed and the previous default is restored. With-input-from-file and with-output-to-file return the value yielded by thunk. If an escape procedure is used to escape from the continuation of these procedures, their behavior is implementation dependent.

procedure: open-input-file filename
Takes a string naming an existing file and returns an input port capable of delivering characters from the file. If the file cannot be opened, an error is signalled.

procedure: open-output-file filename

Takes a string naming an output file to be created and returns an output port capable of writing characters to a new file by that name. If the file cannot be opened, an error is signalled. If a file with the given name already exists, the effect is unspecified.

procedure: close-input-port port
procedure: close-output-port port

Closes the file associated with port, rendering the port incapable of delivering or accepting characters.

These routines have no effect if the file has already been closed. The value returned is unspecified.

Input

essential procedure: read
essential procedure: read port

Read converts written representations of Scheme objects into the objects themselves. That is, it is a parser for the nonterminal <datum> (see section see section External representations). Read returns the next object parsable from the given input port, updating port to point to the first character past the end of the written representation of the object.

If an end of file is encountered in the input before any characters are found that can begin an object, then an end of file object is returned. The port remains open, and further attempts to read will also return an end of file object. If an end of file is encountered after the beginning of an object's written representation, but the written representation is incomplete and therefore not parsable, an error is signalled.

The port argument may be omitted, in which case it defaults to the value returned by current-input-port. It is an error to read from a closed port.

essential procedure: read-char
essential procedure: read-char port

Returns the next character available from the input port, updating the port to point to the following character. If no more characters are available, an end of file object is returned. Port may be omitted, in which case it defaults to the value returned by current-input-port.

procedure: char-ready?
procedure: char-ready? port

Returns #t if a character is ready on the input port and returns #f otherwise. If char-ready returns #t then the next read-char operation on the given port is guaranteed not to hang. If the port is at end of file then char-ready? returns #t. Port may be omitted, in which case it defaults to the value returned by current-input-port.

Rationale: Char-ready? exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input. Any input editors associated with such ports must ensure that characters whose existence has been asserted by char-ready? cannot be rubbed out. If char-ready? were to return #f at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters.

essential procedure: eof-object? obj

Returns #t if obj is an end of file object, otherwise returns #f. The precise set of end of file objects will vary among implementations, but in any case no end of file object will ever be a character or an object that can be read in using read.

Output

essential procedure: write obj
essential procedure: write obj port

Writes a representation of obj to the given port. Strings that appear in the written representation are enclosed in doublequotes, and within those strings backslash and doublequote characters are escaped by backslashes. Write returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.

essential procedure: display obj
essential procedure: display obj port

Writes a representation of obj to the given port. Strings that appear in the written representation are not enclosed in doublequotes, and no characters are escaped within those strings. In those implementations that have a distinct character type, character objects appear in the representation as if written by write-char instead of by write. Display returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.

Rationale: Write is intended for producing machine-readable output and display is for producing human-readable output. Implementations that allow "slashification" within symbols will probably want write but not display to slashify funny characters in symbols.

essential procedure: newline
essential procedure: newline port

Writes an end of line to port. Exactly how this is done differs from one operating system to another. Returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.

essential procedure: write-char char
essential procedure: write-char char port

Writes the character char (not a written representation of the character) to the given port and returns an unspecified value. The port argument may be omitted, in which case it defaults to the value returned by current-output-port.

User interface

Questions of user interface generally fall outside of the domain of this report. However, the following operations are important enough to deserve description here.

essential procedure: load filename

Filename should be a string naming an existing file containing Scheme source code. The load procedure reads expressions and definitions from the file and evaluates them sequentially. It is unspecified whether the results of the expressions are printed. The load procedure does not affect the values returned by current-input-port and current-output-port. Load returns an unspecified value.

Note: For portability, load must operate on source files. Its operation on other kinds of files necessarily varies among implementations.

procedure: transcript-on filename
procedure: transcript-off

Filename must be a string naming an output file to be created. The effect of transcript-on is to open the named file for output, and to cause a transcript of subsequent interaction between the user and the Scheme system to be written to the file. The transcript is ended by a call to transcript-off, which closes the transcript file. Only one transcript may be in progress at any time, though some implementations may relax this restriction. The values returned by these procedures are unspecified.


Go to the first, previous, next, last section, table of contents.