(defn conj
"Returns a vector-set generated by inserting `x` into the appropriate position
in the sorted, distinct vector-set `vset`. The invariant is that if `vset` is
sorted and contains distinct elements, the return value will contain `x` and
also be sorted.
Attempting to insert an element `x` already contained in `vset` throws an
exception."
[vset x]
(cond (empty? vset) [x]
(< x (nth vset 0)) (into [x] vset)
(> x (peek vset)) (core/conj vset x)
:else
(loop [i (long 0)
r (transient [])]
(let [xi (nth vset i nil)]
(cond (not xi) (persistent! (conj! r x))
(< x xi) (into (persistent! (conj! r x))
(subvec vset i))
(= x xi)
(u/illegal (str "elem " x "already present in " vset))
:else (recur (inc i) (conj! r xi)))))))