Is there a function in Base that determines the most specific type?

I’m currently wondering if there is a function anywhere in Base or the standard library that figures out the most specific type element for a given type (e.g. like multiple dispatch does).

I would like to have a function that receives a vector of type signatures (or a vector of types) and a “target type” and that returns the index of the most specific type

Update: Found something that does would I want in an earlier post.
Still, is this the best way to do this?

type_morespecific(a, b) = ccall(:jl_type_morespecific, Cint, (Any, Any), a, b)

function get_most_specific_type(types, target)
    candidates = filter(t -> target <: t, types)
    if isempty(candidates)
        return nothing
    end

    result = sort(candidates, lt = Bool∘type_morespecific)
    return first(result)
end

1 Like

Some notes:

  • there’s the Base.morespecific function, which does the ccall above, and converts to Bool
  • I don’t think there’s any supported way of doing what you want, morespecific isn’t a public interface
  • I guess a reduce(...) would be more efficient than first(sort(...))
3 Likes