How to add this hash table in Clojure?

I have a hash document called a link:

(def *document-hash* (ref (hash-map)))  

Looks like this

 {"documentid" {:term-detail {"term1" count1 ,"term2" count2},  "doclen" 33}}}

How to add to this hash table? I have now

(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))))))
  • I want to update the detail terms for documents.
  • Every time a new term arrives, I want to get the detail terms and update the terms and their number
  • the hash is initially empty

But this eliminates the null pointer exception, because the term-detail hash is not created when I try to add a number term.

+3
source share
3 answers
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
source

Here you rewrite your function, which should work. It uses assoc-in function

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

, , : " , [term, count] ".

, , , ,
, -:

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

then soemthing like:

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

to activate add it to the hash

0
source

Source: https://habr.com/ru/post/1719444/


All Articles