2
votes

When I have a space-separated key, how can I use it to extract a value without re-creating the key?

I have a set of potential keys, column names actually, as the first sequence in data returned from clojure-csv: (This is formatted to avoid scrolling.)

["AGY/DIV " "STS" "GIC-ID     " 
"LAST-NAME      " 
"FIRST-NAME     " 
"COVERAGE DESCRIPTION                                   " 
"PREMIUM  " 
"RUN-DATE" 
"BIL MO "]

Then I create keys from this row and zipmap the keys with each subsequent row (sequence) of data:

(defn create-map-keys
  "Takes a sequence, and turns it into viable keys for a map."
  [in-seq]
  (map (fn [element] (keyword element)) (map #(cstr/trim %1) in-seq)))

; gic-csv-keys    
(:AGY/DIV :STS :GIC-ID :LAST-NAME :FIRST-NAME 
:COVERAGE DESCRIPTION :PREMIUM :RUN-DATE :BIL MO) 

(defn zip-apply-col-nams
   [col-keys row]
   (zipmap col-keys row))

For test data, I zipmap the keys to the second row of the csv-data.

(def zm2 (zip-apply-col-nams gic-csv-keys (first gic-csv-data)))

When I try to extract a value from the :COVERAGE DESCRIPTION key, I get this error

 (:COVERAGE DESCRIPTION zm2)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: DESCRIPTION in this context, compiling:(NO_SOURCE_PATH:23) 

However, this works:

(zm2 (keyword "COVERAGE DESCRIPTION"))
"HARVARD PILGRIM FAMILY - INSURED                       "

Should I be modifying space-separated keys to replace the space with, for example, a dash, or is there another way to refer to the key without recreating it?

Thanks.

2

2 Answers

6
votes

(keyword "some key") does not "recreate" a keyword, it interns a keyword, meaning that it will always return the same keyword object when given the same name. You can also store the returned keyword and re-use it that way:

(def coverage-description (keyword "COVERAGE DESCRIPTION"))

(coverage-description my-row-map)
2
votes

For the record: "some key" is (at the moment) not a valid keyword in Clojure. You should either replace the whitespace with - or _. Or you should go with plain strings as keys and use get.