如何在Clojure中实现自动完成示例?
这篇博文包含Haskell和Python中自动完成的实现,以比较编程语言的可读性如何在Clojure中实现自动完成示例?,clojure,Clojure,这篇博文包含Haskell和Python中自动完成的实现,以比较编程语言的可读性 想知道如何在Clojure中实现同样的功能。Clojure代码会因为其更强大的抽象能力而更具可读性吗 最低限度的实现: (ns trie.example) (defn trie-add [trie & words] (reduce (fn [trie word] (assoc-in trie (concat word [::val]) word)) trie words))
想知道如何在Clojure中实现同样的功能。Clojure代码会因为其更强大的抽象能力而更具可读性吗 最低限度的实现:
(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")
排序、存储非单词值和压缩等工作留给读者作为练习。一个极简实现:
(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")
排序、存储非单词值和压缩等工作留给读者作为练习。我才进入学习Clojure的第五天。对我来说太多了。这个答案对我的学习很有用。提前感谢所有回复密码的人。我才刚刚进入学习Clojure的第五天。对我来说太多了。这个答案对我的学习很有用。提前感谢任何回复代码的人。