我有这样的结构:
[{"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" []}]我的函数应该搜索特定的嵌套映射--比方说,查找映射,其中值10是其b属性的值。我会找到{"a" {"b" 10 "c" 10} "children" []}。一旦我找到它,我就需要用向量改变它的位置。让我们假设,children将变成:
"children" [{"a" {"b" 10 "c" 10} "children" []} {"a" {"b" 9 "c" 10} "children" []}]有了拉链,我能够遍历和定位嵌套的地图,但不知道如何在向量中移动它。
以下是我的拉链是如何创建的:
(z/zipper #(contains? % "children") #(get % "children") (fn [_ c] c) data-structure)发布于 2015-08-24 18:49:25
这能做我想做的事
(defn update-tree [editable? edit loc]
(loop [loc loc]
(if (z/end? loc)
(z/root loc)
(if (editable? (z/node loc))
(recur (-> loc z/up (z/edit edit) z/up z/next))
(recur (z/next loc))))))但它只适用于这种精确的结构。嵌套更多的元素破坏了算法。
发布于 2015-08-24 12:19:47
作为使用幽灵的替代解决方案
(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,但没有成功。如果您找到了更好的解决方案,可以随意编辑它。我对幽灵还是陌生的。
https://stackoverflow.com/questions/32142532
复制相似问题