;; 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 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 new-dict (local {(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) (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. } (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 (new-dict)) (= 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 (new-dict)) (= 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)) (new-dict) (new-dict) (new-dict) (= 6 (dict-id (new-dict)))