We can define a tree by speciying a enum for the Nodes as follows:
pub struct Node(Rc<NodeBase>);
pub enum NodeBase {
String(String),
Int(i32),
Foo(Node),
Bar(Node, Node),
Cat(Node, Node),
Dog(Vec<Node>),
Wolf(Vec<Node>),
}
This is a tree where each Node is either a Terminal (Sgtring, Int), has a fixed number of children (Foo, Bar, Cat), or an arbitrary number of children (Dog, Wolf),
This works fine if all I need is to:
- point at root of tree
- recursively map over entire tree
However, as much as we hate shared mutable state, I need a way to point at individual nodes & modify that node to update the tree.
What is the best way to do this?
Pre-emptive questions:
- Can the structure be a DAG, or is it guaranteed to be a tree?
It's guaranteed to be a tree.
- What is an update causes a loop?
Undefined behaviour. Programmer's fault.