Sets Without Replacement
December 18, 2019
Sets without replacement are easily implemented as two sets, one for the current elements and one for deleted elements. For simplicity, we implement sets as lists; you could use hash tables or binary trees if you prefer, or abstract sets from a previous exercise:
(define s (list)) ; set of current items (define t (list)) ; tombstones of deleted items
(define (add s x) ; add x to set s (if (member x s) (error 'add "can't add already existent element") (if (member x t) (error 'add "can't add previously existent element") (begin (set! s (cons x s)) s))))
(define (del s x) ; remove x from set s (if (not (member x s)) (error 'del "can't delete non-existent element") (begin (set! s (remove x s)) (set! t (cons x t)) s)))
Here are some examples:
> (set! s (add s 1)) > (set! s (add s 3)) > (set! s (add s 5)) > (set! s (add s 3)) Exception in add: can't add already existent element > (set! s (del s 3)) > (set! s (add s 3)) Exception in add: can't add previously existent element > (set! s (del s 4)) Exception in del: can't delete non-existent element > s (5 1) > t (3)
You can run the program at https://ideone.com/0wwfjN.
Quick perl class… keep everything in the single hash – key of each element is the value, the value of each element is true or false dependent on whether it has been deleted or not…. Use overload ‘””‘ to just dump the contents of the set…
I’ve added it to code pad http://codepad.org/qY5FDiGn so you can see it in operation.
Here’s a solution in Python.
Output: