# Efficient lexicographic ordering of custom types?

**URL:** <https://discourse.julialang.org/t/efficient-lexicographic-ordering-of-custom-types/55209>\
**Category:** General Usage\
**Created:** [February 13, 2021, 2:05pm UTC](https://discourse.julialang.org/t/efficient-lexicographic-ordering-of-custom-types/55209 "2021-02-13T14:05:53Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [February 13, 2021, 2:11pm UTC](https://discourse.julialang.org/t/efficient-lexicographic-ordering-of-custom-types/55209/2 "2021-02-13T14:11:09Z")

</div>

Could be like this? Of course the order of evaluation of the fields should be specified somwhere, here  
is just the order they appear in the struct.

```julia
julia> struct Car
           model::String
           year::Int32
           miles::Int32
       end

julia> fieldnames(Car)
(:model, :year, :miles)

julia> function isless(c1::Car,c2::Car)
         for field in fieldnames(Car)
           if getfield(c1,field) < getfield(c2,field)
             return true
           elseif getfield(c1,field) > getfield(c2,field)
             return false
           end
         end
         return false
       end
isless (generic function with 1 method)

julia> c1 = Car("Fusca",1975,10_000)
Car("Fusca", 1975, 10000)

julia> c2 = Car("Chevete",1985,20_000)
Car("Chevete", 1985, 20000)

julia> isless(c1,c2)
false

julia> isless(c2,c1)
true

julia>

```

Edit: `getfield`, if I am not mistaken, is a inherently type-unstable function. Thus, if this is going to be critical for performance, other alternatives are probably better, even if less general.

You may need to fall into this, at the end: [Macro to write function with many conditionals - #8 by Skoffer](https://discourse.julialang.org/t/macro-to-write-function-with-many-conditionals/51616/8)

---

_[View the full topic](https://discourse.julialang.org/t/efficient-lexicographic-ordering-of-custom-types/55209)._
