Skip to content

Commit

Permalink
Short-circuit all for AbstractFill (#329)
Browse files Browse the repository at this point in the history
* Short-circuit all for AbstractFill

* expand the cases in all

* Handle the fallback case through all

* Simplify implementation
  • Loading branch information
jishnub authored Feb 5, 2024
1 parent b04c00d commit 05804e4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/FillArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -643,8 +643,18 @@ end

# In particular, these make iszero(Eye(n)) efficient.
# use any/all on scalar to get Boolean error message
any(f::Function, x::AbstractFill) = !isempty(x) && any(f(getindex_value(x)))
all(f::Function, x::AbstractFill) = isempty(x) || all(f(getindex_value(x)))
function any(f::Function, x::AbstractFill)
isempty(x) && return false
# If the condition is true for one value, then it's true for all
fval = f(getindex_value(x))
any((fval,))
end
function all(f::Function, x::AbstractFill)
isempty(x) && return true
# If the condition is true for one value, then it's true for all
fval = f(getindex_value(x))
return all((fval,))
end
any(x::AbstractFill) = any(identity, x)
all(x::AbstractFill) = all(identity, x)

Expand Down
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,9 @@ end
@test iszero(Fill(SMatrix{2,2}(0,0,0,0), 2))
@test iszero(Fill(SMatrix{2,2}(0,0,0,1), 0))

# compile-time evaluation
@test @inferred((Z -> Val(iszero(Z)))(Zeros(3,3))) == Val(true)

@testset "all/any" begin
@test any(Ones{Bool}(10)) === all(Ones{Bool}(10)) === any(Fill(true,10)) === all(Fill(true,10)) === true
@test any(Zeros{Bool}(10)) === all(Zeros{Bool}(10)) === any(Fill(false,10)) === all(Fill(false,10)) === false
Expand All @@ -1339,6 +1342,11 @@ end
@test all(Fill(2,0))
@test !any(Fill(2,0))
@test any(Trues(2,0)) == any(trues(2,0))
@test_throws TypeError all(Fill(2,2))
@test all(iszero, Fill(missing,0)) === all(iszero, fill(missing,0)) === true
@test all(iszero, Fill(missing,2)) === all(iszero, fill(missing,2)) === missing
@test any(iszero, Fill(missing,0)) === any(iszero, fill(missing,0)) === false
@test any(iszero, Fill(missing,2)) === any(iszero, fill(missing,2)) === missing
end

@testset "Error" begin
Expand Down

0 comments on commit 05804e4

Please sign in to comment.