codon icon indicating copy to clipboard operation
codon copied to clipboard

Tuple Type Extensions

Open AndreiMoraru123 opened this issue 1 year ago • 1 comments

Hi again folks,

Looking for more ways to solve Advent of Code, I found out that at least for Tuples, type extension in the case of addition wants to behave like concatenation, no matter what.

For example:

@extend
class Tuple:
    def __add__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
        print("adding tuples")
        return (self[0] + other[0], self[1] + other[1])

    def __mul__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
        print("multiplying tuples")
        return (self[0] * other[0], self[1] * other[1])

    def rot(self) -> Tuple[int, int]:
        x, y = self
        return tuple((y, -x))


north = Tuple[int, int](-1, 0)
south = north.rot().rot()

radd = north + south
rmul = north * south

print(radd)
print(rmul)

Interestingly ,only the __mul__ dunder is overloaded:

❯ codon run -release bug.py
multiplying tuples
(-1, 0, 1, 0)
(-1, 0)

I suppose that is because default __add__ does exist as a language construct and cannot be overwritten, while the given __mul__ does not exist between two tuple types.

At this point I would say this is not a bug, and this is actually the way someone would want it, as it would be chaotic otherwise. I admit though it would only be fun for AoC challenges, and maybe nothing else outside of that.

In the same vein, if we try to extend tuples with a method that does not exist in the (Python) language for any type of other:

@extend
class Tuple:
    def __sub__(self: Tuple[int, int], other: Tuple[int, int]) -> Tuple[int, int]:
        print("subtracting tuples")
        return (self[0] - other[0], self[1] - other[1])

    def rot(self) -> Tuple[int, int]:
        x, y = self
        return tuple((y, -x))


north = Tuple[int, int](-1, 0)
south = north.rot().rot()

rsub = north - south
print(rsub)

Codon says it cannot type check the program:

❯ codon run -release bug.py
error: cannot typecheck the program

Which I guess I could also see it making sense. But is this the way you would want extensions to behave?

I'm interested in how you see this.

Don't take this as an issue, I don't want to keep you busy with stuff like this =)

AndreiMoraru123 avatar Dec 15 '24 07:12 AndreiMoraru123

Tuples cannot be extended for now (if it works, it is pure luck :) ). We plan to add support for this.

inumanag avatar Sep 30 '25 23:09 inumanag