docs/data-structures.md
Unmodified engine source document, commit af8e0b5f6d97ab379337d3539fd8dbe0d6337fd8. Markdown source is displayed as text to preserve exact content.
# Vectors, hash tables and the sequence library (M40)
M40 gives programs somewhere to keep data other than lists: vectors (with fill pointers) and
hash tables, and one sequence library that treats lists, strings and vectors alike. It also
makes malformed keyword lists catchable. The design is
[ADR 0028](decisions/0028-vectors-hash-tables-and-the-sequence-library.md); lists and the
earlier sequence functions are in [lists and sequences](list-sequences.md) and strings in
[text and data processing](text-data.md) and [text composition](text-composition.md).
## Quick start
```lisp
(defvar *seen* (make-hash-table :test 'equal))
(dolist (w '("a" "b" "a" "c" "a"))
(incf (gethash w *seen* 0))) ; (gethash "a" *seen*) => 3, T
(let ((v (make-array 0 :fill-pointer 0 :adjustable t)))
(dotimes (i 5) (vector-push-extend (* i i) v))
(list v (length v) (reduce #'+ v))) ; => (#(0 1 4 9 16) 5 30)
(remove-if #'oddp #(1 2 3 4)) ; => #(2 4)
(position #\n "banana" :from-end t) ; => 4
(sort (vector 3 1 2) #'<) ; => #(1 2 3), and the vector itself is now sorted
(map 'list #'+ '(1 2 3) #(10 20 30)) ; => (11 22 33)
```
## Which operators, and where they live
| Operators | Where |
|---|---|
| `VECTOR` `MAKE-ARRAY` `AREF` `SVREF` `VECTORP` `ARRAYP` `SIMPLE-VECTOR-P` `FILL-POINTER` `ARRAY-HAS-FILL-POINTER-P` `ADJUSTABLE-ARRAY-P` `ARRAY-TOTAL-SIZE` `ARRAY-DIMENSION` `ARRAY-DIMENSIONS` `ARRAY-RANK` `VECTOR-PUSH` `VECTOR-PUSH-EXTEND` `VECTOR-POP` `ADJUST-ARRAY` | Rust (`src/vector.rs`) |
| `MAKE-HASH-TABLE` `GETHASH` `REMHASH` `CLRHASH` `MAPHASH` `HASH-TABLE-P` `HASH-TABLE-COUNT` `HASH-TABLE-TEST` `EQUALP` `SXHASH` | Rust (`src/hashtable.rs`) |
| `FIND` `FIND-IF` `FIND-IF-NOT` `POSITION` `POSITION-IF` `POSITION-IF-NOT` `COUNT` `COUNT-IF` `COUNT-IF-NOT` `REMOVE` `REMOVE-IF` `REMOVE-IF-NOT` `DELETE` `DELETE-IF` `DELETE-IF-NOT` `SUBSTITUTE` `SUBSTITUTE-IF` `SUBSTITUTE-IF-NOT` `REMOVE-DUPLICATES` `DELETE-DUPLICATES` `REVERSE` `NREVERSE` `COPY-SEQ` `FILL` `REPLACE` `SEARCH` `MISMATCH` `MAP` `EVERY` `SOME` `NOTANY` `NOTEVERY` | Rust (`src/sequence.rs`) |
| `SUBSEQ` `LENGTH` `ELT` `COERCE` `CONCATENATE` `MAKE-STRING` | Rust, extended to vectors |
| `SORT` `STABLE-SORT` `REDUCE` | Layer 0 Lisp, extended to vectors |
| `(SETF (AREF ...))` and the other new places | evaluator (`src/place.rs`) |
All the Rust operators are in the bare kernel and protected from `DEFUN`. `REVERSE`, `REMOVE`,
`POSITION` and `SEARCH` used to be redefinable Lisp; they are protected now.
## Vectors
A vector is a one-dimensional array of any objects. Write one as `#(1 2 3)` (it evaluates to
itself and prints the same way), with `(vector ...)`, or with `MAKE-ARRAY`:
```lisp
(make-array 3) ; => #(0 0 0) (unspecified in Common Lisp; SBCL fills with 0)
(make-array 3 :initial-element 'x) ; => #(X X X)
(make-array 3 :initial-contents '(a b c)) ; => #(A B C)
(make-array '(3)) ; a list of one dimension is accepted
(make-array 5 :fill-pointer 0) ; active length 0, total size 5
(make-array 2 :fill-pointer 0 :adjustable t)
```
* **Fill pointer.** With a fill pointer, `LENGTH` and every sequence function see only the
active elements; `AREF` still reaches the whole array. `VECTOR-PUSH` stores at the fill
pointer and returns the old index, or `NIL` when full; `VECTOR-PUSH-EXTEND` grows the array
(at least doubling, or by its third argument) and keeps the vector's identity;
`VECTOR-POP` returns the last active element. `(setf (fill-pointer v) n)` works for
`n` up to the total size. `ADJUST-ARRAY` resizes an adjustable vector in place; any other
vector gets an adjustable copy.
* **Strings are not vectors here** (they are in Common Lisp): `(vectorp "abc")` and
`(arrayp "abc")` are true, `(aref "abc" 1)` works, and every sequence function accepts a
string, but `SVREF` and `SIMPLE-VECTOR-P` refuse it and nothing can be stored into a string.
* **Limits.** At most 16 Mi (16,777,216) elements; larger `MAKE-ARRAY`, `VECTOR-PUSH-EXTEND`,
`ADJUST-ARRAY` and `CONCATENATE` requests are a type error.
* **Not supported:** multi-dimensional arrays (`(make-array '(2 3))`), `#2A(...)` and `#*101`
syntax, `#3(a)`, displaced arrays, specialised element types (an `:ELEMENT-TYPE` is accepted
and ignored, except character types, which are `NotImplemented`), `BIT`, `VECTOR-PUSH` on a
vector without a fill pointer (a type error), `ARRAY-ROW-MAJOR-INDEX` and friends.
## Hash tables
```lisp
(let ((h (make-hash-table :test 'equal)))
(setf (gethash "one" h) 1)
(gethash "one" h) ; => 1, T (two values: value and whether present)
(gethash "two" h 0) ; => 0, NIL
(incf (gethash "one" h)) ; (setf, incf, decf and push work on GETHASH)
(maphash (lambda (k v) (print (list k v))) h)
(remhash "one" h) ; => T
(hash-table-count h)) ; => 0
```
* **Tests.** `EQ`, `EQL` (the default), `EQUAL` and `EQUALP`, given as a symbol (`'equal`)
or the function (`#'equal`). `EQUAL` compares strings by content and conses structurally;
`EQUALP` is also case-insensitive for strings and characters and compares vectors element
by element. No user-written test functions and no weak tables.
* **Order.** `MAPHASH` visits entries in the order they were first stored (Common Lisp leaves it
open; do not depend on it). The function may `REMHASH` or `SETF` the current key; entries it
adds are not visited.
This also holds across insertion-time compaction, `CLRHASH` and nested
`MAPHASH` calls: active walks keep their entry indices until they finish,
including when a callback leaves by an error or non-local transfer.
* **Keys.** As in Common Lisp, changing a key that is a cons or vector after storing it
under `EQUAL`/`EQUALP` makes the entry unreachable. A circular key is an error when it has
to be compared, never a hang. At most 16 Mi entries.
* **Printing.** `#<HASH-TABLE :TEST EQUAL :COUNT 3>`; it is not readable.
* `MAKE-HASH-TABLE` accepts `:TEST`, `:SIZE`, `:REHASH-SIZE`, `:REHASH-THRESHOLD` and
`:SYNCHRONIZED` (the last four only checked for being keywords, not used) and `:WEAKNESS NIL`.
* `(sxhash x)` is a nonnegative integer that is equal for `EQUAL` objects.
## The sequence library
Every function here takes a list, a string or a vector. The result of `REMOVE`, `SUBSTITUTE`,
`REVERSE`, `SUBSEQ`... is a new object of the argument's kind (a vector result is a simple
vector, even when the argument had a fill pointer); `FIND`, `POSITION`, `COUNT`, `SEARCH` and
`MISMATCH` return elements or indices.
| Function | Keywords | Notes |
|---|---|---|
| `FIND item sequence` and `-IF`, `-IF-NOT` (`predicate sequence`) | `:key :test :test-not :start :end :from-end` (`-IF`: no test) | returns the original element |
| `POSITION`, `-IF`, `-IF-NOT` | same | index into the whole sequence |
| `COUNT`, `-IF`, `-IF-NOT` | same | |
| `REMOVE`, `-IF`, `-IF-NOT`, `DELETE`... | plus `:count` | `:from-end` chooses which matches the count removes |
| `SUBSTITUTE new old sequence`, `-IF`, `-IF-NOT` | same as `REMOVE` | |
| `REMOVE-DUPLICATES`, `DELETE-DUPLICATES` | `:key :test :test-not :start :end :from-end` | keeps the last occurrence, or the first with `:from-end` |
| `SEARCH seq1 seq2` | `:from-end :test :test-not :key :start1 :end1 :start2 :end2` | index in `seq2` |
| `MISMATCH seq1 seq2` | same | index in `seq1`, `NIL` when equal |
| `REVERSE` `COPY-SEQ` `SUBSEQ` | | |
| `NREVERSE` | | reverses a list's elements in place (the argument still names its first cons) and a vector in place |
| `FILL seq item`, `REPLACE seq1 seq2` | `:start :end`, `:start1 :end1 :start2 :end2` | lists and vectors only |
| `MAP result-type fn seq...` | | result type `NIL`, `LIST`, `VECTOR`, `SIMPLE-VECTOR`, `STRING` |
| `EVERY` `SOME` `NOTANY` `NOTEVERY pred seq...` | | stop at the shortest sequence |
| `CONCATENATE type seq...` | | `LIST`, `VECTOR`, `STRING` |
| `COERCE seq type` | | `LIST`, `VECTOR`, `SIMPLE-VECTOR`, `STRING` |
| `REDUCE`, `SORT`, `STABLE-SORT` | as before | `SORT` of a vector sorts it in place and returns it |
Rules that apply to all of them:
* The sequence is read once, before any of your functions run (a copy of the elements), so a test,
key or predicate that changes the list or vector cannot confuse the search; it only affects
what later calls see. A dotted or circular list is therefore a type error, with one exception kept from
M17: `FIND`, `FIND-IF`, `FIND-IF-NOT`, `POSITION`, `POSITION-IF` and `POSITION-IF-NOT` on a list with no
`:start`, `:end` or `:from-end` walk lazily and stop at the first match, so `(find 'a '(a . b))` is `A`
(and a circular list is fine if the item is found before the cycle repeats).
* The comparison is `(funcall test item (funcall key element))`, default `EQL`; for `-IF` it is
`(funcall predicate (funcall key element))`. `NIL` for `:test`, `:test-not` or `:key` means
"not given"; when a keyword is repeated the leftmost wins; `:test` together with `:test-not`
is an error. `:end NIL` means the end.
* `DELETE` and `DELETE-DUPLICATES` do **not** modify their argument (Common Lisp allows it);
use the result.
* Bounds outside the sequence, a non-integer count and a non-sequence are type errors; an
unknown keyword, an odd keyword list or a keyword without a value is an error that
`HANDLER-CASE` takes (see below).
## Errors in arguments are conditions now
A keyword list that is odd, names an unknown keyword (without `:allow-other-keys`), or gives
`:test` with `:test-not` used to be an uncatchable `InvalidSyntax`. It is now an ordinary `ERROR`:
```lisp
(handler-case (find 1 '(1 2) :bogus 3)
(error () :caught)) ; => :CAUGHT
(handler-case (funcall (lambda (&key a) a) :b 1)
(error () :caught)) ; => :CAUGHT (for functions you define as well)
```
Unhandled, the error is exactly what it was. Syntax errors in program text (`(if 1 . 2)`, a
malformed lambda list) are still not conditions.
## More places
`SETF`, `INCF`, `DECF` and `PUSH` work on `(aref v i)`, `(svref v i)`, `(elt s i)`, `(nth n list)`,
`(gethash key table [default])` and `(fill-pointer v)`, as well as `CAR`, `CDR` and variables.
`(setf (nth n list) x)` needs a list with more than `n` elements; `(setf (elt string i) x)` is
`NotImplemented` (strings cannot be modified).
## Differences from Common Lisp
* No multi-dimensional arrays, displaced arrays, bit vectors or specialised element types.
* Strings are separate objects and read-only; `MAKE-ARRAY` with a character element type is
`NotImplemented`. `(make-string n)` builds a string of `#\Nul`s (or `:initial-element`).
* `DELETE`, `DELETE-DUPLICATES` and `SORT` of lists/strings never modify their argument.
* No `MERGE`, `MAPC`-like iteration over vectors, `LOOP` clauses for vectors or hash tables,
`WITH-HASH-TABLE-ITERATOR`, `HASH-TABLE-KEYS`, `NSUBSTITUTE`, `FIND`/`POSITION` `:test` called
on non-sequences, `PROCLAIM` types.
* Hash table iteration order and `SXHASH` values are RustLisp's own.
## Examples
`examples/data/wordfreq.lisp` (word frequencies with an `EQUAL` table and a histogram vector) and
`examples/data/links.lisp` (breadth-first search over a hash-table graph with a vector queue)
are portable Common Lisp; their output is identical under SBCL. Both read standard input:
```
rustlisp --script examples/data/wordfreq.lisp < examples/data/essay.txt
rustlisp --script examples/data/links.lisp home < examples/data/links.txt
```
MediaLisp