From 8cf89d7a373f66411fa0fc3ed06595628d1c4d80 Mon Sep 17 00:00:00 2001 From: Gustavo Goretkin Date: Fri, 12 Nov 2021 12:03:32 -0500 Subject: [PATCH] Reduce code duplication in find* functions (#36965) --- base/array.jl | 49 ++++++------------------------------------------- 1 file changed, 6 insertions(+), 43 deletions(-) diff --git a/base/array.jl b/base/array.jl index db5dc84c0398c..d44a0b44d2e44 100644 --- a/base/array.jl +++ b/base/array.jl @@ -1923,18 +1923,7 @@ julia> findnext(A, CartesianIndex(1, 1)) CartesianIndex(2, 1) ``` """ -function findnext(A, start) - l = last(keys(A)) - i = oftype(l, start) - i > l && return nothing - while true - A[i] && return i - i == l && break - # nextind(A, l) can throw/overflow - i = nextind(A, i) - end - return nothing -end +findnext(A, start) = findnext(identity, A, start) """ findfirst(A) @@ -1971,14 +1960,7 @@ julia> findfirst(A) CartesianIndex(2, 1) ``` """ -function findfirst(A) - for (i, a) in pairs(A) - if a - return i - end - end - return nothing -end +findfirst(A) = findfirst(identity, A) # Needed for bootstrap, and allows defining only an optimized findnext method findfirst(A::AbstractArray) = findnext(A, first(keys(A))) @@ -2114,18 +2096,7 @@ julia> findprev(A, CartesianIndex(2, 1)) CartesianIndex(2, 1) ``` """ -function findprev(A, start) - f = first(keys(A)) - i = oftype(f, start) - i < f && return nothing - while true - A[i] && return i - i == f && break - # prevind(A, f) can throw/underflow - i = prevind(A, i) - end - return nothing -end +findprev(A, start) = findprev(identity, A, start) """ findlast(A) @@ -2163,14 +2134,7 @@ julia> findlast(A) CartesianIndex(2, 1) ``` """ -function findlast(A) - for (i, a) in Iterators.reverse(pairs(A)) - if a - return i - end - end - return nothing -end +findlast(A) = findlast(identity, A) # Needed for bootstrap, and allows defining only an optimized findprev method findlast(A::AbstractArray) = findprev(A, last(keys(A))) @@ -2360,9 +2324,8 @@ julia> findall(falses(3)) Int64[] ``` """ -function findall(A) - collect(first(p) for p in pairs(A) if last(p)) -end +findall(A) = findall(identity, A) + # Allocating result upfront is faster (possible only when collection can be iterated twice) function findall(A::AbstractArray{Bool}) n = count(A)