RazrFalcon / rctree

A "DOM-like" tree implemented using reference counting
MIT License
36 stars 10 forks source link

Best approach for converting from Node<TypeA> tree to a Node<TypeB> tree? #13

Closed Keavon closed 4 years ago

Keavon commented 4 years ago

I have an rctree tree of the type TypeA, which is a type that can be easily converted to type TypeB (in my case, TypeB is just a value stored in an enum variant of TypeA). I would like to convert the whole tree over (by cloning it). I couldn't see any easy way to do this based on the documentation, unless I missed something. However this seems like a commonly needed action. If it's not a built-in feature, what code should I write to make a function that performs this conversion?

RazrFalcon commented 4 years ago

You want to keep a tree structure, but replace values?

Keavon commented 4 years ago

Correct, I want to keep the existing tree structure.

RazrFalcon commented 4 years ago

You have to do this manually. There is no function that does this.

Keavon commented 4 years ago

Could you suggest an approach for the algorithm that best utilizes what's provided by the library, such as one of the different types of iterators? I'm kind of at a loss while trying to design the pseudocode taking into account the features of the library.

RazrFalcon commented 4 years ago

I was wrong. It's not possible. Node's data is generic, so you cannot swap it.

The only solution is to store enum instead and change it via Node::borrow_mut.

Keavon commented 4 years ago

I was able to implement this with the following code:

fn type_b_from_type_a(a: &rctree::Node<TypeA>) -> rctree::Node<TypeB> {
    let b = match &*a.borrow() {
        TypeA::CaseWithTypeB(node) => node.clone(),
        _ => panic!(),
    };

    let mut tree_result = rctree::Node::new(b);

    for tree_node in a.children() {
        tree_result.append(type_b_from_type_a(&tree_node));
    }

    tree_result
}