Skip to content

Commit 8cf89d7

Browse files
authored
Reduce code duplication in find* functions (JuliaLang#36965)
1 parent 3ef1f61 commit 8cf89d7

File tree

1 file changed

+6
-43
lines changed

1 file changed

+6
-43
lines changed

base/array.jl

Lines changed: 6 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1923,18 +1923,7 @@ julia> findnext(A, CartesianIndex(1, 1))
19231923
CartesianIndex(2, 1)
19241924
```
19251925
"""
1926-
function findnext(A, start)
1927-
l = last(keys(A))
1928-
i = oftype(l, start)
1929-
i > l && return nothing
1930-
while true
1931-
A[i] && return i
1932-
i == l && break
1933-
# nextind(A, l) can throw/overflow
1934-
i = nextind(A, i)
1935-
end
1936-
return nothing
1937-
end
1926+
findnext(A, start) = findnext(identity, A, start)
19381927

19391928
"""
19401929
findfirst(A)
@@ -1971,14 +1960,7 @@ julia> findfirst(A)
19711960
CartesianIndex(2, 1)
19721961
```
19731962
"""
1974-
function findfirst(A)
1975-
for (i, a) in pairs(A)
1976-
if a
1977-
return i
1978-
end
1979-
end
1980-
return nothing
1981-
end
1963+
findfirst(A) = findfirst(identity, A)
19821964

19831965
# Needed for bootstrap, and allows defining only an optimized findnext method
19841966
findfirst(A::AbstractArray) = findnext(A, first(keys(A)))
@@ -2114,18 +2096,7 @@ julia> findprev(A, CartesianIndex(2, 1))
21142096
CartesianIndex(2, 1)
21152097
```
21162098
"""
2117-
function findprev(A, start)
2118-
f = first(keys(A))
2119-
i = oftype(f, start)
2120-
i < f && return nothing
2121-
while true
2122-
A[i] && return i
2123-
i == f && break
2124-
# prevind(A, f) can throw/underflow
2125-
i = prevind(A, i)
2126-
end
2127-
return nothing
2128-
end
2099+
findprev(A, start) = findprev(identity, A, start)
21292100

21302101
"""
21312102
findlast(A)
@@ -2163,14 +2134,7 @@ julia> findlast(A)
21632134
CartesianIndex(2, 1)
21642135
```
21652136
"""
2166-
function findlast(A)
2167-
for (i, a) in Iterators.reverse(pairs(A))
2168-
if a
2169-
return i
2170-
end
2171-
end
2172-
return nothing
2173-
end
2137+
findlast(A) = findlast(identity, A)
21742138

21752139
# Needed for bootstrap, and allows defining only an optimized findprev method
21762140
findlast(A::AbstractArray) = findprev(A, last(keys(A)))
@@ -2360,9 +2324,8 @@ julia> findall(falses(3))
23602324
Int64[]
23612325
```
23622326
"""
2363-
function findall(A)
2364-
collect(first(p) for p in pairs(A) if last(p))
2365-
end
2327+
findall(A) = findall(identity, A)
2328+
23662329
# Allocating result upfront is faster (possible only when collection can be iterated twice)
23672330
function findall(A::AbstractArray{Bool})
23682331
n = count(A)

0 commit comments

Comments
 (0)