我有一个文档哈希,这是一个像这样的引用:
(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-number时,不会创建term-detail hash。
答案 0 :(得分:1)
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}}
答案 1 :(得分:1)
这是一个应该有效的功能重写。它使用assoc-in函数
(defn add-doc-hash [docid term-number count]
(dosync (alter *document-hash* assoc-in [docid :term-detail term-number] count)))
答案 2 :(得分:0)
如果我理解正确的话,另一种表达问题的方法是: “我如何编写一个函数来向地图添加另一个[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)
实际将其添加到哈希