2

我有这个结构:

 [{"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" []}]

我的函数应该搜索特定的嵌套地图 - 比如说,找到它是10b属性值的地图。我会定位{"a" {"b" 10 "c" 10} "children" []}。一旦我找到它,我需要用向量改变它的位置。让我们假设,这children将变成:

 "children" [{"a" {"b" 10 "c" 10} "children" []} {"a" {"b" 9 "c" 10} "children" []}]

使用 Zipper,我能够遍历并定位嵌套地图,但不确定如何在矢量内移动它。

这是我的拉链的创建方式:

  (z/zipper #(contains? % "children") #(get % "children")  (fn [_ c] c) data-structure)
4

2 回答 2

1

这将做我想要的:

(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-24T18:49:25.193 回答
1

作为使用幽灵的替代解决方案:

  (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" []})}]

笔记:

  1. walker 一直在走,所以如果你正在寻找一个只有一次的转换,你应该以某种方式适应它。我尝试添加FIRST到变换向量,但即使找到“b”之一,它仍然会继续行走。
  2. 我尝试使用collect-one而不是,get-in但我没有成功。

如果您找到更好的解决方案,请随时对其进行编辑。我还是新来的幽灵。

于 2015-08-24T12:19:47.540 回答