On day 16 of the Advent of Code, I make use of a priority queue for Dijkstra's algorithm. I ported Stephen Adams's weight-balanced binary tree implementation from MIT Scheme to Common Lisp. Stephen Adams's implementation (and therefore my port of it) has the MIT license. Weight-balanced binary trees are a way to implement key-value maps with these properties:
- The trees are immutable. This means that when you add or remove a key, you get a new tree with the change. The old tree is unchanged. This makes the trees easier to reason about and suitable for functional programming. For example, you can iterate over the tree without having to worry about mutating the tree during the iteration.
- Most operations on the tree, and insertion, lookup, and deletion in particular, are O(log n). While theoretically not as fast as a hash table, n has to be quite large before log n becomes a big factor. In practice, a weight balanced binary tree is competitive with a hash table for any reasonably sized table.
- Weight-balanced binary trees support set operations such as union, intersection, and difference. These operations run in O(log n) time as well.
- Keys are stored in sorted order. This makes it easy to iterate from smallest to largest key (or in the direction).
But it occurred to me that I wanted a unified abstract interface to
all the various table-like data structures that Common Lisp
provides. You should be able to call a
generic table/lookup
on a property list, association
list, hash table, or weight-balanced binary tree and have it do the
right thing. I wrote a simple table package that provides this.
https://github.com/jrm-code-project/table
The package is documented in the `README.md` fie.
No comments:
Post a Comment