是否有一种简单的方法来收集满足谓词的所有结构?
(./pull '[com.rpl/specter "1.0.0"])
(use 'com.rpl.specter)
(def data {:items [{:name "Washing machine"
:subparts [{:name "Ballast" :weight 1}
{:name "Hull" :weight 2}]}]})
(reduce + (select [(walker :weight) :weight] data))
;=> 3
(select [(walker :name) :name] data)
;=> ["Washing machine"]我们如何才能得到所有的价值:名称,包括“镇流器”“船体”?
发布于 2017-03-20 22:31:01
这里有一种方法,使用recursive-path和stay-then-continue来完成真正的工作。(如果您省略了path参数到select的最后一个select,您将得到完整的“item/ part映射”,而不仅仅是:name字符串。)
(def data
{:items [{:name "Washing machine"
:subparts [{:name "Ballast" :weight 1}
{:name "Hull" :weight 2}]}]})
(specter/select
[(specter/recursive-path [] p
[(specter/walker :name) (specter/stay-then-continue [:subparts p])])
:name]
data)
;= ["Washing machine" "Ballast" "Hull"]更新:在回答下面的注释时,下面是上面的一个版本--下降到树的任意分支,而不是只降到任何给定节点的:subparts分支,不包括:name (它是我们要提取的树中的值,不应该被看作是分支的断点):
(specter/select
[(specter/recursive-path [] p
[(specter/walker :name)
(specter/stay-then-continue
[(specter/filterer #(not= :name (key %)))
(specter/walker :name)
p])])
:name]
;; adding the key `:subparts` with the value [{:name "Foo"}]
;; to the "Washing machine" map to exercise the new descent strategy
(assoc-in data [:items 0 :subparts2] [{:name "Foo"}]))
;= ["Washing machine" "Ballast" "Hull" "Foo"]发布于 2017-03-19 17:12:29
selected?选择器可用于收集另一个选择器与结构中的某些内容相匹配的结构。
来自https://github.com/nathanmarz/specter/wiki/List-of-Navigators#selected的示例
=> (select [ALL (selected? [(must :a) even?])] [{:a 0} {:a 1} {:a 2} {:a 3}])
[{:a 0} {:a 2}]发布于 2017-03-20 07:26:57
我认为您可以使用clojure.walk包递归地在地图上迭代。在每一步中,您都可以检查谓词的当前值,并将其推入原子中以收集结果。
https://stackoverflow.com/questions/42889373
复制相似问题