logoalt Hacker News

hmrytoday at 2:58 PM3 repliesview on HN

Why have operators at all?

  x = x.add(step.mul(2)).mod(width)
Or in C

  x = imod(iadd(x, imul(step, 2)), width)
vs

  x = (x + 2*step) % width
For me the answer is very simple: Operators make it easier to read the code which makes it easier to spot bugs. It also makes it easier to turn formulas from textbooks into code.

If 50% of the code you're working with is using vectors and matrices, not having operators for those parts is quite annoying.

Note that you can have vector operators without overloading, e.g. Odin has built in vector and matrix types.

But personally I think it's better to give the user more power instead of only letting the compiler author pick which types to allow operators on. Like how Java overloads + but only on the String class. Why do they get to do it, but not me?


Replies

applfanboysbgontoday at 4:22 PM

Woah there, "=" is an operator! I'm afraid you're going to have to go to jail for using an operator in a no-operator zone.

dnauticstoday at 4:33 PM

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);
Decabytestoday at 4:30 PM

> Why have operators at all?

I mean as an avid Lisp fan, I feel like Lisp basically answers the question of how much syntax you need in a langauge. I must admit though, not having to deal with operators precedence is really nice

  (mod (+ x (* 2 step)) width)
show 1 reply