Reputation: 290
I have a toy project where I would like to add some string values into a Redis db. The input is coming from a huge CSV file. The (lazy) function below works fine , but I do not know how to add to the key the indexed value read into the input file - the two commented lines.
Could you give me hint/URL/reference for it? Thank you!
(defn collector [myfile] (with-open [rdr (io/reader myfile)] (doseq [line (line-seq rdr)] ; [idx (iterate inc 0)] (let [[k v1 v2 v3 v4 v5 v6 v7] (clojure.string/split line #",")] (red/set db (str "key:" k) ;(str "key:" k ":" idx) (str v1 "-" v5 "-" v6))))))
Upvotes: 1
Views: 621
Reputation: 17859
the best thing you can do without changing your code structure, is to attach the index to the lines seq this way:
(doseq [[idx line] (map-indexed vector (line-seq rdr))] ...)
then the second commented line would work as planned.
(map-indexed vector coll)
would pass the two parameters (index and the element of the sequence) to the vector
function, making the tuple of them, and destructuring bind [idx line]
binds its elements to desired names.
This is a commonly used idiom to index the collection. Also you could do it this way:
(map vector (range) coll)
, which works the same way as map-indexed
, though this idiom is usable to make tuples of any collections:
(map vector (range) [:a :b :c :d] (iterate (partial * 2) 1))
;;=> ([0 :a 1] [1 :b 2] [2 :c 4] [3 :d 8])
Upvotes: 1