Skip to content

Instantly share code, notes, and snippets.

@Fedreg
Created July 14, 2019 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fedreg/68c89aef201764b1c2d6bea0bcb941c0 to your computer and use it in GitHub Desktop.
Save Fedreg/68c89aef201764b1c2d6bea0bcb941c0 to your computer and use it in GitHub Desktop.
Quick and dirty Trie experiment in Clojure
(use 'clojure.test)
(def trie (atom {}))
(defn in-trie? [a k]
(let [key-chars (mapv str (name k))
xs (first key-chars)
ys (rest key-chars)]
(cond
(and (not-empty ys)
(nil? (get a (keyword xs)))) false
(empty? ys) (some? (get a (keyword xs)))
:else (recur
(get a (keyword xs))
(keyword (apply str ys))))))
(defn insert-in-trie [k]
(let [t @trie
nt (assoc-in
t
(mapv keyword (map str (name k)))
1)]
(reset! trie nt)))
(deftest trie-test
(testing "hacky trie works as expected"
(is (= {} @trie))
(is (false? (in-trie? @trie :dog)))
(insert-in-trie :dog)
(is (true? (in-trie? @trie :dog)))
(is (true? (in-trie? @trie :do)))
(is (false? (in-trie? @trie :doge)))
(insert-in-trie :pickle)
(is (true? (in-trie? @trie :pickle)))
(is (true? (in-trie? @trie :pick)))
(is (false? (in-trie? @trie :pickles)))
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment