Here you have two options:
- Make your objects mutable, and then just use the same methods as in Java.
- Make them immutable, and then discard the two-way dependencies.
To understand why, consider the following conversion between (immutable) trees. They are both defined with each parent node containing a list of child nodes, but the children do not know their parent:
a (a) b (b) cc d --> (d) ee ff gg
In particular, node d was cloned with a new value. To do this, we also had to clone all the parent nodes (shown in brackets).
If the nodes held their parent, then c need to be "updated" to reflect the new b node, and e, f, g would need to be updated to reflect the new a node, i.e. you will need to copy the whole tree!
Only by maintaining relationships in one direction, from parent to child, does it become possible to reuse c, e, f, g for successive versions of the structure. This is a powerful optimization and the key to writing effective functional algorithms.
Kevin wright
source share