Given the following...
(def inTree
\'((1 2)
(1 2 3)
(1 2 4 5 9)
(1 2 4 10 15)
(1 2 4 20 25)))
How would you transform it to this t
Lists are very clumsy here, not to mention inefficient. In Clojure it's more idiomatic to use vectors and hash-maps and sets when appropriate. Using hash-maps:
(def in-tree
'((1 2)
(1 2 3)
(1 2 4 5 9)
(1 2 4 10 15)
(1 2 4 20 25)))
(defn add-to-trie [trie x]
(assoc-in trie `(~@x :terminal) true))
(defn in-trie? [trie x]
(get-in trie `(~@x :terminal)))
If you wanted it to print sorted you could use sorted-map
s instead, but you'd have to write your own version of assoc-in
that used sorted maps the whole way down. In any case:
user> (def trie (reduce add-to-trie {} in-tree))
#'user/trie
user> trie
{1 {2 {4 {20 {25 {:terminal true}}, 10 {15 {:terminal true}}, 5 {9 {:terminal true}}}, 3 {:terminal true}, :terminal true}}}
user> (in-trie? trie '(1 2))
true
user> (in-trie? trie '(1 2 4))
nil
user> (in-trie? trie '(1 2 4 20 25))
true