## 6.10 Unit: extras

This unit contains a collection of useful utility definitions.

### 6.10.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`.

### 6.10.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.

### 6.10.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
  ~S | write the next argument
  ~A | display the next argument
  ~n | skip all whitespace in the format-string until the next non-whitespace
  character ~B | write the next argument as a binary number
  ~O | write the next argument as an octal number
  ~X | write the next argument as a hexadecimal number
  ~C | write 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.

### 6.10.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-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.

### 6.10.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

### 6.10.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.

### 6.10.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.

### 6.10.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])
  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])
  Read `NUM` characters from `PORT`, which defaults to the value of `(current-input-port)`. The characters are returned as a string of length `NUM` or less, if the port contains fewer than `NUM` characters. If `NUM` is `#f`, then all data up to the end-of-file is read.

[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`.

### 6.10.9 Strings

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

[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] (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`.

### 6.10.10 Miscellaneous

[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.

[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] (flip PROC)
  Returns a two-argument procedure that calls `PROC` with its arguments swapped:

      (flip PROC) <=> (lambda (x y) (PROC y x))

[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