Last active
May 25, 2020 14:59
-
-
Save joelittlejohn/5498323 to your computer and use it in GitHub Desktop.
Trie for auto-complete (or: how to implement auto-complete in 4 lines of Clojure)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def t | |
"trie containing the 100,000 most common english words" | |
(with-open [r (clojure.java.io/reader "/tmp/words-100000")] | |
(reduce #(assoc-in %1 %2 (sorted-map \0 nil)) (sorted-map) (line-seq r)))) | |
(defn search [p m] | |
"return a sorted sequence of all words in the trie m that start with the given prefix p" | |
(let [n (get-in m p) | |
next (mapcat #(search (str p (key %)) m) (dissoc n \0))] | |
(if (contains? n \0) (cons p next) next))) | |
(time (search "trie" t)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment