Skip to content

Commit defe187

Browse files
authored
Revert "Optimize findall(f, ::AbstractArray{Bool}) (#42202)" (#51039)
This reverts commit 4c4c94f. (Except keeps the tests and adds a new one) fixes #46425
1 parent be65c65 commit defe187

File tree

2 files changed

+17
-31
lines changed

2 files changed

+17
-31
lines changed

base/array.jl

Lines changed: 8 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2486,42 +2486,19 @@ function findall(A)
24862486
end
24872487

24882488
# Allocating result upfront is faster (possible only when collection can be iterated twice)
2489-
function _findall(f::Function, A::AbstractArray{Bool})
2490-
n = count(f, A)
2489+
function findall(A::AbstractArray{Bool})
2490+
n = count(A)
24912491
I = Vector{eltype(keys(A))}(undef, n)
2492-
isempty(I) && return I
2493-
_findall(f, I, A)
2494-
end
2495-
2496-
function _findall(f::Function, I::Vector, A::AbstractArray{Bool})
2497-
cnt = 1
2498-
len = length(I)
2499-
for (k, v) in pairs(A)
2500-
@inbounds I[cnt] = k
2501-
cnt += f(v)
2502-
cnt > len && return I
2503-
end
2504-
# In case of impure f, this line could potentially be hit. In that case,
2505-
# we can't assume I is the correct length.
2506-
resize!(I, cnt - 1)
2507-
end
2508-
2509-
function _findall(f::Function, I::Vector, A::AbstractVector{Bool})
2510-
i = firstindex(A)
25112492
cnt = 1
2512-
len = length(I)
2513-
while cnt len
2514-
@inbounds I[cnt] = i
2515-
cnt += f(@inbounds A[i])
2516-
i = nextind(A, i)
2493+
for (i,a) in pairs(A)
2494+
if a
2495+
I[cnt] = i
2496+
cnt += 1
2497+
end
25172498
end
2518-
cnt - 1 == len ? I : resize!(I, cnt - 1)
2499+
I
25192500
end
25202501

2521-
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
2522-
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
2523-
findall(A::AbstractArray{Bool}) = _findall(identity, A)
2524-
25252502
findall(x::Bool) = x ? [1] : Vector{Int}()
25262503
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
25272504
findall(p::Fix2{typeof(in)}, x::Number) = x in p.x ? [1] : Vector{Int}()

test/arrayops.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,15 @@ end
604604
@testset "issue 43078" begin
605605
@test_throws TypeError findall([1])
606606
end
607+
608+
@testset "issue #46425" begin
609+
counter = 0
610+
function pred46425(x)
611+
counter += 1
612+
counter < 4 && x
613+
end
614+
@test findall(pred46425, [false, false, true, true]) == [3]
615+
end
607616
end
608617
@testset "find with Matrix" begin
609618
A = [1 2 0; 3 4 0]

0 commit comments

Comments
 (0)