unj2
unj2

Reputation: 53551

How to write this better in Clojure

The structure of my hash is

(def *document-hash*   {"documentid" {:term-detail {"term1" tf1 ,"term2" tf2}})

I wan to find the tf. Right now I have this. Is there a better way to do this in clojure?

;; Find tf
(defn find-tf [documentid term-number]
  (if (nil? *document-hash* documentid)
       0
       (if (nil? (((*document-hash* documentid) :term-detail) term-number))
            0
            (((*document-hash* documentid) :term-detail) term-number))))

Upvotes: 2

Views: 477

Answers (1)

pmf
pmf

Reputation: 7759

Updated to work with a Ref:

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

(dosync (alter *document-hash* conj {12603 {:term-detail {2 10}, :doclen 30}}))

(defn find-tf [documentid term-number]
  (or (get-in @*document-hash* [documentid :term-detail term-number])
      0))

(find-tf 12603 2) ; yields 10

Upvotes: 4

Related Questions