Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tuple Type Extensions #616

Open
AndreiMoraru123 opened this issue Dec 15, 2024 · 0 comments
Open

Tuple Type Extensions #616

AndreiMoraru123 opened this issue Dec 15, 2024 · 0 comments

Comments

@AndreiMoraru123
Copy link

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 =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant