Solution to the table deletion problem; all code up to the delete! code taken directly from SICP.
(define (make-table)
(cons '* ()))
(define (empty-table? t) (null? (cdr t)))
(define (insert! key value table)
(let ((record (assoc key (cdr table))))
(if record
(set-cdr! record value)
(set-cdr! table
(cons (cons key value) (cdr table)))))
'ok)
(define (lookup k t)
(let ((record (assoc k (cdr t))))
(cond (record (cdr record))
(else #f))))
; R5RS in DrRacket does not let you redefine the primitive procedure assoc.
; It has been commented out so as not to produce an error, but what you
; see below is how it would be written if it were not a primitive.
;
; Note that assoc is used in insert!, lookup, and the solution to delete!
; without error.
;
; (define (assoc key records)
; (cond ((null? records) #f)
; ((equal? key (caar records)) (car records))
; (else (assoc key (cdr records)))))
(define (rlookup k t)
(let ((record (rassoc k (cdr t))))
(cond (record (car record))
(else #f))))
(define (rassoc value records)
(cond ((null? records) #f)
((equal? value (cdar records)) (car records))
(else (rassoc value (cdr records)))))
; NOTE: This needs to be run in R5RS as Simply has neither set-car! nor set-cdr!.
(define (delete! k t)
(let ((record (assoc k (cdr t))))
(cond ((not record) "Sorry, key not in table")
((equal? k (caadr t))
(set-cdr! t (cddr t))
record)
(else (delete! k (cdr t))))))
; Code for testing
(define t (make-table))
(insert! 4 'cow t)
(insert! 7 'moose t)
(insert! 2 'wombat t)