I need to get the expression tree for some expression.
expr //TreeForm
The above grabs the expression tree but it isn't in some sort of usable format. Just an image.
Level[expr, {-1}, "Heads"->True]
This does a depth first traversal of the expression tree and does give me a list of all items in the expression tree. The issue with this is that:
expr = a+b*3*c+d
Level[expr, {-1}, "Heads"->True]
{Plus, a, Times, 3, b, c, d}
and now you can see that because of the location of d I have no information on what goes where with Levels.
So the question is, is there a way for me to get the expression tree in some format where I can actually tell where everything is supposed to go?
Acceptable formats would be of the form of {operator/operatorFunctionName, symbol/value, {operator/operatorFunctionName, symbol/value, {... continues as far as can go}}, moreSymbolsRelatedToFirstOperation}
OR
{operator/operatorFunctionName, operator/operatorFunctionName, ...} {{symbol/valueForFirstOperator, ...}, {symbol/valueForSecondOperator,...}, ...}
OR any other similar format.
Answer
Please let me know if this is moving in the right direction:
expr = a + b*3*c + d;
Replace[expr, h_[x___] :> {x}, {0, -1}]
{a, {3, b, c}, d}
Given that heads are lost here, perhaps you want something like:
Replace[expr, h_[x___] :> {h, x}, {0, -1}]
{Plus, a, {Times, 3, b, c}, d}
If this is close to what you a related question that you should read is:
List manipulation to build a functional expression
Note: you may be tempted to try to simplify the code above by using ReplaceAll
(short form /.
) but you will find that it doesn't work. That's because the order of traversal is the opposite of Replace
, despite the similar names.
Comments
Post a Comment