我有这样的结构:
[{"a" {"b" 1 "c" 2}
"children" [{"a" {"b" 3 "c" 4} "children" []}]}
{"a" {"b" 5 "c" 6} "children" []}
{"a" {"b" 7 "c" 8}
"children" [{"a" {"b" 9 "c" 10} "children" []} {"a" {"b" 10 "c" 10} "children" []}]}]
我正在尝试编写一种算法来在向量内移动和元素。例如,在最后一个元素中,它有 children
向量:
"children" [{"a" {"b" 9 "c" 10} "children" []} {"a" {"b" 10 "c" 10} "children" []}]
我的函数应该搜索特定的嵌套映射 - 比方说,找到其 b
属性值为 10
的映射。我将找到 {"a"{"b"10 "c"10} "children"[]}
。一旦找到它,我需要用向量改变它的位置。我们假设,children
将变成:
"children" [{"a" {"b" 10 "c" 10} "children" []} {"a" {"b" 9 "c" 10} "children" []}]
使用 Zipper,我能够遍历并定位嵌套 map ,但不确定如何在向量内移动它。
这是我的 zipper 的创建方式:
(z/zipper #(contains? % "children") #(get % "children") (fn [_ c] c) data-structure)
最佳答案
作为替代解决方案,使用 specter :
(def z [
{"a" {"b" 1 "c" 2}
"children" [{"a" {"b" 3 "c" 4}
"children" []}]}
{"a" {"b" 5 "c" 6}
"children" []}
{"a" {"b" 7 "c" 8}
"children" [{"a" {"b" 9 "c" 10}
"children" []}
{"a" {"b" 10 "c" 10}
"children" []}]}])
(transform
(walker (fn [x]
(and
(vector? x)
(some
#(= 10
(get-in % ["a" "b"]))
x))))
reverse
z)
返回:
[{"a" {"b" 1, "c" 2}, "children" [{"a" {"b" 3, "c" 4}, "children" []}]}
{"a" {"b" 5, "c" 6}, "children" []}
{"a" {"b" 7, "c" 8},
"children"
({"a" {"b" 10, "c" 10}, "children" []}
{"a" {"b" 9, "c" 10}, "children" []})}]
注释:
- 步行者一直在行走,所以如果您正在寻找一次性的转换,您应该以某种方式进行调整。我尝试将
FIRST
添加到变换向量中,但即使找到其中一个“b”,它仍然会继续行走。 - 我尝试使用
collect-one
而不是get-in
,但没有成功。
如果您找到更好的解决方案,请随时编辑它。我对幽灵还是个新手。
关于data-structures - 如何在结构内移动元素(可能使用 zipper )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142532/