Skip to content

Instantly share code, notes, and snippets.

@brunoro
Last active September 5, 2016 15:59
Show Gist options
  • Save brunoro/59cb6b11d2d6c9952b0396cbf72d2d82 to your computer and use it in GitHub Desktop.
Save brunoro/59cb6b11d2d6c9952b0396cbf72d2d82 to your computer and use it in GitHub Desktop.
key-value trie in clojure
(ns kv-trie)
;; adapted from http://stackoverflow.com/questions/1452680/clojure-how-to-generate-a-trie
(defn explode-str [s] (clojure.string/split s #""))
(defn add [trie k v]
"Maps a string key k to any object v"
(let [kchars (explode-str k)]
(assoc-in trie kchars (merge (get-in trie kchars) { :leaf v }))))
(defn add-pair [trie [k v]] (add trie k v))
(defn search [trie prefix]
"Returns a list of matches with the prefix specified in the trie specified."
(keep :leaf (tree-seq map? vals (get-in trie (explode-str prefix)))))
(defn from-pair-coll [coll]
"Builds a trie from the values in the specified coll of pairs."
(reduce add-pair {} coll))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment