[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7. Extensions

7.1 Multiple values  
7.2 Special named constants  
7.3 Keywords  
7.4 Procedures  
7.5 Quantities  
7.6 Logical Number Operations  
7.7 Strings  
7.8 Uniform vectors  
7.9 File System Interface  
7.10 Ports  
7.11 Formatted Output (Common-Lisp-style)  
7.12 Signalling and recovering from exceptions  
7.13 Locations  
7.14 Eval and Environments  
7.15 Debugging  
7.16 Threads  
7.17 Processes  
7.18 Miscellaneous  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.1 Multiple values

The multiple-value feature was added in R5RS.

Function: values object ...
Delivers all of its arguments to its continuation.

Function: call-with-values thunk receiver
Call its thunk argument with a continuation that, when passed some values, calls the receiver procedure with those values as arguments.

Syntax: let-values ((formals expression) ...) body
Each formals should be a formal arguments list as for a lambda, cf section 4.1.4 of the R5RS.

The expressions are evaluated in the current environment, the variables of the formals are bound to fresh locations, the return values of the expressions are stored in the variables, the body is evaluated in the extended environment, and the values of the last expression of body are returned. The body is a "tail body", cf section 3.5 of the R5RS.

The matching of each formals to values is as for the matching of formals to arguments in a ambda expression, and it is an error for an expression to return a number of values that does not match its corresponding formals.
 
(let-values ((a b . c) (values 1 2 3 4)))
  (list a b c))            --> (1 2 (3 4)) 

(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let-values (((a b) (values x y))
               ((x y) (values a b)))
    (list a b x y)))       --> (x y a b)

Syntax: let*-values ((formals expression) ...) body

Each formals should be a formal arguments list as for a lambda expression, cf section 4.1.4 of the R5RS.

let*-values is similar to let-values, but the bindings are performed sequentially from left to right, and the region of a binding indicated by (formals expression) is that part of the let*-values expression to the right of the binding. Thus the second binding is done in an environment in which the first binding is visible, and so on.
 
(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let*-values (((a b) (values x y))
                ((x y) (values a b)))
    (list a b x y)))       --> (x y x y)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.2 Special named constants

Constant: #!optional
Special self-evaluating literal used in lambda parameter lists before optional parameters.

Constant: #!rest
Special self-evaluating literal used in lambda parameter lists before the rest parameter.

Constant: #!key
Special self-evaluating literal used in lambda parameter lists before keyword parameters.

Constant: #!eof
The end-of-file object.

Note that if the Scheme reader sees this literal at top-level, it is returned literally. This is indistinguishable from coming to the end of the input file. If you do not want to end reading, but want the actual value of #!eof, you should quote it.

Constant: #!void
The void value. Same as (values). If this is the value of an expression in a read-eval-print loop, nothing is printed.

Constant: #!null
The Java null value. This is not really a Scheme value, but is useful when interfacing to low-level Java code.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.3 Keywords

Keywords are similar to symbols. The main difference is that keywords are self-evaluating and therefore do not need to be quoted in expressions. They are used mainly for specifying keyword arguments.

 
keyword = identifier:

An alternative syntax, with the colon first, is supported for compatibility with Common Lisp and some other Scheme implementations:

 
keyword = :identifier

Putting the colon first has exactly the same effect as putting it last; putting is last is recommended, and is how keywords are printed.

A keyword is a single token; therefore no whitespace is allowed between the identifier and the colon (which is not considered part of the name of the keyword).

Function: keyword? obj
Return #t if obj is a keyword, and otherwise returns #f.

Function: keyword->string keyword
Returns the name of keyword as a string. The name does not include the final #\:.

Function: string->keyword string
Returns the keyword whose name is string. (The string does not include a final #\:.)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4 Procedures

Function: apply proc [arg1 ...] args
Args must be a sequence (list, vector, or string) or a primitive Java array. (This is an extension over standard Scheme, which requires that args be a list.) Calls the proc (which must be a procedure), using as arguments the arg1... values plus all the elements of args.

Syntax: constant-fold proc arg1 ...
Same as (proc arg1 ...), unless proc and all the following arguments are compile-time constants. (That is: They are either constant, or symbols that have a global binding and no lexical binding.) In that case, proc is applied to the arguments at compile-time, and the result replaces the constant-fold form. If the application raises an exception, a compile-time error is reported. For example:
 
(constant-fold vector 'a 'b 'c)
is equivalent to (quote #(a b c)), assuming vector has not been re-bound.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4.1 Procedure properties

You can associate arbitrary properties with any procedure. Each property is a (key, value)-pair. Usually the key is a symbol, but it can be any object.

The system uses certain internal properties: 'name refers to the name used when a procedure is printed; 'emacs-interactive is used to implement Emacs interactive specification; 'setter will be (not yet implemented) used to associate a setter prcedure.

Function: procedure-property proc key [default]
Get the property value corresponding to the given key. If proc has no property with the given key, return default (which defaults to #f) instead.

Function: set-procedure-property! proc key value
Associate the given value with the key property of proc.

To change the print name of the standard + procedure (probably not a good idea!), you could do:
 
(set-procedure-property! + 'name 'PLUS)
Note this only changes the name property used for printing:
 
+ => #<procedure PLUS>
(+ 2 3) => 5
(PLUS 3 4) => ERROR


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4.2 Generic (dynamically overloaded) procedures

A generic procedure is a collection of method procedures. (A "method procedure" is not the same as a Java method, but the terms are related.) You can call a generic procedure, which selects the "closest match" among the component method procedures: I.e. the most specific method procedure that is applicable give the actual arguments.

Function: make-procedure [keyword: value]... method...
Create a generic procedure given the specific methods. You can also specify property values for the result.

The keywords specify how the arguments are used. A method: keyword is optional and specifies that the following argument is a method. A name: keyword specifies the name of the resulting procedure, when used for printing. Unrecognized keywords are used to set the procedure properties of the result.
 
(define plus10 (make-procedure foo: 33 name: 'Plus10
                            method: (lambda (x y) (+ x y 10))
                            method: (lambda () 10)))


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4.3 Extended Formal Arguments List

The formal arguments list of a lambda expression has two extendsions over standard Scheme: Kawa borrows the extended formal argument list of DSSSL, and Kawa allows you to declare the type of the parameter.

 
lambda-expression = (lambda formals [rtype] body)
where
 
formals = (formal-arguments) | rest-arg
You can of course also use the extended format in a define:
 
(define (name formal-arguments) [rtype] body)

 
formal-arguments =
    req-opt-args (rest-key-args | . rest-arg)
 
req-opt-args = req-arg ... [#!optional opt-arg ...]
rest-key-args = [#!rest rest-arg] [#key key-arg ...]
req-arg = variable [:: type] | (variable [[::] type] )
opt-arg = arg-with-default
key-arg =  arg-with-default
arg-with-default = variable [:: type]
    | ( variable [:: type [initializer] | initializer [[::] type]] )
rest-arg = variable

When the procedure is applied to a list of actual arguments, the formal and actual arguments are processed from left to right as follows:

If a type is specified, the corresponding actual argument (or the initializer default value) is coerced to the specified type. In the function body, the parameter has the specified type.

If rtype (the first form of the function body) is an unbound identifier of the form <TYPE> (that is the first character is `<' and the last is `>'), then tha specifies the functions return type. It is syntactic sugar for (as <TYPE> (begin BODY)).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.5 Quantities

As a super-class of numbers, Kawa also provides quantities. A quantity is a product of a unit and a pure number. The number part can be an arbitrary complex number. The unit is a product of integer powers of base units, such as meter or second.

Kawa quantities are a generalization of the quantities in DSSSL, which only has length-derived quantities.

The precise syntax of quantity literals may change, but some examples are 10pt (10 points), 5s (5 seconds), and 4cm^2 (4 square centimeters).

Function: quantity? object
True iff object is a quantity. Note that all numbers are quantities, but not the other way round. Currently, there are no quantities that re not numbers. To distinguish a plain unit-less number from a quantity, you can use complex?.

Function: quantity->number q
Returns the pure number part of the quantity q, relative to primitive (base) units. If q is a number, returns q. If q is a unit, yields the magitude of q relative to base units.

Function: quantity->unit q
Returns the unit of the quantity q. If q is a number, returns the empty unit.

Function: make-quantity x unit
Returns the product of x (a pure number) and unit. You can specify a string instead of unit, such as "cm" or "s" (seconds).

Syntax: define-base-unit unit-name dimension
Define unit-name as a base (primitive) unit, which is used to measure along the specified dimension.
 
(define-base-unit dollar "Money")

Syntax: define-unit unit-name expression
Define unit-name as a unit (that can be used in literals) equal to the quantity expression.
 
(define-unit cent 0.01dollar)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.6 Logical Number Operations

These functions operate on the 2's complement binary representation of an exact integer.

Function: logand i ...
Returns the bit-wise logical "and" of the arguments. If no argument is given, the result is -1.

Function: logior i ...
Returns the bit-wise logical "(inclusive) or" of the arguments. If no argument is given, the result is 0.

Function: logxor i ...
Returns the bit-wise logical "exclusive or" of the arguments. If no argument is given, the result is 0.

Function: lognot i
Returns the bit-wise logical inverse of the argument.

Function: logop op x y
Perform one of the 16 bitwise operations of x and y, depending on op.

Function: bittest i j
Returns true if the arguments have any bits in common. Same as (not (zero? (logand i j))), but is more efficient.

Function: logbit? i pos
Returns #t iff the bit numbered pos in i is one.

Function: arithmetic-shift i j
Shifts i by j. It is a "left" shift if j>0, and a "right" shift if j<0.

The result is equal to (floor (* i (expt 2 j))).

Function: ash i j
Alias for arithmetic-shift.

Function: logcount i
Count the number of 1-bits in i, if it is non-negative. If i is negative, count number of 0-bits.

Function: integer-length i
Return number of bits needed to represent i in an unsigned field. Regardless of the sign of i, return one less than the number of bits needed for a field that can represent i as a two's complement integer.

Function: bit-extract n start end
Return the integer formed from the (unsigned) bit-field starting at start and ending just before end. Same as (arithmetic-shift (bitand n (bitnot (arithmetic-shift -1 end))) (- start)).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.7 Strings

Function: string-upcase str
Return a new string where the letters in str are replaced by their upper-case equivalents.

Function: string-downcase str
Return a new string where the letters in str are replaced by their lower-case equivalents.

Function: string-capitalize str
Return a new string where the letters in str that start a new word are replaced by their title-case equivalents, while non-initial letters are replaced by their lower-case equivalents.

Function: string-upcase! str
Destructively modify str, replacing the letters by their upper-case equivalents.

Function: string-downcase! str
Destructively modify str, replacing the letters by their upper-lower equivalents.

Function: string-capitalize! str
Destructively modify str, such that the letters that start a new word are replaced by their title-case equivalents, while non-initial letters are replaced by their lower-case equivalents.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.8 Uniform vectors

Uniform vectors are vectors whose elements are of the same numeric type. The are defined by SRFI-4. However, the type names (such as <s8vector>) are a Kawa extension.

Variable: <s8vector>
The type of uniform vectors where each element can contain a signed 8-bit integer. Represented using an array of <byte>.

Variable: <u8vector>
The type of uniform vectors where each element can contain an unsigned 8-bit integer. Represented using an array of <byte>, but each element is treated as if unsigned.

Variable: <s16vector>
The type of uniform vectors where each element can contain a signed 16-bit integer. Represented using an array of <short>.

Variable: <u16vector>
The type of uniform vectors where each element can contain an unsigned 16-bit integer. Represented using an array of <short>, but each element is treated as if unsigned.

Variable: <s32vector>
The type of uniform vectors where each element can contain a signed 32-bit integer. Represented using an array of <int>.

Variable: <u32vector>
The type of uniform vectors where each element can contain an unsigned 32-bit integer. Represented using an array of <int>, but each element is treated as if unsigned.

Variable: <s64vector>
The type of uniform vectors where each element can contain a signed 64-bit integer. Represented using an array of <long>.

Variable: <u64vector>
The type of uniform vectors where each element can contain an unsigned 64-bit integer. Represented using an array of <long>, but each element is treated as if unsigned.

Variable: <f32vector>
The type of uniform vectors where each element can contain a 32-bit floating-point real. Represented using an array of <float>.

Variable: <f64vector>
The type of uniform vectors where each element can contain a 64-bit floating-point real. Represented using an array of <double>.

Function: s8vector? value
Function: u8vector? value
Function: s16vector? value
Function: u16vector? value
Function: s32vector? value
Function: u32vector? value
Function: s64vector? value
Function: u64vector? value
Function: f32vector? value
Function: f64vector? value
Return true iff value is a uniform vector of the specified type.

Function: make-s8vector n [value]
Function: make-u8vector n [value]
Function: make-s16vector n [value]
Function: make-u16vector n [value]
Function: make-s32vector n [value]
Function: make-u32vector n [value]
Function: make-s64vector n [value]
Function: make-u64vector n [value]
Function: make-f32vector n [value]
Function: make-f64vector n [value]
Create a new uniform vector of the specified type, having room for n elements. Initialize each element to value if it is specified; zero otherwise.

Function: s8vector value ...
Function: u8vector value ...
Function: s16vector value ..
Function: u16vector value ...
Function: s32vector value ...
Function: u32vector value ...
Function: s64vector value ...
Function: u64vector value ...
Function: f32vector value ...
Function: f64vector value ...
Create a new uniform vector of the specified type, whose length is the number of values specified, and initialize it using those values.

Function: s8vector-length v
Function: u8vector-length v
Function: s16vector-length v
Function: u16vector-length v
Function: s32vector-length v
Function: u32vector-length v
Function: s64vector-length v
Function: u64vector-length v
Function: f32vector-length v
Function: f64vector-length v
Return the length (in number of elements) of the uniform vector v.

Function: s8vector-ref v i
Function: u8vector-ref v i
Function: s16vector-ref v i
Function: u16vector-ref v i
Function: s32vector-ref v i
Function: u32vector-ref v i
Function: s64vector-ref v i
Function: u64vector-ref v i
Function: f32vector-ref v i
Function: f64vector-ref v i
Return the element at index i of the uniform vector v.

Function: s8vector-set! v i x
Function: u8vector-set! v i x
Function: s16vector-set! v i x
Function: u16vector-set! v i x
Function: s32vector-set! v i x
Function: u32vector-set! v i x
Function: s64vector-set! v i x
Function: u64vector-set! v i x
Function: f32vector-set! v i x
Function: f64vector-set! v i x
Set the element at index i of uniform vector v to the value x, which must be a number coercible to the appropriate type.

Function: s8vector->list v
Function: u8vector->list v
Function: s16vector->list v
Function: u16vector->list v
Function: s32vector->list v
Function: u32vector->list v
Function: s64vector->list v
Function: u64vector->list v
Function: f32vector->list v
Function: f64vector->list v
Convert the uniform vetor v to a list containing the elments of v.

Function: list->s8vector l
Function: list->u8vector l
Function: list->s16vector l
Function: list->u16vector l
Function: list->s32vector l
Function: list->u32vector l
Function: list->s64vector l
Function: list->u64vector l
Function: list->f32vector l
Function: list->f64vector l
Create a uniform vector of the appropriate type, initializing it with the elements of the list l. The elements of l must be numbers coercible the new vector's element type.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.9 File System Interface

Function: file-exists? filename
Returns true iff the file named filename actually exists.

Function: file-directory? filename
Returns true iff the file named filename actually exists and is a directory.

Function: file-readable? filename
Returns true iff the file named filename actually exists and can be read from.

Function: file-writable? filename
Returns true iff the file named filename actually exists and can be writen to. (Undefined if the filename does not exist, but the file can be created in the directory.)

Function: delete-file filename
Delete the file named filename.

Function: rename-file oldname newname
Renames the file named oldname to newname.

Function: copy-file oldname newname-from path-to
Copy the file named oldname to newname. The return value is unspecified.

Function: create-directory dirname
Create a new directory named dirname. Unspecified what happens on error (such as exiting file with the same name). (Currently returns #f on error, but may change to be more compatible with scsh.)

Function: system-tmpdir
Return the name of the default directory for temporary files.

Function: make-temporary-file [format]
Return a file with a name that does not match any existing file. Use format (which defaults to "kawa~d.tmp") to generate a unique filename in (system-tmpdir). The current implementation is not safe from race conditions; this will be fixed in a future release (using Java2 features).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.10 Ports

Function: current-error-port
Return the port to which errors and warnings should be sent (the standard error in Unix and C terminology).

Function: read-line [port [handle-newline]]
Reads a line of input from port. The handle-newline parameter determines what is done with terminating end-of-line delimiter. The default, 'trim, ignores the delimiter; 'peek leaves the delimiter in the input stream; 'concat appends the delimiter to the returned value; and 'split returns the delimiter as a second value. You can use the last three options to tell if the string was terminated by end-or-line or by end-of-file.

Function: open-input-string string
Takes a string and returns an input port that delivers characters from the string. The port can be closed by close-input-port, though its storage will be reclaimed by the garbage collector if it becomes inaccessible.

 
(define p
  (open-input-string "(a . (b c . ())) 34"))

(input-port? p)                 -->  #t
(read p)                        -->  (a b c)
(read p)                        -->  34
(eof-object? (peek-char p))     -->  #t

Function: open-output-string
Returns an output port that will accumulate characters for retrieval by get-output-string. The port can be closed by the procedure close-output-port, though its storage will be reclaimed by the garbage collector if it becomes inaccessible.
 
(let ((q (open-output-string))
  (x '(a b c)))
    (write (car x) q)
    (write (cdr x) q)
    (get-output-string q))        -->  "a(b c)"

Function: get-output-string output-port
Given an output port created by open-output-string, returns a string consisting of the characters that have been output to the port so far.

Function: call-with-input-string string proc
Create an input port that gets its data from string, call proc with that port as its one argument, and return the result from the call of proc

Function: call-with-output-string proc
Create an output port that writes its data to a string, and call proc with that port as its one argument. Return a string consisting of the data written to the port.

Function: force-output [port]
Forces any pending output on port to be delivered to the output device and returns an unspecified value. If the port argument is omitted it defaults to the value returned by (current-output-port).

An interactive input port has a prompt procedure associated with it. The prompt procedure is called before a new line is read. It is passed the port as an argument, and returns a string, which gets printed as a prompt.

Function: input-port-prompter port
Get the prompt procedure associated with port.

Function: set-input-port-prompter! port prompter
Set the prompt procedure associated with port to prompter, which must be a one-argument procedure taking an input port, and returning a string.

Function: default-prompter port
The default prompt procedure. It returns "#|kawa:L|# ", where L is the current line number of port. When reading a continuation line, the result is "#|C---:L|# ", where C is the character returned by (input-port-read-state port). The prompt has the form of a comment to make it easier to cut-and-paste.

Function: port-column input-port
Function: port-line input-port
Return the current column number or line number of input-port, using the current input port if none is specified. If the number is unknown, the result is #f. Otherwise, the result is a 0-origin integer - i.e. the first character of the first line is line 0, column 0. (However, when you display a file position, for example in an error message, we recommend you add 1 to get 1-origin integers. This is because lines and column numbers traditionally start with 1, and that is what non-programmers will find most natural.)

Function: set-port-line! port line
Set (0-origin) line number of the current line of port to num.

Function: input-port-line-number port
Get the line number of the current line of port, which must be a (non-binary) input port. The initial line is line 1. Deprecated; replaced by (+ 1 (port-line port)).

Function: set-input-port-line-number! port num
Set line number of the current line of port to num. Deprecated; replaced by (set-port-line! port (- num 1)).

Function: input-port-column-number port
Get the column number of the current line of port, which must be a (non-binary) input port. The initial column is column 1. Deprecated; replaced by (+ 1 (port-column port)).

Function: input-port-read-state port
Returns a character indicating the current read state of the port. Returns #\Return if not current doing a read, #\" if reading a string; #\| if reading a comment; #\( if inside a list; and #\Space when otherwise in a read. The result is intended for use by prompt prcedures, and is not necessarily correct except when reading a new-line.

Variable: symbol-read-case
A symbol that controls how read handles letters when reading a symbol. If the first letter is `U', then letters in symbols are upper-cased. If the first letter is `D' or `L', then letters in symbols are down-cased. If the first letter is `I', then the case of letters in symbols is inverted. Otherwise (the default), the letter is not changed. (Letters following a `\' are always unchanged.)

Variable: port-char-encoding
Controls how bytes in external files are converted to/from internal Unicode characters. Can be either a symbol or a boolean. If port-char-encoding is #f, the file is assumed to be a binary file and no conversion is done. Otherwise, the file is a text file. The default is #t, which uses a locale-dependent conversion. If port-char-encoding is a symbol, it must be the name of a character encoding known to Java. For all text files (that is if port-char-encoding is not #f), on input a #\Return character or a #\Return followed by #\Newline are converted into plain #\Newline.

This variable is checked when the file is opened; not when actually reading or writing. Here is an example of how you can safely change the encoding temporarily:
 
(define (open-binary-input-file name)
  (fluid-let ((port-char-encoding #f)) (open-input-file name)))


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11 Formatted Output (Common-Lisp-style)

Function: format destination fmt . arguments
An almost complete implementation of Common LISP format description according to the CL reference book Common LISP from Guy L. Steele, Digital Press. Backward compatible to most of the available Scheme format implementations.

Returns #t, #f or a string; has side effect of printing according to fmt. If destination is #t, the output is to the current output port and #t is returned. If destination is #f, a formatted string is returned as the result of the call. If destination is a string, destination is regarded as the format string; fmt is then the first argument and the output is returned as a string. If destination is a number, the output is to the current error port if available by the implementation. Otherwise destination must be an output port and #t is returned.

fmt must be a string or an instance of gnu.text.MessageFormat or java.text.MessageFormat. If fmt is a string, it is parsed as if by parse-format.

Function: parse-format format-string
Parses format-string, which is a string of the form of a Common LISP format description. Returns an instance of gnu.text.ReportFormat, which can be passed to the format function.

A format string passed to format or parse-format consists of format directives (that start with `~'), and regular characters (that are written directly to the destination). Most of the Common Lisp (and Slib) format directives are implemented. Neither justification, nor pretty-printing are supported yet.

Plus of course, we need documentation for format!


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.1 Implemented CL Format Control Directives

Documentation syntax: Uppercase characters represent the corresponding control directive characters. Lowercase characters represent control directive parameter descriptions.

~A
Any (print as display does).
~@A
left pad.
~mincol,colinc,minpad,padcharA
full padding.
~S
S-expression (print as write does).
~@S
left pad.
~mincol,colinc,minpad,padcharS
full padding.

~C
Character.
~@C
prints a character as the reader can understand it (i.e. #\ prefixing).
~:C
prints a character as emacs does (eg. ^C for ASCII 03).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.2 Formatting Integers

~D
Decimal.
~@D
print number sign always.
~:D
print comma separated.
~mincol,padchar,commachar,commawidthD
padding.
~X
Hexadecimal.
~@X
print number sign always.
~:X
print comma separated.
~mincol,padchar,commachar,commawidthX
padding.
~O
Octal.
~@O
print number sign always.
~:O
print comma separated.
~mincol,padchar,commachar,commawidthO
padding.
~B
Binary.
~@B
print number sign always.
~:B
print comma separated.
~mincol,padchar,commachar,commawidthB
padding.
~nR
Radix n.
~n,mincol,padchar,commachar,commawidthR
padding.
~@R
print a number as a Roman numeral.
~:@R
print a number as an "old fashioned" Roman numeral.
~:R
print a number as an ordinal English number.
~:@R
print a number as a cardinal English number.
~P
Plural.
~@P
prints y and ies.
~:P
as ~P but jumps 1 argument backward.
~:@P
as ~@P but jumps 1 argument backward.

commawidth is the number of characters between two comma characters.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.3 Formatting floating-point (real) numbers

~F
Fixed-format floating-point (prints a flonum like mmm.nnn).
~width,digits,scale,overflowchar,padcharF
~@F
If the number is positive a plus sign is printed.

~E
Exponential floating-point (prints a flonum like mmm.nnnEee)
~width,digits,exponentdigits,scale,overflowchar,padchar,exponentcharE
~@E
If the number is positive a plus sign is printed.

~G
General floating-point (prints a flonum either fixed or exponential).
~width,digits,exponentdigits,scale,overflowchar,padchar,exponentcharG
~@G
If the number is positive a plus sign is printed.
A slight difference from Common Lisp: If the number is printed in fixed form and the fraction is zero, then a zero digit is printed for the fraction, if allowed by the width and digits is unspecified.

~$
Dollars floating-point (prints a flonum in fixed with signs separated).
~digits,scale,width,padchar$
~@$
If the number is positive a plus sign is printed.
~:@$
A sign is always printed and appears before the padding.
~:$
The sign appears before the padding.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.4 Miscellaneous formatting operators

~%
Newline.
~n%
print n newlines.
~&
print newline if not at the beginning of the output line.
~n&
prints ~& and then n-1 newlines.
~|
Page Separator.
~n|
print n page separators.
~~
Tilde.
~n~
print n tildes.
~<newline>
Continuation Line.
~:<newline>
newline is ignored, white space left.
~@<newline>
newline is left, white space ignored.
~T
Tabulation.
~@T
relative tabulation.
~colnum,colincT
full tabulation.
~?
Indirection (expects indirect arguments as a list).
~@?
extracts indirect arguments from format arguments.
~(str~)
Case conversion (converts by string-downcase).
~:(str~)
converts by string-capitalize.
~@(str~)
converts by string-capitalize-first.
~:@(str~)
converts by string-upcase.
~*
Argument Jumping (jumps 1 argument forward).
~n*
jumps n arguments forward.
~:*
jumps 1 argument backward.
~n:*
jumps n arguments backward.
~@*
jumps to the 0th argument.
~n@*
jumps to the nth argument (beginning from 0)
~[str0~;str1~;...~;strn~]
Conditional Expression (numerical clause conditional).
~n[
take argument from n.
~@[
true test conditional.
~:[
if-else-then conditional.
~;
clause separator.
~:;
default clause follows.
~{str~}
Iteration (args come from the next argument (a list)).
~n{
at most n iterations.
~:{
args from next arg (a list of lists).
~@{
args from the rest of arguments.
~:@{
args from the rest args (lists).
~^
Up and out.
~n^
aborts if n = 0
~n,m^
aborts if n = m
~n,m,k^
aborts if n <= m <= k


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.5 Not Implemented CL Format Control Directives

~:A
print #f as an empty list (see below).
~:S
print #f as an empty list (see below).
~<~>
Justification.
~:^


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.11.5.1 Extended, Replaced and Additional Control Directives

These are not necesasrily implemented in Kawa!

~I
print a R4RS complex number as ~F~@Fi with passed parameters for ~F.
~Y
Pretty print formatting of an argument for scheme code lists.
~K
Same as ~?.
~!
Flushes the output if format destination is a port.
~_
Print a #\space character
~n_
print n #\space characters.

~nC
Takes n as an integer representation for a character. No arguments are consumed. n is converted to a character by integer->char. n must be a positive decimal number.
~:S
Print out readproof. Prints out internal objects represented as #<...> as strings "#<...>" so that the format output can always be processed by read.
~:A
Print out readproof. Prints out internal objects represented as #<...> as strings "#<...>" so that the format output can always be processed by read.
~F, ~E, ~G, ~$
may also print number strings, i.e. passing a number as a string and format it accordingly.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.12 Signalling and recovering from exceptions

Function: catch key thunk handler
Invoke thunk in the dynamic context of handler for exceptions matching key. If thunk throws to the symbol key, then handler is invoked this way:

 
(handler key args ...)

key may be a symbol. The thunk takes no arguments. If thunk returns normally, that is the return value of catch.

Handler is invoked outside the scope of its own catch. If handler again throws to the same key, a new handler from further up the call chain is invoked.

If the key is #t, then a throw to any symbol will match this call to catch.

Function: throw key &rest args ...
Invoke the catch form matching key, passing args to the handler.

If the key is a symbol it will match catches of the same symbol or of #t.

If there is no handler at all, an error is signaled.

procedure: error message args ...
Raise an error with key misc-error and a message constructed by displaying msg and writing args. This normally prints a stack trace, and brings you back to the top level, or exits kawa if you are not running interactively.

Function: primitive-throw exception
Throws the exception, which must be an instance of a sub-class of <java.lang.Throwable>.

Syntax: try-finally body handler
Evaluate body, and return its result. However, before it returns, evaluate handler. Even if body returns abnormally (by throwing an exception), handler is evaluated.

(This is implemented just like Java's try-finally.)

Syntax: try-catch body handler ...
Evaluate body, in the context of the given handler specifications. Each handler has the form:
 
var type exp ...
If an exception is thrown in body, the first handler is selected such that the thrown exception is an instance of the handler's type. If no handler is selected, the exception is propagated through the dynamic execution context until a matching handler is found. (If no matching handler is found, then an error message is printed, and the computation terminated.)

Once a handler is selected, the var is bound to the thrown exception, and the exp in the handler are executed. The result of the try-catch is the result of body if no exception is thrown, or the value of the last exp in the selected handler if an exception is thrown.

(This is implemented just like Java's try-catch.)

Function: dynamic-wind in-guard thunk out-guard
All three arguments must be 0-argument procedures. First calls in-guard, then thunk, then out-guard. The result of the expression is that of thunk. If thunk is exited abnormally (by throwing an exception or invoking a continuation), out-guard is called.

If the continuation of the dynamic-wind is re-entered (which is not yet possible in Kawa), the in-guard is called again.

This function was added in R5RS.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.13 Locations

A location is a place where a value can be stored. An lvalue is an expression that refers to a location. (The name "lvalue" refers to the fact that the left operand of set! is an lvalue.) The only kind of lvalue in standard Scheme is a variable. Kawa also allows computed lvalues. These are procedure calls used in "lvalue context", such as the left operand of set!.

You can only use procedures that have an associated setter. In that case, (set! (f arg ...) value) is equivalent to ((setter f) value arg ...) (It is possible the definition will change to ((setter f) arg ... value) if Guile goes for that.) Currently, only a few procedures have associated setters, and only builtin procedures written in Java can have setters.

For example:
 
(set! (car x) 10)
is equivalent to:
 
(set-car! x 10)

Kawa also gives you access to locations as first-class values:

Syntax: location lvalue
Returns a location object for the given lvalue. You can get its value (by applying it, as if it were a procedure), and you can set its value (by using set! on the application). The lvalue can be a local or global variable, or a procedure call using a procedure that has a setter.
 
(define x 100)
(define lx (location x))
(set! (lx) (cons 1 2)) ;; set x to (1 . 2)
(lx)  ;; returns (1 . 2)
(define lc (location (car x)))
(set! (lc) (+ 10 (lc)))
;; x is now (11 . 2)

Syntax: define-alias variable lvalue
Define variable as an alias for lvalue. In other words, makes it so that (location variable) is equivalent to (location lvalue). This works both top-level and inside a function.

Some people might find it helpful to think of a location as a settable thunk. Others may find it useful to think of the location syntax as similar to the C `&' operator; for the `*' indirection operator, Kawa uses procedure application.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.14 Eval and Environments

Function: eval expression [environment]
eval evaluates expression in the environment indicated by environment.

The default for environment is the result of (interaction-environment).

Function: null-environment
This procedure returns an environment that contains no variable bindings, but contains (syntactic) bindings for all the syntactic keywords.

The effect of assigning to a variable in this environment (such as let) is undefined.

Function: scheme-report-environment version
The version must be an exact non-negative inetger corresponding to a version of one of the Revisedversion Reports on Scheme. The procedure returns an environment that contains exactly the set of bindings specified in the corresponding report.

This implementation supports version that is 4 or 5.

The effect of assigning to a variable in this environment (such as car) is undefined.

Function: interaction-environment
This procedure return an environment that contains implementation-defined bindings, as well as top-level user bindings.

Function: environment-bound? environment symbol
Return true #t if there is a binding for symbol in environment; otherwise returns #f.

Syntax: fluid-let ((variable init) ...) body ...
Evaluate the init expressions. Then modify the dynamic bindings for the variables to the values of the init expressions, and evaluate the body expressions. Return the result of the last expression in body. Before returning, restore the original bindings. The temporary bindings are only visible in the current thread, and its descendent threads.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.15 Debugging

Syntax: trace procedure
Cause procedure to be "traced", that is debugging output will be written to the standard error port every time procedure is called, with the parameters and return value.

Syntax: untrace procedure
Turn off tracing (debugging output) of procedure.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.16 Threads

There is a very preliminary interface to create parallel threads. The interface is similar to the standard delay/force, where a thread is basically the same as a promise, except that evaluation may be in parallel.

So far, little or no effort has been made into making Kawa thread-safe. There are no per-thread bindings, and the current input and output parts are global. That needs to change.

Syntax: future expression
Creates a new thread that evaluates expression.

Function: force thread
The standard force function has generalized to also work on threads. If waits for the thread's expression to finish executing, and returns the result.

Function: sleep time
Suspends the current thread for the specified time. The time can be either a pure number (in secords), or a quantity whose unit is a time unit (such as 10s).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.17 Processes

Function: make-process command envp
Creates a <java.lang.Process> object, using the specified command and envp. The command is converted to an array of Java strings (that is an object that has type <java.lang.String[]>. It can be a Scheme vector or list (whose elements should be Java strings or Scheme strings); a Java array of Java strings; or a Scheme string. In the latter case, the command is converted using command-parse. The envp is process environment; it should be either a Java array of Java strings, or the special #!null value.

Function: system command
Runs the specified command, and waits for it to finish. Returns the return code from the command. The return code is an integer, where 0 conventionally means successful completion. The command can be any of the types handled by make-process.

Variable: command-parse
The value of this variable should be a one-argument procedure. It is used to convert a command from a Scheme string to a Java array of the constituent "words". The default binding, on Unix-like systems, returns a new command to invoke "/bin/sh" "-c" concatenated with the command string; on non-Unix-systems, it is bound to tokenize-string-to-string-array.

Function: tokenize-string-to-string-array command
Uses a java.util.StringTokenizer to parse the command string into an array of words. This splits the command using spaces to delimit words; there is no special processing for quotes or other special characters. (This is the same as what java.lang.Runtime.exec(String) does.)


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.18 Miscellaneous

Function: scheme-implementation-version
Returns the Kawa version number as a string.

Function: gentemp
Returns a new (interned) symbol each time it is called. The symbol names are implementation-dependent.

Syntax: defmacro name lambda-list form ...
Defines an old-style macro a la Common Lisp, and installs (lambda lambda-list form ...) as the expansion function for name. When the translator sees an application of name, the expansion function is called with the rest of the application as the actual arguments. The resulting object must be a Scheme source form that is futher processed (it may be repeatedly macro-expanded).

If you define a macro with defmacro, you (currently) cannot use the macro in the same compilation as the definition. This restriction does not apply to macros defined by define-syntax.

Variable: command-line-arguments
Any command-line arguments (following flags processed by Kawa itself) are assigned to the global variable `command-line-arguments', which is a vector of strings.

Variable: home-directory
A string containing the home directory of the user.

Function: exit [code]
Exits the Kawa interpreter, and ends the Java session. The integer value code is returned to the operating system. If code is not specified, zero is returned, indicating normal (non-error) termination.

Function: scheme-window [shared]
Create a read-eval-print-loop in a new top-level window. If shared is true, it uses the same environment as the current (interaction-environment); if not (the default), a new top-level environment is created.

You can create multiple top-level window that can co-exist. They run in separate threads.

Syntax: when condition form...
If condition is true, evaluate each form in order, returning the value of the last one.

Syntax: unless condition form...
If condition is false, evaluate each form in order, returning the value of the last one.

Function: reverse! list
The result is a list consisting of the elements of list in reverse order. No new pairs are allocated, instead the pairs of list are re-used, with cdr cells of list reversed in place. Note that if list was pair, it becomes the last pair of the reversed result.

Function: vector-append arg...
Creates a new vector, containing the elements from all the args appended together. Each arg may be a vector or a list.

Function: instance? value type
Returns #t iff value is an instance of type type. (Undefined if type is a primitive type, such as <int>.)

Function: as type value
Converts or coerces value to a value of type type. Throws an exception if that cannot be done. Not supported for type to be a primitive type such as <int>.

Syntax: synchronized object form ...
Synchronize on the given object. (This means getting an exclusive lock on the object, by acquiring its monitor.) Then execute the forms while holding the lock. When the forms finish (normally or abnormally by throwing an exception), the lock is released. Returns the result of the last form. Equivalent to the Java synchronized statement, except that it may return a result.


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by Per Bothner on November, 26 2001 using texi2html