Is there a method to check if a vector is "sortable"?

In a Decision Tree algorithm I implement an optimisation where I first sort the vector of data once and then I pick up the various items with searchsorted.
All fine for integers, floats, even strings… but If the vector is of custom types for which no isless is defined it shouldn’t work.

Is there then a method I can first check on a Vector{T} to see if the vector is sortable, without relying to use exceptions ?

The Julia documentation concerning “sorting” is here, but I couldn’t find any reference to a issortable function :slight_smile:

If the custom type is defined by you can you write your own isless(a::T, b::T) where {T} function?

Unfortunately this is for a library and I don’t know the type in advance…

But you can check if isless is defined for the elements in the vector, for example with applicable.

1 Like

You could check whether there is a isless method for the element type, i.e., hasmethod(isless, Tuple{T,T}).

6 Likes

Thanks. This works:

mutable struct SortableType
    x::Int64
    y::Int64
end

mutable struct UnsortableType
    x::Int64
    y::Int64
end
isless(x::SortableType,y::SortableType) = x.x < y.x

SortableVector   = [SortableType(2,4),SortableType(1,5),SortableType(1,8),missing]
UnsortableVector = [UnsortableType(2,4),UnsortableType(1,5),missing,UnsortableType(1,8)]

issortable(::AbstractArray{T,N})  where {T,N} = hasmethod(isless, Tuple{nonmissingtype(T),nonmissingtype(T)})
issortable(SortableVector)   # true
issortable(UnsortableVector) # false

[Edited: added support for Unions{T,Missing}]
[Edited 2: using AbstractArray instead of Array]

If this has to be fast, you could use static_hasmethod from Tricks.jl.

2 Likes