在 Julia 中修改 AbstractTrees.PreOrderDFS/Leaves 中的元素不会更新原始数据结构

问题描述 投票:0回答:1

我正在与 Julia 合作,并使用

AbstractTrees
包来使用
PreOrderDFS/Leaves
遍历树结构。我的目标是在遍历树时修改树的元素。但是,我注意到在循环中修改
node
似乎并没有更新原始数据结构(在我的例子中为
mainexp
)。这是我的代码的简化版本:

using AbstractTrees

# Assuming mainexp is a tree structure
mainexp = ...#some expression

# Traverse the tree in pre-order
for node in AbstractTrees.PreOrderDFS(mainexp)
    if isa(node, Expr)
        node = :(...)#some other expr
    end
    # ...
end

# mainexp remains unchanged here, despite modifications to the nodes

在这个循环之后,我期望

mainexp
能够反映遍历期间对节点所做的更改,但似乎原始数据结构没有被更新。

有没有办法在 Julia 中实现这一目标?我在使用

AbstractTrees
或修改节点的方式中是否遗漏了某些内容?我将不胜感激任何能够演示如何在遍历原始树结构时修改原始树结构的见解或示例。

提前感谢您的帮助!

tree julia
1个回答
1
投票

node = whatever
始终分配给变量
node
并且从不更新原始变量。执行此操作的正确方法如下所示,它就地更新原始节点。

...
if isa(node, Expr)
    new_ex = :(...) # some other expr
    for fieldname in fieldnames(new_ex)
        setfield!(node, fieldname, getfield(new_ex, fieldname))
    end
end
...
© www.soinside.com 2019 - 2024. All rights reserved.