algorithm - 是否可以编写通用算法来使用 Zippers 更新嵌套(无论嵌套如何)数据结构中的元素?

标签 algorithm clojure functional-programming zipper

上周,我试图用 Zippers 编写一个算法来更新嵌套数据结构中的特定元素,How to move an element within a structure, possibly with zippers?

我的回答解决了那个确切结构的问题,嵌套更多元素会破坏算法。

这让我开始思考,是否可以使用 Zippers 编写通用算法来更新嵌套数据结构中的特定数据(无论其嵌套程度如何)?还是只有当您确切地知道自己的步数时, zipper 才有用?

我需要明白,我正试图让 Zippers 做一些不是 Zippers 被创建的目的。

最佳答案

当然,您可以通过这种方式使用 zipper ,因为您可以沿您选择的任何方向移动 zipper 。举个例子看看 zip-visit library ,它提供了对 zipper 的任意访问,能够根据需要更改节点。

取自文档的例子:

(def s "<div><span id='greeting'>Hello</span> <span id='name'>Mr. Foo</span>!</div>")
(def root (z/xml-zip (xml/parse (java.io.ByteArrayInputStream. (.getBytes s)))))

(defn replace-element [id replacement]
  (visitor :pre [n s]
    (if (= (:id (:attrs n)) id) {:node replacement})))

user=> (pprint (:node (visit root nil [(replace-element "name" "Mr. Smith")])))
{:tag :div,
 :attrs nil,
 :content
 [{:tag :span, :attrs {:id "greeting"}, :content ["Hello"]}
  "Mr. Smith"
  "!"]}

当然,你也可以用简单的步行来完成类似的任务,例子在this SO question on traversing maps上。 .

关于algorithm - 是否可以编写通用算法来使用 Zippers 更新嵌套(无论嵌套如何)数据结构中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189647/

相关文章:

windows - 如何比较文件列表的大小并取最大的?

algorithm - 为什么 O(log(n)) 等于 O(log(n!))?

function - 将可选回调传递给 Swift 函数

scala - 将 Free Monad 与 Either 一起使用

functional-programming - 嵌套函数 : Improper use of side-effects?

arrays - 查找数组中给定范围内的元素数

algorithm - 为什么heapify会交换堆顶元素和堆底元素?

clojure - 如何以纯函数的方式实现观察者设计模式?

clojure - 为什么我可以在 clojure 中使用集合作为谓词?

caching - clojure.core.cache 只是使用他们自己的例子不起作用