Trouble with isless for an immutable type


#1

I feel like I’m missing something obvious, but why doesn’t this work:

julia> immutable Counts
          j::Int32
          i::Int32
          nij::Int64
       end

julia> # allocate something
       test = Array{Counts,1}()
0-element Array{Counts,1}

julia> for i in 1:10
               push!(test,Counts(rand(Int32),rand(Int32),rand(Int64)))
       end

julia> # is x < y ?
       isless(x::Counts, y::Counts) = (x.j < y.j) || ((x.j == y.j) && (x.i < y.i)) || ((x.j == y.j) && (x.i == y.i) && (x.nij < y.nij))
isless (generic function with 1 method)

julia> sort!(test)
ERROR: MethodError: no method matching isless(::Counts, ::Counts)
 in sort!(::Array{Counts,1}, ::Int64, ::Int64, ::Base.Sort.InsertionSortAlg, ::Base.Order.ForwardOrdering) at ./sort.jl:222
 in sort!(::Array{Counts,1}, ::Int64, ::Int64, ::Base.Sort.MergeSortAlg, ::Base.Order.ForwardOrdering, ::Array{Counts,1}) at ./sort.jl:311
 in sort!(::Array{Counts,1}, ::Base.Sort.MergeSortAlg, ::Base.Order.ForwardOrdering) at ./sort.jl:405
 in sort!(::Array{Counts,1}) at ./sort.jl:414

I define a simple immutable type, and just want to sort an array of them
in lexicographic order.

Am I defining isless wrong somehow?

Thanks,
Craig


#2

Try this:
Base.isless(x::Counts, y::Counts) = (x.j < y.j) || ...


#3

Or

import Base.isless

isless(x::Counts, y::Counts) = (x.j < y.j) || ((x.j == y.j) && (x.i < y.i)) || ((x.j == y.j) && (x.i == y.i) && (x.nij < y.nij))

#4

Thanks for the quick reply. I thought there was an implicit ‘using Base’, but apparently not. I’m still new to Julia.


#5

There is an implicit using Base but it doesn’t import all the symbols for extending so that adding a function in Base won’t be a breaking change. Ref http://docs.julialang.org/en/stable/manual/modules/