Julia:如何通过修改用户提供的字段中的原始不可变结构来生成新的不可变结构?

Por*_*dow 3 struct metaprogramming julia

假设我有一些不可变的结构,例如

struct Person
           name::Symbol
           age::Int
       end;
Run Code Online (Sandbox Code Playgroud)

我想写一个函数

function copyWithModification(original_person::Person, fieldToChange::String, valueForNewField)::Person
Run Code Online (Sandbox Code Playgroud)

返回一个新的 Person 结构,就像旧的那样,除了 fieldToChange 中指定的字段的值已设置为 valueForNewField。我该怎么做呢?

我当前的尝试使用Setfield和元编程

using Setfield
function copyWithModification(original_person::Person, fieldToChange::String, valueForNewField)::Person
    return eval(Meta.parse("@set original_person." * fieldToChange * " = " * string(valueForNewField)))
end
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为 eval 是在全局范围内执行的,因此无法访问original_person对象:

julia> struct Person
                  name::Symbol
                  age::Int
              end;

julia> using Setfield

julia> function copyWithModification(original_person::Person, fieldToChange::String, valueForNewField)::Person
           return eval(Meta.parse("@set original_person." * fieldToChange * " = " * string(valueForNewField)))
       end
copyWithModification (generic function with 1 method)

julia> person_local_scope = Person(:test, 10)
Person(:test, 10)

julia> copyWithModification(person_local_scope, "age", 20)
ERROR: UndefVarError: original_person not defined
Stacktrace:
 [1] top-level scope at /Users/lionstarr/.julia/packages/Setfield/XM37G/src/sugar.jl:182
 [2] eval at ./boot.jl:330 [inlined]
 [3] eval(::Expr) at ./client.jl:425
 [4] copyWithModification(::Person, ::String, ::Int64) at ./REPL[3]:2
 [5] top-level scope at REPL[5]:1

julia> 
Run Code Online (Sandbox Code Playgroud)

我应该指出,我并不关心这段代码的性能;它只会被调用一次或两次。重点是节省代码复制和人为错误,因为我实际想要使用此代码的结构要大得多。

ffe*_*tte 5

如果您不关心性能,那么使用简单的内省就可以了,并且在您的情况下非常简单:

function copy_with_modification1(original::T, field_to_change, new_value) where {T}
    val(field) = field==field_to_change ? new_value : getfield(original, field)
    T(val.(fieldnames(T))...)
end
Run Code Online (Sandbox Code Playgroud)

例如,它产生以下结果:

julia> struct Person
           name::Symbol
           age::Int
       end

julia> p = Person(:Joe, 42)
Person(:Joe, 42)

julia> using BenchmarkTools
julia> @btime copy_with_modification1($p, :age, 43)
  666.924 ns (7 allocations: 272 bytes)
Person(:Joe, 43)
Run Code Online (Sandbox Code Playgroud)

为了恢复效率,可以通过在编译时列出字段的方式来实现相同类型的技术。这是使用生成函数的示例:

# Can't have closures inside generated functions, so the helper function
# is declared outside
function val_(original, field, field_to_change, new_value)
    field == field_to_change ? new_value : getfield(original, field)
end

@generated function copy_with_modification2(original, field_to_change, new_value)
    # This is the "compile-time" part
    T = original           # here `original` refers to the type of the argument
    fields = fieldnames(T) # fieldnames is called compile-time

    # This is the "run-time" part
    quote
        # We broadcast only over `fields`, other arguments are treated as scalars
        $T(val_.(Ref(original), $fields, Ref(field_to_change), Ref(new_value))...)
    end
end
Run Code Online (Sandbox Code Playgroud)

现在性能好多了:

julia> @btime copy_with_modification2($p, :age, 43)
  2.533 ns (0 allocations: 0 bytes)
Person(:Joe, 43)
Run Code Online (Sandbox Code Playgroud)