Skip to content

Commit

Permalink
Make zero on array of arrays apply recursively
Browse files Browse the repository at this point in the history
  • Loading branch information
oxinabox committed Sep 27, 2023
1 parent 8de80bd commit 8384dab
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 @@ -35,6 +35,7 @@ New library features
--------------------
* `replace(string, pattern...)` now supports an optional `IO` argument to
write the output to a stream rather than returning a string ([#48625]).
* `zero(::AbstractArray)` now applies recursively, so `zero([[1,2],[3,4,5]])` now produces `[[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 @@ -1198,7 +1198,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 @@ -1860,3 +1860,14 @@ f45952(x) = [x;;]
@test_throws "invalid index: true of type Bool" isassigned(A, 1, true)
@test_throws "invalid index: true of type Bool" isassigned(A, true)
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 8384dab

Please sign in to comment.