From 4efacb69a4da0bdb4742b10885220f49595d4adf Mon Sep 17 00:00:00 2001 From: Sacha Verweij Date: Fri, 30 Dec 2016 03:25:42 -0800 Subject: [PATCH] Make broadcast!(f, A) populate A via independent f() calls rather than fill!(A, f()). (#19722) (cherry picked from commit 50a8b9637d04141d82e4b730bac688f4a6be3c36) --- base/broadcast.jl | 2 +- test/broadcast.jl | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/base/broadcast.jl b/base/broadcast.jl index aee5920bb9386..08f27b053ba89 100644 --- a/base/broadcast.jl +++ b/base/broadcast.jl @@ -17,7 +17,7 @@ broadcast(f, x::Number...) = f(x...) # special cases for "X .= ..." (broadcast!) assignments broadcast!(::typeof(identity), X::AbstractArray, x::Number) = fill!(X, x) -broadcast!(f, X::AbstractArray) = fill!(X, f()) +broadcast!(f, X::AbstractArray) = (@inbounds for I in eachindex(X); X[I] = f(); end; X) broadcast!(f, X::AbstractArray, x::Number...) = fill!(X, f(x...)) function broadcast!{T,S,N}(::typeof(identity), x::AbstractArray{T,N}, y::AbstractArray{S,N}) check_broadcast_shape(size(x), size(y)) diff --git a/test/broadcast.jl b/test/broadcast.jl index d9a5c342d8319..3705cab232300 100644 --- a/test/broadcast.jl +++ b/test/broadcast.jl @@ -320,3 +320,6 @@ end let A17984 = [] @test isa(abs.(A17984), Array{Any,1}) end + +# Check that broadcast!(f, A) populates A via independent calls to f (#12277, #19722). +@test let z = 1; A = broadcast!(() -> z += 1, zeros(2)); A[1] != A[2]; end