Clojure: How to generate a 'trie'?

前端 未结 4 1138
死守一世寂寞
死守一世寂寞 2021-02-08 00:19

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

4条回答
  •  野性不改
    2021-02-08 00:48

    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-maps 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
    

提交回复
热议问题