(insert a x) adds the element
This is the fundamental set constructor. It is similar to cons for lists, but of course performs an ordered insertion. It respects the non-set convention and treats any ill-formed input as the empty set.
Efficiency note. Insert is
The :exec version just inlines the set primitives and does one level of loop unrolling. On CCL, it runs about 1.65x faster than the :logic version on the following loop:
;; 1.92 seconds :logic, 1.16 seconds :exec (let ((acc nil)) (gc$) (time$ (loop for i fixnum from 1 to 10000 do (setq acc (set::insert i acc)))))
Function:
(defun insert (a x) (declare (xargs :guard (setp x))) (mbe :logic (cond ((emptyp x) (list a)) ((equal (head x) a) x) ((<< a (head x)) (cons a x)) (t (cons (head x) (insert a (tail x))))) :exec (cond ((null x) (cons a nil)) ((equal (car x) a) x) ((fast-lexorder a (car x)) (cons a x)) ((null (cdr x)) (cons (car x) (cons a nil))) ((equal (cadr x) a) x) ((fast-lexorder a (cadr x)) (cons (car x) (cons a (cdr x)))) (t (cons (car x) (cons (cadr x) (insert a (cddr x))))))))
Theorem:
(defthm insert-produces-set (setp (insert a x)))
Theorem:
(defthm insert-sfix-cancel (equal (insert a (sfix x)) (insert a x)))
Theorem:
(defthm insert-never-empty (not (emptyp (insert a x))))
Theorem:
(defthm insert-when-emptyp (implies (and (syntaxp (not (equal x ''nil))) (emptyp x)) (equal (insert a x) (insert a nil))))
Theorem:
(defthm head-of-insert-a-nil (equal (head (insert a nil)) a))
Theorem:
(defthm tail-of-insert-a-nil (equal (tail (insert a nil)) nil))
Theorem:
(defthm head-insert (equal (head (insert a x)) (cond ((emptyp x) a) ((<< a (head x)) a) (t (head x)))))
Theorem:
(defthm tail-insert (equal (tail (insert a x)) (cond ((emptyp x) nil) ((<< a (head x)) x) ((equal a (head x)) (tail x)) (t (insert a (tail x))))))
Theorem:
(defthm repeated-insert (equal (insert a (insert a x)) (insert a x)))
Theorem:
(defthm insert-insert (equal (insert a (insert b x)) (insert b (insert a x))) :rule-classes ((:rewrite :loop-stopper ((a b)))))
Theorem:
(defthm insert-head (implies (not (emptyp x)) (equal (insert (head x) x) x)))
Theorem:
(defthm insert-head-tail (implies (not (emptyp x)) (equal (insert (head x) (tail x)) x)))
Theorem:
(defthm insert-induction-case (implies (and (not (<< a (head x))) (not (equal a (head x))) (not (emptyp x))) (equal (insert (head x) (insert a (tail x))) (insert a x))))
Theorem:
(defthm insert-identity (implies (in a x) (equal (insert a x) x)))
Theorem:
(defthm in-insert (equal (in a (insert b x)) (or (in a x) (equal a b))))