:

## Expression trees

Maple
Note added: As correctly pointed out by Joe Riel in his post below, my function fromTree fails doing what it is supposed to do for expressions which contain lists and/or sets. For a version of fromTree which behaves properly (I believe) also for expressions containing lists and/or sets, see my post below. Consider the following two functions:
```toTree   := x -> `if`(op(x) = x,x,[op(0,x),map(toTree,[op(x)])[]]):
fromTree := x -> `if`(op(x) = x,x,x[1](seq(fromTree(x[i]),i=2..nops(x)))):
```
They can be used to transform between an expression itself and its equivalent expression tree (here implemented as nested lists). Among other things, this functionality is useful for gaining some insight into the way Maple internally represent various expressions. Some examples: 1. The complex imaginary unit:
```> toTree(I);
[Complex, 1]
```
This shows that internally to Maple the complex imaginary unit I is implemented as
```> Complex(1);
I
```
2. A general complex number:
```> tree := toTree(a + I*b);
tree := [+, a, [*, [Complex, 1], b]]
```
This tree may be translated back to the original complex number:
```> fromTree(tree);
a + I b
```
3. An unsolvable integral:
```> expr := int(exp(cos(x)),x):
> tree := toTree(expr);
> fromTree(tree);
tree := [int, [exp, [cos, x]], x]
int(exp(cos(x)), x)
```
4. A 'solvable' integral (quite complicated, just for the fun of it):
```expr := int(exp(x^3),x):
tree := toTree(expr);
fromTree(tree);
```
tree := [`*`, [Fraction, -1, 3], [`^`, -1, [Fraction, 2, 3]], [`+`, [`*`, [Fraction, 2, 3], x, [`^`, -1, [Fraction, 1, 3]], Pi, [`^`, 3, [Fraction, 1, 2]], [`^`, [GAMMA, [Fraction, 2, 3]], -1], [`^`, [`*`, -1, [`^`, x, 3]], [Fraction, -1, 3]]], [`*`, -1, x, [`^`, -1, [Fraction, 1, 3]], [`^`, [`*`, -1, [`^`, x, 3]], [Fraction, -1, 3]], [GAMMA, [Fraction, 1, 3], [`*`, -1, [`^`, x, 3]]]]]] -1/3*(-1)^(2/3)*(2/3*x*(-1)^(1/3)*Pi*3^(1/2)/(GAMMA(2/3)*(-x^3)^(1/3))-x*(-1)^(1/3)*GAMMA(1/3, -x^3)/(-x^3)^(1/3))

﻿