;; 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! : ANY ANY --> list-of-entries ;; SIDE-EFFECT: change the contents. ;; lookup-fn: key --> entry or false ;; Does the key occur inside "contents"? ;; If so, return that entry, else return the sentinel false. ;; (define-struct dict (add-fn! lookup-fn)) ; add!: ANY ANY --> ?? ; lookup: key --> entry or false ;;;;;;;;;;;;;;;;;; (define (dict-Factory) (local [;; a local list-of-entries, ;; used only by the dictionary we're creating now: ;; (define contents empty) ; 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))) ] (make-dict add! lookup))) ;;;;;; Tests (define english->german (dict-Factory)) ((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)) ((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) ((dict-lookup-fn english->german) 'gymnasium)