在 Julia 中编写具有多个参数的变异函数

Writing a mutating function with multiple arguments in Julia

我正在尝试编写一个变异函数,其中作为第一个参数传递的值根据第二个参数发生变异。

例如,对于向量 b 不是 0 的那些索引,下面的 remove_when_zero_in_b 应该 return 向量 a 中的值。

"""filters 'a' when there is a zero in 'b'"""
function remove_when_zero_in_b!(a::AbstractVector, b::Vector{<:Real})
    a = a[b .!= 0]
    a
end

例如

x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [0,   1,   0,   2  , 0 ]

remove_when_zero_in_b!(x, y) # should mutate x

那么x应该是:

println(x)
2-element Vector{Float64}:
 2.0
 4.0

但是,上面的函数不会改变 x 并保持为具有 5 个元素的初始向量。

我在这里错过了什么?一个函数如何改变 x 以便我获得所需的结果?

a = a[b .!= 0]新建一个a副本,可以这样写,

function remove_when_zero_in_b!(a::AbstractVector, b::Vector{<:Real})
    deleteat!(a, b .== 0)
    a
end