;; An entry holds a key/value pair ;; for use in Dictionaries. ;; (define-struct entry (key value)) ;; A Dictionary is a structure with two "methods" (fields which are functions): ;; add-fn! and lookup-fn are functions which signatures below. ;; (define-struct dict (add-fn! lookup-fn)) ;; add-fn!: ANY ANY --> ?? ;; SIDE-EFFECT: change the contents. ;; We return (the updated) contents, primarily for debugging purposes. ;; lookup: key --> entry or false ;; Does the key occur inside "contents"? ;; If so, return that entry, else return the sentinel false. ;;;;;;;;;;;;;;;;;; (define (new-dict/vec max-key) (local {; Our local datastore: a vector. (define data (make-vector max-key false)) ;; All contracts as per Dictionary above, ;; except that we are assuming the key is an integer ;; in [0,max-key). (define (add! k v) (begin (vector-set! data k v) data)) (define (lookup k) (vector-ref data k)) } (make-dict add! lookup))) ;;;;;; Tests (define fr (new-dict/vec 5)) (define de (new-dict/vec 10)) (boolean=? false ((dict-lookup-fn fr) 3)) ((dict-add-fn! fr) 3 'trois) ((dict-lookup-fn fr) 3) ((dict-add-fn! de) 2 'zwei) (boolean=? false ((dict-lookup-fn de) 3)) "An error:" ((dict-lookup-fn fr) 5)