Skip to content

Commit b889962

Browse files
committed
Reduce code duplication in find* functions
1 parent 426dd8e commit b889962

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
@@ -1720,18 +1720,7 @@ julia> findnext(A, CartesianIndex(1, 1))
17201720
CartesianIndex(2, 1)
17211721
```
17221722
"""
1723-
function findnext(A, start)
1724-
l = last(keys(A))
1725-
i = oftype(l, start)
1726-
i > l && return nothing
1727-
while true
1728-
A[i] && return i
1729-
i == l && break
1730-
# nextind(A, l) can throw/overflow
1731-
i = nextind(A, i)
1732-
end
1733-
return nothing
1734-
end
1723+
findnext(A, start) = findnext(identity, A, start)
17351724

17361725
"""
17371726
findfirst(A)
@@ -1766,14 +1755,7 @@ julia> findfirst(A)
17661755
CartesianIndex(2, 1)
17671756
```
17681757
"""
1769-
function findfirst(A)
1770-
for (i, a) in pairs(A)
1771-
if a
1772-
return i
1773-
end
1774-
end
1775-
return nothing
1776-
end
1758+
findfirst(A) = findfirst(identity, A)
17771759

17781760
# Needed for bootstrap, and allows defining only an optimized findnext method
17791761
findfirst(A::Union{AbstractArray, AbstractString}) = findnext(A, first(keys(A)))
@@ -1907,18 +1889,7 @@ julia> findprev(A, CartesianIndex(2, 1))
19071889
CartesianIndex(2, 1)
19081890
```
19091891
"""
1910-
function findprev(A, start)
1911-
f = first(keys(A))
1912-
i = oftype(f, start)
1913-
i < f && return nothing
1914-
while true
1915-
A[i] && return i
1916-
i == f && break
1917-
# prevind(A, f) can throw/underflow
1918-
i = prevind(A, i)
1919-
end
1920-
return nothing
1921-
end
1892+
findprev(A, start) = findprev(identity, A, start)
19221893

19231894
"""
19241895
findlast(A)
@@ -1954,14 +1925,7 @@ julia> findlast(A)
19541925
CartesianIndex(2, 1)
19551926
```
19561927
"""
1957-
function findlast(A)
1958-
for (i, a) in Iterators.reverse(pairs(A))
1959-
if a
1960-
return i
1961-
end
1962-
end
1963-
return nothing
1964-
end
1928+
findlast(A) = findlast(identity, A)
19651929

19661930
# Needed for bootstrap, and allows defining only an optimized findprev method
19671931
findlast(A::Union{AbstractArray, AbstractString}) = findprev(A, last(keys(A)))
@@ -2145,9 +2109,8 @@ julia> findall(falses(3))
21452109
Int64[]
21462110
```
21472111
"""
2148-
function findall(A)
2149-
collect(first(p) for p in pairs(A) if last(p))
2150-
end
2112+
findall(A) = findall(identity, A)
2113+
21512114
# Allocating result upfront is faster (possible only when collection can be iterated twice)
21522115
function findall(A::AbstractArray{Bool})
21532116
n = count(A)

0 commit comments

Comments
 (0)