Skip to content

Commit 43d2961

Browse files
JeffBezansonnalimilan
authored andcommitted
Revert "Optimize findall(f, ::AbstractArray{Bool}) (#42202)" (#51039)
This reverts commit 4c4c94f. (Except keeps the tests and adds a new one) fixes #46425 (cherry picked from commit defe187)
1 parent 41d78b0 commit 43d2961

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
@@ -2487,42 +2487,19 @@ function findall(A)
24872487
end
24882488

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

2522-
findall(f::Function, A::AbstractArray{Bool}) = _findall(f, A)
2523-
findall(f::Fix2{typeof(in)}, A::AbstractArray{Bool}) = _findall(f, A)
2524-
findall(A::AbstractArray{Bool}) = _findall(identity, A)
2525-
25262503
findall(x::Bool) = x ? [1] : Vector{Int}()
25272504
findall(testf::Function, x::Number) = testf(x) ? [1] : Vector{Int}()
25282505
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)