seq-lang / seq

A high-performance, Pythonic language for bioinformatics

Home Page:https://seq-lang.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Bug] sorted() builtin fails to compile on lists of objects without all comparison operators defined, even if "key" is passed

jalfje opened this issue · comments

(Seq 0.9.10)

Minimal working example:

class Test:
    value: int

    def __init__(self: Test, value: int):
        self.value = value

def key_func(k: Test)-> int:
    return k.value

ls = list[Test]()

res = sorted(ls, key=key_func) # Note that at runtime, the sort used would be based on key_func.

Which produces the following error (on running seqc test.seq):

insertionsort.seq:6:30: error: unsupported operand type(s) for <: 'Test' and 'Test'

Implementing Test.__lt__() produces:

pdqsort.seq:161:29: error: unsupported operand type(s) for >=: 'Test' and 'Test'

Implementing Test.__ge__() produces:

qsort.seq:20:31: error: unsupported operand type(s) for >: 'Test' and 'Test'

Implementing Test.__gt__() produces:

qsort.seq:44:26: error: unsupported operand type(s) for <=: 'Test' and 'Test'

Implementing Test.__le__() produces:

qsort.seq:45:16: error: unsupported operand type(s) for ==: 'Test' and 'Test'

Implementing Test.__eq__() finally results in no errors. Testing verifies that at runtime, sorted() does use the key function for sorting, so the implemented functions aren't even used.

This forces all comparison operators (including ==) to be implemented on classes that will be sorted, even if they have a custom comparison operation that they would be using for the sort at runtime. In such situations, it often doesn't make sense to have a class comparison operator, as the sorting is intended to be performed only for a particular purpose (as indicated by the key parameter, which likely uses only a subset of the class members). Obviously the current workaround is to dummy-implement these functions, but doing so is not comforting, as it could cause accidental use of those operators in a context where it is not desirable (e.g. forgetting to pass key to a different call to sorted()).

Hi,
This is a known issue with the current type system, and will be resolved in the next major release (0.10) with the new type system. We're planning to finalize this release in the coming weeks!