Skip to content

inference: if it doesn't know how to quack, it can't be a duck #37866

@KristofferC

Description

@KristofferC

It would be cool if inference could figure out that if you call a method on an object inferred as a union, inference could ignore all types that are known to throw with that method for future expressions in that block. For example:

function find_first_above_5(v::Vector{Union{Nothing, Float64}})
    for x in v
        if x > 5.0
            return x # x > 5.0 is MethodError for Nothing so can assume ::Float64
        end
    end
    return 0.0
end

x = Union{Nothing, Float64}[1.0, 2.0, 3.0, 6.0, 4.0]
find_first_above_5(x)
# 6.0

Core.Compiler.return_types(find_first_above_5, Tuple{Vector{Union{Nothing, Float64}}})
# 1-element Array{Any,1}:
#  Union{Nothing, Float64}

code_warntype(find_first_above_5, Tuple{Vector{Union{Nothing, Float64}}})

Here, a return value of Float64 could be inferred.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions