I’m writing a clojure program which parses XML. As a part of this, I wish to create a tree of the nodes in the XML document, based on the clojure.xml/parse function. However I’d like the tree to be bi-directional – that is, each node has a list of children, and a pointer to its parent. There is only one problem: all data is immutable, and so I can’t ‘add’ a pointer to the parent without changing the child, thus making the parent’s pointer useless.
I’ve found this answer: How can one create cyclic (and immutable) data structures in Clojure without extra indirection?
The solution suggested there seems to be creating a separate index map, which refers to the objects inside. This seems like a huge amount of work for a much worse solution. I’d have no problem for the tree to be mutable during construction, however I can’t figure out how can it be done. Is there really no way to get a cyclic pointer in clojure?
Thanks!
It’s logically impossible to make pure immutable structures cyclic, since by adding a parent or child pointer you would be mutating the structure.
There is a hack that works though I’m not sure I’d recommend it: you can put atoms inside Clojure data structures and then mutate these to make the necessary links. e.g.
This is nasty in all sorts of ways:
So, it is possible if you really want to do it……… though I personally think you are still much better off in the long run if you make your document representation properly immutable. You could perhaps use something more like XPath style locations in the document if you want to navigate the structure.