;; 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 as add!,lookup above. ;; (define-struct dict (add-fn! lookup-fn)) ; 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 (new-dict) (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) (lookup-helper key contents)) ;; lookup-helper: key, list-of-entries --> entry or false ;; Does the key occur inside "entries"? ;; If so, return that entry, else return the sentinel false. ;; (define (lookup-helper key entries) (cond [(empty? entries) false] [(cons? entries) (cond [(equal? key (entry-key (first entries))) (first entries)] [else (lookup-helper key (rest entries))])])) ; ; NB this function can be of course easily re-written as a list visitor. } (make-dict add! lookup))) ;;;;;; Tests (define english->german (new-dict)) ((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 (new-dict)) ((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)