首页 > 解决方案 > Convert a lazy sequence of maps into a single map

问题描述

I'm a Clojure noob. I'm trying to take a lazy sequence of maps and convert it into a single map. The map key is an integer and the value is a vector. I've seen lots of examples of merging maps e.g.

(merge map1 map2) ;;or
(into {} [{a: 1} {b: 2} {c: 3}])

but I'm still having difficulty when it's a lazy sequence. When I use:

(into {} mapSeq) 

it returns only the last map in the sequence.

(defn combine-maps [mapSeq]
  (pp/pprint (into {} mapSeq))))

(defn file-input-to-vec [file] 
  (let [page (line-seq (clojure.java.io/reader file))
        page-number (vec (mapv #(str/split %1 #" ") page))] 

    (combine-maps (for [i page-number]  
                { :pageID (edn/read-string (first i)) 
                  :outpages (convert-to-int-vec (drop 1 i)) }))))

I get the last page only:

{:pageID 6, :outpages [9770 0 8758 6103 9560 356 8469 3570 1178]}

I'd like this:

{:pageID 0, :outpages [6 5 2 4 1 3], 
 :pageID 1, :outpages [0 461 4772 1324 1735 487 5668],
 :pageID 2, :outpages [4412 0 209 3130 6902 8397 4373 905 3833],
 :pageID 3, :outpages [5103 1203 7063 0 5866 445 5498 6217 6498], 
 ... }

标签: clojure

解决方案


The return value that you say you would like is not a legal map, because it has multiple occurrences of the key :pageID and multiple occurrences of the key :outpages. Clojure maps (and their corresponding things in most programming languages, e.g. dictionaries in Python) have at most one occurrence of each key.

If you update what you want as a return value to something that is a valid Clojure data structure, someone may be able to help with the code.


推荐阅读