Skip to content

Instantly share code, notes, and snippets.

@joelkuiper
Created July 16, 2016 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelkuiper/a422cea41a26c9a3e2b35ac3abbb06f8 to your computer and use it in GitHub Desktop.
Save joelkuiper/a422cea41a26c9a3e2b35ac3abbb06f8 to your computer and use it in GitHub Desktop.
Clojure Trie for prefix lookup
;; 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