如何在 Julia 中查找和替换 AST 的子表达式

How to find and replace subexpression of AST in Julia

假设我有一个像 :(Main.i / (0.5 * Main.i * sin(Main.i)).

这样的表达式

我想将每次出现的 Main.i 替换为其他符号。在 Julia 中有惯用的方法吗?

Main.i 不是一个符号而是一个表达式,你可以通过 dump(:(Main.i)).

来检查

这是我认为可能满足您需求的快速记录:

function expr_replace(expr, old, new)
    expr == old && return new
    if expr isa Expr
        expr = deepcopy(expr) # to avoid mutation of source
        for i in eachindex(expr.args)
            expr.args[i] = expr_replace(expr.args[i], old, new)
        end
    end
    expr
end

对你有用吗?

编辑:这是一个最小安全使用 deepcopy:

的版本
function expr_replace(expr, old, new)
    function f(expr)
        expr == old && return deepcopy(new)
        if expr isa Expr
            for i in eachindex(expr.args)
                expr.args[i] = f(expr.args[i])
            end
        end
        expr
    end

    f(deepcopy(expr))
end

总的来说,我想这无关紧要,因为您可能不想通过此函数传递 100 行代码。