Skip to content

Commit

Permalink
Make zero on array of arrays etc apply recursively (#51458)
Browse files Browse the repository at this point in the history
I wonder if this breaks things, in practice. It shouldn't. Since old
code behavior errored for the cases I am aware of.
As discussed in #38064, this definition is needed to be consistent with
our other linear algebra operations,
and with us considering a vector of vectors etc as a vector space.

Closes #38064
  • Loading branch information
oxinabox authored Feb 12, 2024
1 parent 57f02bf commit a459926
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ New library features
automatically.
* `@timed` now additionally returns the elapsed compilation and recompilation time ([#52889])
* `filter` can now act on a `NamedTuple` ([#50795]).
* `zero(::AbstractArray)` now applies recursively, so `zero([[1,2],[3,4,5]])` now produces the additive identity `[[0,0],[0,0,0]]` rather than erroring ([#38064]).

Standard library changes
------------------------
Expand Down
3 changes: 2 additions & 1 deletion base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1217,7 +1217,8 @@ function copymutable(a::AbstractArray)
end
copymutable(itr) = collect(itr)

zero(x::AbstractArray{T}) where {T} = fill!(similar(x, typeof(zero(T))), zero(T))
zero(x::AbstractArray{T}) where {T<:Number} = fill!(similar(x, typeof(zero(T))), zero(T))
zero(x::AbstractArray) = map(zero, x)

## iteration support for arrays by iterating over `eachindex` in the array ##
# Allows fast iteration by default for both IndexLinear and IndexCartesian arrays
Expand Down
11 changes: 11 additions & 0 deletions test/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1950,3 +1950,14 @@ end
@test repeat(f, 2, 3, 4) === FillArrays.Fill(3, (8, 6, 4))
@test repeat(f, inner=(1,2), outer=(3,1)) === FillArrays.Fill(3, (12, 4))
end

@testset "zero" begin
@test zero([1 2; 3 4]) isa Matrix{Int}
@test zero([1 2; 3 4]) == [0 0; 0 0]

@test zero([1.0]) isa Vector{Float64}
@test zero([1.0]) == [0.0]

@test zero([[2,2], [3,3,3]]) isa Vector{Vector{Int}}
@test zero([[2,2], [3,3,3]]) == [[0,0], [0, 0, 0]]
end

0 comments on commit a459926

Please sign in to comment.