5.9  Unit: extras

This unit contains a collection of useful utility definitions.

5.9.1  Lists

[procedure] (butlast LIST)
Returns a fresh list with all elements but the last of LIST.

[procedure] (chop LIST N)
Returns a new list of sublists, where each sublist contains N elements of LIST. If LIST has a length that is not a multiple of N, then the last sublist contains the remaining elements.

(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))
(chop '(a b c d) 3)     ==> ((a b c) (d))

[procedure] (compress BLIST LIST)
Returns a new list with elements taken from LIST with corresponding true values in the list BLIST.

(define nums '(99 100 110 401 1234))
(compress (map odd? nums) nums)      ==> (99 401)

[procedure] (flatten LIST1 ...)
Returns LIST1 ... concatenated together, with nested lists removed (flattened).

[procedure] (intersperse LIST X)
Returns a new list with X placed between each element.

[procedure] (join LISTOFLISTS [LIST])
Concatenates the lists in LISTOFLISTS with LIST placed between each sublist. LIST defaults to the empty list.

(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)
(join '((p q) () (r (s) t)) '(-))  ==> (p q - - r (s) t)

join could be implemented as follows:

(define (join lstoflsts . lst)
  (apply append (intersperse lstoflists (:optional lst '()))) )

[procedure] (tail? X LIST)
Returns true if X is one of the tails (cdr's) of LIST.

5.9.2  String-port extensions

[procedure] (call-with-input-string STRING PROC)
Calls the procedure PROC with a single argument that is a string-input-port with the contents of STRING.

[procedure] (call-with-output-string PROC)
Calls the procedure PROC with a single argument that is a string-output-port. Returns the accumulated output-string.

[procedure] (with-input-from-string STRING THUNK)
Call procedure THUNK with the current input-port temporarily bound to an input-string-port with the contents of STRING.

[procedure] (with-output-to-string THUNK)
Call procedure THUNK with the current output-port temporarily bound to a string-output-port and return the accumulated output string.

5.9.3  Formatted output

[procedure] (fprintf PORT FORMATSTRING ARG ...)
[procedure] (printf FORMATSTRING ARG)
[procedure] (sprintf FORMATSTRING ARG ...)
Simple formatted output to a given port (fprintf), the value of (current-output-port) (printf) or a string (sprintf). The FORMATSTRING can contain any sequence of characters. The character '~' prefixes special formatting directives:

~%write newline character
~Swrite the next argument
~Adisplay the next argument
~nskip all whitespace in the format-string until the next non-whitespace character
~Bwrite the next argument as a binary number
~Owrite the next argument as an octal number
~Xwrite the next argument as a hexadecimal number
~Cwrite the next argument as a character
~~ display ' '
~!flush all pending output
~?invoke formatted output routine recursively with the next two arguments as format-string and list of parameters

For more powerful output formatting, see the section about the format unit.

5.9.4  Hash tables

[procedure] (clear-hash-table! HASH-TABLE)
Erases all entries in the hash-table HASH-TABLE.

[procedure] (get HASH-TABLE KEY PROP)
Returns the value of property PROP of the item KEY in HASH-TABLE . This facility can be used as a kind of ``disembodied'' property-list. If no entry named KEY is stored in the hash-table or if no property PROP for that key exists, #f is returned.

[procedure] (hash-table? X)
Returns #t if the argument is a hash-table.

[procedure] (hash-table->list HASH-TABLE)
Converts HASH-TABLE into an association-list.

[procedure] (hash-table-count HASH-TABLE)
Returns the number of entries in the given hash-table.

[procedure] (hash-table-size HASH-TABLE)
Returns the size of the hash-table.

[procedure] (hash-table-for-each PROC HASH-TABLE)
Calls PROC which should expect two arguments. This procedure is called for each entry in the hash-table with the key and the value as parameters.

[procedure] (hash-table-ref HASH-TABLE KEY [DEFAULT])
Returns the entry in the given hash-table under KEY. If no entry is stored in the table, #f is returned.

[procedure] (hash-table-remove! HASH-TABLE KEY)
Removes an entry in the given hash-table.

[procedure] (hash-table-set! HASH-TABLE KEY VALUE)
Adds or changes an entry in the given hash-table.

[procedure] (make-hash-table [PRED [SIZE]])
Creates and returns a hash-table with keys compared via PRED, which defaults to eq?. If SIZE is provided it specifies the initial size of the hash-table. If the hash-table fills above a certain size it is automatically resized to accommodate more entries.

[procedure] (put! HASH-TABLE KEY PROP VALUE)
Stores VALUE as property PROP under the item KEY in the given hash-table. Any previously existing value is overwritten.

5.9.5  Queues

[procedure] (list->queue LIST)
Returns LIST converted into a queue, where the first element of the list is the same as the first element of the queue. The resulting queue may share memory with the list and the list should not be modified after this operation.

[procedure] (make-queue)
Returns a newly created queue.

[procedure] (queue? X)
Returns #t if X is a queue, or #f otherwise.

[procedure] (queue->list QUEUE)
Returns QUEUE converted into a list, where the first element of the list is the same as the first element of the queue. The resulting list may share memory with the queue object and should not be modified.

[procedure] (queue-add! QUEUE X)
Adds X to the rear of QUEUE.

[procedure] (queue-empty? QUEUE)
Returns #t if QUEUE is empty, or #f otherwise.

[procedure] (queue-first QUEUE)
Returns the first element of QUEUE. If QUEUE is empty an error is signaled

[procedure] (queue-last QUEUE)
Returns the last element of QUEUE. If QUEUE is empty an error is signaled

[procedure] (queue-remove! QUEUE)
Removes and returns the first element of QUEUE. If QUEUE is empty an error is signaled

5.9.6  Sorting

[procedure] (merge LIST1 LIST2 LESS?)
[procedure] (merge! LIST1 LIST2 LESS?)
Joins two lists in sorted order. merge! is the destructive version of merge. LESS? should be a procedure of two arguments, that returns true if the first argument is to be ordered before the second argument.

[procedure] (sort SEQUENCE LESS?)
[procedure] (sort! SEQUENCE LESS?)
Sort SEQUENCE, which should be a list or a vector. sort! is the destructive version of sort.

[procedure] (sorted? SEQUENCE LESS?)
Returns true if the list or vector SEQUENCE is already sorted.

5.9.7  Random numbers

[procedure] (random N)
Returns an exact random integer from 0 to N-1.

[procedure] (randomize [X])
Set random-number seed. If X is not supplied, the current time is used.

5.9.8  Input/Output extensions

[procedure] (make-input-port READ READY? CLOSE [PEEK])
Returns a custom input port. Common operations on this port are handled by the given parameters, which should be procedures of no arguments. READ is called when the next character is to be read and should return a character or the value of (end-of-file). READY? is called when char-ready? is called on this port and should return #t or #f. CLOSE is called when the port is closed. PEEK is called when peek-char is called on this port and should return a character or the value of (end-of-file). if the argument PEEK is not given, then READ is used instead and the created port object handles peeking automatically (by calling READ and buffering the character).

[procedure] (make-output-port WRITE CLOSE [FLUSH])
Returns a custom output port. Common operations on this port are handled by the given parameters, which should be procedures. WRITE is called when output is sent to the port and receives a single argument, a string. CLOSE is called when the port is closed and should be a procedure of no arguments. FLUSH (if provided) is called for flushing the output port.

[procedure] (pretty-print EXP [PORT])
[procedure] (pp EXP [PORT])
Print expression nicely formatted. PORT defaults to the value of (current-output-port).

[parameter] pretty-print-width
Specifies the maximal line-width for pretty printing, after which line wrap will occur.

[procedure] (read-file [PORT])
Returns a list containing all toplevel expressions read from PORT, which defaults to the value of (current-input-port).

[procedure] (read-line [PORT [LIMIT]])
[procedure] (write-line STRING [PORT])
Line-input and -output. PORT defaults to the value of (current-input-port) and (current-output-port), respectively. if the optional argument LIMIT is given and not #f, then read-line reads at most LIMIT characters per line.

[procedure] (read-lines [PORT [MAX]])
Read MAX or fewer lines from PORT. PORT defaults to the value of (current-input-port).

[procedure] (read-string [NUM [PORT]])
[procedure] (write-string STRING [NUM [PORT]]
Read or write NUM characters from/to PORT, which defaults to the value of (current-input-port) or (current-output-port), respectively. If NUM is #f or not given, then all data up to the end-of-file is read, or, in the case of write-string the whole string is written. If no more input is available, read-string returns the empty string.

[procedure] (with-error-output-to-port PORT THUNK)
Call procedure THUNK with the current error output-port temporarily bound to PORT.

[procedure] (with-input-from-port PORT THUNK)
Call procedure THUNK with the current input-port temporarily bound to PORT.

[procedure] (with-output-to-port PORT THUNK)
Call procedure THUNK with the current output-port temporarily bound to PORT.

5.9.9  Strings

[procedure] (->string X)
Returns a string-representation of X.

[procedure] (string-compare3 STRING1 STRING2)
[procedure] (string-compare3-ci STRING1 STRING2)
Perform a three-way comparison between the STRING1 and STRING2, returning either -1 if STRING1 is lexicographically less than STRING2, 0 if it is equal, or 1 if it s greater. string-compare3-ci performs a case-insensitive comparison.

[procedure] (string-intersperse LIST STRING)
Returns a string that contains all strings in LIST concatenated together. STRING is placed between each concatenated string.

(string-intersperse '("one" "two") "three")

is equivalent to

(apply string-append (intersperse '("one" "two") "three"))

[procedure] (string-split STRING [DELIMITER-STRING [KEEPEMPTY]])
Split string into substrings separated by the given delimiters. If no delimiters are specified, a string comprising the tab, newline and space characters is assumed. If the parameter KEEPEMPTY is given and not #f, then empty substrings are retained:

(string-split "one  two  three") ==> ("one" "two" "three")
(string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "")

[procedure] (string-translate STRING FROM [TO])
Returns a fresh copy of STRING with characters matching FROM translated to TO. If TO is omitted, then matching characters are removed. FROM and TO may be a character, a string or a list. If both FROM and TO are strings, then the character at the same position in TO as the matching character in FROM is substituted.

[procedure] (string-translate* STRING SMAP)
Substitutes elements of STRING according to SMAP. SMAP should be an association-list where each element of the list is a pair of the form (MATCH REPLACEMENT). Every occurrence of the string MATCH in STRING will be replaced by the string REPLACEMENT:

(string-translate*
  "<h1>this is a \"string\"</h1>"
  '(("<" . "&lt:") (">" . "&gt;") ("\"" . "&quot;")) )

==>  "&lt;h1&gt;this is a &quot;string&quot;&lt;/ht&gt;"

[procedure] (substring=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
[procedure] (substring-ci=? STRING1 STRING2 [START1 [START2 [LENGTH]]])
Returns #t if the strings STRING1 and STRING2 are equal, or #f otherwise. The comparison starts at the positions START1 and START2 (which default to 0), comparing LENGTH characters (which defaults to the minimum of the remaining length of both strings).

[procedure] (substring-index WHICH WHERE [START])
[procedure] (substring-index-ci WHICH WHERE [START])
Searches for first index in string WHERE where string WHICH occurs. If the optional argument START is given, then the search starts at that index. substring-index-ci is a case-insensitive version of substring-index.

5.9.10  Combinators

[procedure] (constantly X ...)
Returns a procedure that always returns the values X ... regardless of the number and value of its arguments.

(constantly X) <=> (lambda args X)

[procedure] (complement PROC)
Returns a procedure that returns the boolean inverse of PROC.
(complement PROC) <=> (lambda (x) (not (PROC x)))

[procedure] (compose PROC1 PROC2 ...)
Returns a procedure that represents the composition of the argument-procedures PROC1 PROC2 ....

(compose F G) <=> (lambda args (call-with-values (lambda () (apply G args)) F))

[procedure] (conjoin PRED ...)
Returns a procedure that returns #t if its argument satisfies the predicates PRED ....
((conjoin odd? positive?) 33)   ==>  #t
((conjoin odd? positive?) -33)  ==>  #f

[procedure] (disjoin PRED ...)
Returns a procedure that returns #t if its argument satisfies any predicate PRED ....
((disjoin odd? positive?) 32)    ==>  #t
((disjoin odd? positive?) -32)   ==>  #f

[procedure] (flip PROC)
Returns a two-argument procedure that calls PROC with its arguments swapped:
(flip PROC) <=> (lambda (x y) (PROC y x))

[procedure] (identity X)
Returns its sole argument X.

[procedure] (project N)
Returns a procedure that returns its Nth argument.

[procedure] (list-of PRED)
Returns a procedure of one argument that returns #t when applied to a list of elements that all satisfy the predicate procedure PRED, or #f otherwise.

((list-of even?) '(1 2 3))   ==> #f
((list-of number?) '(1 2 3)) ==> #t

5.9.11  Binary searching

[procedure] (binary-search SEQUENCE PROC)
Performs a binary search in SEQUENCE, which should be a sorted list or vector. PROC is called to compare items in the sequence, should accept a single argument and return an exact integer: zero if the searched value is equal to the current item, negative if the searched value is ``less'' than the current item, and positive otherwise.