Clojure,增加一个计数器

Eli*_*lie 2 for-loop clojure increment

我有一个看起来像这样的集合:

[({:customer_id "111", :product_id "222"})({:customer_id "333", :product_id "444"}{:customer_id "555", :product_id "666"})...]
Run Code Online (Sandbox Code Playgroud)

我想标记集合中哈希的"位置".最后,我希望我的哈希看起来像这样:

[({:product_id "222", :number "1"})({:product_id "444", :number "1"}{:product_id "666", :number "2"})...]
Run Code Online (Sandbox Code Playgroud)

我试过这样的:

(->> (pig/load-clj "resources/test0_file")
(pig/map
     (fn [ord]
       (for [{:keys [product_id]} ord]
         (let [nb (swap! (atom 0) inc)]
           {:product_id product_id :number nb})))) 
Run Code Online (Sandbox Code Playgroud)

但在那种情况下,nb不会递增.谢谢你的帮助

Kob*_*son 5

map-indexed,assoc和dissoc提供了更清晰的解决方案

(def products ['({:customer_id "111", :product_id "222"})
               '({:customer_id "333", :product_id "444"}
                 {:customer_id "555", :product_id "666"})])


    (for [p products] 
      (map-indexed #(dissoc (assoc %2 :number (str (inc %))) :customer_id ) p))
;user=>(({:number 1, :product_id "222"}) ({:number 1, :product_id "444"} {:number 2, :product_id "666"}))
Run Code Online (Sandbox Code Playgroud)