2009-10-06 53 views
3

我有一個文件哈希是這樣一個參考:你如何在Clojure的這個哈希表中添加?

(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)))))) 
  • 我想更新文件的術語細節
  • 每當一個新的學期來臨的時候,我想獲得長期,細節和更新方面,其計
  • 最初哈希爲空

但是,這將引發空指針異常,因爲療法項細節的散列當我嘗試添加術語編號時未創建。

回答

0

如果我正確理解這個問題,另一種表達問題的方法是: 「我如何編寫一個函數來向地圖添加另一個[term,count]對。

一點輔助函數來獲取當前信息的地圖,如果沒有添加該地圖,那麼顯然它不會有任何的細節,所以我代表這一個空的地圖
這能解決您的裏添加問題第一項數:

(defn get-term-detail [a-hash docid] 
    (let [entry (a-hash docid)] 
    (if nil? entry) 
     {} 
     (:term-details entry)))) 

然後soemthing像:

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

到實際工作中把它添加到哈希

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}} 
+0

也可以利用這一更新在創建節點的事實的優點: 用戶=>(更新在{} [:喜:媽媽]#(如果%(INC%) 0)) - > {:hi {:mum 0}} – 2009-10-07 03:51:28

1

這是你應該工作的函數的重寫。它使用assoc-in功能

(defn add-doc-hash [docid term-number count] 
    (dosync (alter *document-hash* assoc-in [docid :term-detail term-number] count)))