Skip to content

Add recursive findfirst method for tuples. #42423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,23 @@ _totuple(::Type{Tuple}, itr::NamedTuple) = (itr...,)

end

## find ##

_findfirst_rec(f, i::Int, ::Tuple{}) = nothing
_findfirst_rec(f, i::Int, t::Tuple) = (@inline; f(first(t)) ? i : _findfirst_rec(f, i+1, tail(t)))
function _findfirst_loop(f::Function, t)
for i in 1:length(t)
f(t[i]) && return i
end
return nothing
end
findfirst(f::Function, t::Tuple) = length(t) < 32 ? _findfirst_rec(f, 1, t) : _findfirst_loop(f, t)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this should be <= if we want to include the 32 case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with < because Jeff did here: https://github.com/JuliaLang/julia/pull/42263/files


function findlast(f::Function, x::Tuple)
r = findfirst(f, reverse(x))
return isnothing(r) ? r : length(x) - r + 1
end

## filter ##

filter_rec(f, xs::Tuple) = afoldl((ys, x) -> f(x) ? (ys..., x) : ys, (), xs...)
Expand Down
14 changes: 14 additions & 0 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,20 @@ end
@test findnext(isequal(1), (1, 1), UInt(2)) isa Int
@test findprev(isequal(1), (1, 1), UInt(1)) isa Int
end

# recursive implementation should allow constant-folding for small tuples
@test Base.return_types() do
findfirst(==(2), (1.0,2,3f0))
end == Any[Int]
@test Base.return_types() do
findfirst(==(0), (1.0,2,3f0))
end == Any[Nothing]
@test Base.return_types() do
findlast(==(2), (1.0,2,3f0))
end == Any[Int]
@test Base.return_types() do
findlast(==(0), (1.0,2,3f0))
end == Any[Nothing]
end

@testset "properties" begin
Expand Down