;; An entry holds a key/value pair ;; for use in Dictionaries. ;; (define-struct entry (key value)) ;; have-key? key entry --> boolean ;; Returns whether the key is the same as that of the entry. (define (have-key? key entry) (equal? key (entry-key entry))) ;; A Dictionary is a structure with two "methods" (fields which are functions): ;; add-fn! and lookup-fn are functions which signatures as add!,lookup above. ;; (define-struct dict (add-fn! lookup-fn id)) ; add!: ANY ANY --> ?? ; SIDE-EFFECT: change the contents. ; lookup: key --> entry or false ; Does the key occur inside "contents"? ; If so, return that entry, else return the sentinel false. ;;;;;;;;;;;;;;;;;; (define dict-Factory (local [;; A single count, shared by all dictionaries. (define dict-count 0)] (lambda () (local [;; a local list-of-entries, ;; used only by the dictionary we're creating now: ;; (define contents empty) ;; Contracts as per Dictionary, above. ; Return the list-of-entries, for debugging as much as anything. ; (define (add! k val) (begin (set! contents (cons (make-entry k val) contents)) contents)) (define (lookup key) (local [;; helper: list-of-entries --> entry or false ;; Does the key occur inside "entries"? ;; If so, return that entry, else return false. ;; (define (helper entries) (cond [(empty? entries) false] [(cons? entries) (cond [(have-key? key (first entries)) (first entries)] [else (helper (rest entries))])]))] (helper contents))) ] (begin (set! dict-count (add1 dict-count)) (make-dict add! lookup dict-count)))))) ;;;;;; Tests ; Okay, actually both german and french nouns ; *should* be represented by a structure which includes a gender field. (define english->german (dict-Factory)) (= 1 (dict-id english->german)) (boolean=? false ((dict-lookup-fn english->german) 'health)) ((dict-add-fn! english->german) 'health 'gesundheit) ((dict-lookup-fn english->german) 'health) ((dict-add-fn! english->german) 'science 'wissenschaft) ((dict-lookup-fn english->german) 'health) (define english->french (dict-Factory)) (= 1 (dict-id english->german)) (= 2 (dict-id english->french)) (boolean=? false ((dict-lookup-fn english->french) 'health)) ((dict-add-fn! english->french) 'health 'sante) ((dict-add-fn! english->french) 'computer 'ordinateur) ((dict-add-fn! english->french) 'weekend 'weekend) ((dict-lookup-fn english->french) 'health) ((dict-add-fn! english->german) 'computer-science 'informatik) ((dict-lookup-fn english->german) 'science) ((dict-lookup-fn english->german) 'health) (boolean=? false ((dict-lookup-fn english->german) 'gymnasium)) (dict-Factory) (dict-Factory) (dict-Factory) (= 6 (dict-id (dict-Factory)))