如何在Clojure中添加此哈希表?

如何在Clojure中添加此哈希表?,clojure,hashmap,Clojure,Hashmap,我有一个文档哈希,它是这样的引用: (def *document-hash* (ref (hash-map))) 看起来像这样 {"documentid" {:term-detail {"term1" count1 ,"term2" count2}, "doclen" 33}}} 如何添加到这个哈希表中?现在我有 (defn add-doc-hash [docid term-number count] (dosync (alter *document-hash* (fn

我有一个文档哈希,它是这样的引用:

(def *document-hash* (ref (hash-map)))  
看起来像这样

 {"documentid" {:term-detail {"term1" count1 ,"term2" count2},  "doclen" 33}}}
如何添加到这个哈希表中?现在我有

(defn add-doc-hash [docid  term-number count]
  (dosync (alter *document-hash*
    (fn [a-hash]
      (assoc a-hash docid {:term-detail  
        (assoc ((a-hash docid)) :term-detail) term-number count), :doclen 33))))))
  • 我想更新文档的术语详细信息
  • 每次新学期来临时,我都想获得学期的详细信息,并更新学期及其计数
  • 最初,散列是空的

但这会引发空指针异常,因为当我尝试添加术语编号时,不会创建术语详细信息哈希。

如果我理解正确,另一种措辞方式是: “如何编写函数将另一个[term,count]对添加到映射中。”

一个小助手函数,用于获取地图的当前详细信息,如果该地图尚未添加,那么很明显它将没有详细信息,因此我用一个空地图来表示这一点
这解决了在何处添加第一个术语编号的问题:

(defn get-term-detail [a-hash docid]
  (let [entry (a-hash docid)]
    (if nil? entry)
       {}
       (:term-details entry))))
然后是这样的:

(assoc a-hash docid {:term-details (assoc (get-term-detail a-hash docid) term-number count)        :doclen 33)

要将其添加到散列中,这里是对函数的重写,应该可以工作。它使用这个函数

user> (def x (ref {"documentid" {:term-detail {"term1" 1 ,"term2" 2},  "doclen" 33}}))
#'user/x
user> (dosync (alter x assoc-in ["documentid" :term-detail "term3"] 0))
{"documentid" {:term-detail {"term3" 0, "term1" 1, "term2" 2}, "doclen" 33}}
user> (dosync (alter x update-in ["documentid" :term-detail "term3"] inc))
{"documentid" {:term-detail {"term3" 1, "term1" 1, "term2" 2}, "doclen" 33}}

您还可以利用这样一个事实,即在中更新创建节点:user=>(在{}[:hi:mum]#(if%(inc%)0)中更新)->{:hi{:mum 0}
(defn add-doc-hash [docid  term-number count]
  (dosync (alter *document-hash* assoc-in [docid :term-detail term-number] count)))