避免广播朱莉娅的争论

时间:2017-11-17 08:32:19

标签: 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

我希望上面的代码返回[6,7,8],但这并没有发生,因为点所暗示的broadcast会尝试匹配长度为2和3的输入向量,并将标量提供给两个参数foo。我怎么能避免这个?

1 个答案:

答案 0 :(得分:4)

只需将您不想广播的参数包装到Ref

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