Skip to content

Commit

Permalink
Reduce code duplication in find* functions (JuliaLang#36965)
Browse files Browse the repository at this point in the history
  • Loading branch information
goretkin committed Nov 12, 2021
1 parent 3ef1f61 commit 8cf89d7
Showing 1 changed file with 6 additions and 43 deletions.
49 changes: 6 additions & 43 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)))
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 8cf89d7

Please sign in to comment.