How can I replace a subtree with another tree?

In a Scala macro, I want to do something like this:

I have Tree

(possibly a large one). Now I want to find a subtree of this tree that has a specific shape, for example. Apply(_, _)

... And now I want to create a new tree, which is a copy of the original tree, but the found subtree is replaced with another tree.

With something similar, I could, for example, replace a call to a method with a call to another method.

Is this possible?

+3


source to share


2 answers


I am very interested in seeing alternative approaches to tree transformation, however they have not arrived yet (and we are indeed conducting ongoing research in that direction).



To do this, you can extend Transformer

, override its method transform

, and then match the pattern to the specific shape of the trees you are interested in. Call super.transform

to recursively replace in subtrees.

+2


source


Is it possible??? Definitely Yes !

The general concept is "persistent data structures". Those that "retain" as much of the original value as possible in the new version.



When it comes to trees, the Zipper concept applies. It allows you to go into the structure of the graph, while maintaining a data structure that allows you to restore a new value, which is maximally divisible by the original modulo changes that you applied to create a new variation.

Check it. Many references can be found as well as implementations including ScalaZ.

+1


source







All Articles