Find location of node in tree using Clojure zippers
Asked Answered
L

1

7

I have a tree of an unknown structure. First, I want to find a node containing a string of text, "Something". Then, after identifying the string's location in the tree, I want to update a different node relative to the string's location. The data is a deeply nested map with several branches of lists.

Is that possible with zippers?

I've studied this approach to editing trees: http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/. Problem is, I don't beforehand know the location of the string.

Liles answered 1/2, 2014 at 0:5 Comment(0)
C
8

Yes! This is exactly the kind of task zippers where designed for.

  • Repeatedly call zip/next until you find the node you are looking for.
  • Then call zip/path to find out where you are relative to the root.
  • Then call zip/up, zip/down, zip/left etc to get to the node to modify.
  • update the node
  • call zip/root to get your new map containing these changes.
Chatty answered 1/2, 2014 at 0:42 Comment(1)
Excellent! That's all I needed.Liles

© 2022 - 2024 — McMap. All rights reserved.