Skip to content

Create a function to use type inference for eltype #54157

@Tortar

Description

@Tortar

I'm using this function to compute the type generically for iterators:

function compute_eltype(iter)
    T = eltype(iter)
    return T === Any ? Base.@default_eltype(iter) : T
end

and I'm asking myself if this couldn't be applied by default to some generators and iterators which currently returns Any (actually if it is applied specifically to just those types it can be used only Base.@default_eltype(iter) I think)

For example consider

julia> iter = Iterators.flatten(((3,), [4, 5]))
Base.Iterators.Flatten{Tuple{Tuple{Int64}, Vector{Int64}}}(((3,), [4, 5]))

julia> iter = Iterators.flatten(((3,), [4, 5]))

julia> eltype(iter)
Any

julia> compute_eltype(iter)
Int64

julia> iter = (x^2 for x in 1:10)
Base.Generator{UnitRange{Int64}, var"#3#4"}(var"#3#4"(), 1:10)

julia> eltype(iter)
Any

julia> compute_eltype(iter)
Int64

Performance-wise I see a cost of a couple of ns. I found that there is this other issue and associated PR about a special case of this: #48249 and #48277, but I think that a function as above could be applied more generally. Would this be okay? Or is this problematic?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions