2.61 Exercise 2.61
The new adjoin-set does not examine the given set at all if the element is smaller than or equal to its first element. In these cases, we know that the resulting set is either the cons of the element and the set or just the set, respectively. If the element is larger than the first element of the set, then it does need to traverse to the next element until one of the cases above is true (or until the set is empty, in which case a new set just containing the element is returned).
(define (adjoin-set x set) (if (null? set) (list x) (let ((y (car set))) (cond ((= x y) set) ((< x y) (cons x set)) (else (cons y (adjoin-set x (cdr set))))))))
Note that we need to have a null? check in adjoin-set now, because of the operations requiring that set to not be empty. Before, when consing the element and the set, it didn’t matter if the set was empty – and element-of-set?| didn’t care either.
Since we can expect that, on average, elements added to a set will be in the middle of the set, we can expect about half as many recursive calls to adjoin-set as we did previously.