Hacker News new | ask | show | jobs
by dnautics 3 days ago
you actually don't want "operator overloading", you want syntactic sugar. I once proposed just a special operator syntax at the parser level, but it got rejected, but if you REALLY wanted it, you could probably do this in about 100-120 lines as a fork of the zig compiler, just hacking (a <_> b) as a special form to be transformed into @"<_>"(a, b). Requiring parentheses elides questions about operator precedence.

    const @"<+>" = @import("operator_module").plus;

    ...

    const x = (a <+> b);
1 comments

I think both operator overloading and most operators themselves are syntactic sugars. Operator overloading happens to point towards specific functions, whereas arithmetic integer operators point to compiler intrinsics.
no, in general overloading is not syntactic sugar, it's a feature of the language (being able to (re-)define a function in place X and have it change the function in unrelated place Y).
I don't see how it is unrelated. If have a custom type `A` with an overload on `+`, it will only affect places I used custom type `A`. If there wasn't operator overloading, I would just have to use a different notation to call the same function, but with possibly worse ergonomics (which is also why I think your solution doesn't really satisfy that, it doesn't read like algebra which is kind of the point). Given that type A is presumed to be custom, I don't see how place Y would be unrelated since it deliberately uses type `A`.

If we include operator overloading for any types, then sure. i32 + i32 might suddenly start meaning something else. But I think that's beyond the scope of what is normally asked by operator overloading.

one is implementable entirely in the parser. overloading (operator or otherwise) in general is a deeper compiler feature