mzaks / mojo-sort

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not an "issue," but rather an interface idea.

dimitrilw opened this issue · comments

I do not believe that Mojo has a Comparable Trait. However, if we defined a Sortable trait in this repo, then it could enable use of Python standard dunder methods instead of a custom less-than-or-equal function. I'm thinking something like this rough pseudo-Mojo code:

trait Sortable:
    # less than or equal (`<=`)
    fn __le__(self, other: Self) -> Bool: ...

Doing this would allow python devs to think in classic dunder methods when making a "sortable" Struct. Roughly something like:

struct MyStruct(Comparable):
    var s: String
    var i: Int
    var b: Bool

   # ...code for init and whatever else...

    fn __le__(self, other: Self) -> Bool:
        """ Less Than  or Equal (`<=`)
    
            Sorts on the basis of:
                - lowest 'i' first
                - ties broken by lowest 's'
                - b is not factored in at all
        """
        if self.i == other.i:
            # I realize the next line doesn't work with strings. 
            # And that is just awaiting future updates to the std-lib in order to bring the dunder methods
            # to Strings so they match the Python API (pic below)
            return self.s <= other.s 
        return self.i < other.i

By making that sort logic in the __le__() dunder-method, the various sort APIs (like quick_sort) could take any list of Sortable elements, and use the element's built-in __le__() implementation.

Your thoughts?
image