简体   繁体   English

更新Clojure列表中嵌套了几层的地图

[英]Updating a map that is nested a couple layers in lists in clojure

I'm new to functional programming, and I am trying to figure out how to achieve the following. 我是函数编程的新手,我试图弄清楚如何实现以下目标。

I have a data structure as so in Clojure: 我在Clojure中有一个数据结构:

  [
    [
      { 
        :key1 "val1",
        :key2 [
                { :type "D", ... },
                { :type "A", ... },
                { :type "B", ...}
              ]
         ...
       }
    ]
  ]

What I want to do is keep the same overall data structure with all of it's data. 我想做的是保持所有数据的整体数据结构相同。 However, I want the objects in "key2" list to be sorted by "type". 但是,我希望“ key2”列表中的对象按“类型”排序。

After reading some tutorials, I have this much: 阅读一些教程之后,我学到了很多:

(doseq [currentList myDataStructure]
  (doseq [currentItem currentList]
    (println (get currentItem :key2))
)))

By the way, is doseq an alright way to iterate through lists? 顺便说一句, doseq是遍历列表的好方法吗? I see Clojure otherwise does looping through data structures through recursion. 我看到Clojure否则确实会通过递归遍历数据结构。 Seemed kind of odd to me to add frames to the stack just to iterate through a list. 对于我来说,将帧添加到堆栈中只是为了遍历列表似乎有些奇怪。

You can do this with update-in : 您可以使用update-in来做到这一点:

(def x  [[{:key1 "val1",
           :key2 [{:type "D"}
                  {:type "A"}
                  {:type "B"}]}]])

(update-in x [0 0 :key2] (partial sort-by :type))

This is perfect use-case for specter : 这是幽灵的完美用例:

(sp/transform [sp/FIRST sp/ALL :key2] (partial sort-by :type)
  [
   [
    {
     :key1 "val1",
     :key2 [{:type "D", :v 1},
            {:type "A", :v 3},
            {:type "B", :v 89}]}
    {
     :key1 "val3",
     :key2 [{:type "Z", :v 10},
            {:type "A", :v 30},
            {:type "B", :v 890}]}
    ]
   ])
;;=> [[{:key1 "val1", :key2 ({:type "A", :v 3} {:type "B", :v 89} {:type "D", :v 1})}

;;     {:key1 "val3", :key2 ({:type "A", :v 30} {:type "B", :v 890} {:type "Z", :v 10})}]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM