甲简约实现:
(ns trie.example)
(defn trie-add [trie & words]
(reduce
(fn [trie word]
(assoc-in trie (concat word [::val]) word))
trie
words))
(defn trie-matches [trie prefix]
(letfn [(search [node]
(mapcat (fn [[k v]]
(if (= ::val k) [v] (search v)))
node))]
(search (get-in trie prefix))))
实例:
;; Create trie
(def trie (trie-add {} "foo" "ba" "bar" "baz" "qux" "quux"))
;; trie looks like this:
{\q
{\u
{\u {\x {:trie.example/val "quux"}},
\x {:trie.example/val "qux"}}},
\b
{\a
{\z {:trie.example/val "baz"},
\r {:trie.example/val "bar"},
:trie.example/val "ba"}},
\f {\o {\o {:trie.example/val "foo"}}}}
;; Autocomplete
(trie-matches trie "ba")
=> ("baz" "bar" "ba")
比如像分类,存储非字值,并且压缩被留下作为练习给读者。
你为什么不尝试一下? – 2012-02-26 17:44:40
我只进入了我学习Clojure的第5天。它对我来说太多了。答案对我的学习很有帮助。预先感谢谁回复了代码。 – jemeshsu 2012-02-26 17:50:17