Created
July 14, 2019 16:11
-
-
Save Fedreg/68c89aef201764b1c2d6bea0bcb941c0 to your computer and use it in GitHub Desktop.
Quick and dirty Trie experiment in Clojure
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
(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