|
4.1 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? .
(eqv? obj1 obj2) | R5RS procedure |
The eqv? procedure defines a useful equivalence relation on objects.
Briefly, it returns #t if obj1 and obj2 should normally be regarded
as the same object. This relation is left slightly open to interpretation,
but the following partial specification of eqv? holds for all
implementations of Scheme.
The eqv? procedure returns #t if:
-
obj1 and obj2 are both #t or both #f .
-
obj1 and obj2 are both symbols and
(string=? (symbol->string obj1)
(symbol->string obj2))
⇒ #t
|
Note: This assumes that neither obj1 nor obj2 is an
"uninterned symbol".
-
obj1 and obj2 are both keywords and
(string=? (keyword->string obj1)
(keyword->string obj2))
⇒ #t
|
-
obj1 and obj2 are both numbers, are numerically equal
(see -), and are either both exact or both inexact.
-
obj1 and obj2 are both characters and are the same character
according to the char=? procedure (see char--).
-
both
obj1 and obj2 are the empty list.
-
obj1 and obj2 are pairs, vectors, or strings that denote
the same locations in the store.
-
obj1 and obj2 are procedures whose location tags are equal.
Note: STklos extends R5RS eqv? to take into account
the keyword type.
Here are some examples:
(eqv? 'a 'a) ⇒ #t
(eqv? 'a 'b) ⇒ #f
(eqv? 2 2) ⇒ #t
(eqv? :foo :foo) ⇒ #t
(eqv? :foo :bar) ⇒ #f
(eqv? '() '()) ⇒ #t
(eqv? 100000000 100000000) ⇒ #t
(eqv? (cons 1 2) (cons 1 2)) ⇒ #f
(eqv? (lambda () 1)
(lambda () 2)) ⇒ #f
(eqv? #f 'nil) ⇒ #f
(let ((p (lambda (x) x)))
(eqv? p p)) ⇒ #t
|
The following examples illustrate cases in which the above rules do
not fully specify the behavior of eqv? . All that can be said about
such cases is that the value returned by eqv? must be a boolean.
(eqv? "" "") ⇒ unspecified
(eqv? '#() '#()) ⇒ unspecified
(eqv? (lambda (x) x)
(lambda (x) x)) ⇒ unspecified
(eqv? (lambda (x) x)
(lambda (y) y)) ⇒ unspecified
|
Note: In fact, the value returned by STklos depends of
the way code is entered and can yield #t in some cases and #f
in others.
See R5RS for more details on eqv? . |
(eq? obj1 obj2) | R5RS procedure |
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,
keywords, booleans, the empty list, pairs, procedures, and non-empty strings
and vectors. Eq? 's behavior on numbers and characters is
implementation-dependent, but it will always return either true or false,
and will return true only when eqv? would also return true.
Eq? may also behave differently from eqv? on empty vectors
and empty strings.
Note: STklos extends R5RS eq? to take into account
the keyword type.
Note: In STklos, comparison of character returns #t for identical
characters and #f otherwise.
(eq? 'a 'a) ⇒ #t
(eq? '(a) '(a)) ⇒ unspecified
(eq? (list 'a) (list 'a)) ⇒ #f
(eq? "a" "a") ⇒ unspecified
(eq? "" "") ⇒ unspecified
(eq? :foo :foo) ⇒ #t
(eq? :foo :bar) ⇒ #f
(eq? '() '()) ⇒ #t
(eq? 2 2) ⇒ unspecified
(eq? #\A #\A) ⇒ #t (unspecified in R5RS)
(eq? car car) ⇒ #t
(let ((n (+ 2 3)))
(eq? n n)) ⇒ #t (unspecified in R5RS)
(let ((x '(a)))
(eq? x x)) ⇒ #t
(let ((x '#()))
(eq? x x)) ⇒ #t
(let ((p (lambda (x) x)))
(eq? p p)) ⇒ #t
(eq? :foo :foo) ⇒ #t
(eq? :bar bar:) ⇒ #t
(eq? :bar :foo) ⇒ #f
|
|
(equal? obj1 obj2) | R5RS procedure |
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
|
|
4.2 Numbers
R5RS description of numbers is quite long and will not be given here.
STklos support the full number tower as described in R5RS; see this
document for a complete description. STklos extends the number syntax of R5RS with the
following inexact numerical constants:
+inf.0 (infinity), -inf.0 (negative
infinity), +nan.0 (not a number), and
-nan.0 (same as +nan.0).
(number? obj) | R5RS procedure |
(complex? obj)
(real? obj)
(rational? obj)
(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
(and (finite? x) (= 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? 3.2) ⇒ #f
(integer? 8/4) ⇒ #t
(integer? "no") ⇒ #f
(complex? +inf.0) ⇒ #t
(real? -inf.0) ⇒ #t
(rational? +inf.0) ⇒ #f
(integer? -inf.0) ⇒ #f
|
|
(inexact? z)
These numerical predicates provide tests for the exactness of a
quantity. For any Scheme number, precisely one of these predicates
is true. |
(bignum? x) | STklos procedure |
This predicates returns #t if x is an integer number too large to be
represented with a native integer.
(bignum? (expt 2 300)) ⇒ #t (very likely)
(bignum? 12) ⇒ #f
(bignum? "no") ⇒ #f
|
|
(= z1 z2 z3 ...) | R5RS procedure |
(< x1 x2 x3 ...)
(> x1 x2 x3 ...)
(<= x1 x2 x3 ...)
(>= x1 x2 x3 ...)
These procedures return #t if their arguments are (respectively):
equal, monotonically increasing, monotonically decreasing,
monotonically nondecreasing, or monotonically nonincreasing.
(= +inf.0 +inf.0) ⇒ #t
(= -inf.0 +inf.0) ⇒ #f
(= -inf.0 -inf.0) ⇒ #t
For any finite real number x:
(< -inf.0 x +inf.0) ⇒ #t
(> +inf.0 x -inf.0) ⇒ #t
|
|
(finite? z) | R5RS procedure |
(infinite? z)
(zero? z)
(positive? x)
(negative? x)
(odd? n)
(even? n)
These numerical predicates test a number for a particular property,
returning #t or #f .
(positive? +inf.0) =⇒ #t
(negative? -inf.0) =⇒ #t
(finite? -inf.0) =⇒ #f
(infinite? +inf.0) =⇒ #t
|
|
(max x1 x2 ...) | R5RS 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
|
For any real number x:
(max +inf.0 x) ⇒ +inf.0
(min -inf.0 x) ⇒ -inf.0
|
Note: If any argument is inexact, then the result will also be
inexact |
(* z1 ...)
These procedures return the sum or product of their arguments.
(+ 3 4) ⇒ 7
(+ 3) ⇒ 3
(+) ⇒ 0
(+ +inf.0 +inf.0) ⇒ +inf.0
(+ +inf.0 -inf.0) ⇒ +nan.0
(* 4) ⇒ 4
(*) ⇒ 1
(* 5 +inf.0) ⇒ +inf.0
(* -5 +inf.0) ⇒ -inf.0
(* +inf.0 +inf.0) ⇒ +inf.0
(* +inf.0 -inf.0) ⇒ -inf.0
(* 0 +inf.0) ⇒ +nan.0
|
Note: For any finite number z:
(+ +inf.0 z) ⇒ +inf.0
(+ -inf.0 z) ⇒ -inf.0
|
|
(- z1 z2)
(/ z)
(/ 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
(- +inf.0 +inf.0) ⇒ +nan.0
(/ 3 4 5) ⇒ 3/20
(/ 3) ⇒ 1/3
(/ 0.0) ⇒ +inf.0
(/ 0) ⇒ error (division by 0)
|
|
Abs returns the absolute value of its argument.
(abs -7) ⇒ 7
(abs -inf.0) ⇒ +inf.0
|
|
(quotient n1 n2) | R5RS procedure |
(remainder n1 n2)
(modulo n1 n2)
These procedures implement number-theoretic (integer) division. n2 should
be non-zero. All three procedures return integers.
If n1/n2 is an integer:
(quotient n1 n2) ⇒ n1/n2
(remainder n1 n2) ⇒ 0
(modulo n1 n2) ⇒ 0
|
If n1/n2 is not an integer:
(quotient n1 n2) ⇒ nq
(remainder n1 n2) ⇒ nr
(modulo n1 n2) ⇒ nm
|
where nq is n1/n2 rounded towards zero, 0 < abs(nr) < abs(n2),
0 < abs(nm) < abs(n2), nr and nm differ from n1 by a multiple of n2,
nr has the same sign as n1, and nm has the same sign as n2.
From this we can conclude that 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.
(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
|
|
(gcd n1 ...) | R5RS 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
|
|
(numerator q) | R5RS 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
|
|
(ceiling x)
(truncate x)
(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
|
|
(rationalize x y) | R5RS procedure |
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
|
|
(log z)
(sin z)
(cos z)
(tan z)
(asin z)
(acos z)
(atan z)
(atan y x)
These procedures 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))
|
When it is possible these procedures produce a real result from a real
argument. |
Returns the principal square root of z . The result will have either
positive real part, or zero real part and non-negative imaginary part. |
(expt z1 z2) | R5RS procedure |
Returns z1 raised to the power z2 .
Note: 0z is 1 if z = 0 and 0 otherwise. |
(make-rectangular x1 x2) | R5RS procedure |
(make-polar x3 x)
(real-part z)
(imag-part z)
(magnitude z)
(angle z)
If x1, x2, x3, and x4 are real numbers and z is a complex number such that
z = x1 + x2.i = x3 . ei.x4
Then
(make-rectangular x1 x2) ⇒ z
(make-polar x3 x4) ⇒ z
(real-part z) ⇒ x1
(imag-part z) ⇒ x2
(magnitude z) ⇒ abs(x3)
(angle z) ⇒ xa
|
where
-π < xa <= π with xa = x4 + 2πn
for some integer n.
(angle +inf.0) ⇒ 0.0
(angle -inf.0) ⇒ 3.14159265358979
|
Note: Magnitude is the same as abs for a real argument. |
(exact->inexact z) | R5RS 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.
Inexact->exact returns an exact representation of z.
The value returned is the exact number that is numerically closest to
the argument. |
(number->string z) | R5RS procedure |
(number->string z 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 z is inexact, the radix is 10, and the above expression can be
satisfied by a result that contains a decimal point, then the result
contains a decimal point and is expressed using the minimum number of digits
(exclusive of exponent and trailing zeroes) needed to make the above expression
true; otherwise the format of the result is unspecified.
The result returned by number->string never contains an explicit radix
prefix.
Note: The error case can occur only when z is not a complex number or
is a complex number with a non-rational real or imaginary part.
Rationale: If z is an inexact number represented using flonums, and
the radix is 10, then the above expression is normally satisfied by a result
containing a decimal point. The unspecified case allows for infinities,
NaNs, and non-flonum representations. |
(string->number string) | R5RS 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
(string->number "+inf.0") ⇒ +inf.0
(string->number "-inf.0") ⇒ -inf.0
|
|
(bit-and n1 n2 ...) | STklos procedure |
(bit-or n1 n2 ...)
(bit-xor n1 n2 ...)
(bit-not n)
(bit-shift n m)
These procedures allow the manipulation of integers as bit fields.
The integers can be of arbitrary length. Bit-and , bit-or and
bit-xor respectively compute the bitwise and, inclusive and
exclusive or. bit-not eturns the bitwise not of n .
bit-shift returns the bitwise shift of n . The integer n
is shifted left by m bits; If m is negative, n is shifted right by
-m bits.
(bit-or 5 3) ⇒ 7
(bit-xor 5 3) ⇒ 6
(bit-and 5 3) ⇒ 1
(bit-not 5) ⇒ -6
(bit-or 1 2 4 8) ⇒ 15
(bit-shift 5 3) ⇒ 40
(bit-shift 5 -1) ⇒ 2
|
|
(random-integer n) | STklos procedure |
Return an integer in the range [0, ..., n [. Subsequent results of
this procedure appear to be independent uniformly distributed over
the range [0, ..., n [. The argument n must be a positive integer,
otherwise an error is signaled. This function is equivalent to the eponym
function of SRFI-27 (see SRFI-27
(Source of random bits) definition for more details). |
(random-real) | STklos procedure |
Return a real number r such that 0 < r < 1 .
Subsequent results of this procedure appear to be independent uniformly
distributed. This function is equivalent to the eponym
function of SRFI-27 (see SRFI-27
(Source of random bits) definition for more details). |
(decode-float n) | STklos procedure |
decode-float returns three exact integers: significand , exponent
and sign (where -1 <= sign <= 1 ). The values returned by decode-float
satisfy:
n = (* sign significand (expt 2 exponent))
|
Here is an example of decode-float usage.
(receive l (decode-float -1.234) l)
⇒ (5557441940175192 -52 -1)
(exact->inexact (* -1
5557441940175192
(expt 2 -52))
⇒ -1.234
|
|
4.2.1 Fixnums
STklos defines small integers as fixnums. Operations on fixnums
are generally faster than operations which accept general numbers.
Fixnums operations, as described below, may produce results which are incorrect
if some temporary computation falls outside the range of fixnum. These
functions should be used only when speed really matters.
(fixnum? obj) | STklos procedure |
Returns #t if obj is an exact integer within the fixnum range,
#f otherwise. |
(fixnum-width) | STklos procedure |
Returns the number of bits used to represent a fixnum number |
(least-fixnum) | STklos procedure |
(greatest-fixnum)
These procedures return the minimum value and the maximum value of
the fixnum range. |
(fx+ fx1 fx2) | STklos procedure |
(fx- fx1 fx2)
(fx* fx1 fx2)
(fxdiv fx1 fx2)
(fxrem fx1 fx2)
(fxmod fx1 fx2)
(fx- fx)
These procedures compute (respectively) the sum, the difference, the product,
the quotient and the remainder and modulp of the fixnums fx1 and fx2 .
The call of fx- with one parameter fx computes the opposite of fx . |
(fx< fx1 fx2) | STklos procedure |
(fx<= fx1 fx2)
(fx> fx1 fx2)
(fx>= fx1 fx2)
(fx= fx1 fx2)
These procedures compare the fixnums fx1 and fx2 and retun #t if
the comparison is true and #f otherwise. |
4.3 Booleans
Of all the standard Scheme values, only #f counts as false in
conditional expressions. Except for #f , all standard Scheme values,
including #t , pairs, the empty list, symbols, numbers, strings,
vectors, and procedures, count as true. Boolean constants evaluate to themselves, so they do not need to be
quoted in programs.
Not returns #t if obj is false, and returns #f otherwise.
(not #t) ⇒ #f
(not 3) ⇒ #f
(not (list 3)) ⇒ #f
(not #f) ⇒ #t
(not '()) ⇒ #f
(not (list)) ⇒ #f
(not 'nil) ⇒ #f
|
|
(boolean? obj) | R5RS procedure |
Boolean? returns #t if obj is either #t or #f and returns
#f otherwise.
(boolean? #f) ⇒ #t
(boolean? 0) ⇒ #f
(boolean? '()) ⇒ #f
|
|
4.4 Pairs and lists
(pair? obj) | R5RS procedure |
Pair? returns #t if obj is a pair, and otherwise returns #f . |
(cons obj1 obj2) | R5RS procedure |
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)
|
|
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
|
|
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
|
|
(set-car! pair obj) | R5RS procedure |
Stores obj in the car field of pair .
The value returned by set-car! is void.
(define (f) (list 'not-a-constant-list))
(define (g) '(constant-list))
(set-car! (f) 3)
(set-car! (g) 3) ⇒ error
|
|
(set-cdr! pair obj) | R5RS procedure |
Stores obj in the cdr field of pair .
The value returned by set-cdr! is void.
|
(caar pair) | R5RS procedure |
(cadr pair)
...
(cdddar pair)
(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. |
(null? obj) | R5RS procedure |
Returns #t if obj is the empty list, otherwise returns #f . |
(pair-mutable? obj) | STklos procedure |
Returns #t if obj is a mutable pair, otherwise returns #f .
(pair-mutable? '(1 . 2)) ⇒ #f
(pair-mutable? (cons 1 2)) ⇒ #t
(pair-mutable? 12) ⇒ #f
|
|
(list? obj) | R5RS procedure |
Returns #t if obj is a list, otherwise returns #f . By definition,
all lists have finite length and are terminated by the empty list.
(list? '(a b c)) ⇒ #t
(list? '()) ⇒ #t
(list? '(a . b)) ⇒ #f
(let ((x (list 'a)))
(set-cdr! x x)
(list? x)) ⇒ #f
|
|
(list obj ...) | R5RS procedure |
Returns a newly allocated list of its arguments.
(list 'a (+ 3 4) 'c) ⇒ (a 7 c)
(list) ⇒ ()
|
|
(list* obj ...) | STklos procedure |
list* is like list except that the last argument to list* is
used as the cdr of the last pair constructed.
(list* 1 2 3) ⇒ (1 2 . 3)
(list* 1 2 3 '(4 5)) ⇒ (1 2 3 4 5)
(list*) ⇒ ()
|
|
(length list) | R5RS procedure |
Returns the length of list .
(length '(a b c)) ⇒ 3
(length '(a (b) (c d e))) ⇒ 3
(length '()) ⇒ 0
|
|
(append list ...) | R5RS procedure |
Returns a list consisting of the elements of the first list
followed by the elements of the other lists.
(append '(x) '(y)) ⇒ (x y)
(append '(a) '(b c d)) ⇒ (a b c d)
(append '(a (b)) '((c))) ⇒ (a (b) (c))
|
The resulting list is always newly allocated, except that it shares
structure with the last list argument. The last argument may actually
be any object; an improper list results if the last argument is not a
proper list.
(append '(a b) '(c . d)) ⇒ (a b c . d)
(append '() 'a) ⇒ a
|
|
(append! list ...) | STklos procedure |
Returns a list consisting of the elements of the first list
followed by the elements of the other lists.
Contrarily to append , the parameter lists (except the last one) are
physically modified: their last pair is changed to the value of the next
list in the append! formal parameter list.
(let* ((l1 (list 1 2))
(l2 (list 3))
(l3 (list 4 5))
(l4 (append! l1 l2 l3)))
(list l1 l2 l3)) ⇒ ((1 2 3 4 5) (3 4 5) (4 5))
|
An error is signaled if one of the given lists is a constant list. |
(reverse list) | R5RS procedure |
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)
|
|
(reverse! list) | STklos procedure |
Returns a list consisting of the elements of list in reverse order.
Contrarily to reverse , the returned value is not newly allocated but
computed "in place".
(let ((l '(a b c)))
(list (reverse! l) l)) ⇒ ((c b a) (a))
(reverse! '(a constant list)) ⇒ error
|
|
(list-tail list k) | R5RS procedure |
Returns the sublist of list obtained by omitting the first k elements.
It is an error if list has fewer than k elements. List-tail could
be defined by
(define list-tail
(lambda (x k)
(if (zero? k)
x
(list-tail (cdr x) (- k 1)))))
|
|
(last-pair list) | STklos procedure |
Returns the last pair of list .
(last-pair '(1 2 3)) ⇒ (3)
(last-pair '(1 2 . 3)) ⇒ (2 . 3)
|
|
(list-ref list k) | R5RS procedure |
Returns the k th element of list . (This is the same as the car
of (list-tail list k) .) It is an error if list has fewer than k
elements.
(list-ref '(a b c d) 2) ⇒ c
(list-ref '(a b c d)
(inexact->exact (round 1.8))) ⇒ c
|
|
(memq obj list) | R5RS procedure |
(memv obj list)
(member obj list)
These procedures return the first sublist of list whose car is obj ,
where the sublists of list are the non-empty lists returned by
(list-tail list k) for k less than the length of list.
If obj does not occur in list , then #f (not the empty list) is
returned. Memq uses eq? to compare obj with the elements of list,
while memv uses eqv? and member 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)
(memv 101 '(100 101 102)) ⇒ (101 102)
|
|
(assq obj alist) | R5RS procedure |
(assv obj alist)
(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, then #f (not the empty
list) is returned. Assq uses eq? to compare obj with the car fields
of the pairs in alist , while assv uses eqv? and assoc uses 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))
(assv 5 '((2 3) (5 7) (11 13)))
⇒ (5 7)
|
Rationale: Although they are ordinarily used as predicates,
memq , memv , member , assq , assv , and assoc do not have question
marks in their names because they return useful values rather than just
#t or #f . |
(copy-tree obj) | STklos procedure |
Copy-tree recursively copies trees of pairs. If obj is
not a pair, it is returned; otherwise the result is a new pair whose
car and cdr are obtained by calling copy-tree on
the car and cdr of obj , respectively. |
(filter pred list) | STklos procedure |
(filter! pred list)
Filter returns all the elements of list that satisfy predicate
pred . The list is not disordered: elements that appear in the
result list occur in the same order as they occur in the argument
list. Filter! does the same job than filter by physically
modifying its list argument
(filter even? '(0 7 8 8 43 -4)) ⇒ (0 8 8 -4)
(let* ((l1 (list 0 7 8 8 43 -4))
(l2 (filter! even? l1)))
(list l1 l2)) ⇒ ((0 8 8 -4) (0 8 8 -4))
|
An error is signaled if list is a constant list. |
(remove pred list) | STklos procedure |
Remove returns list without the elements that satisfy predicate pred :
The list is not disordered -- elements that appear in the result list occur
in the same order as they occur in the argument list. Remove! does the
same job than remove by physically modifying its list argument
(remove even? '(0 7 8 8 43 -4)) ⇒ (7 43)
|
|
(delete x list [=]) | STklos procedure |
(delete! x list [=])
Delete uses the comparison procedure = , which defaults to
equal? , to find all elements of list that are equal to x , and
deletes them from list . The dynamic order in which the various
applications of = are made is not specified.
The list is not disordered -- elements that appear in the result
list occur in the same order as they occur in the argument list.
The comparison procedure is used in this way: (= x ei) . That is,
x is always the first argument, and a list element is always the
second argument. The comparison procedure will be used to compare
each element of list exactly once; the order in which it is applied
to the various ei is not specified. Thus, one can reliably remove
all the numbers greater than five from a list with
delete! is the linear-update variant of delete . It is allowed,
but not required, to alter the cons cells in its argument list to
construct the result. |
4.5 Symbols
The STklos reader can read symbols whose names contain special
characters or letters in the non standard case. When a symbol is
read, the parts enclosed in bars "|" will be entered
verbatim into the symbol's name. The "|" characters are not
part of the symbol; they only serve to delimit the sequence of
characters that must be entered "as is". In order to maintain
read-write invariance, symbols containing such sequences of special
characters will be written between a pair of "|".
'|a| ⇒ a
(string->symbol "a") ⇒ |A|
(symbol->string '|A|) ⇒ "A"
'|a b| ⇒ |a b|
'a|B|c ⇒ |aBc|
(write '|FoO|) -| |FoO|
(display '|FoO|) -| FoO
|
(symbol? obj) | R5RS procedure |
Returns #t if obj is a symbol, otherwise returns #f .
(symbol? 'foo) ⇒ #t
(symbol? (car '(a b))) ⇒ #t
(symbol? "bar") ⇒ #f
(symbol? 'nil) ⇒ #t
(symbol? '()) ⇒ #f
(symbol? #f) ⇒ #f
(symbol? :key) ⇒ #f
|
|
(symbol->string string) | R5RS procedure |
Returns the name of symbol as a string. If the symbol was part of an
object returned as the value of a literal expression 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 -- STklos prefers 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.
(symbol->string 'flying-fish) ⇒ "flying-fish"
(symbol->string 'Martin) ⇒ "martin"
(symbol->string (string->symbol "Malvina"))
⇒ "Malvina"
|
|
(string->symbol string) | R5RS procedure |
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.
(eq? 'mISSISSIppi 'mississippi) ⇒ #t
(string->symbol "mISSISSIppi") ⇒ |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
|
|
(string->unterned-symbol string) | STklos procedure |
Returns the symbol whose print name is made from the characters of
string . This symbol is guaranteed to be unique (i.e. not
eq? to any other symbol):
(let ((ua (string->uninterned-symbol "a")))
(list (eq? 'a ua)
(eqv? 'a ua)
(eq? ua (string->uninterned-symbol "a"))
(eqv? ua (string->uninterned-symbol "a"))))
⇒ (#f #t #f #t)
|
|
(gensym prefix)
Creates a new symbol. The print name of the generated symbol
consists of a prefix (which defaults to "G ") followed by the decimal
representation of a number. If prefix is specified, it must be
either a string or a symbol.
(gensym) ⇒ |G100|
(gensym "foo-") ⇒ foo-101
(gensym 'foo-) ⇒ foo-102
|
|
4.6 Characters
The following table gives the list of allowed character names with their
ASCII eqivalent expressed in octal. Some chracaters have an alternate name
which is also shown in this table.
name | value | alt. name | name | value | alt. name |
nul | 000 | null | soh | 001 | |
stx | 002 | | etx | 003 | |
eot | 004 | | enq | 005 | |
ack | 006 | | bel | 007 | bell |
bs | 010 | backspace | ht | 011 | tab |
nl | 012 | newline | vt | 013 | |
np | 014 | page | cr | 015 | return |
so | 016 | | si | 017 | |
dle | 020 | | dc1 | 021 | |
dc2 | 022 | | dc3 | 023 | |
dc4 | 024 | | nak | 025 | |
syn | 026 | | etb | 027 | |
can | 030 | | em | 031 | |
sub | 032 | | esc | 033 | escape |
fs | 034 | | gs | 035 | |
rs | 036 | | us | 037 | |
sp | 040 | space | del | 177 | delete |
(char? obj) | R5RS procedure |
Returns #t if obj is a character, otherwise returns #f . |
(char=? char1 char2) | R5RS procedure |
(char<? char1 char2)
(char>? char1 char2)
(char<=? char1 char2)
(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.
- The lower case characters are in order.
- The digits are in order.
- Either all the digits precede all the upper case letters, or vice versa.
- Either all the digits precede all the lower case letters, or vice versa.
|
(char-ci=? char1 char2) | R5RS procedure |
(char-ci<? char1 char2)
(char-ci>? char1 char2)
(char-ci<=? char1 char2)
(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 . |
(char-alphabetic? char) | R5RS procedure |
(char-numeric? char)
(char-whitespace? char)
(char-upper-case? letter)
(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. |
(char->integer char) | R5RS procedure |
(integer->char n)
Given a character, char->integer returns an exact integer
representation of the character. Given an exact integer that is the
image of a character under char->integer , integer->char returns
that character. These procedures implement order-preserving
isomorphisms between the set of characters under the char<=?
ordering and some subset of the integers under the <=
ordering. That is, if
(char<=? a b) ⇒ #t and (<= x y) ⇒ #t
|
and x and y are in the domain of integer->char , then
(<= (char->integer a)
(char->integer b)) ⇒ #t
(char<=? (integer->char x)
(integer->char y)) ⇒ #t
|
|
(char-upcase char) | R5RS 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. |
4.7 Strings
STklos string constants allow the insertion of arbitrary characters
by encoding them as escape sequences. An escape sequence is introduced
by a backslash "\". The valid escape sequences are shown in
the following table.
Sequence | Character inserted |
\b | Backspace |
\e | Escape |
\n | Newline |
\t | Horizontal Tab |
\n | Carriage Return |
\0abc | ASCII character with octal value abc |
\xab | ASCII character with hexadecimal value ab |
\<newline> | None (permits to enter a string on several lines) |
\<other> | <other> |
For instance, the string
is the string consisting of the characters
#\a , #\b , #\space ,
#\c , #\newline , #\d and #\e .
(string? obj) | R5RS procedure |
Returns #t if obj is a string, otherwise returns #f . |
(make-string k) | R5RS 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. |
(string char ...) | R5RS procedure |
Returns a newly allocated string composed of the arguments. |
(string-length string) | R5RS procedure |
Returns the number of characters in the given string . |
(string-ref string k) | R5RS procedure |
String-ref returns character k of string using zero-origin indexing
(k must be a valid index of string). |
(string-set! string k char) | R5RS procedure |
String-set! stores char in element k of string and returns
void (k must be a valid index of string ).
(define (f) (make-string 3 #*))
(define (g) "***")
(string-set! (f) 0 #?) ⇒ void
(string-set! (g) 0 #?) ⇒ error
(string-set! (symbol->string 'immutable) 0 #?)
⇒ error
|
|
(string=? string1 string2) | R5RS 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. |
(string<? string1 string2) | R5RS procedure |
(string>? string1 string2)
(string<=? string1 string2)
(string>=? string1 string2)
(string-ci<? string1 string2)
(string-ci>? string1 string2)
(string-ci<=? string1 string2)
(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.
|
(substring string start end) | R5RS procedure |
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). |
(string-append string ...) | R5RS procedure |
Returns a newly allocated string whose characters form the concatenation
of the given strings. |
(string->list string) | R5RS procedure |
(list->string list)
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 list , which must be a list of
characters. String->list and list->string are inverses so far as
equal? is concerned. |
(string-copy string) | R5RS procedure |
Returns a newly allocated copy of the given string . |
(string-split str) | STklos procedure |
(string-split str delimiters)
parses string and returns a list of tokens ended by a character of the
delimiters string. If delimiters is omitted, it defaults to a string
containing a space, a tabulation and a newline characters.
(string-split "/usr/local/bin" "/")
⇒ ("usr" "local" "bin")
(string-split "once upon a time")
⇒ ("once" "upon" "a" "time")
|
|
(string-index str1 str2) | STklos procedure |
Returns the (first) index where str1 is a substring of str2 if it exists;
otherwise returns #f .
(string-index "ca" "abracadabra") ⇒ 4
(string-index "ba" "abracadabra") ⇒ #f
|
|
(string-find? str1 str2) | STklos procedure |
Returns #t if str1 appears somewhere in str2 ; otherwise returns #f . |
(string-fill! string char) | STklos procedure |
Stores char in every element of the given string and returns void. |
(string-blit! s1 s2 offset) | STklos procedure |
This function places the characters of string s2 in the string s1
starting at position offset . The result of string-blit! may modify
the string s1 . Note that the characters of s2 can be written after
the end of s1 (in which case a new string is allocated).
(string-blit! (make-string 6 #X) "abc" 2)
⇒ "XXabcX"
(string-blit! (make-string 10 #X) "abc" 5)
⇒ "XXXXXabc"
(string-blit! (make-string 6 #X) "a" 10)
⇒ "XXXXXX0000a"
|
|
(string-mutable? obj) | STklos procedure |
Returns #t if obj is a mutable string, otherwise returns #f .
(string-mutable? "abc") ⇒ #f
(string-mutable? (string-copy "abc")) ⇒ #t
(string-mutable? (string #a #b #c)) ⇒ #t
(string-mutable? 12) ⇒ #f
|
|
The following string primitives are compatible with SRFI-13
(String Library)
and their documentation comes from the SRFI document. Note: The string SRFI is supported by STklos. The
function listed below just don't need to load the full SRFI to be used
(string-downcase str) | STklos procedure |
(string-downcase str start)
(string-downcase str start end)
Returns a string in which the upper case letters of string str between the
start and end indices have been replaced by their lower case equivalent.
If start is omited, it defaults to 0. If end is omited, it defaults to
the length of str .
(string-downcase "Foo BAR") ⇒ "foo bar"
(string-downcase "Foo BAR" 4) ⇒ "bar"
(string-downcase "Foo BAR" 4 6) ⇒ "ba"
|
|
(string-downcase! str) | STklos procedure |
(string-downcase! str start)
(string-downcase! str start end)
This is the in-place side-effecting variant of string-downcase .
(string-downcase! (string-copy "Foo BAR") 4) ⇒ "Foo bar"
(string-downcase! (string-copy "Foo BAR") 4 6) ⇒ "Foo baR"
|
|
(string-upcase str) | STklos procedure |
(string-upcase str start)
(string-upcase str start end)
Returns a string in which the lower case letters of string str between the
start and end indices have been replaced by their upper case equivalent.
If start is omited, it defaults to 0. If end is omited, it defaults to
the length of str . |
(string-upcase! str) | STklos procedure |
(string-upcase! str start)
(string-upcase! str start end)
This is the in-place side-effecting variant of string-upcase . |
(string-titlecase str) | STklos procedure |
(string-titlecase str start)
(string-titlecase str start end)
This function returns a string. For every character c in the
selected range of str , if c is preceded by a cased character, it
is downcased; otherwise it is titlecased. If start is omited, it
defaults to 0. If end is omited, it defaults to the length of str .
Note that if a start index is specified, then the character preceding
s`(start) has no effect on the titlecase decision for character s`(start) .
(string-titlecase "--capitalize tHIS sentence.")
⇒ "--Capitalize This Sentence."
(string-titlecase "see Spot run. see Nix run.")
⇒ "See Spot Run. See Nix Run."
(string-titlecase "3com makes routers.")
⇒ "3Com Makes Routers."
(string-titlecase "greasy fried chicken" 2)
⇒ "Easy Fried Chicken"
|
|
(string-titlecase! str) | STklos procedure |
(string-titlecase! str start)
(string-titlecase! str start end)
This is the in-place side-effecting variant of string-titlecase . |
4.8 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:
Note: In STklos, vectors constants don't need to be quoted.
(vector? obj) | R5RS procedure |
Returns #t if obj is a vector, otherwise returns #f . |
(make-vector k) | R5RS 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. |
(vector obj ...) | R5RS procedure |
Returns a newly allocated vector whose elements contain the given arguments.
Analogous to list .
(vector 'a 'b 'c) ⇒ #(a b c)
|
|
(vector-length vector) | R5RS procedure |
Returns the number of elements in vector as an exact integer. |
(vector-ref vector k) | R5RS procedure |
k must be a valid index of vector . Vector-ref returns the contents of
element k of vector.
(vector-ref '#(1 1 2 3 5 8 13 21)
5) ⇒ 8
(vector-ref '#(1 1 2 3 5 8 13 21)
(let ((i (round (* 2 (acos -1)))))
(if (inexact? i)
(inexact->exact i)
i))) ⇒ 13
|
|
(vector-set! vector k obj) | R5RS procedure |
k must be a valid index of vector . Vector-set! stores obj in element
k of vector . The value returned by vector-set! is void.
(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
|
|
(vector->list vector) | R5RS 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)
|
|
(vector-fill! vector fill) | R5RS procedure |
Stores fill in every element of vector . The value returned by
vector-fill! is void. |
(vector-copy v) | STklos procedure |
Return a copy of vector v . Note that, if v is a constant vector,
its copy is not constant. |
(vector-resize v size) | STklos procedure |
(vector-resize v size fill)
Returns a copy of v of the given size . If size is greater
than the vector size of v , the contents of the newly allocated vector cells
is set to the value of fill . If fill is omitted the content of the
new cells is void. |
(vector-mutable? obj) | STklos procedure |
Returns #t if obj is a mutable vector, otherwise returns #f .
(vector-mutable? '#(1 2 a b)) ⇒ #f
(vector-mutable? (vector-copy '#(1 2))) ⇒ #t
(vector-mutable? (vector 1 2 3)) ⇒ #t
(vector-mutable? 12) ⇒ #f
|
|
(sort obj predicate) | STklos procedure |
Obj must be a list or a vector. Sort returns a copy of obj sorted
according to predicate . Predicate must be a procedure which takes
two arguments and returns a true value if the first argument is strictly
``before'' the second.
(sort '(1 2 -4 12 9 -1 2 3) <)
⇒ (-4 -1 1 2 2 3 9 12)
(sort '#("one" "two" "three" "four")
(lambda (x y) (> (string-length x) (string-length y))))
⇒ '#("three" "four" "one" "two")
|
|
4.9 Structures
A structure type is a record data type composing a number of slots. A
structure, an instance of a structure type, is a first-class value
that contains a value for each field of the structure type. Structures can be created with the define-struct high
level syntax. However, STklos also offers some low-level functions
to build and access the internals of a structure.
(define-struct <name> <slot> ...) | STklos syntax |
Defines a structure type whose name is <name> . Once a structure type is
defined, the following symbols are bound:
<name> denotes the structure type.
make-<name> is a procedure which takes 0 to n parameters (if there
are n slots defined). Each parameter is assigned to the corresponding
field (in the definition order).
<name>? is a predicate which returns #t when applied to an
instance of the <name> structure type and #f otherwise.
<name>-<slot> (one for each defined <slot> ) to read the
content of an instance of the <name> structure type. Writting the
content of a slot can be done using a generalized set! .
(define-struct point x y)
(define p (make-point 1 2))
(point? p) ⇒ #t
(point? 100) ⇒ #f
(point-x p) ⇒ 1
(point-y p) ⇒ 2
(set! (point-x p) 10)
(point-x p) ⇒ 10
|
|
(make-struct-type name parent slots) | STklos procedure |
This form which is more general than define-struct permits to define a
new structure type whose name is name . Parent is the structure
type from which is the new structure type is a subtype (or #f is the
new structure-type has no super type). Slots is the list of the slot
names which constitute the structure tpe.
When a structure type is s subtype of a previous type, its slots are added
to the ones of the super type. |
(struct-type? obj) | STklos procedure |
Returns #t if obj is a structure type, otherwise return #f .
(let ((type (make-struct-type 'point #f '(x y))))
(struct-type? type)) ⇒ #t
|
|
(struct-type-slots structype) | STklos procedure |
Returns the slots of the structure type structype as a list.
(define point (make-struct-type 'point #f '(x y)))
(define circle (make-struct-type 'circle point '(r)))
(struct-type-slots point) ⇒ (x y)
(struct-type-slots circle) ⇒ (x y r)
|
|
(struct-type-parent structype) | STklos procedure |
Returns the super type of the structure type structype , if it exists
or #f otherwise. |
(struct-type-name structype) | STklos procedure |
Returns the name associated to the structure type structype . |
(struct-type-change-writer! structype proc) | STklos procedure |
Change the default writer associated to structures of type structype to
to the proc procedure. The proc procedure must accept 2 arguments
(the structure to write and the port wher the structure must be written
in that order). The value returned by struct-type-change-writer! is the
old writer associated to structype . To restore the standard wtructure
writer for structype , use the special value #f .
(define point (make-struct-type 'point #f '(x y)))
(struct-type-change-writer!
point
(lambda (s port)
(let ((type (struct-type s)))
(format port "{~A" (struct-type-name type))
;; display the slots and their value
(for-each (lambda (x)
(format port " ~A=~S" x (struct-ref s x)))
(struct-type-slots type))
(format port "}"))))
(display (make-struct point 1 2)) -| {point x=1 y=2}
|
|
(make-struct structype expr ...) | STklos procedure |
Returns a newly allocated instance of the structure type structype ,
whose slots are initialized to expr ... If fewer expr than the number of
instances are given to make-struct , the remaining slots are inialized with
the special void value. |
(struct? obj) | STklos procedure |
Returns #t if obj is a structure, otherwise return #f# .
(let* ((type (make-struct-type 'point #f '(x y)))
(inst (make-struct type 1 2)))
(struct? inst)) ⇒ #t
|
|
(struct-type s) | STklos procedure |
Returns the structure type of the s structure |
(struct-ref s slot-name) | STklos procedure |
Returns the value associated to slot slot-name of the s structure.
(define point (make-struct-type 'point #f '(x y)))
(define circle (make-struct-type 'circle point '(r)))
(define p (make-struct point 1 2))
(define c (make-struct circle 10 20 30))
(struct-ref p 'y) ⇒ 2
(struct-ref c 'r) ⇒ 30
|
|
(struct-set! s slot-name value) | STklos procedure |
Stores value in the to slot slot-name of the s structure. The value
returned by struct-set! is void.
(define point (make-struct-type 'point #f '(x y)))
(define p (make-struct point 1 2))
(struct-ref p 'x) ⇒ 1
(struct-set! p 'x 0)
(struct-ref p 'x) ⇒ 0
|
|
(struct-is-a? s structype) | STklos procedure |
Return a boolean that indicates if the structure s is a of type structype .
Note that if s is an instance of a subtype of S, it is considered
also as an instance of type S.
(define point (make-struct-type 'point #f '(x y)))
(define circle (make-struct-type 'circle point '(r)))
(define p (make-struct point 1 2))
(define c (make-struct circle 10 20 30))
(struct-is-a? p point) ⇒ #t
(struct-is-a? c point) ⇒ #t
(struct-is-a? p circle) ⇒ #f
(struct-is-a? c circle) ⇒ #t
|
|
(struct->list s) | STklos procedure |
Returns the content of structure s as an A-list whose keys are the
slots of the structure type of s .
(define point (make-struct-type 'point #f '(x y)))
(define p (make-struct point 1 2))
(struct->list p) ⇒ ((x . 1) (y . 2))
|
|
4.10 Control features
(procedure? obj) | R5RS procedure |
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
|
|
(apply proc arg1 ... args) | R5RS procedure |
Proc must be a procedure and args must be a list. 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
|
|
(map proc list1 list2 ...) | R5RS procedure |
The list s must be lists, and proc must be a procedure taking as many
arguments as there are lists and returning a single value.
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 list s and returns
a list of the results, in order. The dynamic order in which proc is applied
to the elements of the lists is unspecified.
(map cadr '((a b) (d e) (g h))) ⇒ (b e h)
(map (lambda (n) (expt n n))
'(1 2 3 4 5)) ⇒ (1 4 27 256 3125)
(map + '(1 2 3) '(4 5 6)) ⇒ (5 7 9)
(let ((count 0))
(map (lambda (ignored)
(set! count (+ count 1))
count)
'(a b))) ⇒ (1 2) or (2 1)
|
|
(for-each proc list1 list2 ...) | R5RS procedure |
The arguments to for-each are like the arguments to map , but for-each
calls proc for its side effects rather than for its values.
Unlike map , for-each is guaranteed to call proc on the elements of
the lists in order from the first element(s) to the last, and the value
returned by for-each is void.
(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)
|
|
(every pred list1 list2 ...) | STklos procedure |
every applies the predicate pred across the lists, returning true if
the predicate returns true on every application.
If there are n list arguments list1 ... listn , then pred must be
a procedure taking n arguments and returning a boolean result.
every applies pred to the first elements of the listi parameters. If
this application returns false, every immediately returns #f .
Otherwise, it iterates, applying pred to the second elements of the listi
parameters, then the third, and so forth. The iteration stops when a
false value is produced or one of the lists runs out of values.
In the latter case, every returns the true value produced by its final
application of pred. The application of pred to the last element of the
lists is a tail call.
If one of the listi has no elements, every simply returns #t .
Like any , every's name does not end with a question mark -- this is to
indicate that it does not return a simple boolean (#t or #f ), but a
general value. |
(any pred list1 list2 ...) | STklos procedure |
any applies the predicate across the lists, returning true if the
predicate returns true on any application.
If there are n list arguments list1 ... listn , then pred must be
a procedure taking n arguments.
any applies pred to the first elements of the listi parameters. If
this application returns a true value, any immediately returns that value.
Otherwise, it iterates, applying pred to the second elements of the listi
parameters, then the third, and so forth. The iteration stops when a true
value is produced or one of the lists runs out of values; in the latter case,
any returns #f . The application of pred to the last element of the
lists is a tail call.
Like every, any 's name does not end with a question mark -- this is
to indicate that it does not return a simple boolean (#t or #f ), but
a general value.
(any integer? '(a 3 b 2.7)) ⇒ #t
(any integer? '(a 3.1 b 2.7)) ⇒ #f
(any < '(3 1 4 1 5)
'(2 7 1 8 2)) ⇒ #t
|
|
(force promise) | R5RS procedure |
Forces the value of promise (see delay). 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
|
Note: See R5RS for details on a posssible way to implement
force and delay . |
(call-with-current-continuation proc) | R5RS procedure |
(call/cc proc)
Proc must be a procedure of one argument. The procedure
call-with-current-continuation packages up the current continuation
(see the rationale below) as an ``escape procedure'' and passes it as
an argument to proc . The escape procedure is a Scheme procedure that, if
it is later called, will abandon whatever continuation is in effect at
that later time and will instead use the continuation that was in effect
when the escape procedure was created. Calling the escape procedure may cause
the invocation of before and after thunks installed using dynamic-wind .
The escape procedure accepts the same number of arguments as
the continuation to the original call to
call-with-current-continuation . Except for continuations created
by the call-with-values procedure, all continuations take exactly
one value.
The escape procedure that is passed to proc has unlimited extent
just like any other procedure in Scheme. It may be stored in variables
or data structures and may be called as many times as desired.
The following examples show only the most common ways in which
call-with-current-continuation is used. If all real uses were as simple
as these examples, there would be no need for a procedure with the power
of call-with-current-continuation .
(call-with-current-continuation
(lambda (exit)
(for-each (lambda (x)
(if (negative? x)
(exit x)))
'(54 0 37 -3 245 19))
#t)) ⇒ -3
(define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(letrec ((r
(lambda (obj)
(cond ((null? obj) 0)
((pair? obj)
(+ (r (cdr obj)) 1))
(else (return #f))))))
(r obj))))))
(list-length '(1 2 3 4)) ⇒ 4
(list-length '(a b . c)) ⇒ #f
|
Rationale: A common use of call-with-current-continuation
is for structured, non-local exits from loops or procedure bodies,
but in fact call-with-current-continuation is extremely useful
for implementing a wide variety of advanced control structures.
Whenever a Scheme expression is evaluated there is a continuation
wanting the result of the expression. The continuation represents
an entire (default) future for the computation. If the expression
is evaluated at top level, for example, then the continuation
might take the result, print it on the screen, prompt for the
next input, evaluate it, and so on forever. Most of the time the
continuation includes actions specified by user code, as in a
continuation that will take the result, multiply it by the value
stored in a local variable, add seven, and give the answer to the
top level continuation to be printed. Normally these ubiquitous
continuations are hidden behind the scenes and programmers do not
think much about them. On rare occasions, however, a programmer
may need to deal with continuations explicitly.
Call-with-current-continuation allows Scheme
programmers to do that by creating a procedure that acts just
like the current continuation.
Note: call/cc is just another name for
call-with-current-continuation . |
(call/ec proc) | STklos procedure |
call/ec is an short name for call-with-escape-continuation . call/ec
calls proc with one parameter, which is the current escape continuation
(a continuation which can only be used to abort a computation and hence
cannot be "re-enterered".
(list 1
(call/ec (lambda (return) (list 'a (return 'b) 'c)))
3) ⇒ (1 b 3)
|
call/ec is cheaper than the full call/cc. It is particularily useful
when all the power of call/cc is not needded. |
(values obj ...) | R5RS procedure |
Delivers all of its arguments to its continuation.
Note: R5RS imposes to use multiple values in the context of
of a call-with-values . In STklos, if values is not used with
call-with-values , only the first value is used (i.e. others values are
ignored).
|
(call-with-values producer consumer) | R5RS procedure |
Calls its producer argument with no values and a continuation that,
when passed some values, calls the consumer procedure with those values
as arguments. The continuation for the call to consumer is the
continuation of the call to call-with-values.
(call-with-values (lambda () (values 4 5))
(lambda (a b) b)) ⇒ 5
(call-with-values * -) ⇒ -1
|
|
(receive <formals> <expression> <body>) | STklos syntax |
This form is defined in SRFI-8
(Receive: Binding to multiple values). It simplifies
the usage of multiple values. Specifically, <formals> can have any
of three forms:
- (
<variable1> ... <variablen> ):
The environment in which the
receive-expression is evaluated is extended by binding <variable1> , ...,
<variablen> to fresh locations.
The <expression> is evaluated, and its
values are stored into those locations. (It is an error if <expression>
does not have exactly n values.)
<variable> :
The environment in which the receive-expression is
evaluated is extended by binding <variable> to a fresh location.
The <expression> is evaluated, its values are converted into a newly
allocated list, and the list is stored in the location bound to <variable> .
- (
<variable1> ... <variablen> . <variablen + 1> ):
The environment
in which the receive-expression is evaluated is extended by binding
<variable1> , ..., <variablen + 1> to fresh locations.
The <expression> is evaluated. Its first n values are stored into the
locations bound to <variable1> ... <variablen> . Any remaining values
are converted into a newly allocated list, which is stored into the location
bound to <variablen + 1> . (It is an error if <expression> does not have
at least n values.)
In any case, the expressions in <body> are evaluated sequentially in
the extended environment. The results of the last expression in the body
are the values of the receive-expression.
(let ((n 123))
(receive (q r)
(values (quotient n 10) (modulo n 10))
(cons q r)))
⇒ (12 . 3)
|
|
(dynamic-wind before thunk after) | R5RS procedure |
Current version of dynamic-wind mimics the R5RS one. In particular, it
does not yet interact with call-with-current-continuation as required by
R5RS.
Calls thunk without arguments, returning the result(s) of this call.
Before and after are called, also without arguments, as required by
the following rules (note that in the absence of calls to continuations
captured using call-with-current-continuation the three arguments are
called once each, in order). Before is called whenever execution enters
the dynamic extent of the call to thunk and after is called whenever
it exits that dynamic extent. The dynamic extent of a procedure call is
the period between when the call is initiated and when it returns.
In Scheme, because of call-with-current-continuation , the dynamic
extent of a call may not be a single, connected time period. It is
defined as follows:
- The dynamic extent is entered when execution of the body of
the called procedure begins.
- The dynamic extent is also entered when execution is not
within the dynamic extent and a continuation is invoked that was
captured (using
call-with-current-continuation ) during the dynamic extent.
- It is exited when the called procedure returns.
- It is also exited when execution is within the dynamic
extent and a continuation is invoked that was captured while not within
the dynamic extent.
If a second call to dynamic-wind occurs within the dynamic extent
of the call to thunk and then a continuation is invoked in such a
way that the afters from these two invocations of dynamic-wind
are both to be called, then the after associated with the
second (inner) call to dynamic-wind is called first.
If a second call to dynamic-wind occurs within the dynamic extent
of the call to thunk and then a continuation is invoked in such a
way that the befores from these two invocations of dynamic-wind
are both to be called, then the before associated with the
first (outer) call to dynamic-wind is called first.
If invoking a continuation requires calling the before from one
call to dynamic-wind and the after from another, then the after
is called first.
The effect of using a captured continuation to enter or exit the
dynamic extent of a call to before or after is undefined.
(let ((path '())
(c #f))
(let ((add (lambda (s)
(set! path (cons s path)))))
(dynamic-wind
(lambda () (add 'connect))
(lambda ()
(add (call-with-current-continuation
(lambda (c0)
(set! c c0)
'talk1))))
(lambda () (add 'disconnect)))
(if (< (length path) 4)
(c 'talk2)
(reverse path))))
⇒ (connect talk1 disconnect
connect talk2 disconnect)
|
|
(eval expression environment) | R5RS procedure |
(eval expression)
Evaluates expression in the specified environment and returns its
value. Expression must be a valid Scheme expression represented
as data. Environment may be a R5RS environment-specifier
(interaction-environment , scheme-report-environment or
null-environment ) or a STklos module.
(eval '(* 7 3) (scheme-report-environment 5))
⇒ 21
(let ((f (eval '(lambda (f x) (f x x))
(null-environment 5))))
(f + 10))
⇒ 20
(define-module A
(define x 1))
(eval '(cons x x) (find-module 'A))
⇒ (1 . 1)
|
|
(scheme-report-environment) | R5RS procedure |
(scheme-report-environment version)
Returns a specifier for an environment that contains the bindings defined
in the R5RS report.
Note: In STklos, scheme-report-environment function can be called
without the version number (defaults to 5). |
(null-environment) | R5RS procedure |
(null-environment version)
Returns a specifier for an environment that is empty except for
the (syntactic) bindings for all syntactic keywords defined in
the R5RS report.
Note: In STklos, null-environment function can be called
without the version number (defaults to 5). |
(interaction-environment) | R5RS procedure |
This procedure returns the environment in the expression are
evaluated by default (the STklos module). |
(eval-from-string str) | STklos procedure |
(eval-from-string str module)
Read an expression from str and evaluates it with eval . If a module
is passed, the evaluation takes place in the environment of this module.
Otherwise, the evaluation takes place in the environment returned by
current-module .
(define x 10)
(define-module M
(define x 100))
(eval-from-string "(+ x x)") ⇒ 20
(eval-from-string "(+ x x)" (find-module 'M)) ⇒ 200
|
|
R5RS states that ports represent input and output
devices. However, it defines only ports which are attached to
files. In STklos, ports can also be attached to strings, to a
external command input or output, or even be virtual (i.e. the
behavior of the port is given by the user). - String ports are similar to file ports, except that characters
are read from (or written to) a string rather than a file.
- External command input or output ports are implemented
with Unix pipes and are called pipe ports. A pipe port
is created by specifying the command to execute prefixed with the
string
"| " (that is a pipe bar followed by a space).
Specification of a pipe port can occur everywhere a file name is needed.
- Virtual ports are created by supplying basic I/O functions at
port creation time. These functions will be used to simulate low
level accesses to a ``virtual device''. This kind of port is
particularly convenient for reading or writing in a graphical
window as if it was a file. Once a virtual port is created, it can
be accessed as a normal port with the standard Scheme primitives.
4.11.1 Ports
(call-with-input-file string proc) | R5RS procedure |
(call-with-output-file string proc)
String should be a string naming a file, and proc should be a procedure
that accepts one argument. For call-with-input-file , the file should
already exist. 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 signaled. If proc returns, then the port is closed
automatically and the value(s) yielded by the proc is(are) returned.
If proc does not return, then the port will not be closed automatically.
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 . |
(call-with-input-string string proc) | STklos procedure |
behaves as call-with-input-file except that the port passed to proc
is the sting port obtained from port .
(call-with-input-string "123 456"
(lambda (x)
(let* ((n1 (read x))
(n2 (read x)))
(cons n1 n2)))) ⇒ (123 . 456)
|
|
(call-with-output-string proc) | STklos procedure |
Proc should be a procedure of one argument. Call-with-output-string
calls proc with a freshly opened output string port. The result of
this procedure is a string containing all the text that has been written
on the string port.
(call-with-output-string
(lambda (x) (write 123 x) (display "Hello" x))) ⇒ "123Hello"
|
|
(input-port? obj) | R5RS procedure |
(output-port? obj)
Returns #t if obj is an input port or output port respectively,
otherwise returns #f. |
(port? obj) | STklos procedure |
Returns #t if obj is an input port or an output port,
otherwise returns #f. |
(input-string-port? obj) | STklos procedure |
(output-string-port? obj)
Returns #t if obj is an input string port or output string port
respectively, otherwise returns #f. |
(input-file-port? obj) | STklos procedure |
(output-file-port? obj)
Returns #t if obj is a file input port or a file output port respectively,
otherwise returns #f. |
(input-virtual-port? obj) | STklos procedure |
(output-virtual-port? obj)
Returns #t if obj is a virtual input port or a virtual output port
respectively, otherwise returns #f. |
(interactive-port? port) | STklos procedure |
Returns #t if port is connected to a terminal and #f otherwise. |
(current-input-port obj) | R5RS procedure |
(current-output-port obj)
Returns the current default input or output port. |
(current-error-port obj) | STklos procedure |
Returns the current default error port. |
(with-input-from-file string thunk) | R5RS procedure |
(with-output-to-file string thunk)
String should be a string naming a file, and proc should be a
procedure of no arguments. For with-input-from-file , the file should
already exist. 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 is used by (read) ,
(write obj) , and so forth), 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(s)
the value(s) yielded by thunk.
The following example uses a pipe port opened for reading. It permits to
read all the lines produced by an external ls command (i.e. the
output of the ls command is redirected to the Scheme pipe
port).
(with-input-from-file "| ls -ls"
(lambda ()
(do ((l (read-line) (read-line)))
((eof-object? l))
(display l)
(newline))))
|
Hereafter is another example of Unix command redirection. This time,
it is the standard input of the Unix command which is redirected.
(with-output-to-file "| mail root"
(lambda ()
(display "A simple mail from Scheme")
(newline)))
|
|
(with-error-to-file string thunk) | STklos procedure |
This procedure is similar to with-output-to-file, excepted that it uses the
current error port instead of the output port. |
(with-input-from-string string thunk) | STklos procedure |
A string port is opened for input from string . Current-input-port
is set to the port and thunk is called. When thunk returns,
the previous default input port is restored. With-input-from-string
returns the value(s) computed by thunk .
(with-input-from-string "123 456"
(lambda () (read))) ⇒ 123
|
|
(with-output-to-string thunk) | STklos procedure |
A string port is opened for output. Current-output-port
is set to it and thunk is called. When thunk returns,
the previous default output port is restored. With-output-to-string
returns the string containing the text written on the string port.
(with-output-to-string
(lambda () (write 123) (write "Hello"))) ⇒ "123\"Hello\""
|
|
(with-input-from-port port thunk) | STklos procedure |
(with-output-to-port port thunk)
(with-error-to-port port thunk)
Port should be a port, and proc should be a
procedure of no arguments. These procedures do a job similar to the
with-...-file counterparts excepted that they use an open port instead
of string specifying a file name |
(open-input-file filename) | R5RS procedure |
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.
Note: if filename starts with the string "| " ,
this procedure returns a pipe port. Consequently, it is not possible to
open a file whose name starts with those two characters. |
(open-input-string str) | STklos procedure |
Returns an input string port capable of delivering characters from
str . |
(open-input-virtual :key (read-char #f) (ready? #f) (eof? #f) (close #f)) | STklos procedure |
Returns a virtual port using the read-char procedure to read a
character from the port, ready? to know if there is any data to
read from the port, eof? to know if the end of file is reached
on the port and finally close to close the port. All theses
procedure takes one parameter which is the port from which the input
takes place. Open-input-virtual accepts also the special value
#f for the I/O procedures with the following conventions:
- if
read-char or eof? is #f , any attempt to read
the virtual port will return an eof object;
- if
ready? is #f , the file is always ready
for reading;
- if
close is #f , no action is done when the port is
closed.
Hereafter is a possible implementation of open-input-string
using virtual ports:
(define (open-input-string str)
(let ((index 0))
(open-input-virtual
:read-char (lambda (p)
;; test on eof is already done by the system
(let ((res (string-ref str index)))
(set! index (+ index 1))
res))
:eof? (lambda (p) (>= index (string-length str))))))
|
|
(open-output-file filename) | R5RS procedure |
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, it is rewritten.
Note: if filename starts with the string "| " ,
this procedure returns a pipe port. Consequently, it is not possible to
open a file whose name starts with those two characters. |
(open-output-string) | STklos procedure |
Returns an output string port capable of receiving and collecting characters. |
(open-output-virtual :key (write-char #f) (write-string #f) (flush #f) (close #f)) | STklos procedure |
Returns a virtual port using the write-char procedure to write a
character to the port, write-string to write a string to the port,
flush to (eventuelly) flush the characters on the port and finally
close to close the port. Write-char takes two parameters: a character and
the port to which the output must be done. write-string takes two
parameters: a string and a port. Flush and Close take one
parameter which is the port on which the action must be done.
Open-output-virtual accepts also the special value #f
for the I/O procedures. If a procedure is #f nothing is done
on the corresponding action.
Hereafter is an (very inefficient) implementation of a variant of
open-output-string using virtual ports. The value of the output
string is printed when the port is closed:
(define (open-output-string)
(let ((str ""))
(open-output-virtual
:write-char (lambda (c p)
(set! str (string-append str (string c))))
:write-string (lambda (s p)
(set! str (string-append str s)))
:close (lambda (p) (write str) (newline)))))
|
Note: write-string is mainly used for writing strings and is
generally more efficient than writing the string character by character.
However, if write-string is not provided, strings are printed with
write-char . On the other hand, if write-char is absent,
characters are written by successive allocation of one character strings.
Hereafter is another example: a virtual file port where all characters
are converted to upper case:
(define (open-output-uppercase-file file)
(let ((out (open-file file "w")))
(and out
(open-output-virtual
:write-string (lambda (s p)
(display (string-upper s) out))
:close (lambda (p)
(close-port out))))))
|
|
(open-file filename mode) | STklos procedure |
Opens the file whose name is filename with the specified string
mode which can be:
"r" to open file for reading. The stream is positioned at
the beginning of the file.
"r+" to open file for reading and writing. The stream is
positioned at the beginning of the file.
"w" to truncate file to zero length or create file for writing.
The stream is positioned at the beginning of the file.
"w+" to open file for reading and writing. The file is created
if it does not exist, otherwise it is truncated. The stream is positioned
at the beginning of the file.
"a" to open for writing. The file is created if it does
not exist. The stream is positioned at the end of the file.
"a+" to open file for reading and writing. The file is created
if it does not exist. The stream is positioned at the end of the file.
If the file can be opened, open-file returns the port associated with
the given file, otherwise it returns #f . Here again, the ``magic''
string "| " permits to open a pipe port (in this case mode can only be
"r" or "w" ). |
(get-output-string port) | STklos procedure |
Returns a string containing all the text that has been written on the
output string port .
(let ((p (open-output-string)))
(display "Hello, world" p)
(get-output-string p)) ⇒ "Hello, world"
|
|
(close-input-port port) | R5RS procedure |
(close-output-port port)
Closes the port associated with port , rendering the port incapable of
delivering or accepting characters. These routines have no effect if the
port has already been closed. The value returned is void. |
(close-port port) | STklos procedure |
Closes the port associated with port . |
(port-rewind port) | STklos procedure |
Sets the port position to the beginning of port . The value returned by
port-rewind is void. |
(port-seek port pos) | STklos procedure |
(port-seek port pos whence)
Sets the file position for the given port to the position pos .
The new position, measured in bytes, is obtained by adding pos
bytes to the position specified by whence . If passed, whence
must be one of :start , :current or :end . The resulting
position is relative to the start of the file, the current position
indicator, or end-of-file, respectively. If whence is omitted, it
defaults to :start .
Note: After using port-seek, the value returned by
port-current-line may be incorrect. |
(port-current-line) | STklos procedure |
(port-current-line port)
Returns the current line number associated to the given input port as an
integer. The port argument may be omitted, in which case it defaults to
the value returned by current-input-port .
Note: The port-seek , read-chars and read-chars! procedures
generally break the line-number. After using one of theses procedures, the
value returned by port-current-line will be -1 (except a port-seek
at the beginning of the port reinitializes the line counter). |
(port-current-position) | STklos procedure |
(port-current-position port)
Returns the position associated to the given port as an
integer (i.e. number of characters from the beginning of the port).
The port argument may be omitted, in which case it defaults to
the value returned by current-input-port . |
(port-file-name port) | STklos procedure |
Returns the file name used to open port ; port must be a file port. |
(port-idle-register! port thunk) | STklos procedure |
(port-idle-unregister! port thunk)
(port-idle-reset! port)
port-idle-register! allows to register thunk as an idle handler
when reading on port. That means that thunk will be called continuously
while waiting an input on port (and only while using a reading
primitive on this port). port-idle-unregister! can be used to
unregister a handler previously set by port-idle-register! . The
primitive port-idle-reset! unregisters all the handlers set on
port .
Hereafter is a (not too realistic) example: a message will be displayed
repeatedly until a sexpr is read on the current input port.
(let ((idle (lambda () (display "Nothing to read!\n"))))
(port-idle-register! (current-input-port) idle)
(let ((result (read)))
(port-idle-unregister! (current-input-port) idle)
result))
|
|
(port-closed? port) | STklos procedure |
Returns #t if port is closed and #f otherwise. |
(read port)
Read converts external representations of Scheme objects into the
objects themselves. Read returns the next object parsable from the given
input port, updating port to point to the first character past the end of
the external 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
external representation, but the external 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.
STklos read supports the SRFI-10
(Sharp Comma External Form) # form that can be used
to denote values that do not have a convenient printed representation. See
the SRFI document for more information. |
(read-with-shared-structure) | STklos procedure |
(read-with-shared-structure port)
(read/ss)
(read/ss port)
read-with-shared-structure is identical to read . It has been added to
be compatible with SRFI-38
(External representation of shared structures). STklos always knew how to deal with
recursive input data. read/ss is only a shorter name for
read-with-shared-structure .
|
(define-reader-ctor tag proc) | STklos procedure |
This procedure permits to define a new user to reader constructor procedure
at run-time. It is defined in SRFI-10
(Sharp Comma External Form) document. See SRFI document
for more information.
(define-reader-ctor 'rev (lambda (x y) (cons y x)))
(with-input-from-string "#,(rev 1 2)" read)
⇒ (2 . 1)
|
|
(read-char) | R5RS 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 . |
(read-chars size) | STklos procedure |
(read-chars size port)
Returns a newly allocated string made of size characters read from port .
If less than size characters are available on the input port, the returned
string is smaller than size and its size is the number of available
characters. Port may be omitted, in which case it defaults to the
value returned by current-input-port . |
(read-chars! str) | STklos procedure |
(read-chars! str port)
This function reads the characters available from port in the string str
by chuncks whose size is equal to the length of str .
The value returned by read-chars! is an integer indicating the number
of characters read. Port may be omitted, in which case it defaults to the
value returned by current-input-port .
This function is similar to read-chars except that it avoids to allocate
a new string for each read.
(define (copy-file from to)
(let* ((size 1024)
(in (open-input-file from))
(out (open-output-file to))
(s (make-string size)))
(let Loop ()
(let ((n (read-chars! s in)))
(cond
((= n size)
(write-chars s out)
(Loop))
(else
(write-chars (substring s 0 n) out)
(close-port out)))))))
|
|
(read-byte) | STklos procedure |
(read-byte port)
Returns the next character available from the input port as an integer.
If the end of file is readched, thuis function returns the end of file
object. |
(peek-char) | R5RS procedure |
(peek-char port)
Returns the next character available from the input port , without updating
the port to point to the following character. If no more characters are
available, an end of file object is returned. Port may be omitted, in
which case it defaults to the value returned by current-input-port .
Note: The value returned by a call to peek-char is the same as the
value that would have been returned by a call to read-char with the same
port. The only difference is that the very next call to read-char or
peek-char on that port will return the value returned by the preceding
call to peek-char . In particular, a call to peek-char on an interactive
port will hang waiting for input whenever a call to read-char would have
hung. |
(peek-byte) | STklos procedure |
(peek-byte port)
Returns the next character available from the input port , without updating
the port to point to the following character. Whereas peek-char
returns a character, this function returns an integer between 0and 255. |
(eof-object? obj) | R5RS procedure |
Returns #t if obj is an end of file object, otherwise returns #f . |
(eof-object) | STklos procedure |
Returns an end of file object. Note that the special notation #eof is
another way to return such an end of file object. |
(char-ready?) | R5RS 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 . |
(read-line) | STklos procedure |
(read-line port)
Reads the next line available from the input port port . This function
returns 2 values: the first one is is the string which contains the line
read, and the second one is the end of line delimiter. The end of line
delimiter can be an end of file object, a character or a string in case
of a multiple character delimiter. If no more characters are available
on port , an end of file object is returned. Port may be omitted,
in which case it defaults to the value returned by current-input-port .
Note: As said in values, if read-line is not
used in the context of call-with-values , the second value returned by
this procedure is ignored. |
(read-from-string str) | STklos procedure |
Performs a read from the given str . If str is the empty string,
an end of file object is returned.
(read-from-string "123 456") ⇒ 123
(read-from-string "") ⇒ an eof object
|
|
(port->string port) | STklos procedure |
(port->sexp-list port)
(port->string-list port)
All these procedure take a port opened for reading. Port->string reads
port until the it reads an end of file object and returns all the
characters read as a string. Port->sexp-list) and port->string-list
do the same things except that they return a list of S-expressions and
a list of strings respectively. For the following example we suppose that
file "foo" is formed of two lines which contains respectively the number
100 and the string "bar" .
(port->sexp-list (open-input-file "foo")) ⇒ (100 "bar")
(port->string-list (open-input-file "foo")) ⇒ ("100" ""bar"")
|
|
4.11.3 Output
(write obj) | R5RS procedure |
(write obj port)
Writes a written 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. Character objects are written using the #\ notation.
Write returns an unspecified value. The port argument may be omitted, in
which case it defaults to the value returned by current-output-port . |
(write* obj) | STklos procedure |
(write* obj port)
Writes a written representation of obj to the given port. The
main difference with the write procedure is that write*
handles data structures with cycles. Circular structure written by
this procedure use the "#n=" and "#n#"
notations (see Circular-structure).
|
(write-with-shared-structure obj) | STklos procedure |
(write-with-shared-structure obj port)
(write-with-shared-structure obj port optarg)
(write/ss obj)
(write/ss obj port)
(write/ss obj port optarg)
write-with-shared-structure has been added to be compatible with
SRFI-38
(External representation of shared structures). It is is identical to write* , except that it accepts one
more parameter (optarg ). This parameter, which is not specified
in SRFI-38 (External representation of shared structures), is always ignored. write/ss is only a shorter name for
write-with-shared-structure .
|
(display obj) | R5RS 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. 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. |
(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 . |
(write-char char) | R5RS procedure |
(write-char char port)
Writes the character char (not an external representation of the
character) to the given port and returns an unspecified value.
The port argument may be omitted, in which case it defaults to the
value returned by current-output-port . |
(write-chars str) | STklos procedure |
(write-char str port)
Writes the character of string str 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 . Note: This function is generally
faster than display for strings. Furthermore, this primitive does
not use the buffer associated to port .
|
(write-byte b) | STklos procedure |
(write-byte b port)
Write byte b to the port. b must be an exact integer in range between 0
and 255. |
(format port str obj ...) | STklos procedure |
(format str obj)
Writes the obj s to the given port , according to the format
string str . Str is written literally, except for the following
sequences:
~a or ~A is replaced by the printed representation
of the next obj .
~s or ~S is replaced by the ``slashified'' printed
representation of the next obj .
~w or ~W is replaced by the printed representation
of the next obj (circular structures are correctly handled and
printed using write* ).
~d or ~D is replaced by the decimal printed representation
of the next obj (which must be a number).
~x or ~X is replaced by the hexadecimal printed representation
of the next obj (which must be a number).
~o or ~O is replaced by the octal printed representation
of the next obj (which must be a number).
~b or ~B is replaced by the binary printed representation
of the next obj (which must be a number).
~c or ~C is replaced by the printed representation
of the next obj (which must be a character).
~y or ~Y is replaced by the pretty-printed representation
of the next obj . The standard pretty-printer is used here.
~? is replaced by the result of the recursive call of format
with the two next obj .
~k or ~K is another name for ~?
~[w[,d]]f or ~[w[,d]]F is replaced by the printed
representation of next obj (which must be a number) with width w
and d digits after the decimal. Eventually, d may be omitted.
~~ is replaced by a single tilde character.
~% is replaced by a newline
~t or ~t is replaced by a tabulation character.
~& is replaced by a newline character if it is known that the
previous character was not a newline
~_ is replaced by a space
~h or ~H provides some help
Port can be a boolean or a port. If port is #t , output goes to
the current output port; if port is #f , the output is returned as a
string. Otherwise, the output is printed on the specified port.
(format #f "A test.") ⇒ "A test."
(format #f "A ~a." "test") ⇒ "A test."
(format #f "A ~s." "test") ⇒ "A \"test\"."
(format "~8,2F" 1/3) ⇒ " 0.33"
(format "~6F" 32) ⇒ " 32"
(format "~1,2F" 4321) ⇒ "4321.00"
(format "~1,2F" (sqrt -3.9)) ⇒ "0.00+1.97i"
(format "#d~d #x~x #o~o #b~b~%" 32 32 32 32)
⇒ "#d32 #x20 #o40 #b100000\n"
(format #f "~&1~&~&2~&~&~&3~%")
⇒ "1\n2\n3\n"
(format "~a ~? ~a" 'a "~s" '(new) 'test)
⇒ "a new test"
|
Note: The second form of format is compliant with
SRFI-28
(Basic Format Strings). That is, when
port is omitted, the output is returned as a string as if port was
given the value #f .
Note: Since version 0.58, format is also compliant with
SRFI-48
(Intermediate Format Strings). |
(flush-output-port) | STklos procedure |
(flush-output-port port)
Flushes the buffer associated with the given output port . The
port argument may be omitted, in which case it defaults to the value
returned by current-output-port |
(print obj ...) | STklos procedure |
(printerr obj ...)
These procedures display all their arguments followed by a newline. The
procedure print uses the standard output port, whereas printerr uses the
current error port |
(printf fmt obj ...) | STklos procedure |
(fprintf port fmt obj ...)
(eprintf fmt obj ...)
These procedures are specialized version of format .
In these procedures, fmt is a string using the format conventions.
printf outputs go on the current output port.
fprintf outputs go on the specified port .
eprintf outputs go on the current error port (note that eprintf always
flushes the characters printed). |
4.11.4 System interface
(load filename) | R5RS procedure |
Filename should be a string naming an existing file containing Scheme
expressions. Load has been extended in STklos to allow loading of
file containing Scheme compiled code as well as object files
(aka shared objects). The loading of object files is not available on
all architectures. The value returned by load is void.
If the file whose name is filename cannot be located, load will try
to find it in one of the directories given by load-path
with the suffixes given by load-suffixes . |
(try-load filename) | STklos procedure |
try-load tries to load the file named filename . As load ,
try-load tries to find the file given the current load path
and a set of suffixes if filename cannot be loaded. If try-load
is able to find a readable file, it is loaded, and try-load returns
#t . Otherwise, try-load retuns #f . |
(find-path str) | STklos procedure |
(find-path str path)
(find-path str path suffixes)
In its first form, find-path returns the path name of the file
that should be loaded by the procedure load given the name str .
The string returned depends of the current load path and of the
currently accepted suffixes.
The other forms of find-path are more general and allow to give a path
list (a list of strings representing supposed directories) and a set
of suffixes (given as a list of strings too) to try for finding a file.
If no file is found, find-path returns #f .
For instance, on a "classical" Unix box:
(find-path "passwd" '("/bin" "/etc" "/tmp"))
⇒ "/etc/passwd"
(find-path "stdio" '("/usr" "/usr/include") '("c" "h" "stk"))
⇒ "/usr/include/stdio.h"
|
|
(current-loading-file) | STklos procedure |
Returns the path of the file that is currently being load. |
(require string) | STklos procedure |
(provide string)
(require/provide string)
(provided? string)
Require loads the file whose name is string if it was not
previously "provided". Provide permits to store string in
the list of already provided files. Providing a file permits to avoid
subsequent loads of this file. Require/provide is more or less equivalent to
a require followed by a provide . Provided? returns #t if
string was already provided; it returns #f otherwise. |
4.12 Keywords
Keywords are symbolic constants which evaluate to themselves.
A keyword is a symbol whose first (or last) character is a colon
(":").
(keyword obj) | STklos procedure |
Returns #t if obj is a keyword, otherwise returns #f .
(keyword? 'foo) ⇒ #f
(keyword? ':foo) ⇒ #t
(keyword? 'foo:) ⇒ #t
(keyword? :foo) ⇒ #t
(keyword? foo:) ⇒ #t
|
|
(make-keyword s) | STklos procedure |
Builds a keyword from the given s . The parameter s must be a symbol
or a string.
(make-keyword "test") ⇒ :test
(make-keyword 'test) ⇒ :test
(make-keyword ":hello") ⇒ ::hello
|
|
(keyword->string key) | STklos procedure |
Returns the name of key as a string. The result does not contain a colon. |
(string->keyword str) | STklos procedure |
This function function has been added to be compatibe with SRFI-88.
It is equivalent to make-keyword, except that the parameter cannot be
a symbol. |
(key-get list key) | STklos procedure |
(key-get list key default)
List must be a list of keywords and their respective values.
key-get scans the list and returns the value
associated with the given key . If key does
not appear in an odd position in list , the specified
default is returned, or an error is raised if no default was
specified.
(key-get '(:one 1 :two 2) :one) ⇒ 1
(key-get '(:one 1 :two 2) :four #f) ⇒ #f
(key-get '(:one 1 :two 2) :four) ⇒ error
|
|
(key-set! list key value) | STklos procedure |
List must be a list of keywords and their respective values.
key-set! sets the value associated to key in the keyword list.
If the key is already present in list , the keyword list is
physically changed.
(let ((l (list :one 1 :two 2)))
(set! l (key-set! l :three 3))
(cons (key-get l :one)
(key-get l :three))) ⇒ (1 . 3)
|
|
(key-delete list key) | STklos procedure |
(key-delete! list key)
List must be a list of keywords and their respective values.
key-delete remove the key and its associated value of the keyword
list. The key can be absent of the list.
key-delete! does the
same job than key-delete by physically modifying its list argument.
(key-delete '(:one 1 :two 2) :two) ⇒ (:one 1)
(key-delete '(:one 1 :two 2) :three) ⇒ (:one 1 :two 2)
|
|
4.13 Hash Tables
A hash table consists of zero or more entries, each consisting of a key
and a value. Given the key for an entry, the hashing function can very
quickly locate the entry, and hence the corresponding value. There may
be at most one entry in a hash table with a particular key, but many
entries may have the same value. STklos hash tables grow gracefully as the number of entries
increases, so that there are always less than three entries per hash
bucket, on average. This allows for fast lookups regardless of the
number of entries in a table. STklos hash tables procedures are identical to the ones
defined in SRFI-69
(Basic Hash Tables). Note that the default comparison function
is eq? whereas it is equal? in this SRFI. See
SRFIs for more information.
(make-hash-table) | STklos procedure |
(make-hash-table comparison)
(make-hash-table comparison hash)
Make-hash-table admits three different forms. The most general form
admit two arguments. The first argument is a comparison function which
determines how keys are compared; the second argument is a function which
computes a hash code for an object and returns the hash code as a non
negative integer. Objets with the same hash code are stored in an A-list
registered in the bucket corresponding to the key.
If omitted,
hash defaults to the hash-table-hash procedure (see
hash-table-hash).
comparison defaults to the eq? procedure (see eq-).
Consequently,
(define h (make-hash-table))
|
is equivalent to
(define h (make-hash-table eq? hash-table-hash))
|
An interesting example is
(define h (make-hash-table string-ci=? string-length))
|
which defines a new hash table which uses string-ci=? for
comparing keys. Here, we use the string-length as a (very simple)
hashing function. Of course, a function which gives a key depending
of the characters composing the string gives a better repartition
and should probably enhance performances. For instance, the following
call to make-hash-table should return a more efficient, even if
not perfect, hash table:
(make-hash-table
string-ci=?
(lambda (s)
(let ((len (string-length s)))
(do ((h 0) (i 0 (+ i 1)))
((= i len) h)
(set! h
(+ h (char->integer
(char-downcase (string-ref s i)))))))))
|
Note: Hash tables with a comparison function equal to eq? or
string=? are handled in an more efficient way (in fact, they don't use
the hash-table-hash function to speed up hash table retrievals). |
(hash-table? obj) | STklos procedure |
Returns #t if obj is a hash table, returns #f otherwise. |
(hash-table-hash obj) | STklos procedure |
Computes a hash code for an object and returns this hash code as a
non negative integer. A property of hash-table-hash is that
(equal? x y) ⇒ (equal? (hash-table-hash x) (hash-table-hash y)
|
as the the Common Lisp sxhash function from which this procedure is
modeled. |
(alist->hash-table alist) | STklos procedure |
(alist->hash-table alist comparison)
(alist->hash-table alist comparison hash)
Returns hash-table built from the ``association list''
alist . This function maps the car of every element in alist
to the cdr of corresponding elements in alist . the comparison and
hash functions are interpreted as in make-hash-table . If some key
occurs multiple times in alist , the value in the first
association will take precedence over later ones.
|
(hash-table->alist hash) | STklos procedure |
Returns an ``association list'' built from the entries in hash .
Each entry in hash will be represented as a pair whose car is the
entry's key and whose cdr is its value.
Note: the order of pairs in the resulting list is unspecified.
(let ((h (make-hash-table)))
(dotimes (i 5)
(hash-table-set! h i (number->string i)))
(hash-table->alist h))
⇒ ((3 . "3") (4 . "4") (0 . "0")
(1 . "1") (2 . "2"))
|
|
(hash-table-set! hash key value) | STklos procedure |
Enters an association between key and value in thehash table.
The value returned by hash-table-set! is void. |
(hash-table-ref hash key) | STklos procedure |
(hash-table-ref hash key thunk)
Returns the value associated with key in the given hash table. If no
value has been associated with key in hash , the specified thunk is
called and its value is returned; otherwise an error is raised.
(define h1 (make-hash-table))
(hash-table-set! h1 'foo (list 1 2 3))
(hash-table-ref h1 'foo) ⇒ (1 2 3)
(hash-table-ref h1 'bar
(lambda () 'absent)) ⇒ absent
(hash-table-ref h1 'bar) ⇒ error
(hash-table-set! h1 '(a b c) 'present)
(hash-table-ref h1 '(a b c)
(lambda () 'absent)) ⇒ absent
(define h2 (make-hash-table equal?))
(hash-table-set! h2 '(a b c) 'present)
(hash-table-ref h2 '(a b c)) ⇒ present
|
|
(hash-table-ref/default hash key) | STklos procedure |
This function is equivalent to
(hash-table-ref hash key (lambda () default))
|
|
(hash-table-delete! hash key) | STklos procedure |
Deletes the entry for key in hash , if it exists. Result of
hash-table-delete! is void.
(define h (make-hash-table))
(hash-table-set! h 'foo (list 1 2 3))
(hash-table-ref h 'foo) ⇒ (1 2 3)
(hash-table-delete! h 'foo)
(hash-table-ref h 'foo
(lambda () 'absent) ⇒ absent
|
|
(hash-table-exists? hash key) | STklos procedure |
Returns #t if there is any association of key in
hash . Returns #f otherwise. |
(hash-table-update! hash key update-fun thunk) | STklos procedure |
(hash-table-update!/default hash key update-fun default)
Update the value associated to key in table hash if key is already in
table with the value (update-fun current-value) . If no value is
associated to key , a new entry in the table is first inserted
before updating it (this new entry being the result of calling thunk ).
Note that the expression
(hash-table-update!/default hash key update-fun default)
|
is equivalent to
(hash-table-update! hash key update-fun (lambda () default))
|
(let ((h (make-hash-table))
(1+ (lambda (n) (+ n 1))))
(hash-table-update!/default h 'test 1+ 100)
(hash-table-update!/default h 'test 1+)
(hash-table-ref h 'test)) ⇒ 102
|
|
(hash-table-for-each hash proc) | STklos procedure |
(hash-table-walk hash proc)
Proc must be a procedure taking two arguments. Hash-table-for-each
calls proc on each key/value association in hash , with the key as
the first argument and the value as the second. The value returned by
hash-table-for-each is void.
Note: The order of application of proc is unspecified.
Note: hash-table-walk is another name for hash-table-for-each
(this is the name used in SRFI-69
(Basic Hash Tables)).
(let ((h (make-hash-table))
(sum 0))
(hash-table-set! h 'foo 2)
(hash-table-set! h 'bar 3)
(hash-table-for-each h (lambda (key value)
(set! sum (+ sum value))))
sum) ⇒ 5
|
|
(hash-table-map hash proc) | STklos procedure |
Proc must be a procedure taking two arguments. Hash-table-map
calls proc on each key/value association in hash , with the key as
the first argument and the value as the second. The result of
hash-table-map is a list of the values returned by proc , in an
unspecified order.
Note: The order of application of proc is unspecified.
(let ((h (make-hash-table)))
(dotimes (i 5)
(hash-table-set! h i (number->string i)))
(hash-table-map h (lambda (key value)
(cons key value))))
⇒ ((3 . "3") (4 . "4") (0 . "0") (1 . "1") (2 . "2"))
|
|
(hash-table-keys hash) | STklos procedure |
(hash-table-values hash)
Returns the keys or the values of hash . |
(hash-table-fold hash func init-value) | STklos procedure |
This procedure calls func for every association in hash
with three arguments: the key of the association key, the value
of the association value, and an accumulated value, val . Val is
init-value for the first invocation of func , and for subsequent
invocations of func , the return value of the previous invocation of
func . The value final-value returned by hash-table-fold is the
return value of the last invocation of func . The order in which func is
called for different associations is unspecified.
For instance, the following expression
(hash-table-fold ht (lambda (k v acc) (+ acc 1)) 0)
|
computes the number of associations present in the ht hash table. |
(hash-table-copy hash) | STklos procedure |
Returns a copy of hash . |
(hash-table-merge! hash1 hash2) | STklos procedure |
Adds all mappings in hash2 into hash1 and returns the resulting
hash table. This function may modify hash1 destructively. |
(hash-table-equivalence-function hash) | STklos procedure |
Returns the equivalence predicate used for keys in hash . |
(hash-table-hash-function hash) | STklos procedure |
Returns the hash function used for keys in hash . |
(hash-table-size hash) | STklos procedure |
Returns the number of entries in the hash . |
(hash-table-stats hash) | STklos procedure |
(hash-table-stats hash port)
Prints overall information about hash , such as the number of entries
it contains, the number of buckets in its hash array, and the utilization
of the buckets. Informations are printed on port . If no port is given
to hash-table-stats , information are printed on the current output port
(see current-output-port). |
4.14 Dates and Times
STklos stores dates and times with a compact
representation which consists is an integer which represents the
number of seconds elapsed since the Epoch (00:00:00 on
January 1, 1970, Coordinated Universal Time --UTC). Dates can
also be represented with date structures.
(current-seconds) | STklos procedure |
Returns the time since the Epoch (that is 00:00:00 UTC, January 1, 1970),
measured in seconds. |
(current-time) | R5RS procedure |
Returns a time object corresponding to the current time. |
(time? obj) | STklos procedure |
Return #t if obj is a time object, othererwise returns #f . |
(time->seconds time) | STklos procedure |
Convert the time object time into an inexact real number representing
the number of seconds elapsed since the Epoch.
(time->seconds (current-time)) =⇒ 1138983411.09337
|
|
(seconds->time x) | STklos procedure |
Converts into a time object the real number x representing the number
of seconds elapsed since the Epoch.
(seconds->time (+ 10 (time->seconds (current-time)))
=⇒ a time object representing 10 seconds in the future
|
|
(current-date) | STklos procedure |
Returns the current system date. |
(make-date :key second minute hour day month year) | STklos procedure |
Build a date from its argument. hour , minute , second default to 0;
day and month default to 1; year defaults to 1970 |
(date? obj) | STklos procedure |
Return #t if obj is a date, and otherwise returns #f . |
(date-second d) | STklos procedure |
Return the second of date d , in the range 0 to 59. |
(date-minute d) | STklos procedure |
Return the minute of date d , in the range 0 to 59. |
(date-hour d) | STklos procedure |
Return the hour of date d , in the range 0 to 23. |
(date-day d) | STklos procedure |
Return the day of date d , in the range 1 to 31 |
(date-month d) | STklos procedure |
Return the month of date d , in the range 1 to 12 |
(date-year d) | STklos procedure |
Return the year of date d . |
(date-week-day d) | STklos procedure |
Return the week day of date d , in the range 0 to 6 (0 is Sunday). |
(date-year-day d) | STklos procedure |
Return the the number of days since January 1 of date d , in the range
1 to 366. |
(date-dst d) | STklos procedure |
Return an indication about daylight saving adjustment:
- 0 if no daylight saving adjustment
- 1 if daylight saving adjustment
- -1 if the information is not available
|
(date-tz d) | STklos procedure |
Return the time zone of date d . |
(date->seconds d) | STklos procedure |
Convert the date d to the number of seconds since the Epoch. |
(date->string format d) | STklos procedure |
Convert the date d using the string format as a
specification. Conventions for format are the same as the one
of seconds--string. |
(seconds->date n) | STklos procedure |
Convert the date n expressed as a number of seconds since the Epoch
to a date. |
(seconds->string format n) | STklos procedure |
Convert a date expressed in seconds using the string format as a
specification. Conventions for format are given below:
- ~~ a literal ~
- ~a locale's abbreviated weekday name (Sun...Sat)
- ~A locale's full weekday name (Sunday...Saturday)
- ~b locale's abbreviate month name (Jan...Dec)
- ~B locale's full month day (January...December)
- ~c locale's date and time
(e.g.,
Fri Jul 14 20:28:42-0400 2000 )
- ~d day of month, zero padded (01...31)
- ~D date (mm/dd/yy)
- ~e day of month, blank padded ( 1...31)
- ~f seconds+fractional seconds, using locale's
decimal separator (e.g. 5.2).
- ~h same as ~b
- ~H hour, zero padded, 24-hour clock (00...23)
- ~I hour, zero padded, 12-hour clock (01...12)
- ~j day of year, zero padded
- ~k hour, blank padded, 24-hour clock (00...23)
- ~l hour, blank padded, 12-hour clock (01...12)
- ~m month, zero padded (01...12)
- ~M minute, zero padded (00...59)
- ~n new line
- ~p locale's AM or PM
- ~r time, 12 hour clock, same as
~I:~M:~S ~p
- ~s number of full seconds since "the epoch" (in UTC)
- ~S second, zero padded (00...61)
- ~t horizontal tab
- ~T time, 24 hour clock, same as
~H:~M:~S
- ~U week number of year with Sunday as first day of week
(00...53)
- ~V weekISO 8601:1988 week number of year (01...53)
(week 1 is the first week that has at least 4 days in the current year,
and with Monday as the first day of the week)
- ~w day of week (1...7, 1 is Monday)
- ~W week number of year with Monday as first day of week
(01...52)
- ~x week number of year with Monday as first day of week
(00...53)
- ~X locale's date representation, for example: "07/31/00"
- ~y last two digits of year (00...99)
- ~Y year
- ~z time zone in RFC-822 style
- ~Z symbol time zone
|
(seconds->list sec) | STklos procedure |
Returns a keyword list for the date given by sec (a date based on the
Epoch). The keyed values returned are
- second : 0 to 59 (but can be up to 61 to allow for leap seconds)
- minute : 0 to 59
- hour : 0 to 23
- day : 1 to 31
- month : 1 to 12
- year : e.g., 2002
- week-day : 0 (Sunday) to 6 (Saturday)
- year-day : 0 to 365 (365 in leap years)
- dst : indication about daylight savings time. See date-dst
- tz : the difference between Coordinated Universal Time
(UTC) and local standard time in seconds.
(seconds->list (current-second))
⇒ (:second 51 :minute 26 :hour 19
:day 5 :month 11 :year 2004
:week-day 5 :year-day 310
:dst 0 :tz -3600)
|
|
Returns the current date in a string |
4.15 Boxes
Boxes are records that have a single field. A box may be constructed with
the make-box, make-constant-box or the read primitives.
A box produced by read (using the "#&" notation) is mutable. Note that
two boxes are equal? iff their content are equal?.
(make-box obj) | STklos procedure |
Returns a new box that contains obj . The box is mutable.
(let ((x (make-box 10)))
(list 10 x)) ⇒ (10 #&10)
|
|
(make-constant-box obj) | STklos procedure |
Returns a new box that contains obj . The box is immutable. |
(box? obj) | STklos procedure |
Returns #t if obj is box, #f otherwise. |
(box-mutable? obj) | STklos procedure |
Returns #t if obj is mutable box, #f otherwise. |
(box-set! box x) | STklos procedure |
Sets the content of box to x . The box must be mutable. |
(unbox box) | STklos procedure |
Returns the content of box . For any obj , (unbox (make-box obj))
returns obj . |
4.16 Processes
STklos provides access to Unix processes as first class objects.
Basically, a process contains several informations such as the standard
system process identification (aka PID on Unix Systems), the files where
the standard files of the process are redirected.
(run-process command p1 p2 ...) | STklos procedure |
run-process creates a new process and run the executable
specified in command . The p correspond to the command line
arguments. The following values of p have a special meaning:
:input permits to redirect the standard input file of the
process. Redirection can come from a file or from a pipe. To redirect
the standard input from a file, the name of this file must be
specified after :input . Use the special keyword :pipe to
redirect the standard input from a pipe.
:output permits to redirect the standard output file of the
process. Redirection can go to a file or to a pipe. To redirect
the standard output to a file, the name of this file must be
specified after :output . Use the special keyword :pipe to
redirect the standard output to a pipe.
:error permits to redirect the standard error file of the
process. Redirection can go to a file or to a pipe. To redirect
the standard error to a file, the name of this file must be
specified after error . Use the special keyword :pipe to
redirect the standard error to a pipe.
:wait must be followed by a boolean value. This value
specifies if the process must be run asynchronously or not. By
default, the process is run asynchronously (i.e. :wait is #f ).
:host must be followed by a string. This string represents
the name of the machine on which the command must be executed. This
option uses the external command rsh . The shell variable
PATH must be correctly set for accessing it without specifying its
abolute path.
:fork must be followed by a boolean value. This value
specifies if a fork system call must be done before running
the process. If the process is run without fork the Scheme
program is lost. This feature mimics the ``exec '' primitive of the
Unix shells. By default, a fork is executed before running the process
(i.e. :fork is #t ). This option works on Unix implementations only.
The following example launches a process which executes the
Unix command ls with the arguments -l and /bin . The lines
printed by this command are stored in the file /tmp/X
(run-process "ls" "-l" "/bin" :output "/tmp/X")
|
|
(process? obj) | STklos procedure |
Returns #t if obj is a process , otherwise returns #f . |
(process-alive? proc) | STklos procedure |
Returns #t if process proc is currently running, otherwise returns #f . |
(process-pid proc) | STklos procedure |
Returns an integer which represents the Unix identification (PID) of the
processus. |
(process-input proc) | STklos procedure |
(process-output proc)
(process-error proc)
Returns the file port associated to the standard input, output or error
of proc , if it is redirected in (or to) a pipe; otherwise
returns #f . Note that the returned port is opened for reading
when calling process-output or process-error ; it is opened
for writing when calling process-input . |
(process-wait proc) | STklos procedure |
Stops the current process (the Scheme process) until proc completion.
Process-wait returns #f when proc is already terminated; it returns
#t otherwise. |
(process-exit-status proc) | STklos procedure |
Returns the exit status of proc if it has finished its execution;
returns #f otherwise. |
(process-send-signal proc sig) | STklos procedure |
Sends the integer signal sig to proc . Since value of sig is system
dependant, use the symbolic defined signal constants to make your program
independant of the running system (see signals).
The result of process-send-signal is void. |
(process-kill proc) | STklos procedure |
Kills (brutally) process . The result of process-kill
is void. This procedure is equivalent to
(process-send-signal process 'SIGTERM)
|
|
(process-stop proc) | STklos procedure |
(process-continue proc)
Process-stop stops the execution of proc and process-continue resumes
its execution. They are equivalent, respectively, to
(process-send-signal process 'SIGSTOP)
(process-send-signal process 'SIGCONT)
|
|
(process-list) | STklos procedure |
Returns the list of processes which are currently running (i.e. alive). |
(fork thunk)
This procedure is a wrapper around the standard Unix fork system
call which permits to create a new (heavy) process.
When called without parameter, this procedure returns two times
(one time in the parent process and one time in the child process).
The value returned in the parent process is a process object
representing the child process and the value returned in the child
process is always the value #f .
When called with a parameter (which must be a thunk), the new process
excutes thunk and terminate it execution when thunk returns. The
value returned in the parent process is a process object representing
the child process. |
4.17 Sockets
STklos defines sockets, on systems which support them,
as first class objects. Sockets permits processes to communicate even if
they are on different machines. Sockets are useful for creating client-server
applications.
(make-client-socket hostname port-number) | STklos procedure |
(make-client-socket hostname port_number line-buffered)
make-client-socket returns a new socket object. This socket
establishes a link between the running program and the application
listening on port port-number of hostname . If the optional argument
line-buffered has a true value, a line buffered policy is used when writing
to the client socket (i.e. characters on the socket are tranmitted as soon
as a #\newline character is encountered). The default value of
line-buffered is #t .
|
(make-server-socket) | STklos procedure |
(make-server-socket port-number)
make-server-socket returns a new socket object. If port-number
is specified, the socket is listening on the specified port;
otherwise, the communication port is chosen by the system. |
(socket-shutdown sock) | STklos procedure |
(socket-shutdown sock close)
Socket-shutdown shutdowns the connection associated to
socket . If the socket is a server socket, socket-shutdown is called
on all the client sockets connected to this server.
Close indicates if the the socket must be closed or not, when
the connection is destroyed. Closing the socket forbids further
connections on the same port with the socket-accept procedure.
Omitting a value for close implies the closing of socket.
The following example shows a simple server: when there is
a new connection on the port number 12345, the server displays
the first line sent to it by the client, discards the others and
go back waiting for further client connections.
(let ((s (make-server-socket 12345)))
(let loop ()
(let ((ns (socket-accept s)))
(format #t "I've read: ~A\n"
(read-line (socket-input ns)))
(socket-shutdown ns #f)
(loop))))
|
|
(socket-accept socket) | STklos procedure |
(socket-accept socket line-buffered)
socket-accept waits for a client connection on the given
socket . If no client is already waiting for a connection, this
procedure blocks its caller; otherwise, the first connection request
on the queue of pending connections is connected and socket-accept
returns a new client socket to serve this request.
This procedure must be called on a server socket created
with make-server-socket . The result of socket-accept is undefined.
Line-buffered indicates if the port should be considered as a
line buffered. If line-buffered is omitted, it defaults to #t .
The following example is a simple server which waits for a connection
on the port 12345 1.
Once the connection with the
distant program is established, we read a line on the input port
associated to the socket and we write the length of this line on its
output port.
(let* ((server (make-server-socket 13345))
(client (socket-accept server))
(l (read-line (socket-input client))))
(format (socket-output client)
"Length is: ~an" (string-length l))
(socket-shutdown server))
|
Note that shutting down the server socket suffices here to close
also the connection to client . |
(socket? obj) | STklos procedure |
Returns #t if socket is a socket, otherwise returns #f . |
(socket-server? obj) | STklos procedure |
Returns #t if socket is a server socket, otherwise returns #f . |
(socket-client? obj) | STklos procedure |
Returns #t if socket is a client socket, otherwise returns #f . |
(socket-host-name socket) | STklos procedure |
Returns a string which contains the name of the distant host
attached to socket . If socket has been created with
make-client-socket this procedure returns the official name of
the distant machine used for connection. If socket has been
created with make-server-socket , this function returns the
official name of the client connected to the socket. If no client
has used yet socket , this function returns #f . |
(socket-host-address socket) | STklos procedure |
Returns a string which contains the IP number of the distant host
attached to socket . If socket has been created with
make-client-socket this procedure returns the IP number of the
distant machine used for connection. If socket has been created
with make-server-socket , this function returns the address of the
client connected to the socket. If no client has used yet
socket , this function returns #f . |
(socket-local-address socket) | STklos procedure |
Returns a string which contains the IP number of the local host
attached to socket . |
(socket-port-number socket) | STklos procedure |
Returns the integer number of the port used for socket . |
(socket-input socket) | STklos procedure |
(socket-output socket)
Returns the file port associated for reading or writing with the
program connected with socket . If no connection has already been
established, these functions return #f .
The following example shows how to make a client socket. Here we
create a socket on port 13 of the machine kaolin.unice.fr 2:
(let ((s (make-client-socket "kaolin.unice.fr" 13)))
(format #t "Time is: ~A~%" (read-line (socket-input s)))
(socket-shutdown s))
|
|
4.18 System Procedures
4.18.1 File Primitives
(temporary-file-name) | STklos procedure |
Generates a unique temporary file name. The value returned by
temporary-file-name is the newly generated name of #f
if a unique name cannot be generated. |
(rename-file string1 string2) | STklos procedure |
Renames the file whose path-name is string1 to a file whose path-name is
string2 . The result of rename-file is void. |
(remove-file string) | STklos procedure |
Removes the file whose path name is given in string .
The result of remove-file is void. |
(copy-file string1 string2) | STklos procedure |
Copies the file whose path-name is string1 to a file whose path-name is
string2 . If the file string2 already exists, its content prior
the call to copy-file is lost. The result of copy-file is void. |
(copy-port in out) | STklos procedure |
(copy-port in out max)
Copy the content of port in , which must be opened for reading, on
port out , which must be opened for writing. If max is not specified,
All the characters from the input port are copied on ouput port. If max
is specified, it must be an integer indicating the maximum number of characters
which are copied from in to out . |
(file-is-directory? string) | STklos procedure |
(file-is-regular? string)
(file-is-readable? string)
(file-is-writable? string)
(file-is-executable? string)
(file-exists? string)
Returns #t if the predicate is true for the path name given in
string ; returns #f otherwise (or if string denotes a file
which does not exist). |
(file-size string) | STklos procedure |
Returns the size of the file whose path name is given in
string .If string denotes a file which does not exist,
file-size returns #f . |
Returns a string containing the current working directory. |
(chmod str) | STklos procedure |
(chmod str option1 ...)
Change the access mode of the file whose path name is given in string .
The options must be composed of either an integer or one of the
following symbols read , write or execute . Giving no option to chmod
is equivalent to pass it the integer 0 . If the operation succeeds,
chmod returns #t ; otherwise it returns #f .
(chmod "~/.stklos/stklosrc" 'read 'execute)
(chmod "~/.stklos/stklosrc" #o644)
|
|
(chdir dir) | STklos procedure |
Changes the current directory to the directory given in string dir . |
(make-directory dir) | STklos procedure |
Create a directory with name dir . |
(make-directories str) | STklos procedure |
Create a directory with name dir . No error is signaled if dir already exists,
Parent directories of dir are created as needed. |
(ensure-directories-exist path) | STklos procedure |
Create a directory with name dir (and its parent directories if needed), if it
does not exist yet. |
(remove-directory dir) | STklos procedure |
Delete the directory with name dir . |
(directory-files path) | STklos procedure |
Returns the list of the files in the directory path . Directories "."
and ".." don't appear in the result. |
(expand-file-name path) | STklos procedure |
Expand-file-name expands the filename given in path to
an absolute path.
;; Current directory is ~eg/stklos (i.e. /users/eg/stklos)
(expand-file-name "..") ⇒ "/users/eg"
(expand-file-name "~eg/../eg/bin") ⇒ "/users/eg/bin"
(expand-file-name "~/stklos)" ⇒ "/users/eg/stk"
|
|
(canonical-file-name path) | STklos procedure |
Expands all symbolic links in path and returns its canonicalized
absolute path name. The resulting path does not have symbolic links.
If path doesn't designate a valid path name, canonical-file-name
returns #f . |
(decompose-file-name string) | STklos procedure |
Returns an ``exploded'' list of the path name components given in
string .
The first element in the list denotes if the given string is an
absolute path or a relative one, being "/" or "." respectively.
Each component of this list is a string.
(decompose-file-name "/a/b/c.stk") ⇒ ("/" "a" "b" "c.stk")
(decompose-file-name "a/b/c.stk") ⇒ ("." "a" "b" "c.stk")
|
|
(winify-file-name fn) | STklos procedure |
On Win32 system, when compiled with the Cygwin environment,
file names are internally represented in a POSIX-like internal form.
Winify-file-bame permits to obtain back the Win32 name of an interned
file name
(winify-file-name "/tmp")
⇒ "C:\\cygwin\\tmp"
(list (getcwd) (winify-file-name (getcwd)))
⇒ ("//saxo/homes/eg/Projects/,(stklos)"
"\\\\saxo\\homes\\eg\\Projects\\,(stklos)")
|
|
(posixify-file-name fn) | STklos procedure |
On Win32 system, when compiled with the Cygwin environment,
file names are internally represented in a POSIX-like internal form.
posixify-file-bame permits to obtain the interned file name from
its external form.
file name
(posixify-file-name "C:\\cygwin\\tmp")
⇒ "/tmp"
|
|
(basename str) | STklos procedure |
Returns a string containing the last component of the path name
given in str .
(basename "/a/b/c.stk") ⇒ "c.stk"
|
|
(dirname str) | STklos procedure |
Returns a string containing all but the last component of the path
name given in str .
(dirname "/a/b/c.stk") ⇒ "/a/b"
|
|
(file-suffix pathname) | STklos procedure |
Returns the suffix of given pathname . If no suffix is found, file-suffix
returns an empty string.
(file-suffix "./foo.tar.gz") ⇒ "gz"
(file-suffix "./a.b/c") ⇒ ""
|
|
(file-prefix pathname) | STklos procedure |
Returns the suffix of given pathname .
(file-prefix "./foo.tar.gz") ⇒ "./foo.tar"
(file-prefix "./a.b/c") ⇒ "./a.b/c"
|
|
(file-separator) | STklos procedure |
Retuns the operating system file separator as a character. This is typically
#\/ on Unix (or Cygwin) systems and #\\ on Windows. |
(make-path dirname . names) | STklos procedure |
Builds a file name from the directory dirname and names . For instance,
on a Unix system:
(make-path "a" "b" "c") ⇒ "a/b/c"
|
|
(glob pattern ...) | STklos procedure |
Glob performs file name ``globbing'' in a fashion similar to the
csh shell. Glob returns a list of the filenames that match at least
one of pattern arguments. The pattern arguments may contain
the following special characters:
? Matches any single character.
* Matches any sequence of zero or more characters.
[chars] Matches any single character in chars .
If chars contains a sequence of the form a-b then any character
between a and b (inclusive) will match.
\x Matches the character x .
{a,b,...} Matches any of the strings a , b , etc.
As with csh, a '.' at the beginning of a file's name or just after
a '/ must be matched explicitly or with a @{@} construct.
In addition, all '/' characters must be matched explicitly.
If the first character in a pattern is '~' then it refers to
the home directory of the user whose name follows the '~'.
If the '~' is followed immediately by `/' then the value of
the environment variable HOME is used.
Glob differs from csh globbing in two ways. First, it does not
sort its result list (use the sort procedure if you want the list
sorted).
Second, glob only returns the names of files that actually exist;
in csh no check for existence is made unless a pattern contains a
? , * , or [] construct. |
4.18.2 Environment
(getenv str) | STklos procedure |
(getenv)
Looks for the environment variable named str and returns its
value as a string, if it exists. Otherwise, getenv returns #f .
If getenv is called without parameter, it returns the list of
all the environment variables accessible from the program as an
A-list.
(getenv "SHELL")
⇒ "/bin/zsh"
(getenv)
⇒ (("TERM" . "xterm") ("PATH" . "/bin:/usr/bin") ...)
|
|
(setenv! var value) | STklos procedure |
Sets the environment variable var to value . Var and
value must be strings. The result of setenv! is void. |
(unsetenv! var) | STklos procedure |
Unsets the environment variable var . Var must be a string.
The result of unsetenv! is void. |
(running-os) | STklos procedure |
Returns the name of the underlying Operating System which is running
the program.
The value returned by runnin-os is a symbol. For now, this procedure
returns either unix , windows , or cygwin-windows . |
(hostname) | STklos procedure |
Return the host name of the current processor as a string. |
Returns the number of argument present on the command line |
Returns a list of the arguments given on the shell command line. The
interpreter options are no included in the result |
(program-name) | STklos procedure |
Returns the invocation name of the current program as a string. |
(version) | STklos procedure |
Returns a string identifying the current version of the system. A version is
constituted of three numbers separated by a point: the version, the release
and sub-release numbers. |
(machine-type) | STklos procedure |
Returns a string identifying the kind of machine which is running the
program. The result string is of the form
`(os-name)-`(os-version)-`(processor-type) . |
Returns an approximation of processor time, in milliseconds, used so far by the
program. |
(sleep n) | STklos procedure |
Suspend the execution of the program for at ms milliseconds. Note that due
to system clock resolution, the pause may be a little bit longer. If a
signal arrives during the pause, the execution may be resumed.
|
(time expr1 expr2 ...) | STklos syntax |
Evaluates the expressions expr1 , expr2 , ... and returns the
result of the last expression. This form prints also the time spent
for this evaluation on the current error port. |
Returns the system process number of the current program (i.e. the
Unix pid) as an integer. |
4.18.4 Program Arguments Parsing
STklos provides a simple way to parse program arguments with the
|parse-arguments| special form. This form is generally used into
the |main| function in a Scheme script. See SRFI-22
(Running Scheme Scripts on Unix) on how to
use a |main| function in a Scheme program.
(parse-arguments <args> <clause1> <clause2> ...) | STklos procedure |
The parse-arguments special form is used to parse the
command line arguments of a Scheme script. The implementation of
this form internally uses the GNU C getopt function. As a
consequence parse-arguments accepts options which start with
the '-' (short option) or '--' characters (long option).
The first argument of parse-arguments is a list of the arguments
given to the program (comprising the program name in the CAR of this
list). Following arguments are clauses. Clauses are described later.
By default, parse-arguments permutes the contents of (a copy) of
the arguments as it scans, so that eventually all the non-options are
at the end. However, if the shell environment variable POSIXLY_CORRECT
is set, then option processing stops as soon as a non-option argument
is encountered.
A clause must follow the syntax:
<clause> ⇒ string | <list-clause>
<list clause> ⇒ (<option descr> <expr> ...) | (else <expr> ...)
<option descr> ⇒ (<option name> `(<keyword> value)*)
<option name> ⇒ string
<keyword> ⇒ :alternate | :arg | :help
|
A string clause is used to build the help associated to the command.
A list clause must follow the syntax describes an option. The <expr> s
associated to a list clauses are executed when the option is recognized.
The else clauses is executed when all parameters have been parsed.
The :alternate key permits to have an alternate name for an option
(generally a short or long name if the option name is a
short or long name). The :help is used to provide help about the
the option. The :arg is used when the option admit a parameter:
the symbol given after :arg will be bound to the value of the option
argument when the corresponding <expr> s will be executed.
In an else clause the symbol other-arguments is bound to the
list of the arguments which are not options.
The following example shows a rather complete usage of the
parse-arguments form
#!/usr/bin/env stklos-script
(define (main args)
(parse-arguments args
"Usage: foo [options] [parameter ...]"
"General options:"
(("verbose" :alternate "v" :help "be more verbose")
(format #t "Seen the verbose option~%"))
(("long" :help "a long option alone")
(format #t "Seen the long option~%"))
(("s" :help "a short option alone")
(format #t "Seen the short option~%"))
"File options:"
(("input" :alternate "f" :arg file
:help "use <file> as input")
(format #t "Seen the input option with ~S argument~%" file))
(("output" :alternate "o" :arg file
:help "use <file> as output")
(format #t "Seen the output option with ~S argument~%" file))
"Misc:"
(("help" :alternate "h"
:help "provides help for the command")
(arg-usage (current-error-port))
(exit 1))
(else
(format #t
"All options parsed. Remaining arguments are ~S~%"
other-arguments))))
|
The following program invocation
foo -vs --input in -o out arg1 arg2
|
produces the following output
Seen the verbose option
Seen the short option
Seen the input option with "in" argument
Seen the output option with "out" argument
All options parsed. Remaining arguments are ("arg1" "arg2")
|
Finally, the program invocation
produces the following output
Usage: foo `(options) `(parameter ...)
General options:
--verbose, -v be more verbose
--long a long option alone
-s a short option alone
File options:
--input=<file>, -f <file> use <file> as input
--output=<file>, -o <file> use <file> as output
Misc:
--help, -h provides help for the command
|
Note:
- Short option can be concatenated. That is,
is equivalent to the following program call
- Any argument following a '--' argument is no more considered as
an option, even if it starts with a '-' or '--'.
- Option with a parameter can be written in several ways. For instance
to set the output in the
bar file for the previous example can be expressed as
--output=bar
-o bar
-obar
|
(arg-usage port) | STklos procedure |
(arg-usage port as-sexpr)
This procedure is only bound inside a parse-arguments form.
It pretty prints the help associated to the clauses of the
parse-arguments form on the given port. If the argument
as-sexpr is passed and is not #f , the help strings are
printed on port as S-exprs. This is useful if the help
strings need to be manipulated by a program.
|
4.18.5 Misc. System Procedures
(system string) | STklos procedure |
Sends the given string to the system shell /bin/sh . The result of
system is the integer status code the shell returns. |
(exec str) | STklos procedure |
(exec-list str)
These procedures execute the command given in str . The command given
in str is passed to /bin/sh . Exec returns a strings which contains
all the characters that the command str has printed on it's standard
output, whereas exec-list returns a list of the lines which constitute
the output of str .
(exec "echo A; echo B") ⇒ "A\nB\n"
(exec-list "echo A; echo B") ⇒ ("A" "B")
|
|
(address-of obj) | R5RS procedure |
Returns the address of the object obj as an integer. |
(exit ret-code)
Exits the program with the specified integer return code. If ret-code
is omitted, the program terminates with a return code of 0.
If program has registered exit functions with register-exit-function! ,
they are called (in an order which is the reverse of their call order). |
(die message) | STklos procedure |
(die message status)
Die prints the given message on the current error port and exits
the program with the status value. If status is omitted, it
defaults to 1. |
(get-password) | STklos procedure |
This primitive permits to enter a password (character echoing
being turned off). The value returned by get-password is the entered
password as a string. |
(register-exit-function! proc) | STklos procedure |
This function registers proc as an exit function. This function will
be called when the program exits. When called, proc will be passed one
parmater which is the status given to the exit function (or 0 if the
programe terminates normally). The result of register-exit-function!
is undefined.
(let* ((tmp (temporary-file-name))
(out (open-output-file tmp)))
(register-exit-function! (lambda (n)
(when (zero? n)
(remove-file tmp))))
out)
|
|
4.19 Signals
4.20 Parameter Objects
STklos parameters correspond to the ones defined in SRFI-39
(Parameters objects).
See SRFI document for more information.
(make-parameter init) | STklos procedure |
(make-parameter init converter)
Returns a new parameter object which is bound in the global dynamic
environment to a cell containing the value returned by the call
(converter init) . If the conversion procedure converter is not
specified the identity function is used instead.
The parameter object is a procedure which accepts zero or one
argument. When it is called with no argument, the content of the
cell bound to this parameter object in the current dynamic
environment is returned. When it is called with one argument, the
content of the cell bound to this parameter object in the current
dynamic environment is set to the result of the call
(converter arg) , where arg is the argument passed to the
parameter object, and
an unspecified value is returned.
(define radix
(make-parameter 10))
(define write-shared
(make-parameter
#f
(lambda (x)
(if (boolean? x)
x
(error 'write-shared "bad boolean ~S" x)))))
(radix) ⇒ 10
(radix 2)
(radix) ⇒ 2
(write-shared 0) ⇒ error
(define prompt
(make-parameter
123
(lambda (x)
(if (string? x)
x
(with-output-to-string (lambda () (write x)))))))
(prompt) ⇒ "123"
(prompt ">")
(prompt) ⇒ ">"
|
|
(parameterize ((expr1 expr2) ...) <body>) | STklos syntax |
The expressions expr1 and expr2 are evaluated in an unspecified order.
The value of the expr1 expressions must be parameter objects.
For each expr1 expression and in an unspecified order, the local
dynamic environment is extended with a binding of the parameter object
expr1 to a new cell whose content is the result of the call
(converter val) , where val is the value of expr2 and converter
is the conversion procedure of the parameter object. The resulting
dynamic environment is then used for the evaluation of <body>
(which refers to the R5RS grammar nonterminal of that name).
The result(s) of the parameterize form are the result(s) of
the <body> .
(radix) ⇒ 2
(parameterize ((radix 16)) (radix)) ⇒ 16
(radix) ⇒ 2
(define (f n) (number->string n (radix)))
(f 10) ⇒ "1010"
(parameterize ((radix 8)) (f 10)) ⇒ "12"
(parameterize ((radix 8) (prompt (f 10))) (prompt)) ⇒ "1010"
|
|
(parameter? obj) | STklos procedure |
Returns #t if obj is a parameter object, otherwise returns #f . |
4.21 Misc
Returns the address of the object obj as an integer. |
(void arg1 ...)
Returns the special void object. If arguments are passed to void ,
they are evalued and simply ignored. |
(error str obj ...) | STklos procedure |
(error name str obj ...)
error is used to signal an error to the user. The second form
of error takes a symbol as first parameter; it is generally used for the
name of the procedure which raises the error.
Note: The specification string may follow the
tilde conventions
of format (see format); in this case this procedure builds an
error message according to the specification given in str . Otherwise,
this procedure is conform to the error procedure defined in
SRFI-23
(Error reporting mechanism) and str is printed with the display procedure,
whereas the obj s are printed with the write procedure.
Hereafter, are some calls of the error procedure using a formatted string
(error "bad integer ~A" "a")
-| bad integer a
(error 'vector-ref "bad integer ~S" "a")
-| vector-ref: bad integer "a"
(error 'foo "~A is not between ~A and ~A" "bar" 0 5)
-| foo: bar is not between 0 and 5
|
and some conform to SRFI-23 (Error reporting mechanism)
(error "bad integer" "a")
-| bad integer "a"
(error 'vector-ref "bad integer" "a")
-| vector-ref: bad integer "a"
(error "bar" "is not between" 0 "and" 5)
-| bar "is not between" 0 "and" 5
|
|
(signal-error cond str obj ...) | STklos procedure |
(signal-error cond name str obj ...)
This procedure is similar to error, except that the type of the error
can be passed as the first parameter. The type of the error must be a
condition which inherits from &error-message .
Note that (error arg ...) is equivalent to
(signal-error &error-message arg ...)
|
|
(require-extension <clause> ...) | STklos syntax |
The syntax of require-extension is as follows:
(require-extension <clause> ...)
|
A clause has the form:
(srfi <extension-argument> ...)
|
where <extension-argument> s may be any Scheme-values.
If an <extension-argument> is a nonnegative integer, the functionality
of the indicated SRFIs is made available in the context in
which the require-extension form appears. For instance,
(require-extension (srfi 1 2))
; Make the SRFI 1 and 2 available
|
This form is compatible with SRFI-55
(Require-extension). However, STklos
accepts also some symbolic names for requiring some extensions.
For instance,
(require-extension (srfi lists and-let*))
|
is equivalent to the previous require-extension . A list of available
symbols as <extension-argument> is given in chapter
SRFIs. |
(repl :in inport :out outport :err errport)
This procedure launches a new Read-Eval-Print-Loop. Calls to repl can be
embedded. The ports used for input/output as well as the error port can
be passed when repl is called. If not passed, they default to
current-input-port , current-output-port and current-error-port . |
(apropos obj) | STklos procedure |
(apropos obj module)
Apropos returns a list of symbols whose print name contains the
characters of obj as a substring . The given obj can be a string or
symbol. This function returns the list of matched symbols which can
be accessed from the given module (defaults to the current module if not
provided).
|
(help obj) | STklos procedure |
(help)
When called with an argument, help tries to give some help on the
given object, which could be a symbol, a procedure, a generic function
or a method. Whe called called without arguments, help enters a
read-help-print loop. The documentation for an object is searched in
the object itself or, if absent, in STklos documentation. Inserting
the documentation in an objet is very similar to Emacs docstrings: a
documentation string is defined among the code. Exemples of such
strings are given below
(define (foo n)
"If the function body starts with a string, it's a docstring"
(+ n 1))
(define-generic bar
:documentation "Generic function docsting for bar")
(define-method bar ((x <integer>))
"Probably less useful: as in functions, methods can have docstrings"
(- x 1))
|
|
(trace f-name ...) | STklos syntax |
Invoking trace with one or more function names causes the functions
named to be traced. Henceforth, whenever such a function is invoked,
information about the call and the returned values, if any, will be
printed on the current error port.
Calling trace with no argument returns the list of traced functions. |
(untrace f-name ...) | STklos syntax |
Invoking untrace with one or more function names causes the functions
named not to be traced anymore.
Calling untrace with no argument will untrace all the functions
currently traced. |
(pretty-print sexpr :key port width) | STklos procedure |
(pp sexpr :key port width)
This function tries to obtain a pretty-printed representation of sexpr .
The pretty-printed form is written on port with lines which are no
more long than width characters. If port is omitted if defaults to
the current error port. As a special convention, if port is #t ,
output goes to the current output port and if port is #f , the output
is returned as a string by pretty-print .
Note that pp is another name for pretty-print .
|
(uri-parse str) | STklos procedure |
Parses the string str as a RFC-2396 URI and return a keyed list with the
following components
scheme : the scheme used as a string (defaults to "file" )
user : the user information (generally expressed as
login:password )
host : the host as a string (defaults to "")
port : the port as an integer (0 if no port specified)
path : the path
query : the qury part of the URI as a string (defaults to the
empty string)
fragment : the fragment of the URI as a string (defaults to the
empty string)
(uri-parse "http://google.com")
⇒ (:scheme "http" :user "" :host "google.com" :port 80
:path "/" :query "" :fragment "")
(uri-parse "http://stklos.net:8080/a/file?x=1;y=2#end")
⇒ (:scheme "http" :user "" :host "stklos.net" :port 8080
:path "/a/file" :query "x=1;y=2" :fragment "end")
(uri-parse "http://foo:secret@stklos.net:2000/a/file")
⇒ (:scheme "http" :user "foo:secret" :host "stklos.net"
:port 2000 :path "/a/file" :query "" :fragment "")
(uri-parse "/a/file")
⇒ (:scheme "file" :user "" :host "" :port 0 :path "/a/file"
:query "" :fragment "")
(uri-parse "")
⇒ (:scheme "file" :user "" :host "" :port 0 :path ""
:query "" :fragment "")
|
|
(string->html str) | STklos procedure |
This primitive is a convenience function; it returns a string where
the HTML special chars are properly translated. It can easily written
in Scheme, but this version is fast.
(string->html "Just a <test>")
⇒ "Just a <test>"
|
|
(md5sum obj) | STklos procedure |
Return a string contening the md5 dum of obj . The given parameter can
be a string or an open input port. |
(md5sum-file str) | STklos procedure |
Return a string contening the md5 dum of the file whose name is str . |
(base64-encode in) | STklos procedure |
(base64-encode in out)
Encode in Base64 the characters from input port in to the output port
out . If out is not specified, it defaults to the current output port. |
(base64-decode in) | STklos procedure |
(base64-decode in out)
Decode the Base64 characters from input port in to the output port
out . If out is not specified, it defaults to the current output port. |
(base64-encode-string str) | STklos procedure |
Return a string contening the contents of str converted to Base64
encoded format |
(base64-encode-string str) | STklos procedure |
Decode the contents of str expressed in Base64. |
1: Under Unix, you can simply connect to
a listening socket with the telnet command. With the given
example, this can be achieved by typing the following command in a
window shell:
2: Port 13 is generally used for testing:
making a connection to it permits to know the distant system's idea
of the time of day.
|