(require 'array) or (require 'srfi-63)
Returns #t if the obj is an array, and #f if not.
Note: Arrays are not disjoint from other Scheme types.
Vectors and possibly strings also satisfy array?.
A disjoint array predicate can be written:
(define (strict-array? obj) (and (array? obj) (not (string? obj)) (not (vector? obj))))
Returns #t if obj1 and obj2 have the same rank and dimensions and the
corresponding elements of obj1 and obj2 are equal?.
equal? recursively compares the contents of pairs, vectors, strings, and
arrays, applying eqv? on other objects such as numbers
and symbols. A rule of thumb is that objects are generally equal? if
they print the same. equal? may fail to terminate if its arguments are
circular data structures.
(equal? 'a 'a) => #t
(equal? '(a) '(a)) => #t
(equal? '(a (b) c)
'(a (b) c)) => #t
(equal? "abc" "abc") => #t
(equal? 2 2) => #t
(equal? (make-vector 5 'a)
(make-vector 5 'a)) => #t
(equal? (make-array (A:fixN32b 4) 5 3)
(make-array (A:fixN32b 4) 5 3)) => #t
(equal? (make-array '#(foo) 3 3)
(make-array '#(foo) 3 3)) => #t
(equal? (lambda (x) x)
(lambda (y) y)) => unspecified
Returns the number of dimensions of obj. If obj is not an array, 0 is returned.
Returns a list of dimensions.
(array-dimensions (make-array '#() 3 5)) => (3 5)
Creates and returns an array of type prototype with dimensions k1, ... and filled with elements from prototype. prototype must be an array, vector, or string. The implementation-dependent type of the returned array will be the same as the type of prototype; except if that would be a vector or string with rank not equal to one, in which case some variety of array will be returned.
If the prototype has no elements, then the initial contents of the returned array are unspecified. Otherwise, the returned array will be filled with the element at the origin of prototype.
create-array is an alias for make-array.
make-shared-array can be used to create shared subarrays of other
arrays. The mapper is a function that translates coordinates in
the new array into coordinates in the old array. A mapper must be
linear, and its range must stay within the bounds of the old array, but
it can be otherwise arbitrary. A simple example:
(define fred (make-array '#(#f) 8 8))
(define freds-diagonal
(make-shared-array fred (lambda (i) (list i i)) 8))
(array-set! freds-diagonal 'foo 3)
(array-ref fred 3 3)
=> FOO
(define freds-center
(make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
2 2))
(array-ref freds-center 0 0)
=> FOO
list must be a rank-nested list consisting of all the elements, in row-major order, of the array to be created.
list->array returns an array of rank rank and type proto consisting of all the
elements, in row-major order, of list. When rank is 0, list is the lone
array element; not necessarily a list.
(list->array 2 '#() '((1 2) (3 4)))
=> #2A((1 2) (3 4))
(list->array 0 '#() 3)
=> #0A 3
Returns a rank-nested list consisting of all the elements, in
row-major order, of array. In the case of a rank-0 array, array->list returns
the single element.
(array->list #2A((ho ho ho) (ho oh oh)))
=> ((ho ho ho) (ho oh oh))
(array->list #0A ho)
=> ho
vect must be a vector of length equal to the product of exact nonnegative integers dim1, ....
vector->array returns an array of type proto consisting of all the elements, in
row-major order, of vect. In the case of a rank-0 array, vect has a
single element.
(vector->array #(1 2 3 4) #() 2 2)
=> #2A((1 2) (3 4))
(vector->array '#(3) '#())
=> #0A 3
Returns a new vector consisting of all the elements of array in row-major order.
(array->vector #2A ((1 2)( 3 4)))
=> #(1 2 3 4)
(array->vector #0A ho)
=> #(ho)
Returns #t if its arguments would be acceptable to
array-ref.
Returns the (k1, ...) element of array.
Stores obj in the (k1, ...) element of array. The value returned
by array-set! is unspecified.
These functions return a prototypical uniform-array enclosing the optional argument (which must be of the correct type). If the uniform-array type is supported by the implementation, then it is returned; defaulting to the next larger precision type; resorting finally to vector.
selects a subset of an array. For array of rank n, there must be at least n selects arguments. For 0 <= j < n, selectsj is either an integer, a list of two integers within the range for the jth index, or #f.
When selectsj is a list of two integers, then the jth index is restricted to that subrange in the returned array.
When selectsj is #f, then the full range of the jth index is accessible in the returned array. An elided argument is equivalent to #f.
When selectsj is an integer, then the rank of the returned array is less than array, and only elements whose jth index equals selectsj are shared.
> (define ra '#2A((a b c) (d e f))) #<unspecified> > (subarray ra 0 #f) #1A(a b c) > (subarray ra 1 #f) #1A(d e f) > (subarray ra #f 1) #1A(b e) > (subarray ra '(0 1) #f) #2A((a b c) (d e f)) > (subarray ra #f '(0 1)) #2A((a b) (d e)) > (subarray ra #f '(1 2)) #2A((b c) (e f)) > (subarray ra #f '(2 1)) #2A((c b) (f e))
Arrays can be reflected (reversed) using subarray:
> (subarray '#1A(a b c d e) '(4 0)) #1A(e d c b a)
Returns a subarray sharing contents with array except for slices removed from either side of each dimension. Each of the trims is an exact integer indicating how much to trim. A positive s trims the data from the lower end and reduces the upper bound of the result; a negative s trims from the upper end and increases the lower bound.
For example:
(array-trim '#(0 1 2 3 4) 1) => #1A(1 2 3 4) (array-trim '#(0 1 2 3 4) -1) => #1A(0 1 2 3) (require 'array-for-each) (define (centered-difference ra) (array-map ra - (array-trim ra 1) (array-trim ra -1))) (centered-difference '#(0 1 3 5 9 22)) => #(1 2 2 4 13)
array1, ... must have the same number of dimensions as array0 and have a range for each index which includes the range for the corresponding index in array0. proc is applied to each tuple of elements of array1 ... and the result is stored as the corresponding element in array0. The value returned is unspecified. The order of application is unspecified.
array2, ... must have the same number of dimensions as array1 and have a range for each index which includes the range for the corresponding index in array1. proc is applied to each tuple of elements of array1, array2, ... and the result is stored as the corresponding element in a new array of type prototype. The new array is returned. The order of application is unspecified.
proc is applied to each tuple of elements of array0 ... in row-major order. The value returned is unspecified.
Returns an array of lists of indexes for array such that, if li is a list of indexes for which array is defined, (equal? li (apply array-ref (array-indexes array) li)).
applies proc to the indices of each element of array in turn. The value returned and the order of application are unspecified.
One can implement array-index-map! as
(define (array-index-map! ra fun) (array-index-for-each ra (lambda is (apply array-set! ra (apply fun is) is))))
applies proc to the indices of each element of array in turn, storing the result in the corresponding element. The value returned and the order of application are unspecified.
One can implement array-indexes as
(define (array-indexes array)
(let ((ra (apply make-array '#() (array-dimensions array))))
(array-index-map! ra (lambda x x))
ra))
Another example:
(define (apl:index-generator n)
(let ((v (make-vector n 1)))
(array-index-map! v (lambda (i) i))
v))
Copies every element from vector or array source to the corresponding element of destination. destination must have the same rank as source, and be at least as large in each dimension. The order of copying is unspecified.
(require 'array-interpolate)
ra must be an array of rank j containing numbers. interpolate-array-ref returns a
value interpolated from the nearest j-dimensional cube of elements
of ra.
(interpolate-array-ref '#2A:fixZ32b((1 2 3) (4 5 6)) 1 0.1)
==> 4.1
(interpolate-array-ref '#2A:fixZ32b((1 2 3) (4 5 6)) 0.5 0.25)
==> 2.75
ra1 and ra2 must be numeric arrays of equal rank. resample-array! sets ra1 to
values interpolated from ra2 such that the values of elements at the
corners of ra1 and ra2 are equal.
(define ra (make-array (A:fixZ32b) 2 2)) (resample-array! ra '#2A:fixZ32b((1 2 3) (4 5 6))) ra ==> #2A:fixZ32b((1 3) (4 6)) (define ra (make-array (A:floR64b) 3 2)) (resample-array! ra '#2A:fixZ32b((1 2 3) (4 5 6))) ra ==> #2A:floR64b((1.0 3.0) (2.5 4.5) (4.0 6.0))
Alist functions provide utilities for treating a list of key-value pairs as an associative database. These functions take an equality predicate, pred, as an argument. This predicate should be repeatable, symmetric, and transitive.
Alist functions can be used with a secondary index method such as hash tables for improved performance.
Returns an association function (like assq, assv, or
assoc) corresponding to pred. The returned function
returns a key-value pair whose key is pred-equal to its first
argument or #f if no key in the alist is pred-equal to the
first argument.
Returns a procedure of 2 arguments, alist and key, which
returns the value associated with key in alist or #f if
key does not appear in alist.
Returns a procedure of 3 arguments, alist, key, and value, which returns an alist with key and value associated. Any previous value associated with key will be lost. This returned procedure may or may not have side effects on its alist argument. An example of correct usage is:
(define put (alist-associator string-ci=?)) (define alist '()) (set! alist (put alist "Foo" 9))
Returns a procedure of 2 arguments, alist and key, which returns an alist with an association whose key is key removed. This returned procedure may or may not have side effects on its alist argument. An example of correct usage is:
(define rem (alist-remover string-ci=?)) (set! alist (rem alist "foo"))
Returns a new association list formed by mapping proc over the keys and values of alist. proc must be a function of 2 arguments which returns the new value part.
Applies proc to each pair of keys and values of alist. proc must be a function of 2 arguments. The returned value is unspecified.
Some algorithms are expressed in terms of arrays of small integers. Using Scheme strings to implement these arrays is not portable vis-a-vis the correspondence between integers and characters and non-ascii character sets. These functions abstract the notion of a byte.
k must be a valid index of bytes. byte-ref returns byte k of bytes using
zero-origin indexing.
k must be a valid index of bytes, and byte must be a small
nonnegative integer. byte-set! stores byte in element k of bytes and
returns an unspecified value.
make-bytes returns a newly allocated byte-array of length k. If byte is
given, then all elements of the byte-array are initialized to byte,
otherwise the contents of the byte-array are unspecified.
bytes-length returns length of byte-array bytes.
Returns a newly allocated byte-array composed of the small nonnegative arguments.
list->bytes returns a newly allocated byte-array formed from the small
nonnegative integers in the list bytes.
bytes->list returns a newly allocated list of the bytes that make up the
given byte-array.
Bytes->list and list->bytes are inverses so far as
equal? is concerned.
Returns a new string formed from applying integer->char to
each byte in bytes->string. Note that this may signal an error for bytes
having values between 128 and 255.
Returns a new byte-array formed from applying char->integer
to each character in string->bytes. Note that this may signal an error if an
integer is larger than 255.
Returns a newly allocated copy of the given bytes.
bytes must be a bytes, and start and end must be exact integers satisfying
0 <= start <= end <= (bytes-length bytes).
subbytes returns a newly allocated bytes formed from the bytes of
bytes beginning with index start (inclusive) and ending with index
end (exclusive).
Reverses the order of byte-array bytes.
Returns a newly allocated bytes-array consisting of the elements of bytes in reverse order.
Input and output of bytes should be with ports opened in binary
mode (see section Input/Output). Calling open-file with 'rb or
'wb modes argument will return a binary port if the Scheme
implementation supports it.
current-output-port.
current-input-port.
When reading and writing binary numbers with read-bytes and
write-bytes, the sign of the length argument determines the
endianness (order) of bytes. Positive treats them as big-endian,
the first byte input or output is highest order. Negative treats
them as little-endian, the first byte input or output is the lowest
order.
Once read in, SLIB treats byte sequences as big-endian. The multi-byte sequences produced and used by number conversion routines see section Byte/Number Conversions are always big-endian.
read-bytes returns a newly allocated bytes-array filled with
(abs n) bytes read from port. If n is positive, then
the first byte read is stored at index 0; otherwise the last byte
read is stored at index 0. Note that the length of the returned
byte-array will be less than (abs n) if port reaches
end-of-file.
port may be omitted, in which case it defaults to the value returned
by current-input-port.
write-bytes writes (abs n) bytes to output-port port. If n is
positive, then the first byte written is index 0 of bytes; otherwise
the last byte written is index 0 of bytes. write-bytes returns an unspecified
value.
port may be omitted, in which case it defaults to the value returned
by current-output-port.
subbytes-read! and subbytes-write provide
lower-level procedures for reading and writing blocks of bytes. The
relative size of start and end determines the order of
writing.
(abs (- start end)) bytes
read from port. The first byte read is stored at index bts.
subbytes-read! returns the number of bytes read.
port may be omitted, in which case it defaults to the value returned
by current-input-port.
subbytes-write writes (abs (- start end)) bytes to
output-port port. The first byte written is index start of bts. subbytes-write
returns the number of bytes written.
port may be omitted, in which case it defaults to the value returned
by current-output-port.
The multi-byte sequences produced and used by numeric conversion
routines are always big-endian. Endianness can be changed during
reading and writing bytes using read-bytes and
write-bytes See section Byte.
The sign of the length argument to bytes/integer conversion procedures determines the signedness of the number.
Converts the first (abs n) bytes of big-endian bytes array
to an integer. If n is negative then the integer coded by the
bytes are treated as two's-complement (can be negative).
(bytes->integer (bytes 0 0 0 15) -4) => 15 (bytes->integer (bytes 0 0 0 15) 4) => 15 (bytes->integer (bytes 255 255 255 255) -4) => -1 (bytes->integer (bytes 255 255 255 255) 4) => 4294967295 (bytes->integer (bytes 128 0 0 0) -4) => -2147483648 (bytes->integer (bytes 128 0 0 0) 4) => 2147483648
Converts the integer n to a byte-array of (abs n)
bytes. If n and len are both negative, then the bytes in the
returned array are coded two's-complement.
(bytes->list (integer->bytes 15 -4)) => (0 0 0 15) (bytes->list (integer->bytes 15 4)) => (0 0 0 15) (bytes->list (integer->bytes -1 -4)) => (255 255 255 255) (bytes->list (integer->bytes 4294967295 4)) => (255 255 255 255) (bytes->list (integer->bytes -2147483648 -4)) => (128 0 0 0) (bytes->list (integer->bytes 2147483648 4)) => (128 0 0 0)
bytes must be a 4-element byte-array. bytes->ieee-float calculates and returns the
value of bytes interpreted as a big-endian IEEE 4-byte (32-bit) number.
(bytes->ieee-float (bytes 0 0 0 0)) => 0.0 (bytes->ieee-float (bytes #x80 0 0 0)) => -0.0 (bytes->ieee-float (bytes #x40 0 0 0)) => 2.0 (bytes->ieee-float (bytes #x40 #xd0 0 0)) => 6.5 (bytes->ieee-float (bytes #xc0 #xd0 0 0)) => -6.5 (bytes->ieee-float (bytes 0 #x80 0 0)) => 11.754943508222875e-39 (bytes->ieee-float (bytes 0 #x40 0 0)) => 5.877471754111437e-39 (bytes->ieee-float (bytes 0 0 0 1)) => 1.401298464324817e-45 (bytes->ieee-float (bytes #xff #x80 0 0)) => -inf.0 (bytes->ieee-float (bytes #x7f #x80 0 0)) => +inf.0 (bytes->ieee-float (bytes #x7f #x80 0 1)) => 0/0 (bytes->ieee-float (bytes #x7f #xc0 0 0)) => 0/0
bytes must be a 8-element byte-array. bytes->ieee-double calculates and returns the
value of bytes interpreted as a big-endian IEEE 8-byte (64-bit) number.
(bytes->ieee-double (bytes 0 0 0 0 0 0 0 0)) => 0.0 (bytes->ieee-double (bytes #x80 0 0 0 0 0 0 0)) => -0.0 (bytes->ieee-double (bytes #x40 0 0 0 0 0 0 0)) => 2.0 (bytes->ieee-double (bytes #x40 #x1A 0 0 0 0 0 0)) => 6.5 (bytes->ieee-double (bytes #xC0 #x1A 0 0 0 0 0 0)) => -6.5 (bytes->ieee-double (bytes 0 8 0 0 0 0 0 0)) => 11.125369292536006e-309 (bytes->ieee-double (bytes 0 4 0 0 0 0 0 0)) => 5.562684646268003e-309 (bytes->ieee-double (bytes 0 0 0 0 0 0 0 1)) => 4.0e-324 (bytes->ieee-double (bytes #xFF #xF0 0 0 0 0 0 0)) => -inf.0 (bytes->ieee-double (bytes #x7F #xF0 0 0 0 0 0 0)) => +inf.0 (bytes->ieee-double (bytes #x7F #xF8 0 0 0 0 0 0)) => 0/0
Returns a 4-element byte-array encoding the IEEE single-precision floating-point of x.
(bytes->list (ieee-float->bytes 0.0)) => (0 0 0 0) (bytes->list (ieee-float->bytes -0.0)) => (128 0 0 0) (bytes->list (ieee-float->bytes 2.0)) => (64 0 0 0) (bytes->list (ieee-float->bytes 6.5)) => (64 208 0 0) (bytes->list (ieee-float->bytes -6.5)) => (192 208 0 0) (bytes->list (ieee-float->bytes 11.754943508222875e-39)) => ( 0 128 0 0) (bytes->list (ieee-float->bytes 5.877471754111438e-39)) => ( 0 64 0 0) (bytes->list (ieee-float->bytes 1.401298464324817e-45)) => ( 0 0 0 1) (bytes->list (ieee-float->bytes -inf.0)) => (255 128 0 0) (bytes->list (ieee-float->bytes +inf.0)) => (127 128 0 0) (bytes->list (ieee-float->bytes 0/0)) => (127 192 0 0)
Returns a 8-element byte-array encoding the IEEE double-precision floating-point of x.
(bytes->list (ieee-double->bytes 0.0)) => (0 0 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes -0.0)) => (128 0 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 2.0)) => (64 0 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 6.5)) => (64 26 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes -6.5)) => (192 26 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 11.125369292536006e-309))
=> ( 0 8 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 5.562684646268003e-309))
=> ( 0 4 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 4.0e-324))
=> ( 0 0 0 0 0 0 0 1)
(bytes->list (ieee-double->bytes -inf.0)) => (255 240 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes +inf.0)) => (127 240 0 0 0 0 0 0)
(bytes->list (ieee-double->bytes 0/0)) => (127 248 0 0 0 0 0 0)
The string<? ordering of big-endian byte-array
representations of fixed and IEEE floating-point numbers agrees with
the numerical ordering only when those numbers are non-negative.
Straighforward modification of these formats can extend the byte-collating order to work for their entire ranges. This agreement enables the full range of numbers as keys in indexed-sequential-access-method databases.
Modifies sign bit of byte-vector so that string<? ordering of
two's-complement byte-vectors matches numerical order. integer-byte-collate! returns
byte-vector and is its own functional inverse.
Returns copy of byte-vector with sign bit modified so that string<?
ordering of two's-complement byte-vectors matches numerical order.
integer-byte-collate is its own functional inverse.
Modifies byte-vector so that string<? ordering of IEEE floating-point
byte-vectors matches numerical order. ieee-byte-collate! returns byte-vector.
Given byte-vector modified by ieee-byte-collate!, reverses the byte-vector
modifications.
Returns copy of byte-vector encoded so that string<? ordering of IEEE
floating-point byte-vectors matches numerical order.
Given byte-vector returned by ieee-byte-collate, reverses the byte-vector
modifications.
http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf
This package reads MAT-File Format version 4 (MATLAB) binary data files. MAT-files written from big-endian or little-endian computers having IEEE format numbers are currently supported. Support for files written from VAX or Cray machines could also be added.
The numeric and text matrix types handled; support for sparse matrices awaits a sample file.
matfile:read procedure reads matrices from the
file and returns a list of the results; a list of the name string and
array for each matrix.
matfile:load procedure reads matrices from the
file and defines the string-ci->symbol for each matrix to its
corresponding array. matfile:load returns a list of the symbols defined.
The string path must name a portable bitmap graphics file.
pnm:type-dimensions returns a list of 4 items:
The current set of file-type symbols is:
Reads the portable bitmap graphics file named by path into array. array must be the correct size and type for path. array is returned.
pnm:image-file->array creates and returns an array with the
portable bitmap graphics file named by path read into it.
Writes the contents of array to a type image file named path. The file will have pixel values between 0 and maxval, which must be compatible with type. For `pbm' files, maxval must be `1'. comments are included in the file header.
Routines for managing collections. Collections are aggregate data structures supporting iteration over their elements, similar to the Dylan(TM) language, but with a different interface. They have elements indexed by corresponding keys, although the keys may be implicit (as with lists).
New types of collections may be defined as YASOS objects (see section Yasos). They must support the following operations:
(collection? self) (always returns #t);
(size self) returns the number of elements in the collection;
(print self port) is a specialized print operation
for the collection which prints a suitable representation on the given
port or returns it as a string if port is #t;
(gen-elts self) returns a thunk which on successive
invocations yields elements of self in order or gives an error if
it is invoked more than (size self) times;
(gen-keys self) is like gen-elts, but yields the
collection's keys in order.
They might support specialized for-each-key and
for-each-elt operations.
#t to collection?.
do-elts is used when only side-effects of proc are of
interest and its return value is unspecified. map-elts returns a
collection (actually a vector) of the results of the applications of
proc.
Example:
(map-elts + (list 1 2 3) (vector 1 2 3)) => #(2 4 6)
map-elts and do-elts, but each
iteration is over the collections' keys rather than their
elements.
Example:
(map-keys + (list 1 2 3) (vector 1 2 3)) => #(0 2 4)
do-keys and do-elts but only for a single
collection; they are potentially more efficient.
reduce-init
(see section Lists as sequences) to collections.
Examples:
(reduce + 0 (vector 1 2 3)) => 6 (reduce union '() '((a b c) (b c d) (d a))) => (c b d a).
Reduce called with two arguments will work as does the
procedure of the same name from See section Common List Functions).
some
(see section Lists as sequences) to collections.
Example:
(any? odd? (list 2 3 4 5)) => #t
every
(see section Lists as sequences) to collections.
Example:
(every? collection? '((1 2) #(1 2))) => #t
#t iff there are no elements in collection.
(empty? collection) == (zero? (size collection))
(setter list-ref) doesn't work properly for element 0 of a
list.
Here is a sample collection: simple-table which is also a
table.
(define-predicate TABLE?)
(define-operation (LOOKUP table key failure-object))
(define-operation (ASSOCIATE! table key value)) ;; returns key
(define-operation (REMOVE! table key)) ;; returns value
(define (MAKE-SIMPLE-TABLE)
(let ( (table (list)) )
(object
;; table behaviors
((TABLE? self) #t)
((SIZE self) (size table))
((PRINT self port) (format port "#<SIMPLE-TABLE>"))
((LOOKUP self key failure-object)
(cond
((assq key table) => cdr)
(else failure-object)
))
((ASSOCIATE! self key value)
(cond
((assq key table)
=> (lambda (bucket) (set-cdr! bucket value) key))
(else
(set! table (cons (cons key value) table))
key)
))
((REMOVE! self key);; returns old value
(cond
((null? table) (slib:error "TABLE:REMOVE! Key not found: " key))
((eq? key (caar table))
(let ( (value (cdar table)) )
(set! table (cdr table))
value)
)
(else
(let loop ( (last table) (this (cdr table)) )
(cond
((null? this)
(slib:error "TABLE:REMOVE! Key not found: " key))
((eq? key (caar this))
(let ( (value (cdar this)) )
(set-cdr! last (cdr this))
value)
)
(else
(loop (cdr last) (cdr this)))
) ) )
))
;; collection behaviors
((COLLECTION? self) #t)
((GEN-KEYS self) (collect:list-gen-elts (map car table)))
((GEN-ELTS self) (collect:list-gen-elts (map cdr table)))
((FOR-EACH-KEY self proc)
(for-each (lambda (bucket) (proc (car bucket))) table)
)
((FOR-EACH-ELT self proc)
(for-each (lambda (bucket) (proc (cdr bucket))) table)
) ) ) )
dynamic? satisfies any of the other standard type
predicates.
The dynamic-bind macro is not implemented.
Returns a hash function (like hashq, hashv, or
hash) corresponding to the equality predicate pred.
pred should be eq?, eqv?, equal?, =,
char=?, char-ci=?, string=?, or
string-ci=?.
A hash table is a vector of association lists.
Returns a vector of k empty (association) lists.
Hash table functions provide utilities for an associative database.
These functions take an equality predicate, pred, as an argument.
pred should be eq?, eqv?, equal?, =,
char=?, char-ci=?, string=?, or
string-ci=?.
Returns a hash association function of 2 arguments, key and
hashtab, corresponding to pred. The returned function
returns a key-value pair whose key is pred-equal to its first
argument or #f if no key in hashtab is pred-equal to
the first argument.
Returns a procedure of 2 arguments, hashtab and key, which
returns the value associated with key in hashtab or
#f if key does not appear in hashtab.
Returns a procedure of 3 arguments, hashtab, key, and value, which modifies hashtab so that key and value associated. Any previous value associated with key will be lost.
Returns a procedure of 2 arguments, hashtab and key, which modifies hashtab so that the association whose key is key is removed.
Returns a new hash table formed by mapping proc over the keys and values of hash-table. proc must be a function of 2 arguments which returns the new value part.
Applies proc to each pair of keys and values of hash-table. proc must be a function of 2 arguments. The returned value is unspecified.
hash-rehasher accepts a hash table predicate and returns a function of two
arguments hashtab and new-k which is specialized for
that predicate.
This function is used for nondestrutively resizing a hash table. hashtab should be an existing hash-table using pred, new-k is the size of a new hash table to be returned. The new hash table will have all of the associations of the old hash table.
This is the Macroless Object System written by Wade Humeniuk (whumeniu@datap.ca). Conceptual Tributes: section Yasos, MacScheme's %object, CLOS, Lack of R4RS macros.
eq?) of methods
(procedures). Methods can be added (make-method!), deleted
(unmake-method!) and retrieved (get-method). Objects may
inherit methods from other objects. The object binds to the environment
it was created in, allowing closures to be used to hide private
procedures and data.
eq?) object's method.
This allows scheme function style to be used for objects. The calling
scheme for using a generic method is (generic-method object param1
param2 ...).
#t.
get-method.
unmake-method!
will restore the object's previous association with the
generic-method. method must be a procedure.
(require 'object)
(define instantiate (make-generic-method))
(define (make-instance-object . ancestors)
(define self (apply make-object
(map (lambda (obj) (instantiate obj)) ancestors)))
(make-method! self instantiate (lambda (self) self))
self)
(define who (make-generic-method))
(define imigrate! (make-generic-method))
(define emigrate! (make-generic-method))
(define describe (make-generic-method))
(define name (make-generic-method))
(define address (make-generic-method))
(define members (make-generic-method))
(define society
(let ()
(define self (make-instance-object))
(define population '())
(make-method! self imigrate!
(lambda (new-person)
(if (not (eq? new-person self))
(set! population (cons new-person population)))))
(make-method! self emigrate!
(lambda (person)
(if (not (eq? person self))
(set! population
(comlist:remove-if (lambda (member)
(eq? member person))
population)))))
(make-method! self describe
(lambda (self)
(map (lambda (person) (describe person)) population)))
(make-method! self who
(lambda (self) (map (lambda (person) (name person))
population)))
(make-method! self members (lambda (self) population))
self))
(define (make-person %name %address)
(define self (make-instance-object society))
(make-method! self name (lambda (self) %name))
(make-method! self address (lambda (self) %address))
(make-method! self who (lambda (self) (name self)))
(make-method! self instantiate
(lambda (self)
(make-person (string-append (name self) "-son-of")
%address)))
(make-method! self describe
(lambda (self) (list (name self) (address self))))
(imigrate! self)
self)
Inheritance:
<inverter>::(<number> <description>)
Generic-methods
<inverter>::value => <number>::value
<inverter>::set-value! => <number>::set-value!
<inverter>::describe => <description>::describe
<inverter>::help
<inverter>::invert
<inverter>::inverter?
Inheritance
<number>::()
Slots
<number>::<x>
Generic Methods
<number>::value
<number>::set-value!
(require 'object)
(define value (make-generic-method (lambda (val) val)))
(define set-value! (make-generic-method))
(define invert (make-generic-method
(lambda (val)
(if (number? val)
(/ 1 val)
(error "Method not supported:" val)))))
(define noop (make-generic-method))
(define inverter? (make-generic-predicate))
(define describe (make-generic-method))
(define help (make-generic-method))
(define (make-number x)
(define self (make-object))
(make-method! self value (lambda (this) x))
(make-method! self set-value!
(lambda (this new-value) (set! x new-value)))
self)
(define (make-description str)
(define self (make-object))
(make-method! self describe (lambda (this) str))
(make-method! self help (lambda (this) "Help not available"))
self)
(define (make-inverter)
(let* ((self (make-object
(make-number 1)
(make-description "A number which can be inverted")))
(<value> (get-method self value)))
(make-method! self invert (lambda (self) (/ 1 (<value> self))))
(make-predicate! self inverter?)
(unmake-method! self help)
(make-method! self help
(lambda (self)
(display "Inverter Methods:") (newline)
(display " (value inverter) ==> n") (newline)))
self))
;;;; Try it out
(define invert! (make-generic-method))
(define x (make-inverter))
(make-method! x invert! (lambda (x) (set-value! x (/ 1 (value x)))))
(value x) => 1
(set-value! x 33) => undefined
(invert! x) => undefined
(value x) => 1/33
(unmake-method! x invert!) => undefined
(invert! x) error--> ERROR: Method not supported: x
This algorithm for priority queues is due to Introduction to Algorithms by T. Cormen, C. Leiserson, R. Rivest. 1989 MIT Press.
Returns a binary heap suitable which can be used for priority queue operations.
Returns the number of elements in heap.
Inserts item into heap. item can be inserted multiple times. The value returned is unspecified.
Returns the item which is larger than all others according to the
pred<? argument to make-heap. If there are no items in
heap, an error is signaled.
A queue is a list where elements can be added to both the front and rear, and removed from the front (i.e., they are what are often called dequeues). A queue may also be used like a stack.
Returns a new, empty queue.
Returns #t if obj is a queue.
Returns #t if the queue q is empty.
Adds datum to the front of queue q.
Adds datum to the rear of queue q.
queue-pop! is used to suggest that the queue is
being used like a stack.
All of the following functions raise an error if the queue q is empty.
Removes and returns (the list) of all contents of queue q.
Returns the datum at the front of the queue q.
Returns the datum at the rear of the queue q.
The Record package provides a facility for user to define their own record data types.
make-record-type that created the type represented by rtd;
if the field-names argument is provided, it is an error if it
contains any duplicates or any symbols not in the default list.
make-record-type
that created the type represented by rtd.
make-record-type that created the type represented by
rtd.
In May of 1996, as a product of discussion on the rrrs-authors
mailing list, I rewrote `record.scm' to portably implement type
disjointness for record data types.
As long as an implementation's procedures are opaque and the
record code is loaded before other programs, this will give
disjoint record types which are unforgeable and incorruptible by R4RS
procedures.
As a consequence, the procedures record?,
record-type-descriptor, record-type-name.and
record-type-field-names are no longer supported.
(require 'common-list-functions)
The procedures below follow the Common LISP equivalents apart from optional arguments in some cases.
make-list creates and returns a list of k elements. If
init is included, all elements in the list are initialized to
init.
Example:
(make-list 3) => (#<unspecified> #<unspecified> #<unspecified>) (make-list 5 'foo) => (foo foo foo foo foo)
list except that the cdr of the last pair is the last
argument unless there is only one argument, when the result is just that
argument. Sometimes called cons*. E.g.:
(list* 1) => 1 (list* 1 2 3) => (1 2 . 3) (list* 1 2 '(3 4)) => (1 2 3 4) (list* args '()) == (list args)
copy-list makes a copy of lst using new pairs and returns
it. Only the top level of the list is copied, i.e., pairs forming
elements of the copied list remain eq? to the corresponding
elements of the original; the copy is, however, not eq? to the
original, but is equal? to it.
Example:
(copy-list '(foo foo foo)) => (foo foo foo) (define q '(foo bar baz bang)) (define p q) (eq? p q) => #t (define r (copy-list q)) (eq? q r) => #f (equal? q r) => #t (define bar '(bar)) (eq? bar (car (copy-list (list bar 'foo)))) => #t
eqv? is used to test for membership by procedures which treat
lists as sets.
adjoin returns the adjoint of the element e and the list
l. That is, if e is in l, adjoin returns
l, otherwise, it returns (cons e l).
Example:
(adjoin 'baz '(bar baz bang)) => (bar baz bang) (adjoin 'foo '(bar baz bang)) => (foo bar baz bang)
union returns a list of all elements that are in l1 or
l2. Duplicates between l1 and l2 are culled.
Duplicates within l1 or within l2 may or may not be
removed.
Example:
(union '(1 2 3 4) '(5 6 7 8)) => (1 2 3 4 5 6 7 8) (union '(0 1 2 3 4) '(3 4 5 6)) => (5 6 0 1 2 3 4)
intersection returns a list of all elements that are in both
l1 and l2.
Example:
(intersection '(1 2 3 4) '(3 4 5 6)) => (3 4) (intersection '(1 2 3 4) '(5 6 7 8)) => ()
set-difference returns a list of all elements that are in
l1 but not in l2.
Example:
(set-difference '(1 2 3 4) '(3 4 5 6)) => (1 2) (set-difference '(1 2 3 4) '(1 2 3 4 5 6)) => ()
#t if every element of list1 is eqv? an
element of list2; otherwise returns #f.
Example:
(subset? '(1 2 3 4) '(3 4 5 6)) => #f (subset? '(1 2 3 4) '(6 5 4 3 2 1 0)) => #t
member-if returns the list headed by the first element of
lst to satisfy (pred element).
Member-if returns #f if pred returns #f for
every element in lst.
Example:
(member-if vector? '(a 2 b 4)) => #f (member-if number? '(a 2 b 4)) => (2 b 4)
some i.e., lst plus any optional arguments.
pred is applied to successive elements of the list arguments in
order. some returns #t as soon as one of these
applications returns #t, and is #f if none returns
#t. All the lists should have the same length.
Example:
(some odd? '(1 2 3 4)) => #t (some odd? '(2 4 6 8)) => #f (some > '(1 3) '(2 4)) => #f
every is analogous to some except it returns #t if
every application of pred is #t and #f
otherwise.
Example:
(every even? '(1 2 3 4)) => #f (every even? '(2 4 6 8)) => #t (every > '(2 3) '(1 4)) => #f
notany is analogous to some but returns #t if no
application of pred returns #t or #f as soon as any
one does.
notevery is analogous to some but returns #t as soon
as an application of pred returns #f, and #f
otherwise.
Example:
(notevery even? '(1 2 3 4)) => #t (notevery even? '(2 4 6 8)) => #f
list-of?? returns a predicate which returns true if its argument
is a list of length between low-bound and high-bound
(inclusive); every element of which satisfies predicate.
list-of??
returns a predicate which returns true if its argument is a list of
length greater than (- bound); every element of which
satisfies predicate. Otherwise, list-of?? returns a
predicate which returns true if its argument is a list of length less
than or equal to bound; every element of which satisfies
predicate.
find-if searches for the first element in lst such
that (pred element) returns #t. If it finds
any such element in lst, element is returned.
Otherwise, #f is returned.
Example:
(find-if number? '(foo 1 bar 2)) => 1 (find-if number? '(foo bar baz bang)) => #f (find-if symbol? '(1 2 foo bar)) => foo
remove removes all occurrences of elt from lst using
eqv? to test for equality and returns everything that's left.
N.B.: other implementations (Chez, Scheme->C and T, at least) use
equal? as the equality test.
Example:
(remove 1 '(1 2 1 3 1 4 1 5)) => (2 3 4 5) (remove 'foo '(bar baz bang)) => (bar baz bang)
remove-if removes all elements from lst where
(pred element) is #t and returns everything
that's left.
Example:
(remove-if number? '(1 2 3 4)) => () (remove-if even? '(1 2 3 4 5 6 7 8)) => (1 3 5 7)
remove-if-not removes all elements from lst for which
(pred element) is #f and returns everything that's
left.
Example:
(remove-if-not number? '(foo bar baz)) => () (remove-if-not odd? '(1 2 3 4 5 6 7 8)) => (1 3 5 7)
#t if 2 members of lst are equal?, #f
otherwise.
Example:
(has-duplicates? '(1 2 3 4)) => #f (has-duplicates? '(2 4 3 4)) => #t
The procedure remove-duplicates uses member (rather than
memv).
equal?.
Example:
(remove-duplicates '(1 2 3 4)) => (1 2 3 4) (remove-duplicates '(2 4 3 4)) => (2 4 3)
position returns the 0-based position of obj in lst,
or #f if obj does not occur in lst.
Example:
(position 'foo '(foo bar baz bang)) => 0 (position 'baz '(foo bar baz bang)) => 2 (position 'oops '(foo bar baz bang)) => #f
reduce combines all the elements of a sequence using a binary
operation (the combination is left-associative). For example, using
+, one can add up all the elements. reduce allows you to
apply a function which accepts only two arguments to more than 2
objects. Functional programmers usually refer to this as foldl.
collect:reduce (see section Collections) provides a version of
collect generalized to collections.
Example:
(reduce + '(1 2 3 4))
=> 10
(define (bad-sum . l) (reduce + l))
(bad-sum 1 2 3 4)
== (reduce + (1 2 3 4))
== (+ (+ (+ 1 2) 3) 4)
=> 10
(bad-sum)
== (reduce + ())
=> ()
(reduce string-append '("hello" "cruel" "world"))
== (string-append (string-append "hello" "cruel") "world")
=> "hellocruelworld"
(reduce anything '())
=> ()
(reduce anything '(x))
=> x
What follows is a rather non-standard implementation of reverse
in terms of reduce and a combinator elsewhere called
C.
;;; Contributed by Jussi Piitulainen (jpiitula @ ling.helsinki.fi)
(define commute
(lambda (f)
(lambda (x y)
(f y x))))
(define reverse
(lambda (args)
(reduce-init (commute cons) '() args)))
reduce-init is the same as reduce, except that it implicitly
inserts init at the start of the list. reduce-init is
preferred if you want to handle the null list, the one-element, and
lists with two or more elements consistently. It is common to use the
operator's idempotent as the initializer. Functional programmers
usually call this foldl.
Example:
(define (sum . l) (reduce-init + 0 l))
(sum 1 2 3 4)
== (reduce-init + 0 (1 2 3 4))
== (+ (+ (+ (+ 0 1) 2) 3) 4)
=> 10
(sum)
== (reduce-init + 0 '())
=> 0
(reduce-init string-append "@" '("hello" "cruel" "world"))
==
(string-append (string-append (string-append "@" "hello")
"cruel")
"world")
=> "@hellocruelworld"
Given a differentiation of 2 arguments, diff, the following will
differentiate by any number of variables.
(define (diff* exp . vars) (reduce-init diff exp vars))
Example:
;;; Real-world example: Insertion sort using reduce-init.
(define (insert l item)
(if (null? l)
(list item)
(if (< (car l) item)
(cons (car l) (insert (cdr l) item))
(cons item l))))
(define (insertion-sort l) (reduce-init insert '() l))
(insertion-sort '(3 1 4 1 5)
== (reduce-init insert () (3 1 4 1 5))
== (insert (insert (insert (insert (insert () 3) 1) 4) 1) 5)
== (insert (insert (insert (insert (3)) 1) 4) 1) 5)
== (insert (insert (insert (1 3) 4) 1) 5)
== (insert (insert (1 3 4) 1) 5)
== (insert (1 1 3 4) 5)
=> (1 1 3 4 5)
last returns the last n elements of lst. n
must be a non-negative integer.
Example:
(last '(foo bar baz bang) 2) => (baz bang) (last '(1 2 3) 0) => 0
butlast returns all but the last n elements of
lst.
Example:
(butlast '(a b c d) 3) => (a) (butlast '(a b c d) 4) => ()
last and butlast split a list into two parts when given
identical arguments.
(last '(a b c d e) 2) => (d e) (butlast '(a b c d e) 2) => (a b c)
nthcdr takes n cdrs of lst and returns the
result. Thus (nthcdr 3 lst) == (cdddr
lst)
Example:
(nthcdr 2 '(a b c d)) => (c d) (nthcdr 0 '(a b c d)) => (a b c d)
butnthcdr returns all but the nthcdr n elements of
lst.
Example:
(butnthcdr 3 '(a b c d)) => (a b c) (butnthcdr 4 '(a b c d)) => (a b c d)
nthcdr and butnthcdr split a list into two parts when
given identical arguments.
(nthcdr 2 '(a b c d e)) => (c d e) (butnthcdr 2 '(a b c d e)) => (a b)
These procedures may mutate the list they operate on, but any such mutation is undefined.
nconc destructively concatenates its arguments. (Compare this
with append, which copies arguments rather than destroying them.)
Sometimes called append! (see section Rev2 Procedures).
Example: You want to find the subsets of a set. Here's the obvious way:
(define (subsets set)
(if (null? set)
'(())
(append (map (lambda (sub) (cons (car set) sub))
(subsets (cdr set)))
(subsets (cdr set)))))
But that does way more consing than you need. Instead, you could
replace the append with nconc, since you don't have any
need for all the intermediate results.
Example:
(define x '(a b c)) (define y '(d e f)) (nconc x y) => (a b c d e f) x => (a b c d e f)
nconc is the same as append! in `sc2.scm'.
nreverse reverses the order of elements in lst by mutating
cdrs of the list. Sometimes called reverse!.
Example:
(define foo '(a b c)) (nreverse foo) => (c b a) foo => (a)
Some people have been confused about how to use nreverse,
thinking that it doesn't return a value. It needs to be pointed out
that
(set! lst (nreverse lst))
is the proper usage, not
(nreverse lst)
The example should suffice to show why this is the case.
remove remove-if, and
remove-if-not.
Example:
(define lst (list 'foo 'bar 'baz 'bang)) (delete 'foo lst) => (bar baz bang) lst => (foo bar baz bang) (define lst (list 1 2 3 4 5 6 7 8 9)) (delete-if odd? lst) => (2 4 6 8) lst => (1 2 4 6 8)
Some people have been confused about how to use delete,
delete-if, and delete-if, thinking that they don't return
a value. It needs to be pointed out that
(set! lst (delete el lst))
is the proper usage, not
(delete el lst)
The examples should suffice to show why this is the case.
and? checks to see if all its arguments are true. If they are,
and? returns #t, otherwise, #f. (In contrast to
and, this is a function, so all arguments are always evaluated
and in an unspecified order.)
Example:
(and? 1 2 3) => #t (and #f 1 2) => #f
or? checks to see if any of its arguments are true. If any is
true, or? returns #t, and #f otherwise. (To
or as and? is to and.)
Example:
(or? 1 2 #f) => #t (or? #f #f #f) => #f
#t if object is not a pair and #f if it is
pair. (Called atom in Common LISP.)
(atom? 1) => #t (atom? '(1 2)) => #f (atom? #(1 2)) ; dubious! => #t
These are operations that treat lists a representations of trees.
subst makes a copy of tree, substituting new for
every subtree or leaf of tree which is equal? to old
and returns a modified tree. The original tree is unchanged, but
may share parts with the result.
substq and substv are similar, but test against old
using eq? and eqv? respectively. If subst is
called with a fourth argument, equ? is the equality predicate.
Examples:
(substq 'tempest 'hurricane '(shakespeare wrote (the hurricane)))
=> (shakespeare wrote (the tempest))
(substq 'foo '() '(shakespeare wrote (twelfth night)))
=> (shakespeare wrote (twelfth night . foo) . foo)
(subst '(a . cons) '(old . pair)
'((old . spice) ((old . shoes) old . pair) (old . pair)))
=> ((old . spice) ((old . shoes) a . cons) (a . cons))
Makes a copy of the nested list structure tree using new pairs and
returns it. All levels are copied, so that none of the pairs in the
tree are eq? to the original ones -- only the leaves are.
Example:
(define bar '(bar)) (copy-tree (list bar 'foo)) => ((bar) foo) (eq? bar (car (copy-tree (list bar 'foo)))) => #f
The `chap:' functions deal with strings which are ordered like chapter numbers (or letters) in a book. Each section of the string consists of consecutive numeric or consecutive aphabetic characters of like case.
Returns #t if the first non-matching run of alphabetic upper-case or
the first non-matching run of alphabetic lower-case or the first
non-matching run of numeric characters of string1 is
string<? than the corresponding non-matching run of
characters of string2.
(chap:string<? "a.9" "a.10") => #t
(chap:string<? "4c" "4aa") => #t
(chap:string<? "Revised^{3.99}" "Revised^{4}") => #t
Implement the corresponding chapter-order predicates.
Returns the next string in the chapter order. If string
has no alphabetic or numeric characters,
(string-append string "0") is returnd. The argument to
chap:next-string will always be chap:string<? than the result.
(chap:next-string "a.9") => "a.10"
(chap:next-string "4c") => "4d"
(chap:next-string "4z") => "4aa"
(chap:next-string "Revised^{4}") => "Revised^{5}"
(require 'sort) or (require 'srfi-95)
[by Richard A. O'Keefe, 1991]
I am providing this source code with no restrictions at all on its use (but please retain D.H.D.Warren's credit for the original idea).
The code of merge and merge! could have been quite a bit
simpler, but they have been coded to reduce the amount of work done per
iteration. (For example, we only have one null? test per
iteration.)
I gave serious consideration to producing Common-LISP-compatible
functions. However, Common LISP's sort is our sort!
(well, in fact Common LISP's stable-sort is our sort!;
merge sort is fast as well as stable!) so adapting CL code to
Scheme takes a bit of work anyway. I did, however, appeal to CL to
determine the order of the arguments.
The standard functions <, >, char<?, char>?,
char-ci<?, char-ci>?, string<?, string>?,
string-ci<?, and string-ci>? are suitable for use as
comparison functions. Think of (less? x y) as saying when
x must not precede y.
[Addendum by Aubrey Jaffer, 2006]
These procedures are stable when called with predicates which return
#f when applied to identical arguments.
The sorted?, merge, and merge! procedures consume
asymptotic time and space no larger than O(N), where N is the
sum of the lengths of the sequence arguments.
The sort and sort! procedures consume asymptotic time
and space no larger than O(N*log(N)), where N is the length of
the sequence argument.
All five functions take an optional key argument corresponding to a CL-style `&key' argument. A less? predicate with a key argument behaves like:
(lambda (x y) (less? (key x) (key y)))
All five functions will call the key argument at most once per element.
The `!' variants sort in place; sort! returns its
sequence argument.
#t when the sequence argument is in non-decreasing
order according to less? (that is, there is no adjacent pair
... x y ... for which (less? y x)).
Returns #f when the sequence contains at least one out-of-order
pair. It is an error if the sequence is not a list or array
(including vectors and strings).
(sorted? (sort sequence less?) less?) => #t
(sorted? (sort! sequence less?) less?) => #t
(require 'topological-sort) or (require 'tsort)
The algorithm is inspired by Cormen, Leiserson and Rivest (1990) Introduction to Algorithms, chapter 23.
eq?, eqv?, equal?, =,
char=?, char-ci=?, string=?, or string-ci=?.
Sort the directed acyclic graph dag so that for every edge from vertex u to v, u will come before v in the resulting list of vertices.
Time complexity: O (|V| + |E|)
Example (from Cormen):
Prof. Bumstead topologically sorts his clothing when getting dressed. The first argument to
tsortdescribes which garments he needs to put on before others. (For example, Prof Bumstead needs to put on his shirt before he puts on his tie or his belt.)tsortgives the correct order of dressing:
(require 'tsort)
(tsort '((shirt tie belt)
(tie jacket)
(belt jacket)
(watch)
(pants shoes belt)
(undershorts pants shoes)
(socks shoes))
eq?)
=>
(socks undershorts pants shoes watch shirt belt tie jacket)
These hashing functions are for use in quickly classifying objects. Hash tables use these functions.
For hashq, (eq? obj1 obj2) implies (= (hashq obj1 k)
(hashq obj2)).
For hashv, (eqv? obj1 obj2) implies (= (hashv obj1 k)
(hashv obj2)).
For hash, (equal? obj1 obj2) implies (= (hash obj1 k)
(hash obj2)).
hash, hashv, and hashq return in time bounded by a
constant. Notice that items having the same hash implies the
items have the same hashv implies the items have the same
hashq.
The Hilbert Space-Filling Curve is a one-to-one mapping between a unit line segment and an n-dimensional unit cube. This implementation treats the nonnegative integers either as fractional bits of a given width or as nonnegative integers.
The integer procedures map the non-negative integers to an arbitrarily large n-dimensional cube with its corner at the origin and all coordinates are non-negative.
For any exact nonnegative integer scalar and exact integer rank > 2,
(= scalar (hilbert-coordinates->integer
(integer->hilbert-coordinates scalar rank)))
=> #t
When treating integers as k fractional bits,
(= scalar (hilbert-coordinates->integer
(integer->hilbert-coordinates scalar rank k)) k)
=> #t
Returns a list of rank integer coordinates corresponding to exact
non-negative integer scalar. The lists returned by integer->hilbert-coordinates for scalar arguments
0 and 1 will differ in the first element.
scalar must be a nonnegative integer of no more than
rank*k bits.
integer->hilbert-coordinates Returns a list of rank k-bit nonnegative integer
coordinates corresponding to exact non-negative integer scalar. The
curves generated by integer->hilbert-coordinates have the same alignment independent of
k.
A Gray code is an ordering of non-negative integers in which exactly one bit differs between each pair of successive elements. There are multiple Gray codings. An n-bit Gray code corresponds to a Hamiltonian cycle on an n-dimensional hypercube.
Gray codes find use communicating incrementally changing values between asynchronous agents. De-laminated Gray codes comprise the coordinates of Hilbert space-filling curves.
integer-length as
k.
integer-length as k.
For any non-negative integer k,
(eqv? k (gray-code->integer (integer->gray-code k)))
For any non-negative integers k1 and k2, the Gray code
predicate of (integer->gray-code k1) and
(integer->gray-code k2) will return the same value as the
corresponding predicate of k1 and k2.
Returns a list of count integers comprised of the jth bit of the integers ks where j ranges from count-1 to 0.
(map (lambda (k) (number->string k 2))
(delaminate-list 4 '(7 6 5 4 0 0 0 0)))
=> ("0" "11110000" "11000000" "10100000")
delaminate-list is its own inverse:
(delaminate-list 8 (delaminate-list 4 '(7 6 5 4 0 0 0 0)))
=> (7 6 5 4 0 0 0 0)
Returns a list of rank nonnegative integer coordinates corresponding
to exact nonnegative integer scalar. The lists returned by natural->peano-coordinates for scalar
arguments 0 and 1 will differ in the first element.
Returns an exact nonnegative integer corresponding to coords, a list of nonnegative integer coordinates.
Returns a list of rank integer coordinates corresponding to exact
integer scalar. The lists returned by integer->peano-coordinates for scalar arguments 0 and 1 will
differ in the first element.
Returns an exact integer corresponding to coords, a list of integer coordinates.
max-coordinate is the maximum coordinate (a positive integer) of a population of points. The returned procedures is a function that takes the x and y coordinates of a point, (non-negative integers) and returns an integer corresponding to the relative position of that point along a Sierpinski curve. (You can think of this as computing a (pseudo-) inverse of the Sierpinski spacefilling curve.)
Example use: Make an indexer (hash-function) for integer points lying in square of integer grid points [0,99]x[0,99]:
(define space-key (make-sierpinski-indexer 100))
Now let's compute the index of some points:
(space-key 24 78) => 9206 (space-key 23 80) => 9172
Note that locations (24, 78) and (23, 80) are near in index and therefore, because the Sierpinski spacefilling curve is continuous, we know they must also be near in the plane. Nearness in the plane does not, however, necessarily correspond to nearness in index, although it tends to be so.
Example applications:
Soundex was a classic algorithm used for manual filing of personal records before the advent of computers. It performs adequately for English names but has trouble with other languages.
See Knuth, Vol. 3 Sorting and searching, pp 391--2
To manage unusual inputs, soundex omits all non-alphabetic
characters. Consequently, in this implementation:
(soundex <string of blanks>) => "" (soundex "") => ""
Examples from Knuth:
(map soundex '("Euler" "Gauss" "Hilbert" "Knuth"
"Lloyd" "Lukasiewicz"))
=> ("E460" "G200" "H416" "K530" "L300" "L222")
(map soundex '("Ellery" "Ghosh" "Heilbronn" "Kant"
"Ladd" "Lissajous"))
=> ("E460" "G200" "H416" "K530" "L300" "L222")
Some cases in which the algorithm fails (Knuth):
(map soundex '("Rogers" "Rodgers")) => ("R262" "R326")
(map soundex '("Sinclair" "St. Clair")) => ("S524" "S324")
(map soundex '("Tchebysheff" "Chebyshev")) => ("T212" "C121")
#f if the string does not contain a
character char.
#f if the string does not contain a
character char.
substring? returns the index of the first
character of the first substring of string that is equal to
pattern; or #f if string does not contain
pattern.
(substring? "rat" "pirate") => 2 (substring? "rat" "outrage") => #f (substring? "" any-string) => 0
When the str is found, find-string-from-port? returns the
number of characters it has read from the port, and the port is set to
read the first char after that (that is, after the str) The
function returns #f when the str isn't found.
find-string-from-port? reads the port strictly
sequentially, and does not perform any buffering. So
find-string-from-port? can be used even if the in-port is
open to a pipe or other communication channel.
diff:edit-length implements the algorithm:
S. Wu, E. Myers, U. Manber, and W. Miller, "An O(NP) Sequence Comparison Algorithm", Information Processing Letters 35, 6 (1990), 317-323.
The values returned by diff:edit-length can be used to gauge
the degree of match between two sequences.
diff:edits and diff:longest-common-subsequence combine
the algorithm with the divide-and-conquer method outlined in:
E. Myers, and W. Miller, "Optimal alignments in linear space", Computer Application in the Biosciences (CABIOS), 4(1):11-17, 1988.
If the items being sequenced are text lines, then the computed edit-list is equivalent to the output of the diff utility program. If the items being sequenced are words, then it is like the lesser known spiff program.
The non-negative integer p-lim, if provided, is maximum number of
deletions of the shorter sequence to allow. diff:longest-common-subsequence will return #f
if more deletions would be necessary.
diff:longest-common-subsequence returns a one-dimensional array of length (quotient (- (+
len1 len2) (diff:edit-length array1 array2)) 2) holding the longest sequence
common to both arrays.
The non-negative integer p-lim, if provided, is maximum number of
deletions of the shorter sequence to allow. diff:edits will return #f
if more deletions would be necessary.
diff:edits returns a vector of length (diff:edit-length array1 array2) composed
of a shortest sequence of edits transformaing array1 to array2.
Each edit is an integer:
(array-ref array1 (+ -1 j)) into the sequence.
(array-ref array2 (- -1 k)) from the sequence.
The non-negative integer p-lim, if provided, is maximum number of
deletions of the shorter sequence to allow. diff:edit-length will return #f
if more deletions would be necessary.
diff:edit-length returns the length of the shortest sequence of edits transformaing
array1 to array2.
(diff:longest-common-subsequence "fghiejcklm" "fgehijkpqrlm")
=> "fghijklm"
(diff:edit-length "fghiejcklm" "fgehijkpqrlm")
=> 6
(diff:edits "fghiejcklm" "fgehijkpqrlm")
=> #A:fixZ32b(3 -5 -7 8 9 10)
; e c h p q r
Anything that doesn't fall neatly into any of the other categories winds up here.
Returns a symbol name for the type of obj.
Converts and returns obj of type char, number,
string, symbol, list, or vector to
result-type (which must be one of these symbols).
read.
StudlyCapsExpand returns a
copy of str where delimiter is inserted between each
lower-case character immediately followed by an upper-case character;
and between two upper-case characters immediately followed by a
lower-case character.
(StudlyCapsExpand "aX" " ") => "a X" (StudlyCapsExpand "aX" "..") => "a..X" (StudlyCapsExpand "AX") => "AX" (StudlyCapsExpand "Ax") => "Ax" (StudlyCapsExpand "AXLE") => "AXLE" (StudlyCapsExpand "aAXACz") => "a-AXA-Cz" (StudlyCapsExpand "AaXACz") => "Aa-XA-Cz" (StudlyCapsExpand "AAaXACz") => "A-Aa-XA-Cz" (StudlyCapsExpand "AAaXAC") => "A-Aa-XAC"
current-input-port.
#f is returned. The port argument may be
omitted, in which case it defaults to the value returned by
current-input-port.
current-input-port.
system->line calls system with command as argument,
redirecting stdout to file tmp. system->line returns a string containing the
first line of output from tmp.
system->line is intended to be a portable method for getting one-line results
from programs like pwd, whoami, hostname,
which, identify, and cksum. Its behavior when
called with programs which generate lots of output is unspecified.
This module implements asynchronous (non-polled) time-sliced
multi-processing in the SCM Scheme implementation using procedures
alarm and alarm-interrupt.
Until this is ported to another implementation, consider it an example
of writing schedulers in Scheme.
process:queue. The
value returned is unspecified. The argument to proc should be
ignored. If proc returns, the process is killed.
process:queue and runs the next
process from process:queue. The value returned is
unspecified.
process:queue. If there are no more processes on
process:queue, (slib:exit) is called (see section System).
http://swiss.csail.mit.edu/~jaffer/MIXF
Metric Interchange Format is a character string encoding for numerical values and units which:
In the expression for the value of a quantity, the unit symbol is placed after the numerical value. A dot (PERIOD, `.') is placed between the numerical value and the unit symbol.
Within a compound unit, each of the base and derived symbols can optionally have an attached SI prefix.
Unit symbols form