Why does findfirst(==(T), ...) on a tuple of typed only constant fold for the first?

Should we define a recursive findfirst implementation for tuples?

julia> _findfirst(f, i, ::Tuple{}) = nothing
_findfirst (generic function with 1 method)

julia> _findfirst(f, i, x) = f(first(x)) ? i : _findfirst(f, i+1, Base.tail(x))
_findfirst (generic function with 2 methods)

julia> myfindfirst(f::F, x::Tuple) where {F} = _findfirst(f, 1, x)
myfindfirst (generic function with 1 method)

julia> position(::T) where {T} = myfindfirst(==(T), (Int, Float64, Char))
position (generic function with 1 method)

julia> @code_typed position(10)
CodeInfo(
1 ─     return 1
) => Int64

julia> @code_typed position(2.4)
CodeInfo(
1 ─     return 2
) => Int64

julia> @code_typed position('a')
CodeInfo(
1 ─     return 3
) => Int64

julia> @code_typed position(1f0)
CodeInfo(
1 ─     return nothing
) => Nothing
4 Likes