This commit is contained in:
2025-09-25 23:34:02 -04:00
parent ca133f77df
commit 34cee3e910
2 changed files with 23 additions and 78 deletions
+23 -4
View File
@@ -1,7 +1,7 @@
;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-reader.ss" "lang")((modname main) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
#|; A MaybeTree is one of
; A MaybeTree is one of
; - (make-tree [Number MaybeTree MaybeTree])
(define-struct tree [n left right])
; - 'end
@@ -41,7 +41,6 @@
(check-expect (bst? sapling) #t)
(check-expect (bst? good-tree) #t)
(check-expect (bst? broke-tree) #f)
|#
; A Trie is a [Node]
@@ -90,6 +89,26 @@
(local [; String w, Trie t -> Trie
; Adds word w to a Trie.
(define (triadd w t)
(if (
(local [; String c, String wrest, Trie t -> Trie
; Helper function to insert a chacater (and the rest of the word) to the Trie.
(define (insert-char c wrest t)
(cond [(empty? t)
(list (make-node c ; Node character.
(string=? wrest "") ; Mark whether Node's a word end.
(if (string=? wrest "") ; If more left in the word, recurse.
'()
(triadd wrest '()))))]
[(string=? (node-c (first t)) c) ; Character matches -- return existing Trie Node + whatever added if necessary.
(cons (make-node c
(or (node-e (first t))
(string=? wrest ""))
(if (string=? wrest "")
(node-l (first t))
(triadd wrest (node-l (first t))))) ; Recurse.
(rest t))]
[else
(cons (first t) (insert-char c wrest (rest t)))]))]
(insert-char (substring w 0 1) (substring w 1) t)))]
(foldl triadd '() l)))
(check-exepct (strie '("and" "bee" "cat" "an" "a" "ant" "better" "bet" "be")) example-trie)
(check-expect (strie '("and" "bee" "cat" "an" "a" "ant" "better" "bet" "be")) example-trie)