;; 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 (dict-n-Factory num-keys) (local [; Our local datastore: a vector. (define data (make-vector num-keys false)) ;; All contracts as per Dictionary above, ;; except that we are assuming the key is an integer ;; in [0,num-keys - 1). (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 (dict-n-Factory 5)) (define de (dict-n-Factory 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)