data-structures - 如何在结构内移动元素(可能使用 zipper )?

标签 data-structures clojure zipper

我有这样的结构:

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

注释:

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

如果您找到更好的解决方案,请随时编辑它。我对幽灵还是个新手。

关于data-structures - 如何在结构内移动元素(可能使用 zipper )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142532/

相关文章:

clojure - 给定一个部分有序的集合,删除所有较小的项目

clojure - 为什么使用 lein run 按 ENTER 键后 read-line 不返回(看起来像是挂起),但使用 lein repl 却可以?

Clojure: zipper -> html

clojure - 如何使用 clojure zippers 获取只有叶子的树中所有子节点的路径?

c++ - 在现代 C++ 中实现专门的数据结构

c++ - 用于有序迭代、有序推送和移除的排序数据结构(仅从顶部开始的 N 个元素)

clojure - 为什么多方法不能用作试剂/重组的功能?

haskell - 在haskell中制作类似网格的数据类型

c - 如何在 C 中存储结构指针以便数据不丢失?

python - Python 列表的底层数据结构是什么?