上周,我试图用 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/