过滤以下嵌套映射并保持嵌套映射结构的最佳方法是什么。在我的示例中,Alice 和 Bob 可以重复,例如同一名员工可以同时在几个不同的工厂工作。
(def universe
{:customer1
{:plant1
{ "Alice" {:age 35 :sex "F"}
"Bob" {:age 25 :sex "M"}}
:plant2 {}}
:customer2 {}
})
例如,我想按年龄 >30 进行过滤并返回相同的 map 结构。理想情况下,这适用于任何嵌套 map 深度,在最内层进行过滤。预期结果:
(def universe
{:customer1
{:plant1
{ "Alice" {:age 35 :sex "F"}
}
:plant2 {}}
:customer2 {}
})
我看过clojure filter nested map to return keys based on inner map values但它看起来并没有解决我的问题。谢谢,
最佳答案
这与之前的问题之一非常相似:
(use '[com.rpl.specter])
(let [input {:customer1
{:plant1
{"Alice" {:age 35 :sex "F"}
"Bob" {:age 25 :sex "M"}}
:plant2 {}}
:customer2 {}}
desired-output {:customer1
{:plant1 {"Alice" {:age 35 :sex "F"}}
:plant2 {}}
:customer2 {}}
RECUR-MAP (recursive-path [] p (cond-path map? (continue-then-stay [MAP-VALS p])))]
(clojure.test/is (= (setval [RECUR-MAP (pred :age) #(> 30 (:age %))] NONE input)
desired-output)))
关于dictionary - Clojure - 在最内层过滤嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54143713/