This is r4rs.info, produced by Makeinfo version 3.12a from r4rs.texi. INFO-DIR-SECTION Scheme Programming START-INFO-DIR-ENTRY * r4rs: (r4rs). Revised(4) Report on Scheme END-INFO-DIR-ENTRY  File: r4rs.info, Node: Implementation restrictions, Next: Syntax of numerical constants, Prev: Exactness, Up: Numbers Implementation restrictions --------------------------- Implementations of Scheme are not required to implement the whole tower of subtypes given in *Note Numerical types::, but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, an implementation in which all numbers are real may still be quite useful. Implementations may also support only a limited range of numbers of any type, subject to the requirements of this section. The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type. For example, an implementation that uses flonums to represent all its inexact real numbers may support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the flonum format. Furthermore the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached. An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists, vectors, and strings or that may result from computing the length of a list, vector, or string. The `length', `vector-length', and `string-length' procedures must return an exact integer, and it is an error to use anything but an exact integer as an index. Furthermore any integer constant within the index range, if expressed by an exact integer syntax, will indeed be read as an exact integer, regardless of any implementation restrictions that may apply outside this range. Finally, the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation: + - * quotient remainder modulo max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize expt Implementations are encouraged, but not required, to support exact integers and exact rationals of practically unlimited size and precision, and to implement the above procedures and the `/' procedure in such a way that they always return exact results when given exact arguments. If one of these procedures is unable to deliver an exact result when given exact arguments, then it may either report a violation of an implementation restriction or it may silently coerce its result to an inexact number. Such a coercion may cause an error later. An implementation may use floating point and other approximate representation strategies for inexact numbers. This report recommends, but does not require, that the IEEE 32-bit and 64-bit floating point standards be followed by implementations that use flonum representations, and that implementations using other representations should match or exceed the precision achievable using these floating point standards [IEEE]. In particular, implementations that use flonum representations must follow these rules: A flonum result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation. It is desirable (but not required) for potentially inexact 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, however, an exact number is operated upon so as to produce an inexact result (as by `sqrt'), and if the result is represented as a flonum, then the most precise flonum format available must be used; but if the result is represented in some other way then the representation must have at least as much precision as the most precise flonum format available. Although Scheme allows a variety of written notations for numbers, any particular implementation may support only some of them. For example, an implementation in which all numbers are real need not support the rectangular and polar notations for complex numbers. If an implementation encounters an exact numerical constant that it cannot represent as an exact number, then it may either report a violation of an implementation restriction or it may silently represent the constant by an inexact number.  File: r4rs.info, Node: Syntax of numerical constants, Next: Numerical operations, Prev: Implementation restrictions, Up: Numbers Syntax of numerical constants ----------------------------- The syntax of the written representations for numbers is described formally in *Note Lexical structure::. A number may be written in binary, octal, decimal, or hexadecimal by the use of a radix prefix. The radix prefixes are `#b' (binary), `#o' (octal), `#d' (decimal), and `#x' (hexadecimal). With no radix prefix, a number is assumed to be expressed in decimal. A numerical constant may be specified to be either exact or inexact by a prefix. The prefixes are `#e' for exact, and `#i' for inexact. An exactness prefix may appear before or after any radix prefix that is used. If the written representation of a number has no exactness prefix, the constant may be either inexact or exact. It is inexact if it contains a decimal point, an exponent, or a ``#'' character in the place of a digit, otherwise it is exact. In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant. For this purpose, numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation. The letters `s', `f', `d', and `l' specify the use of SHORT, SINGLE, DOUBLE, and LONG precision, respectively. (When fewer than four internal inexact representations exist, the four size specifications are mapped onto those available. For example, an implementation with two internal representations may map short and single together and long and double together.) In addition, the exponent marker `e' specifies the default precision for the implementation. The default precision has at least as much precision as DOUBLE, but implementations may wish to allow this default to be set by the user. 3.14159265358979F0 Round to single -- 3.141593 0.6L0 Extend to long -- .600000000000000  File: r4rs.info, Node: Numerical operations, Next: Numerical input and output, Prev: Syntax of numerical constants, Up: Numbers Numerical operations -------------------- The reader is referred to *Note Entry format:: for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines. The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number. Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy; the inexact constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers. -- 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 `#t' if the object is of the named type, and otherwise they return `#f'. In general, if a type predicate is true of a number then all higher type predicates are also true of that number. Consequently, if a type predicate is false of a number, then all lower type predicates are also false of that number. If Z is an inexact complex number, then `(real? Z)' is true if and only if `(zero? (imag-part Z))' is true. If X is an inexact real number, then `(integer? X)' is true if and only if `(= X (round X))'. (complex? 3+4i) => #t (complex? 3) => #t (real? 3) => #t (real? -2.5+0.0i) => #t (real? #e1e10) => #t (rational? 6/10) => #t (rational? 6/3) => #t (integer? 3+0i) => #t (integer? 3.0) => #t (integer? 8/4) => #t _Note:_ The behavior of these type predicates on inexact numbers is unreliable, since any inaccuracy may affect the result. _Note:_ In many implementations the `rational?' procedure will be the same as `real?', and the `complex?' procedure will be the same as `number?', but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non-complex numbers. -- essential procedure: exact? z -- essential procedure: inexact? z These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of these predicates is true. -- essential procedure: = z1 z2 z3 ... -- essential procedure: < x1 x2 x3 ... -- essential procedure: > x1 x2 x3 ... -- essential procedure: <= x1 x2 x3 ... -- essential procedure: >= x1 x2 x3 ... These procedures return `#t' if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing. These predicates are required to be transitive. _Note:_ The traditional implementations of these predicates in Lisp-like languages are not transitive. _Note:_ While it is not an error to compare inexact numbers using these predicates, the results may be unreliable because a small inaccuracy may affect the result; this is especially true of `=' and `zero?'. When in doubt, consult a numerical analyst. -- essential procedure: zero? z -- essential procedure: positive? x -- essential procedure: negative? x -- essential procedure: odd? n -- essential procedure: even? n These numerical predicates test a number for a particular property, returning `#t' or `#f'. See note above. -- essential procedure: max x1 x2 ... -- essential procedure: min x1 x2 ... These procedures return the maximum or minimum of their arguments. (max 3 4) => 4 ; exact (max 3.9 4) => 4.0 ; inexact _Note:_ If any argument is inexact, then the result will also be inexact (unless the procedure can prove that the inaccuracy is not large enough to affect the result, which is possible only in unusual implementations). If `min' or `max' is used to compare numbers of mixed exactness, and the numerical value of the result cannot be represented as an inexact number without loss of accuracy, then the procedure may report a violation of an implementation restriction. -- essential procedure: + z1 ... -- essential 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 -- essential procedure: - z -- procedure: - z1 z2 ... -- essential procedure: / z1 z2 -- essential procedure: / z -- 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 x `Abs' returns the magnitude of its argument. (abs -7) => 7 -- essential procedure: quotient n1 n2 -- essential procedure: remainder n1 n2 -- essential procedure: modulo n1 n2 These procedures implement number-theoretic (integer) division: For positive integers N1 and N2, if N3 and N4 are integers such that `(= n1 (+ (* n2 n3) n4))', `(<= 0 n4)', and `(< n4 n2)'. Then (quotient N1 N2) => N3 (remainder N1 N2) => N4 (modulo N1 N2) => N4 For integers N1 and N2 with N2 not equal to 0, (= N1 (+ (* N2 (quotient N1 N2)) (remainder N1 N2))) => #t provided all numbers involved in that computation are exact. The value returned by `quotient' always has the sign of the product of its arguments. `Remainder' and `modulo' differ on negative arguments---the `remainder' is either zero or has the sign of the dividend, while 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 (remainder -13 -4.0) => -1.0 ; inexact -- essential procedure: gcd n1 ... -- essential 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 32.0 -36) => 288.0 ; inexact (lcm) => 1 -- procedure: numerator q -- procedure: denominator q These procedures return the numerator or denominator of their argument; the result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1. (numerator (/ 6 4)) => 3 (denominator (/ 6 4)) => 2 (denominator (exact->inexact (/ 6 4))) => 2.0 -- essential procedure: floor x -- essential procedure: ceiling x -- essential procedure: truncate x -- essential procedure: round x These procedures return integers. `Floor' returns the largest integer not larger than X. `Ceiling' returns the smallest integer not smaller than X. `Truncate' returns the integer closest to X whose absolute value is not larger than the absolute value of X. `Round' returns the closest integer to X, rounding to even when X is halfway between two integers. _Rationale:_ `Round' rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard. _Note:_ If the argument to one of these procedures is inexact, then the result will also be inexact. If an exact value is needed, the result should be passed to the `inexact->exact' procedure. (floor -4.3) => -5.0 (ceiling -4.3) => -4.0 (truncate -4.3) => -4.0 (round -4.3) => -4.0 (floor 3.5) => 3.0 (ceiling 3.5) => 4.0 (truncate 3.5) => 3.0 (round 3.5) => 4.0 ; inexact (round 7/2) => 4 ; exact (round 7) => 7 -- procedure: rationalize x y `Rationalize' returns the _simplest_ rational number differing from X by no more than Y. A rational number R1 is _simpler_ than another rational number R2 if `(= r1 (/ p1 q1))' and `(= r2 (/ p2 q2))' (in lowest terms) and `(<= (abs p1) (abs p2))' and `(<= (abs q1) (abs q2))'. Thus `(3/5)' is simpler than `(4/7)'. Although not all rationals are comparable in this ordering (consider `(2/7)' and `(3/5)') any interval contains a rational number that is simpler than every other rational number in that interval (the simpler `(2/5)' lies between `(2/7)' and `(3/5)'). Note that 0 (`0/1') is the simplest rational of all. (rationalize (inexact->exact .3) 1/10) => 1/3 ; exact (rationalize .3 1/10) => #i1/3 ; inexact -- procedure: exp z -- procedure: log z -- procedure: sin z -- procedure: cos z -- procedure: tan z -- procedure: asin z -- procedure: acos z -- procedure: atan z -- procedure: atan y x These procedures are part of every implementation that supports general real numbers; they compute the usual transcendental functions. `Log' computes the natural logarithm of Z (not the base ten logarithm). `Asin', `acos', and `atan' compute arcsine , arccosine , and arctangent , respectively. The two-argument variant of `atan' computes `(angle (make-rectangular X Y))' (see below), even in implementations that don't support general complex numbers. In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. 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 (define (log z) (+ (log (magnitude z)) (* +i (angle z)))) With `(log)' defined this way, the values of `arcsin', `arccos', and `arctan' are according to the following formulae: (define (asin z) (* -i (log (+ (* +i z) (sqrt (- 1 (* z z))))))) (define (acos z) (- (/ pi 2) (asin z))) (define (atan z) (/ (log (/ (+ 1 (* +i z)) (- 1 (* +i z)))) (* +i 2)) The above specification follows [CLTL], which in turn cites [PENFIELD81]; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions. When it is possible these procedures produce a real result from a real argument. -- procedure: 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: (define (expt z1 z2) (exp z2 (log z1))) `(expt 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 general complex numbers. Suppose X1, X2, X3, and X4 are real numbers and Z is a complex number such that `(= z (+ x1 (* +i x2) (* x3 (exp (* +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). _Rationale:_ `Magnitude' is the same as `abs' for a real argument, but `abs' must be present in all implementations, whereas `magnitude' need only be present in implementations that support general complex numbers. -- procedure: exact->inexact z -- procedure: inexact->exact z `Exact->inexact' returns an inexact representation of Z. The value returned is the inexact number that is numerically closest to the argument. If an exact argument has no reasonably close inexact equivalent, then a violation of an implementation restriction may be reported. `Inexact->exact' returns an exact representation of Z. The value returned is the exact number that is numerically closest to the argument. If an inexact argument has no reasonably close exact equivalent, then a violation of an implementation restriction may be reported. These procedures implement the natural one-to-one correspondence between exact and inexact integers throughout an implementation-dependent range. See *Note Implementation restrictions::.  File: r4rs.info, Node: Numerical input and output, Prev: Numerical operations, Up: Numbers Numerical input and output -------------------------- -- essential procedure: number->string number -- essential procedure: number->string number radix RADIX must be an exact integer, either 2, 8, 10, or 16. If omitted, RADIX defaults to 10. The procedure `number->string' takes a number and a radix and returns as a string an external representation of the given number in the given radix such that (let ((number NUMBER) (radix RADIX)) (eqv? number (string->number (number->string number radix) radix))) is true. It is an error if no possible result makes this expression true. If NUMBER is inexact, the radix is 10, and the above expression can be satisfied by a result that contains a decimal point, then the result contains a decimal point and is expressed using the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the above expression true [HOWTOPRINT], [HOWTOREAD]; otherwise the format of the result is unspecified. The result returned by `number->string' never contains an explicit radix prefix. _Note:_ The error case can occur only when NUMBER is not a complex number or is a complex number with a non-rational real or imaginary part. _Rationale:_ If NUMBER is an inexact number represented using flonums, and the radix is 10, then the above expression is normally satisfied by a result containing a decimal point. The unspecified case allows for infinities, NaNs, and non-flonum representations. -- essential procedure: string->number string -- essential procedure: string->number string radix Returns a number of the maximally precise representation expressed by the given STRING. RADIX must be an exact integer, either 2, 8, 10, or 16. If supplied, RADIX is a default radix that may be overridden by an explicit radix prefix in STRING (e.g. `"#o177"'). If RADIX is not supplied, then the default radix is 10. If STRING is not a syntactically valid notation for a number, then `string->number' returns `#f'. (string->number "100") => 100 (string->number "100" 16) => 256 (string->number "1e2") => 100.0 (string->number "15##") => 1500.0 _Note:_ Although `string->number' is an essential procedure, an implementation may restrict its domain in the following ways. `String->number' is permitted to return `#f' whenever STRING contains an explicit radix prefix. If all numbers supported by an implementation are real, then `string->number' is permitted to return `#f' whenever STRING uses the polar or rectangular notations for complex numbers. If all numbers are integers, then `string->number' may return `#f' whenever the fractional notation is used. If all numbers are exact, then `string->number' may return `#f' whenever an exponent marker or explicit exactness prefix is used, or if a `#' appears in place of a digit. If all inexact numbers are integers, then `string->number' may return `#f' whenever a decimal point is used.  File: r4rs.info, Node: Characters, Next: Strings, Prev: Numbers, Up: Standard procedures Characters ========== Characters are objects that represent printed characters such as letters and digits. Characters are written using the notation #\ or #\. 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 #\, but not in #\. If in #\ is alphabetic, then the character following must be a delimiter character such as a space or parenthesis. This rule resolves the ambiguous case where, for example, the sequence of characters ```#\space''' could be taken to be either a representation of the space character or a representation of the character ```#\s''' followed by a representation of the symbol ```pace'.'' Characters written in the #\ notation are self-evaluating. That is, they do not have to be quoted in programs. Some of the procedures that operate on characters ignore the difference between upper case and lower case. The procedures that ignore case have ```-ci''' (for ``case insensitive'') embedded in their names. -- 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 These procedures impose a total ordering on the set of characters. It is guaranteed that under this ordering: * The upper case characters are in order. For example, `(char? char1 char2 -- essential procedure: char-ci<=? char1 char2 -- essential 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 numerical predicates. -- essential procedure: char-alphabetic? char -- essential procedure: char-numeric? char -- essential procedure: char-whitespace? char -- essential procedure: char-upper-case? letter -- essential procedure: char-lower-case? letter These procedures return `#t' if their arguments are alphabetic, numeric, whitespace, upper case, or lower case characters, respectively, otherwise they return `#f'. The following remarks, which are specific to the ASCII character set, are intended only as a guide: The alphabetic characters are the 52 upper and lower case letters. The numeric characters are the ten decimal digits. The whitespace characters are space, tab, line feed, form feed, and carriage return. -- essential procedure: char->integer char -- essential procedure: integer->char n Given a character, `char->integer' returns an exact integer representation of the character. Given an exact integer that is the image of a character under `char->integer', `integer->char' returns that character. These procedures implement injective 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 domain of `integer->char', then (<= (char->integer A) (char->integer B)) => #t (char<=? (integer->char X) (integer->char Y)) => #t -- essential procedure: char-upcase char -- essential 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.  File: r4rs.info, Node: Strings, Next: Vectors, Prev: Characters, Up: Standard procedures Strings ======= Strings are sequences of characters. 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 constant may continue from one line to the next, but the exact contents of such a string are unspecified. 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 ```-ci''' (for ``case insensitive'') embedded in their names. -- essential procedure: string? obj Returns `#t' if OBJ is a string, otherwise returns `#f'. -- essential procedure: make-string k -- essential procedure: make-string k char `Make-string' returns a newly allocated string of length K. If CHAR is given, then all elements of the string are initialized to CHAR, otherwise the contents of the STRING are unspecified. -- essential procedure: string char ... Returns a newly allocated string composed of the arguments. -- 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. -- essential procedure: string-set! string k char K must be a valid index of STRING%, and CHAR must be a character . `String-set!' stores CHAR in element K of STRING and returns an unspecified value. (define (f) (make-string 3 #\*)) (define (g) "***") (string-set! (f) 0 #\?) => _unspecified_ (string-set! (g) 0 #\?) => _error_ (string-set! (symbol->string 'immutable) 0 #\?) => _error_ -- essential procedure: string=? string1 string2 -- essential 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-ci? string1 string2 -- essential procedure: string-ci<=? string1 string2 -- essential procedure: string-ci>=? string1 string2 These procedures are the lexicographic extensions to strings of the corresponding orderings on characters. For example, `stringlist 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 newly allocated string formed from the characters in the list CHARS. `String->list' and `list->string' are inverses so far as `equal?' is concerned. -- 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.  File: r4rs.info, Node: Vectors, Next: Control features, Prev: Strings, Up: Standard procedures Vectors ======= Vectors are heterogenous structures whose elements are indexed by integers. A vector typically occupies less space than a list of the same length, and the average time required to access a randomly chosen element is typically less for the vector than for the list. The _length_ of a vector is the number of elements that it contains. This number is a non-negative integer that is fixed when the vector is created. The _valid indexes_ of a vector are the exact non-negative integers less than the length of the vector. The first element in a vector is indexed by zero, and the last element is indexed by one less than the length of the vector. Vectors are written using the notation `#(OBJ ...)'. For example, a vector of length 3 containing the number zero in element 0, the list `(2 2 2 2)' in element 1, and the string `"Anna"' in element 2 can be written as following: #(0 (2 2 2 2) "Anna") 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 (vector-ref '#(1 1 2 3 5 8 13 21) (inexact->exact (round (* 2 (acos -1))))) => 13 -- 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") (vector-set! '#(0 1 2) 1 "doe") => _error_ ; constant vector -- essential procedure: vector->list vector -- essential procedure: list->vector list `Vector->list' returns a newly allocated list of the objects contained in the elements of VECTOR. `List->vector' returns a newly created vector initialized to the elements of the list LIST. (vector->list '#(dah dah didah)) => (dah dah didah) (list->vector '(dididit dah)) => #(dididit dah) -- procedure: vector-fill! vector fill Stores FILL in every element of VECTOR. The value returned by `vector-fill!' is unspecified.  File: r4rs.info, Node: Control features, Next: Input and output, Prev: Vectors, Up: Standard procedures 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 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, in order from left to right. The dynamic 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 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 (*note delay: 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. (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 only one value is computed for a promise, no matter how many times it is forced. (define count 0) (define p (delay (begin (set! count (+ count 1)) (if (> count x) count (force p))))) (define x 5) p => _a promise_ (force p) => 6 p => _a promise, still_ (begin (set! x 10) (force p)) => 6 Here is a possible implementation of `delay' and `force'. Promises are implemented here as procedures of no arguments, and `force' simply calls its argument: (define force (lambda (object) (object))) We define the expression (delay ) to have the same meaning as the procedure call (make-promise (lambda () )), where `make-promise' is defined as follows: (define make-promise (lambda (proc) (let ((result-ready? #f) (result #f)) (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? #t) (set! result x) result)))))))) _Rationale:_ A promise may refer to its own value, as in the last example above. Forcing such a promise may cause the promise to be forced a second time before the value of the first force has been computed. This complicates the definition of `make-promise'. Various extensions to this semantics of `delay' and `force' are supported in some implementations: * Calling `force' on an object that is not a promise may simply return the object. * It may be the case that there is no means by which a promise can be operationally distinguished from its forced value. That is, expressions like the following may evaluate to either `#t' or to `#f', depending on the implementation: (eqv? (delay 1) 1) => _unspecified_ (pair? (delay (cons 1 2))) => _unspecified_ * Some implementations may implement ``implicit forcing,'' where the value of a promise is forced by primitive procedures like `cdr' and `+': (+ (delay (* 3 7)) 13) => 34 -- 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 that is passed to PROC has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired. The following examples show only the most common 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 might take the result, print it on the screen, prompt for the next input, evaluate it, and so on forever. Most of the time the continuation includes actions specified by user code, as in a continuation that will take the result, multiply it by the value stored in a local variable, add seven, and give the answer to the top level continuation to be printed. Normally these ubiquitous continuations are hidden behind the scenes and programmers 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.  File: r4rs.info, Node: Input and output, Prev: Control features, Up: Standard procedures Input and output ================ * Menu: * Ports:: * Input:: * Output:: * System interface::