避免在 Julia 中广播争论

gTc*_*TcV 5 julia

考虑这个非常现实问题的玩具版本:

julia> foo(a,b) = sum(a) + b
foo (generic function with 1 method)

julia> foo.([1,2],[3,4,5])
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape at ./broadcast.jl:57 [inlined] (repeats 2 times)
 [4] broadcast_indices at ./broadcast.jl:53 [inlined]
 [5] broadcast_c at ./broadcast.jl:311 [inlined]
 [6] broadcast(::Function, ::Array{Int64,1}, ::Array{Int64,1}) at ./broadcast.jl:434
Run Code Online (Sandbox Code Playgroud)

我希望上面的代码返回[6,7,8],但这并没有发生,因为broadcast点暗示的尝试匹配长度为 2 和 3 的输入向量,并将标量输入foo. 我怎样才能避免这种情况?

gTc*_*TcV 11

只需将您不想广播的参数包装成一个Ref

julia> foo.(Ref([1,2]),[3,4,5])
3-element Array{Int64,1}:
 6
 7
 8
Run Code Online (Sandbox Code Playgroud)

  • 最惯用的方法是将您不想广播的每个参数包装在一个 `Ref` 中:`Ref(myargument)`。 (3认同)