Created
July 16, 2016 22:29
-
-
Save joelkuiper/a422cea41a26c9a3e2b35ac3abbb06f8 to your computer and use it in GitHub Desktop.
Clojure Trie for prefix lookup
This file contains 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
;; From http://stackoverflow.com/questions/1452680/clojure-how-to-generate-a-trie | |
(defn add-to-trie [trie x] | |
(assoc-in trie x (merge (get-in trie x) {:val x :terminal true}))) | |
(defn in-trie? [trie x] | |
"Returns true if the value x exists in the specified trie." | |
(:terminal (get-in trie x) false)) | |
(defn prefix-matches [trie prefix] | |
"Returns a list of matches with the prefix specified in the trie specified." | |
(keep :val (tree-seq map? vals (get-in trie prefix)))) | |
(defn build-trie [coll] | |
"Builds a trie over the values in the specified seq coll." | |
(reduce add-to-trie {} coll)) | |
(def coll [#{"a" "b" "c"} #{"a" "b"} #{"c" "d"} #{"c" "d" "e"} #{"e" "d" "a"}]) | |
(def trie (build-trie (map (comp sort vec) coll))) | |
user=> (prefix-matches trie ["a"]) | |
(("a" "b") ("a" "b" "c") ("a" "d" "e")) | |
user=> (prefix-matches trie ["a" "b"]) | |
(("a" "b") ("a" "b" "c")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment