如何在Clojure中实现自动完成示例?

时间:2012-02-26 17:31:32

标签: clojure

此博客文章(http://williamedwardscoder.tumblr.com/post/18319031919/programming-language-readability)包含Haskell和Python中自动完成的实现,以比较编程语言的可读性。

很想知道如何在Clojure中实现相同的功能。由于具有更强的抽象能力,Clojure代码是否更具可读性?

1 个答案:

答案 0 :(得分:4)

极简主义的实施:

(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")

排序,存储非单词值和压缩等内容留给读者练习。