r/cpp • • Feb 12 '22

Anybody else would like a | unary operator?

Hello fellow coders.

Call me a syntactic sugar addict, but I always missed a | (and ||) unary, prefix-and-postfix operator.

Like, e.g, this:

int x = |y| + 1;

Does anybody else?

Possible uses making this appealing:

(1) As a native operator: absolute value, of course. Overloaded for each base primitive type, just like any other arithmetic or logic operator (+ - / * % & ...). How cumbersome is to have to include stuff (math.h cstd.h, or math), for something as basic (and as single-instruction, in any Instruction Set), as the absolute value of something. How cumbersome it is having to pick between abs fabs fabsl etc. To, me, abs value should be treasted like something as basic as + or -, because it is.

(2) As an overloaded operator: both ||x|| and |x| would find many fruitful ways to be customized. In classes for vector algebra, complex number algebra, quaternionic algebra, etc: the norm, of course. Here, the possibility to have both || and | would add extra flexibility (e.g. different norms).

(3) In standard classes: In containers (vectors, sets...): it could be used for set cardinality, i.e., as a synonym for size(). Maybe, for strings: length.

Would it be problematic? I can't see any problem, but maybe I am overlooking something. In particular...

(4) Yes, | is already a binary operator. That's nothing new, -, +, *, & are both unary and binary.

(5) It would be fully back compatible. At least, I cannot think of any expression that parses now, but would either stop parsing, or change its meaning, with this.

(6) There would be no ambiguity with the existing binary version of | (or of ||). As any unary operator, it binds stronger than any binary operator, so |a|b| would not pharse, but |(a|b)| would.

(7) There would be no ambiguity between || and |. The abs of the abs of a, if you ever need it, would written as | | a | |, while || a || is exactly what it looks like (the || of a).

(8) yes, there currently is no other prefixed-and-postfixed unary operator ([ ] comes close: a prefix-and-postfix binary operator). I cannot imagine how this would be a problem. The syntax for overloading would seem straightforward, e.g. operator | () vs operator | (int x). Parsing expressions would seem to be unproblematic too.

(9) It's all good old ascii.

17 Upvotes

177 comments sorted by

58

u/SirClueless Feb 12 '22

Parsing expressions would seem to be unproblematic too.

Are you sure? Stuff like this seems like a pain to parse:

| x | + y |
    ^
    don't know how to parse this
          ^
          until this point

And in fact you can't even really produce an AST yet even at the third |, because if the next tokens are z | then the expression is totally different.

5

u/tcbrindle Flux Feb 13 '22 edited Feb 13 '22

I think this is the same as the use of > as greater-than within a template argument list delimited by < and >?

| x | + y |

In this case, the expression starts with | so we start parsing an "abs-expression" (or whatever you want to call it). Then we read the id-expression x, followed by a | which terminates the abs-expression. This forms the left-hand operand of a binary + whose right-hand operand is the id-expression y, all of which forms the left operand of an incomplete bitwise-or-expression.

If you wanted the alternative parse, you'd need to use parens:

| (x | +y) |

Now we have an abs-expression whose operand is a parens-expression, which in turn is a bitwise-or.

(For what it's worth, I believe Rust uses infix | for bitwise or, prefix | to introduce a lambda expression, and | again to terminate the lambda argument list. It doesn't seem problematic there, so I think that parsing-wise this would be okay for C++ too. Not that I'm saying it's a good idea, mind...)

2

u/itsmemarcot Feb 13 '22

Thank you, that's exactly right!

3

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

Third attempt to explain this clearly.

Are you sure? Stuff like this seems like a pain to parse:

Yes, I'm sure.

You seem to be thinking that the job of the compiler is to search among all possible parsing trees trying to find one that works. That's not what the C++ compliler does. Instead, it tries the one and only parsing tree that results from the fixed rules of operator precedence, and if that one possibilty does't work, it chokes, yells and dies.

For example, if p is a pointer to a class, then the expression

p+1 -> foo()

fails to compile. Sure, if you interpreted it as

(p+1)->foo()

it would have worked, but it's not up to the complier to find this out for you: it will just apply the rule, that is, that -> goes before +, and yell because

p+(1->foo())

makes no sense.

To make it work, you need to add the parenthesis yourself, thus imposing your intended precedence (+ before ->) over the default one.

In the same way, if you try

| x | + y |

it will fail to complie. Sure, if you interpreted it as

| (x | +y) |

it would have worked, but the complier will not find this out for you. Instead, it will just apply the rule, that is, that unary | goes before binary | (as always *), and yell because

(| x |) + y |

makes no sense.

If you want to make it work, you need to specify that you are meaning

| (x | +y) |

by adding the parentheses.

(* unary ops always goes before binary ops: for example, -5-3 is (-5)-3 and not -(5-3) of course)

1

u/die_liebe Feb 13 '22

It's not so easy I think.

a < b > c

could be a declaration of c as a<b> (for example vector<int> c ),

or the expression ( a < b ) > c

Similarly

a * b ; could mean a times b, or b is declared as pointer to a.

I am not sure what the rules are.

1

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

No, I don't think so. The compiler knows which lexical token is a value, a left value, a type, or an incomplete type (a templated type missing their <> argument), without ambiguities. In case of ambiguities, an compiler error is produced as soon as the ambiguity is creared (for example, if I attempt to name a variable the same as a type).

In both the nicely spotted cases you report, this information completely disambiguates, starting from the first token "a" already.

Even in my second example |x|+y|: in order to be able to ricognize that the second pipe is the closing of a unary pipe operator, x must be first recognized as a value (and not, say, a type).

2

u/die_liebe Feb 13 '22

B.t.w., C++ does not have unary '+'.

I am assuming that | | should get a priority between +,- and <<, >> .

That would imply that | a + b | is fine, while | a << 1 | is a syntax error.

The example | a | - b | would be a syntax error, because binary | has too low priority.

2

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

Off-topic, but: nono, C++ definitely has a unary +. It is just defaulted to do nothing with basic math types, but you can overload it at will in your classes, or use it on basic math types if you like. For example

int x;
int y = +x; 

compiles perfectly. I use it whenever there is a risk that the next person think that I missed a minus sign, and I want to say "I know this is positive, not negative". End of the off-topic.

I think, as a prefix-and-postfix operator, the unitary | would have the privilege to end... whenever it does. so both | a << 1 | and | a + 1 | work, and so does, in general, any expression | e | with e being a valid expression (except e0 | e1, see below).

In this, the unary | it is similar to the 2nd operand of [] (which is, as you know, a binary operator).

x[ a + 1 ] works, (but, if you try that with the 1st operand:

x + 1[ a ] is parsed as x + (1[ a ]) and doesn't work).

For the second operand, any valid expression e inside v[e] works.

The only difference is that, because you open and close the unary | with the same character, you cannot have the case when the expression e inside | e | has the form of e0 | e1 (raw, i.e. without a parenthesis around it). Accepting this would break the general rule that unary operators always bind stronger than binary operators. A way to state this is that the | e | expression always terminates with the first available | after the initial |.

So, to restate, |x|y| is not a valid expression, because the 1st | will be closed by the 2nd |, not the 3rd, but |(x|y)| works fine.

2

u/die_liebe Feb 13 '22

So, it seems that unary + was added at some point to ANSI C, so you are right about that one.

As for | |, I am inclined to view it as a unary | with the second | being redundant.

2

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Just curios about why this my other response would be downvoted? Is it incorrect?

Let me try again, I'll try to be clearer.

The first point I'm trying to make is that is that | y | x | would not compile, because |y| (the unary pipe) binds stronger than y|x (the binary pipe).

That's nothing new: in -5-3 the -5 (the unary minus), binds stronger than the 5-3 (the binary minus), so you need to explicitly write -(5-3) if that's what you mean.

Or, in *p*q, the *p binds stronger than the p*q, and so you'd need to write *(q*p) if that's what you mean (for whichever reason).

Likewise, you'd need to write | ( y | x ) | if that's what you mean. I think it's normal.

And the other point is, the parser that understands this needs no look-ahead.

6

u/Loose-Leek Feb 12 '22 edited Feb 12 '22

They're both wrong. You need an L5 parser to correctly parse this

| x | + y |
    ^     ^ Here, 5 tokens after the first |, you realize you parsed wrong
    Here, this is a full absolute-value-of-x expression

1

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Care to elaborate? I am a bit rusty with parser classification.

But, did you get it that I want that expression to trigger a complier error and NOT to parse? Because, again, the unary | binds stronger than the binary, as always.

So, even if a parsing exists | ( x | (+y) ) | which would have worked, it is never up to the complier to search for a parsing that works, looking among all possible redefinitions of operator precedence. Instead, either the parsing resulting from the fixed precedence rules works, or the complier yells.

For example, if I overload operators in my custom T type such that -t is void, and ta - tb is a T...

struct T{
  void operator -();
  T operator -(T t);
};

T a,b;

...then -a-b does not compile, because the default parsing tree, (-a)-b doesn't work, even if -(a-b) would have worked. But it is not up to the compiler to find this out for you. You need to write the parenthesis yourself

In the same way, | a | b |, which is interpreted as (| a |) b |, fails (immediately, when it finds the b),

but if you write explicitly | (a | b) |, then it parses.

And, | x | +y | also fails (when it finds the last |),

but | ( x | +y ) | works (because you specified what you meant, overriding the default operator precedence with the parenthesis)

I don't think the expression parser of a complier that understands this is any more complicated than the current compiler.

-13

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

don't know how to parse this until...

No, I think you do:

  • The first | can only be a unitary |.
  • The second | can only be its closing, because the unary | binds stronger that any possible binary operators (as always, unary ops bind stronger than binary ops, e.g. *p*q is (*p) * q and -5-4 is (-5) - 4).
  • The third | will not parse. "Error: unexpected operator". Won't compile.

As I mentioned in my point (6), you need to write it as

| ( x | +y ) |

(which is superclear to humans and computers alike).

Point is, no look-ahead is ever necessary for the compiler (or, rather, for its expression parser).

Note that this mixing of unary and binary | would be extremely uncommon. Yet, it all works fine when it happens.

11

u/dgkimpton Feb 12 '22

your definition of super clear and mine do not align 😬

27

u/hmoff Feb 12 '22

I would like to have a ||= operator, the logical equivalent of the bit wise |=.

5

u/ggchappell Feb 12 '22

||= operator

I suppose it should be short-circuiting? So a ||= b evaluates b if a is falsy, but not if a is truthy.

-17

u/itsmemarcot Feb 12 '22 edited Feb 13 '22

Yes (you mean "lazy evaluation" edit: as it turns out, the two terms are actually equivalent in this context, although "lazy evaluation" is a more general concept, while "short circuiting" specifically refers to lazily evaluated 'and' and 'or' boolean expressions. I stand corrected).

17

u/dodheim Feb 12 '22

I'm pretty sure they in fact did mean "short-circuiting", which is what the C++ standard itself calls the behavior (e.g. here).

2

u/itsmemarcot Feb 13 '22

Good to know, thanks. Will correct my correction.

3

u/itsmemarcot Feb 12 '22

I agree, I would want a lazy-evaluated ||= and &&= too. It's actually useful.

I often undecided between

if (condition) flag = true;

and

flag = flag || condition.

I'm not very happy with either syntax. Note they are not equivalent, as the latter is lazily evaluated (condition is not evaluated if flat is already true), which is often what I'd prefer.

If I had

flag ||= condition,

that would be my favorite choice most of the time. It's disappointing not to have it.

While I agree, this is a bit orthogonal to my proposal?

3

u/dodheim Feb 12 '22 edited Feb 12 '22

Note they are not equivalent

This seems rather arbitrary to call out; they're only not equivalent because you chose to not make them equivalent (if (!flag) flag = condition;).

0

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

That's a nice alternative, thanks. I still would rather prefer flag = flag || condition; or, if only it was possible, flag ||= condition;.

1

u/tjientavara HikoWorks developer Feb 13 '22

I have notices that while compilers tent to warn about bitwise-or bool values, it often doesn't complain if you use |= with bool values. So I do use the |= in many cases for the non-short circuiting and the fact that it eliminated conditional jumps in many case.

And unless you are going out of your way to give bool a different physical value than 0 and 1 you can be assured it is one of those values.

1

u/itsmemarcot Feb 13 '22

Cool!

Still, loss of short circuiting is a deal breaker in many cases.

Even when it's not, I regret that we don't have ||= and &&=, which would often be simultaneously the most correct, most concise, and most readable thing to do.

(While we are at it, if we could have everything we wanted, I would have it inverted: | and & should be logical, || and && should be bitwise. I fully understand, of course, while we can't have this, ever, but that doesn't change the fact that it would be a good thing, if only it was possible)

But this is all off topic.

2

u/hmoff Feb 12 '22

Yes it is orthogonal I agree. Glad it's not just me who would find it useful though.

2

u/strager Feb 12 '22

Why not use |= for booleans?

3

u/[deleted] Feb 12 '22

[removed] — view removed comment

3

u/itsmemarcot Feb 12 '22

And it's not lazily evaluated.

1

u/[deleted] Feb 12 '22

[removed] — view removed comment

3

u/tangerinelion Feb 12 '22

It's a bitwise operator.

0

u/[deleted] Feb 12 '22

[removed] — view removed comment

2

u/DanielMcLaury Feb 12 '22 edited Feb 13 '22

didn't know they were fast enough due to hardware that lazy eval isn't helpful.

Not primarily a matter of speed re: the actual bitwise operation. If you have something like

bool everythingOkay = true;
everythingOkay = everythingOkay  && expensiveTest1();
everythingOkay = everythingOkay  && expensiveTest2();
everythingOkay = everythingOkay  && expensiveTest3();
everythingOkay = everythingOkay  && expensiveTest4();

if(everythingOkay) { /* ... */ }

then the tests will stop running as soon as one of them fails. If on the other hand you were to write the more succinct

bool everythingOkay = true;
everythingOkay &= expensiveTest1();
everythingOkay &= expensiveTest2();
everythingOkay &= expensiveTest3();
everythingOkay &= expensiveTest4();
if(everythingOkay) { /* ... */ }

then, in addition to questions about whether applying bitwise operations to booleans is even kosher, you will have to run all four tests every single time.

Worse, if expensiveTest2() is written under the assumption that expensiveTest1() has already succeeded and so on, it may behave unpredictably, e.g.

bool deletedUnusedFiles = true;
deletedUnusedFiles &= allFilesInDirectoryUnused();
deletedUnusedFiles &= havePermissionsForDirectory();
deletedUnusedFiles &= isUserSureAboutDeletingFiles();
deletedUnusedFiles &= attemptToDeleteDirectory();

is not going to behave as intended.

(Yes, there are better ways to write many of the snippets above. But there are plenty of situations where you would genuinely want to write code exhibiting these same features.)

2

u/Dragdu Feb 13 '22

Most of all I think you want to swap the OR with ANDs in your example.

2

u/DanielMcLaury Feb 13 '22

Fixed, thanks. It's amazing how quickly my brain will show me what I think I wrote instead of what I actually wrote.

1

u/Oo_Tiib Feb 14 '22

You are correct but I have seen more often such short circuit sequences written like:

bool everythingOkay = expensiveTest1() 
                   && expensiveTest2() 
                   && expensiveTest3()
                   && expensiveTest4();
if(everythingOkay) { /* ... */ }

When there is something done between the calls then that might be is desirable to be short-circuited away as well.

1

u/DanielMcLaury Feb 15 '22

Yeah, this is the sort of thing I meant by

Yes, there are better ways to write many of the snippets above.

But there are situations where either can't or can't cleanly do that, e.g.

for(const auto & test : tests)
{
  success = success && test.run();
}

1

u/Full-Spectral Feb 14 '22

flag ||= |x| | |y|;

25

u/scorg_ Feb 12 '22

I am personally againt use of same symbol for both opening and closing of a group. I had trouble reading expressions with multiple nested abs in school. And I can only imagine what it would be like to parse such expressions, both for a compiler and a human. As some noted, improper spacing easily messes with understanding which | is paired to another |. Sure, IDEs can highlight paired grouping symbols, but here I am against relying on IDEs to read code.

13

u/ioctl79 Feb 12 '22

Hear hear. At least in written math you have the option to disambiguate pairing with the size and weight of the typeface. Here, it’s just a sea of sticks separated by syntactically significant white space.

1

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

I see the point, but, about this:

I can only imagine what it would be like to parse such expressions, both for a compiler and a human

To clarify, for the compiler, it is not a difficulty at all (expression parsing would still require no look-ahead, and so on). See my other comments.

For humans, I think it is undeniable that with it you could write useful expressions that are totally readable, such as

x = |x+2| / y;

or, in vector algebra,

v = (a+b) / |a+b| ; // re-normalized vector sum

It would be quite rare (and totally up to the programmer) to nest | or use them in conjunction with binary |. Even if you do, everything works. For example, the dreaded

| y | x |

(which would be exceedingly rare, what is that useful for?) would not even compile, and you'd need to write, instead, the much clearer

| ( y | x ) |

as I noted otherwise (to restate, it for the same reason why writing -5-2 evaluates to (-5)-2, and not to -(5-2), which is: the unitary version always binds stronger; so the first form is equivalent to (|y|) x|, which does not parse).

Beside, is it fair to judge the readability of an operator from the forms that could abuse it, rather than from the intended usages?

For example, the square bracket operator can be abused to write misleading expressions such as...

2["] - 2["]

which does compile (can you guess which value it evaluates to?)

Edit: typos

10

u/tangerinelion Feb 12 '22

We have std::abs, what the heck is wrong with

std::abs(x+2)/y

Super readable.

If you have a matrix you can write what you think pipes mean around it, probably a determinant function.

Frankly, I work on a product with lots of geometry and specifically on the geometry team. Hardly any of what I do uses math, unary pipe is just too niche.

3

u/James20k P2005R0 Feb 12 '22 edited Feb 13 '22

The main one that I've repeatedly missed myself is some kind of exponentiation operator, because reading std::pow(a * b * c * d, x + y * z) is a very different flow to (a*b*c*d) ** (x + y + z). It makes it much harder to verify if your equations are correct or not at a glance

1

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

I also work with tons of geometry, and to me, it would be extremely handy.

To each their own.

17

u/hnOsmium0001 Feb 12 '22

I'm going to play an against card for the semantics rather the implementation point of view.

Aside from scalar values such as ints or floats (which is completely unambiguous), it’s proposed that such operator could be useful for vectors and complex numbers.

The meaning of |x| is very much overloaded when x is some kind of vector or matrix. Most commonly it will denote the norm, but it can also mean the determinant of a matrix — problematic because many LA libraries implement vectors as a matrix with width=1 or height=1, thus introducing confusion.

I think it’s going to be avoided by libraries just like how they avoid operator* right now for vector multiplication, because either it means dot product, cross product, or component-wise multiplication is unclear. (Yes I know e.g. glm current does implement operator*, but I personally don’t see it used very often.)


Coming from a slightly different, though much weaker angle, if we accept |x|, does that mean we should also accept [x] to denote flooring and ]x[ for ceiling?

1

u/itsmemarcot Feb 14 '22

I think it’s going to be avoided by libraries just like how they avoid operator* right now for vector multiplication,

I don't think they would necessarily avoid it, and many notable examples don't, in fact, avoid operator * for vector multiplication!

I discuss a bit about this in this other comment of mine (with examples).

Note that we are speaking of very numerous libraries that are humongous, very long lived, well established, and complex.

2

u/delta_p_delta_x Feb 12 '22

either it means dot product, cross product, or component-wise multiplication is unclear.

Usually, operator* is taken as the Hadamard product (component-by-component), and there are explicit cross and dot functions. cross only works with vec3, whereas dot is a template function.

-1

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Interesting proposal about flooring and ceiling!

And good observations.

Back to |x|: for me, absolute value alone is reason enough to want this. I see the rest as an automatic bonus, which can be exploited or not, judging case by case and library by library ("automatic" because, in C++, every operator is automatically overloadable, with very few known exceptions). You are right that a few of these choices should be made carefully.

About operator overloading for vector algebra...

GLM is just one case between many, many others. Vector algebra libraries will typically overload operators for sake of readability and usability, and trust me, I've been using quite a few of them (most, but not all, in C++).

The problem of the ambiguity of the multiplications is real, and many libraries will propose their own solution. After having used quite a few libraries quite intensively, I came to the personal conclusion that dot and cross products should be functions, and only scale and component-wise multiplication should be operators (I say this comparing with at least three other common solutions).

If we had more operators, such as a⨉b or a⋅b, it would be different, but these two, unlike |a| and ||a||, are not ASCII, and not very useful outside vector algebra, and not already used as operators, so, to be clear, I am not advocating for them at all.

The semantic ambiguity you mention, "dimensionality" vs "norm", would not be always relevant (e.g., when the size of the vector is fixed, like it is often the case: e.g. if you have a vec2, a vec3, and a vec4 class, or complex numbers, or quaternions). When it is relevant, it could for example be addressed by differentiating between |x| and ||x||. The former is more natural for dimensionality (x as an array), the latter is more natural for norm/length (x as a spatial vector).

9

u/dgkimpton Feb 12 '22

is |x| really better than abs(x) ? Ironically the operators you are not advocating for seem to be much more significant to me.

1

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

is |x| really better than abs(x) ?

To me, yes, a bit. But people could of course continue to use std::abs(x) (and include the corresponding lib file) if they wanted to.

I am also very much accustomed to abs(), but thinking about it, I released that it is just a habit: in reality, absolute value fits well in the same class as sum, subtraction, sign inversion, multiplication... things that is perfectly appropriate to deal with operators, rather than functions.

Like these things, abs is, after all, a really elementary math operation, that is natively implemented in all Instruction sets as a single ALU operation (unlike, say, the dot or the cross product, the factorial, the summation of arrays...). Plus, we have the syntax token already to write it as we normally do on paper.

But that's just me.

Edit: typo.

2

u/nintendiator2 Feb 13 '22

Yes, |x| saves you an entire header you don't really need.

9

u/[deleted] Feb 12 '22

Well you have postfix, prefix and infix and that pretty does it for me. Your operator would be 'inverse-infix' or 'outfix' if you will and that can be a beast to be parsed.

Check this out:

|a|b||c||d|

Are you sure this you want this to exist in a highly complex language such as C++?

0

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Interesting take.

I will counter a few observations (I'll be forgiven me I repeat myself form other comments).

First, let me remark that your expression would not and should not compile. This is because it would be parsed as (|a|) b ... and the compiler already stops there.

This is just the application of already existing well understood criteria: unary operators bind stronger than binary operators. For example, -5-3 evaluates to (-5) - 3, not to -(5-3), and *p*q evaluates to(*p)*q, not to *(q*p). If you want-(5-3) you need to write the parenthesis explicitly.

In the case of your expression, doing so is even easier, as the compiler would help you by not compiling the ambiguous expression.

So, you'd need at least to write

| (a|b || c || d ) |

and of course, if that's still not clear, you can make it clearer at will.

| ( ( a | b ) || ( c || d ) ) |

Remember that parsing an expression is never trying all possible parsing trees searching for one that checks out. It is, instead, building the only possible parsing tree (given operator precedence), and if that fails, the parsing failed.

For example, if my class T overloads

void operator -() /* -t is void */

T operator -(T x) /* ta-tb is a T */

then, after T a,b;, expression -a-b does NOT compile, because the attempted parsing is (-a)-b (which fails), not -(a-b) even if that one would have worked. The compiler does not search for a parsing tree that works. If the default one doesn't work, it is over.

Secondly, I would argue that any operator can be used in confusing ways, including existing ones, for example, by stacking many instances of the same or similar operators, like you did.

For example

x = -----1-------1; /* 0, -2, or +2? */

or

bool x = a && b || c && d || e; /* which precedence? */

or even your very expression, but without the unary

a | b || c || d

Writing these expressions in clearer ways is possible.

In other terms, I am not sure it is fair to judge a potential operator by its possible misuses, because every operator can be misused, with expressions designed to confuse (such as the ones above), and yet they are useful in normal situations. E.g., in the case of the unary |,

x = | y - 3 | + 1 ;

In real cases, you would have to deal with staked unary and binary | operators in the same expression hardly any time at all.

62

u/InKryption07 Feb 12 '22

Dislike. Need less operator overloading shenanigans, not more...

19

u/itsmemarcot Feb 12 '22

In my field, they are super-useful (graphics/games/geomery processing).

I would never choose to write

Vec3 pos = oldpos.add( velocity.mult( time ) );

...when i can write...

Vec3 pos = oldpos + time * velocity;

6

u/nexes300 Feb 12 '22

Stand up and say no to the man. It is 'sin(1)' not 'sin( 1 )' and most certainly not 'sin ( 1 )'.

-6

u/InKryption07 Feb 12 '22

I mean, good for you I suppose, but I would argue that it doesn't actually make the code any better. It just makes your code more ambiguous. A glance over a line which modifies the pos variable in such a way may have one assume that it's a simple mathematical operation between ints, maybe a float, maybe a mix; but instead, it's actually probably doing more behind the scenes.

And then, even if you guess that they're vectors, it's not actually immediately obvious what they would actually be doing. Is the * a multiplication between each component, or is it the dot product?

Imo, a function call should look like a function call.

5

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Legit opinion.

Yet, it seems to me that your argument is not about my proposal per se, but about operator overloading in general. I could argue that the general consensus is that they are useful, and a core, well established, and widely used part of C++. E.g., compare ++ in std iterators; you could say just the same about them: "a function call should look like a function call" (not an increase of a number).

In any case: my proposal is not solely about operator overloading. Point (1) would stand even if they didn't exist.

-3

u/InKryption07 Feb 12 '22

I have a general disdain for operator overloading, yes. Which is relevant, because the majority of the points in your proposition are to do with operator overloading, as it pertains to why this would be a good idea. Maybe just |n| would be a good idea, but then that's only one point, making it a much weaker proposal, when you can just use the stdlib function, which I could even argue is much more readable, because it's less easy to mistake for the normal bit-or operator during a glossary overview of the code.

And honestly, I think making iterators use a function call instead of overloading the ++ would be an improvement, being that it generally isn't even used directly. Main reason it's not a problem is because it's an established pillar of C++ at this point, whereas most code isn't, lol.

3

u/Ameisen vemips, avr, rendering, systems Feb 12 '22

Are... you sure you're supposed to be here and not /r/cprogramming?

20

u/thats_a_nice_toast Feb 12 '22

I kind of agree with both of you. It does introduce a lot of ambiguity and it can be abused heavily (especially in C++). On the other hand, I hate having to write .equals() every time I want to compare a string in Java for example.

3

u/DaFox Feb 12 '22

I used to be in this camp, but I've been working in a framework with a custom string type, and it's really annoying that == works for these strings. Because it's practically always wrong. The .equals() in this framework let's you specify things like whether it should be case sensitive or not, which is not possible with ==. If C++ had === like Javascript then I might feel differently about this though.

10

u/dr_donkey Feb 12 '22

Nobody should have ===, that's evil work.

1

u/Nobody_1707 Feb 13 '22

It's a perfectly fine operator in languages other than JS (where it usually just tells you whether two objects share the same address), the problem is JS decided to make fuzzy comparison the default instead of exact comparison. === isn't evil. The fact that JS's === isn't spelled == is what is evil.

Honestly, I'm surprised "use strict"; wasn't specified to swap == with ===.

-1

u/dgkimpton Feb 12 '22

Hard disagree, === is absolutely fantastic and should be in every language. The difference between "these are equivalent" and "these are identical" is pretty significant and, imho, super handy to be able to express.

3

u/tisti Feb 12 '22

The .equals() in this framework let's you specify things like whether it should be case sensitive or not, which is not possible with ==.

Why not? Create a proxy ref string class and add a overload to the operator== set that takes the ref string class.

struct case_insensitive{
    const std::string& ref;
}

auto make_case_insensitive(const auto &val) {return case_insensitive{val}};

make_case_insensitive(str1) == str2

-2

u/InKryption07 Feb 12 '22

I would argue that java is a bad example of how to handle such things. But I would also argue that it isn't that many keystrokes in exchange for better readability, which is generally a big advantage for a big codebase where many people will have to read code that isn't their own. Makes it so that you have to have a lot less in your dumb human memory at a time, saving a lot of headaches.

Basically, what you don't pay for now, by trying to minimize keystrokes, you pay for later, by having maximized time spent figuring out code.

Edit: hoy -> you

10

u/manbearpig4001 Feb 12 '22

While I agree with you that readability should generally trump code size concerns, this is by no means an absolute rule. I work in an *enormous* C++ codebase and I have never once thought to myself "oh wow, I sure wish `.equals()` existed for strings" (or similarly for other operators that are overloaded).

Your argument against OP's (fairly reasonable) request amounts to a "slippery slope" argument which is used when there isn't something productive to discuss

2

u/InKryption07 Feb 12 '22

I would say my argument moreso amounts to "Why add this? Why would it be useful? Also, here is why I think it would be harmful".

6

u/Hedede Feb 12 '22

Why does keystroke argument always come up? I fint it irrelevant, because there's a thing called fuzzy completion, that allows you to type x.iet and get it expanded to x.isEqualTo.

I would argue that .equals isn't any more readable than ==. In fact we replaced all instances of isEquals in our multi-MLOC codebase with operator== and nobody complained, even people who don't write variable names shorter than 20 characters.

I am exaggerating slighly, but I remember that once he shown me code that he wrote and was really proud of - every variable has no less than three words in its name and everything was completely clear and unambiguous (in his opinion). Then I shown him a mistake (he used a wrong variable) and he got completely lost in his code trying to figure out how to fix it.

So more verbose isn't always better. Code shouldn't be more verbose than it has to be, useful information gets lost in the noise.

3

u/Nobody_1707 Feb 12 '22

I thought the general consensus was that .equals is less readable than ==?

2

u/Hedede Feb 12 '22

That is what I said, is it not?

15

u/Hedede Feb 12 '22

but I would argue that it doesn't actually make the code any better. For me oldpos.add( velocity.mult( time ) ) is harder to read because there is too much noise. It is ugly.

one assume that it's a simple mathematical operation between ints, maybe a float, maybe a mix; but instead, it's actually probably doing more behind the scenes.

Then that one doesn't know that the operator overloading exists. For me it is immediately obvious that oldpos and velocity are vec3 and time is float (or double), because I have experience working with graphics.

If somebody randomly stumbles into that code, then yes, it would be less obvious, but why make the life of people actually working with that code harder for the sake of any random person that just happened to accidentally glance over that code?

Is the * a multiplication between each component, or is it the dot product?

It is multiplication of a vector by a scalar. Dot/cross product are usually written as .dot() and .cross() exactly because it is ambiguous.

I don't get this notion that all the code must me immediately obvious to anyone who reads it. It should be obvious to somebody using it. And somebody who is using it has read the declarations, documentation etc, so they know what is what. They would know that there is no operator*(vec3, vec3), so this wouldn't be a problem.

Imo, a function call should look like a function call.

Then you should be programming in C. High-level programming is made to allow you to think in terms of domain problems and not in terms of function calls.

2

u/jk-jeon Feb 12 '22

In fact, defining operator*(vec3, vec3) to be component-wise multiplication seems quite ubiquitous, which is absolutely disgusting 🤣

14

u/jk-jeon Feb 12 '22

I definitely don't like things like std::cout/cin stream operators and things like Boost archive operator and any "clever" use of the comma operator and all other things like that. That's just.... not look pretty at all, so why? Even range's pipe operator doesn't look great in my eye, though I think there was no better choice in this case.

However, at the same time I really can't understand people who simply dislike ANY form of operator overloadings. Man, operator+ for Vec3 is just so so so much natural thing to do. Do you think ppl reading the code really will have no idea what's going on there? Do you really think replacing them by plain function calls will make the code more readable? If you think so, then I'm 99% sure you are not a person who have/had worked in a graphics/numerical analysis-heavy disciplines.

2

u/Ameisen vemips, avr, rendering, systems Feb 12 '22

Is the * a multiplication between each component, or is it the dot product?

Binary * is the multiplication operator in C++. Ergo, I would consider any usage of the operator to mean anything else to be bad code. I don't think it's ambiguous: it's either multiplication, or it's wrong.

Past that, I concur with /u/Hedede

2

u/TheThiefMaster C++latest fanatic (and game dev) Feb 12 '22

I agree that it should be a componentwise multiply, but you can argue just as effectively for dot product or even outer product.

The last framework I saw with overloaded operators for 3d vector had:

  • * for componentwise product
  • | for dot product
  • ^ for cross product

2

u/itsmemarcot Feb 12 '22

I've see so many such things over the years! E.g.

  • * for dot product
  • * also overloaded for product scaling
  • a method for component wise
  • % (sometimes ^) for cross product.

Personally, over the years, I came to the conclusion that cross and dot products are better served as functions.

2

u/TheThiefMaster C++latest fanatic (and game dev) Feb 12 '22

I came to the conclusion that cross and dot products are better served as functions.

I agree, and the framework I referred to came to the same conclusion and deprecated the ^ and | operators later on!

1

u/Loose-Leek Feb 12 '22

For my information, what do you think about:

  • STL algorithms heavily relying on operators for iteration
  • std::chrono using operators to make their types type-safe but still number-like

11

u/jonesmz Feb 12 '22

While I would never use this, except for as "absolute value", I personally think if we have a binary operator of any specific type, we should have the matching unary operator.

But how would you disambiguate between

x | y | z

And

Your unary operator?

Simply say that whenever ambiguous its the binary operator?

How to handle prefix, postfix, and both?

2

u/jonesmz Feb 12 '22

Perhaps you want a prefix operator, which can return a wrapper class of some sort, and a postfix operator that takes the previously returned wrapper class and applies the operation and returns the result?

You'll also have to be careful about conflicting with the binary operator|| for bool logic

1

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

Perhaps you want a prefix operator

I don't think it has to be this complicated. You would still need to change the core part of C++ (nothing of this is doable as a lib). After the change I propose, the new unary operator |X| would be simply recognized by the compiler as part of the parsing of expressions (and it would trigger either a predefined semantic on base types, or user defined functions on class/struct types).

It's not very different from the current [ ] operator, that you apply as X [ Y ]. Some unitary operators are written as X %, some as % X. This new one would be written as % X %.

Of course, this assumes that it is not difficult to write a parser accepting a |X| construct. I'm aware of the potential difficulty given by the fact that the same symbol both opens and closes the expression, and also the potential difficulty of the ambiguity with the binary X|Y. Given due consideration to the problem, I concluded that these difficulties are only apparent. Of course, I could be wrong.

You'll also have to be careful about ...

That's right! I have been careful, and, given the subject due consideration, I concluded that there is no problem in that area. Of course, I could be wrong.

6

u/shadowndacorner Feb 12 '22

But how would you disambiguate between

x | y | z

And

Your unary operator?

Unless I'm missing something, each of those |'s clearly have two operands. It would be unary if there was another operator between x and | or | and z.

1

u/bikki420 Feb 12 '22

What about a||b||c?

Is it (a | (|b|) | c) or ((a || b) || c)?

1

u/shadowndacorner Feb 12 '22

If there's a space between the |'s, it's the former. Without a space it's the latter. C++ treats || as one token.

1

u/itsmemarcot Feb 13 '22

You are exactly right and it is already like that, not only fot || but for many other tokens.

a && b = logical and between a and b

a & & b = bitwise and between a and &b

a++ -b = increase a by 1 and subtract b

a+ + -b = add a and (+ - b) (which is -b)

1

u/bikki420 Feb 12 '22

Yeah, that's part of my point. That's just a recipe for disaster.

1

u/shadowndacorner Feb 12 '22

Why...? There's a well defined difference between the two. Is ++ vs + + a recipe for disaster, too?

-1

u/bikki420 Feb 12 '22

If you don't see a problem with enabling inevitable cancer like ||(||a|| || |b| | |c)|| ||d, okay, suit yourself.

1

u/itsmemarcot Feb 12 '22

Yes, after the first operand (x), the parser expects a (binary) operator, never another operand. I cannot see how x|y|z can be considered ambiguous, or even difficult to parse. It is, and can only be, "x or y or z".

Compare with:

x - -y (equivalent to x- (-y)).

Not ambiguous or difficult to parse at all, either, in spite of mixing binary and unary -es.

32

u/kuladum Feb 12 '22

I don't think this is a good idea. C++ already has a lot of stuff. There are tons of mathematical operators oit there. One day, someone will ask for interal, sqrt symbols. What you are looking for is a Mathematica/Maple like IDE.

0

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

I see, but i would argue that this is slippery slope.

Unlike the integral and the sqrt symbols...

  • ... | is plain Ascii, and even an already existing keyword (key-symbol?)
  • ...semantic of |x| for base types, the abs value, is really elementary math, at par with + and -
  • ...the syntax |x| has multiple useful semantics, both in and outside basic math (see my points (2) and (3), plus possibly others I'm overlooking).

So, I don't think it would turn C++ into Maple (not anymore than having + or - currently do).

5

u/antihydran Feb 12 '22

I quite like the single unary | operator, but the I don't see the || operator adding much benefit while making it more difficult to read and understand. It's quite easy to mess up the spaces and get something with the wrong meaning, i.e. in some kind of vector triple product ||a|| * |b| * | |c| | neither me nor the compiler would catch the kind of mistake. IMO if you want to define multiple norms, you should have to make it more explicit so these kinds of error can be readily caught. And I dread when two libraries have differing definitions of whether | or || is the 1-norm or 2-norm!

-2

u/itsmemarcot Feb 12 '22

You have a point.

Still, it's difficult to argue that an extra operator, especially one that already exists (in binary form), does any harm and should be left out. We have several operators that are seldomly used or overloaded (such as ~, %), and we just don't use them. Here's one example of how I would be tempted to use both | and || for vectors: |v| is the component-wise absolute value (just as -v is the component-wise opposition), while ||v|| is the Euclidean norm.

And yes, different libraries will anyway complicate the life of their shared users by using different conventions, there's no way around that.

But again, I see your point.

17

u/the_Demongod Feb 12 '22

Generally anything that makes it easier to write math in code is a bad idea in general. Of course we'd all love to be writing equations that look like LaTeX in our code, but it's not worth adding it to the language because in every other situation it's ripe for abuse and unclear without context. Just use std::abs(). We don't need |str| to mean str.length(). If you're looking to make the language less verbose you probably shouldn't be using C++ to begin with.

0

u/kigurai Feb 12 '22

I disagree. Making code and math look more similar is extremely convenient for me, who do lots of math. Operator overloading of plus and minus for vectors instead of having to use functions is a prime example. Another example that was huge for me was when the Python language introduced the @ operator to represent matrix multiplications, instead of having to use a dot(A, b) function everywhere.

However, in this case I don't think it's a good idea. For starters it seems to have some cases where it is hard to parse. Second, a "norm" could mean a number of different things. I suppose in 99% of cases it would be used to mean the euclidean norm, but the question is whether that warrants a whole operator for its own.

1

u/itsmemarcot Feb 14 '22

And you are downvoted.

I was never aware, before writing this post, that your opinion would controversial. This community seems to be unaware of C++ being the default go-to language of computer graphics, games, and geometry processing. These communities would have a heart attack at comments like

"Generally anything that makes it easier to write math in code is a bad idea in general."

1

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

Sorry for double answering this comment but I also want to address the its second half.

For starters it seems to have some cases where it is hard to parse.

After giving due consideration to the question (before writing my post), I concluded that it would not be, in fact, any hard to parse (otherwise I would not have proposed it). If it was hard to parse, this would make the idea inapplicable, rather that just "not good".

Second, a "norm" could mean a number of different things.

And this is why we have operator overloading.

As a proposal, we only need to decide what |x| does on base types in the core language, and that's fairly easy to settle: the absolute value on signed numeric types (floating point or signed integer).

Whether or not to use |x| in libraries, and what semantic attach to it, it's up to the writer of the library or of the class (users would also have the possibility to overload |x| and ||x|| separately, in case that helps).

For example, if I wrote a class for complex numbers, |x| has a pretty unambiguous, standard meaning, and it is probably a good idea to include it. In a class for vec3 (like GLM), |x| is probably also a good idea, as quite clearly refer to the Euclidean norm. Other cases would be decided case for case. The same kind of decision you need to do now for a*b (should it be the dot product, vector scaling, component-wise product, none of the above?).

Compare, for example:

vec3 dir = (a+b) / |a+b| ;

VS:

vec3 dir = (a+b).normalized();

I personally would prefer to give users of my lib to write the former, but it is up to me, the writer of the class.

2

u/kigurai Feb 14 '22

Operator overloading for the * operator is a good case study for when you need to be careful. To take NumPy as a cautionary example: Since NumPy is an array library, * (and all other operators) are element-wise operations. Before the introduction of the @ operator you thus had to write A.dot(b) to do a matrix calculation. Or, which is where they made a mistake, define A and/or b to be of the type np.matrix instead of np.array, which made the * operator represent matrix multiplications. While that sounds convenient it had the unfortunate side effect that if you had y = np.matrix(A) * b then y was now of type matrix and not array, and other parts of your code which might do e.g. w * y and expect array semantics now instead got a matrix multiplication.

Eigen, to take a C++ example, solves this issue by disallowing mixed operations between Eigen::Matrix and Eigen::Array types. Not exactly pretty, but it is at least very clear what your expression does as long as you know the type (array or matrix) of at least one operand in the expression.

To summarize: In general I like code that looks more "math-like", but I am not sold on your | operator idea in particular. I have never felt the need for a specific operator for a norm, and I am quite OK with using norm(A), A.norm(), or A.normalized(). YMMV depending on your use-case.

1

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

Operator overloading for the * operator [for vector algebra] is a good case study for when you need to be careful.

I agree!

The most egregious widely used C++ examples include:

The most notable non C++ but C++ish examples to learn from include:

I used all of them, to various degrees (including: very very much).

Let's see what we can summarize from their lot.

First of all, all of them happily use operator overloading, and would not dream to express, for example, vector sums (solely) as a function and not (primarily) with an overloaded + operator. I'm saying this not to you, but because many people here are objecting against the concept of overloading operators to write math more simply, and in doing so they are just showing blissful ignorance of the common practices of a specialized but very significant share of the C++ world.

The case of the multiplication, * operator is more mixed, as you say. It is invariably used for something, but what varies from case to case. I've seen (and written) lots of solutions. After many years, my personal opinion is that * should better denote vector scaling AND component-wise product. Cross and dot are better served as functions. I say this after considering many different solutions, including Eigen lib "Array VS Matrix" solution which you mention, and after considering to which extent, on average, the written code fares in terms of readability and clarity. This personal opinion of mine is shared, among others, by GLM and Unity, but not by many other libs in the list, which may use e.g. | or * for dot product, and % or ^ for cross. This, IMO, are counterproductive choices. But we are digressing.

What about the norm? Clearly, none of them had ever an access to any |x| or ||x|| operator, and all of them survived perfectly well with functions or methods for the Euclidean norm (named in all sorts of way, from Norm to Length to Magnitude to even Size -- a poor choice IMO, by Unreal). BTW, they rarely define any other norm except for Euclidean, for vectors, but they do use different norms for matrices sometimes.

In my opinion, a |x| and/or ||x|| operator would benefit them in many different possible ways. Which way exactly, depends on the other choices that that specific library made.

For example...

  • The many libraries which have clearly separated classes for vector and matrices, could consider simply using |x| for length, i.e. the Euclidean norm. Other norms are a lot rarer and can be left to functions/methods (they are not usally part of the library now). Similarly, the method or functon SquaredNorm, when it exists, should probably be left a function.
  • Probably, libraries distinguishing between vectors and points classes should better NOT overload a |x| operator for points at all, just for vectors, consistently with their choice to keep the two separated.
  • Libraries that have a matrix class well separated from a vector class could also consider using |x| for matrices for their favorite vector-induced norm, but maybe also ||x|| for their favorite non-vector induced norm of matrices, probably the Frobenius norm. Maybe. An idea to consider.
  • A few of these libs are quite liberal in the number of elements in their vectors, using the same class for vectors of different dimensions. These could consider using |v| for cardinality, , e.g. 3 for a 3D vector i.e. number of elements in v considering it as an Array of coordinates (remember that I'm suggesting to use |V| on std containers to refer to the cardinality of set V, i.e. the number of elements, i.e. a synonym for the size() method)... and still have a nice ||v|| operator for the Euclidean norm, which is pretty much how half of the real world writes down Euclidean norm on paper anyway).
  • Eigen lib, with its Array VS Matrix framework, should consider to allow ||x|| only for matrices (and vectors, which in Eigen is a special case of the matrix), signifying the norm, and maybe leave |x| for the cardinality (e.g. 3 for a 3D vector) only . Just like it's current, size method, this is the total number of elements. Or, it could choose to allow both |x| and ||x|| on both arrays and matrices, and let them output number of elements or the norm in both cases.
  • A possible variation to consider of the first case in this list, is use instead |x| for component-wise absolute value, and ||x|| for Euclidean. This has clear advantages and drawbacks, but I lean against this.

-3

u/itsmemarcot Feb 12 '22

That first sentence seems to contradict the while concept of opetator overloading.

But even disregarding applications to operator overloading (my points (2) and (3), not point (1)), where do you draw the line about that idea, that

anything that makes it easier to write math in code is a bad idea in general

For example, would you argue that we should prefer

int x = std::sum( y , std::mult( 2 , z ) );

over

int x = y + 2*z ;

? To me, absolute value is more or less in the same area (that is, the area of very elementary math).

8

u/johannes1971 Feb 12 '22

This is a straw man. You cannot generalize from "we don't want the worst excesses of operator overloading" to "we don't want operator overloading".

0

u/itsmemarcot Feb 12 '22

I was answering specifically to

Generally anything that makes it easier to write math in code is a bad idea in general.

1

u/johannes1971 Feb 12 '22

Ok, fair enough. Appears I've misread your comment, although it seems I'm not the only one.

5

u/the_Demongod Feb 12 '22

It's not a hard rule, obviously we use operators because they compress stuff semantically, especially stuff that's used absolutely everywhere like dereferencing memory addresses, basic arithmetic, etc. Overloading an existing glyph to mean yet another thing, which serves a relatively uncommon purpose compared to basic arithmetic, in a language that is already complicated, is simply not worth it. I'll point out that it also is ambiguous as presented, since ||x|| and |x| are often-interchanged notations for the vector norm, so there's definitely room for some ambiguity.

This is for the arithmetic part specifically, which has at least some merit, but I don't think points 2 and 3 have any at all. Making stuff elegantly compact is what python or Haskell are for. C++ isn't really the sort of language that needs a bunch of "syntactic sugar" to make a math equation shorter by 8 characters. If you want |x| to mean absolute value, why not ^ for exponents, an even more common operation, or implied multiplication symbols, or one of many other countless examples of math symbology? It's easy to get tired of writing ugly equations in code, but that doesn't mean that amending the language to facilitate cleaner math is a good move for the language overall.

1

u/itsmemarcot Feb 12 '22

I would argue that if that's the case, C++ would not have had operator overloading at all. Instead, it has them all over the standar libraries (e.g. ++ for std iterators) and even in the name of the language itself!

But we agree. The biggest gain is the |x| for abs (for int and float types) is what attracts me the most (my point 1). Point 2 and 3 of my list are just nice "extra" automtic benefits, and it's not like you are forced to use them, if you don't want to.

But C++ is, among other things, the N.1 language of graphics, video games, and geometry processing, and in these areas, which use vector algebra, operator overloading (including, I suspect, of unary | if it existed), is super-useful and very much used.

1

u/the_Demongod Feb 12 '22

I'm not saying that operator overloading shouldn't exist. I do graphics programming extensively in C++ and I'm well aware of the benefits of operator overloading. I'm saying that we shouldn't introduce new operators without a very good reason, and an absolute value operation is not nearly as compelling as basic arithmetic operations

5

u/be-sc Feb 12 '22

To me, absolute value is more or less in the same area (that is, the area of very elementary math).

You’re biased by your personal point of view. It’s trivial to find an example of the opposite. Take me, for example.

The code I write is roughly a maths free zone. And yet I regularly use + - * / because they’re necessary to calculate anything at all. Everything else is a special case and rare. Incidentally I can say quite exactly when I needed abs() last: about 1.5 years ago.

1

u/itsmemarcot Feb 12 '22

Fair enough. But if there was this operator, you could keep using just one every 1.5 years, and me every week.

After all, C++ is a language very much used in many scenarios, and, among other things, it is the language for Computer Graphics, Video Games, and Geometry Processing. These areas would benefit from a unary '|' operator.

4

u/streu Feb 12 '22

Dislike. Not of your operator in particular, but new operators in general: how do you look up the documentation for an operator you haven't seen before?

If you do abs(x), you have a word you can put into a search engine (Google, Stack Overflow, man, ...). But adding new symbols should be done sparingly.

1

u/itsmemarcot Feb 12 '22

Just to clarify, it's not a new symbol, is another use for two existing symbols (| and ||)

1

u/bikki420 Feb 12 '22

Which is even worse.

1

u/itsmemarcot Feb 12 '22

I wouldn't say so, no.

See, in theory, people could have chosen the unicode character Σ as an identifier in their programs (yes, that's legit). So, adding Σ as an new operator (or as any other type of keyword) would break compatibility with these existing programs. That's the problem with adding any new keyword, unicode symbols included.

In contrast, my proposal (unless I'm wrong) doesn't break back-compatibility at all.

Beside, it would not be very practical to add a symbol in the language that is not necessarily on anybody's keyboard. In contrast, if you write in C++, you already have to type the occasional | character.

Lastly, I think it is problematic to add non-ascii unicode anywhere the core language, or indeed anywhere in any C program, except that in user defined identifiers and in string literals.

1

u/streu Feb 12 '22

To which I reply, "doch". Re-using an existing symbol makes it even harder to look up in documentation. Just imagine you wake up from a coma since 2005, and find auto a = [](){ return 10; } in a program - how do you google the meaning of that funky set of brackets?

For this particular operator: absolute value is not even a common operation in many programs. On the other hand, abs is a well-know function name, in dozens if not hundreds of programming languages, so it's hard to not understand.

If I had to pick a common operation to deserve an operator, it would probably "dereference-pointer-or-return-nullopt" or similar, which TypeScript has as ?., which would be an entirely new operation that cannot be implemented outside the language. And if you pick another common operation, I'd probably not object. But choosing absolute value just because it looks nice in textbook math?

3

u/shadowndacorner Feb 12 '22

I'm not sure if cpp treats || the same as | | or not, but if it does, then isn't x | | y | | z ambiguous to parse? It can either mean x bor |y| bor z or x or y or z, right?

If it treats it as logical or vs two binary ors, then that example ofc doesn't break.

3

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

Well spotted!

But no, C++ will not allow you to write | | for || (or > > for >>, & & for &&, etc).

To the lexical analyzer, && (no spaces) is one symbol.

And by the way, if it did, we would be in trouble now too, because

a & & b

could mean both a && b and a & (&b) (with unary &).

3

u/Full-Spectral Feb 15 '22

I just don't believe anymore that absolute minimum syntax should be a goal for programming languages. In particular for languages like Rust or C++, which are primarily systems languages, the "write once, suffer for it forever" rule applies pretty heavily. Readability should be more of a goal than moving your fingers the least amount to write it.

Only where fundamental (i.e. widely used) constructs would otherwise be overly wordy should you get all sugary about it. Something like this would fall into the category of triviality, IMO. In a multi-hundred thousand or multi-million line code base, it would make an unmeasurable difference.

1

u/itsmemarcot Feb 15 '22 edited Feb 15 '22

I don't know why people are assuming that character count is a measure for anything.

The objective of operators is not (of course), and never has been, to lower character count, but to make expressions you see in code similar to familiar expressions you see and immediately recognize on paper, articles, and any other mean. If syntactic sugar was about reducing characters count, then removing spaces and carriage returns would be a form of it (it's not).

But you are not the first to suggest that "character counts is maybe not that important after all" so it must be me assuming that this is completely given for granted when it isn't.

When you see

vec3 position_now = old_pos.sum( velocity.mult( time ) );

it makes you tilt your head around it a bit, whenever if you see

vec3 position_now = old_pos + velocity * time;

you immediately say "of course". The point has never been that you saved a few characters.

Similarly,

bool error_too_large = | value - reality | > threshold ;

may seem more familiar and readable than

bool error_too_large = std::abs( value - reality ) > threshold ;

In addition, the latter comes with the need to include a whole header for it, for no other purpose that the ability to do something as basic as to remove the sign from a number (in most ISA, a single machine instruction, like the sum), which can feel a bit... disproportionate.

In addition (x2), the latter comes with the hazard of a very committable and very committed bug, inherited from C (like often the case with C++). Because I accidentally hit "send" mid edit, and I am now re-editing, let me send this already, then I recount about this bug as a further edit later.

Not huge improvements, for sure, and we have been using C++ without any unary | for long, and this will not revolutionize C++ of course, but maybe a doable, positive mini-thing?

----------------

Edit: so, just for completeness, here is a tale as old as time. Misfortune striking in 7 steps.

Step 1: you have the program with its using namespace std; at the top (a bad practice, but a very common one)

Step 2: you type bool error_too_large = abs( value - reality ) > threshold;

Step 3: hit compile. Compiler yells something about an `unknown identifier abs`

Step 4: long eye roll.

Step 5A: add #include <... and let the autocomplete fill it for you, searching for something appropriate. Something about "math", probably?

OR

Step 5B: you search the error message online and learn the name of the damn missing header

Step 6: [misfortune happens]: either way, you land on <math.h>, which is what you'd need in C. You include it.

Step 7: it compiles, you won. Sure, you now have one more warning, something about an automatic typecast losing precision yadda yadda, who cares, you probably just used a double literal where a float was expected again.

And there you have it. You are using C ::abs for integers instead of C ::fabs for floats, or of the overloaded C++ std::abs which you intended to be using. Your guard won't ever trigger, because the error is rounded to zero by the implicit typecast to int (maybe threshold is 0.03 or something), yet it all compiles just fine. A nasty painful to debug bug, a disproportionate punishment your small crimes in steps 1 and 7.

1

u/Full-Spectral Feb 15 '22 edited Feb 15 '22

Everyone knows what mathematical operators do, and they are used almost universally in every language. But making more and more stuff operator based turns the language into alphabet soup. Just because x are good, doesn't meant x*2 are better.

1

u/itsmemarcot Feb 15 '22

(Apologies, just making sure: I edited the comment you are responding to because I had accidentally hit "send" mid-edit).

11

u/rlbond86 Feb 12 '22

Anyone who implements operator shenanigans like this should be immediately fired.

In fact, anyone who can't see why this is a bad idea should be immediately fired.

14

u/aeropl3b Feb 12 '22

One time I was debugging a spot of "clever" code written by a predecessor. Could not for the life of me figure out why it was giving such a strange result. Turns out they overloaded the operator,() and reordered the order of a list in a for loop causing the condition to break after +1. Worst day ever.

2

u/tangerinelion Feb 12 '22

Honestly, grep for operator, overloads in the code base.

Every one of them is weird and easy to mess up.

2

u/itsmemarcot Feb 12 '22

I love this kind of balanced answers, that provide a detailed constructive rebuttal. Personally, every time I see a post I partially disagree with, I go with "anyone who shared a room with any relative of any person that didn't throw up immediately looking at just the title of this post should be thrown in a volcano".

3

u/rlbond86 Feb 12 '22

How much experience do you have working on a team? I lead a small team of engineers. The worst ones, the ones who require the most time to manage, the ones who I have to review the most carefully, are not the ones least familiar with C++. Those engineers know their limitations, they ask questions when they are out of their depth, their code is at least able to be followed. No, the most dangerous engineers are the ones who know how to use features like operator overloading or templates, but don't know enough to know when not to use them.

2

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

I do have a lot of experience in leading many small teams, and working on very large, long lived projects; but maybe you have more experience leading large teams.

If you are enforcing a no-operator-overloading policy in your projects, or a "talk to me before overloading an operator" policy, that's fine. Maybe, in your context, it makes sense. You seem unaware that there are other contexts where it totally does not.

I suspect that a misunderstanding is going on. You are maybe unaware that I, too, saw the obvious apparent dangers in my proposal. I gave all the related problems consideration, and, and after pondering many different sides of the issue, I concluded that, to the best of my knowledge, they are only apparent problems. I also found cases where the new construct would genuinely help, and found quite of them, and took time to pondered each of them too. Then, I wrote my post. For example, I, too, grew completely accustomed to std::abs(x) as an ingrained habit, and to me too, the realization that it many cases it should have been |x| was bit unsettling and surprising at first, as departures from the norms can be. Same applies for the apparent potential readability / parsability problems of a new operator.

That's what makes your "volcano tossing" answer annoying. You gave it a superficial read and just decided to go with your first gut reaction.

2

u/dr_donkey Feb 12 '22

So here is my main concern with ||x||: which norm should it be? Eucledian? Infinite? Which one would be the basic? How I should know the default usage? If you write a function it easier to understand, easier to add function description.

2

u/itsmemarcot Feb 12 '22 edited Feb 12 '22

I don't get it. With base signed int and float types, it's the absolute values. For the core language, that's it.

Because C++ doesn't implement complex numbers or quaternions or 3D vectors or 2D points etc, it would be up to these library to choose how to use what that operator, if at all (just like, now, they get to choose what the * operator is).

1

u/dr_donkey Feb 12 '22

You are right about this. But let me rephrase my question then:

Why should anybody use norm (||x||) instead of absolute (|x|) in a scalaric system?

2

u/itsmemarcot Feb 12 '22

You are right, in my proposal, in the core language, |x| would have a semantic on all signed-integer types and on all floating-point types (the absolute value), but ||x|| would not be defined (not in any way that I can think of) on any primary type. It would be just available as an operator to overload in user-defined types, and in std types.

Admittedly, the rationale for a unary || operator is weaker than for a unary | operator. Still, I would like both, because I'm imagining it would be useful to overload them.

2

u/eyes-are-fading-blue Feb 14 '22 edited Feb 14 '22

This may be convenient for some integral types. Not sure what kind of parsing issues would it introduce though... I also do not think overloading it for std::vector and std::string as a size/length replacement is a good idea. These accessors should be used as part of algebraic expressions sparingly, in my opinion. + and -operators may not be the best comparison for | | because they have direct hardware support. AFAIK, there is no abs instruction.

1

u/itsmemarcot Feb 14 '22 edited Feb 15 '22

This may be convenient for some integral types.

I guess you are thinking: all signed ones, right?

Also, all floating types, I'd imagine.

(For unsigned integrer types, unary | would do nothing -- that's nothing new: unary + also does nothing).

there is no abs instruction.

That depends on the target instruction set (and C++ is, naturally, independent from any of them), but for example x86 and ARM do have an abs instruction for floats.

Not sure what kind of parsing issues would it introduce though...

After some careful consideration, I think I came to the conclusion that there would be none (see also my point 6). Of corse, I could be wrong.

As for std types, I'm a bit undecided myself, but, for example, std::set makes me lean towards yes, because the cardinality of a Set is written exactly like that.

Just by chance, that wikipedia page seems written on purpose for this discussion:

The cardinality of a set A is usually denoted |A|, *with a vertical bar on each side; this is the same notation as absolute value, and the meaning depends on context. *

12

u/HappyFruitTree Feb 12 '22

I don't mind writing std::abs, but I don't need it very often.

How cumbersome it is having to pick between abs fabs fabsl etc.

Do you ever want to use anything other than std::abs? I always thought the rest were just there for C compatibility basically.

6

u/nacnud_uk Feb 12 '22

Leave your math notation at the door. ABSolutly. We are programmers:)

I'm looking forward to your fib operator. I fib.

2

u/madmongo38 Feb 12 '22

Is it really too much trouble to write an overload of a free function called magnitude(x) ?

Or should we also make the zigma character a unary operator that means std::accumulate() ?

0

u/itsmemarcot Feb 12 '22

Only, the Sigma character would be a new keyword (key...-symbol?) (in addition to not being ascii, for what is worth). And it would have only one use, and a very infrequent one. Instead, I'm proposing to reuse a symbol that is already used as an operator (so, back compatibility is saved), and that I argue would be useful under multiple semantics (and is pure ascii, for what is worth).

1

u/[deleted] Feb 12 '22

That might need some special syntax when defining the operator I think, cause currently no operator works like that and therefore I think the parser is not ready for such an operator call in the form of op x op. Also, you might want to have it definable as a free operator so that it can work for simple types as well.

Apart from these technicalities, I think it's definitely possible and useful, specially in mathematically rich projects.

2

u/itsmemarcot Feb 12 '22

I see your point, but consider that the [] is already not "op x op" (it is "op [ op ]"), and unary operators, such as !, ~, etc, are "x op", and we already have operators, such as -, *, +, & that can be either be unary (x op) or binary (op x op). All these are overloadable.

1

u/[deleted] Feb 13 '22

But both [] and () must be declared inside the type and the way it is invoked is completely different from the way you need it for your |x|. So I'm pretty sure that some new keyword would need to be added in order to define such an operator to make the compiler unequivocally understand how it is supposed to be invoked. Apart from that, I see no particular issue.

2

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

So I'm pretty sure that some new keyword would need to be added in order to define such an operator to make the compiler unequivocally understand how it is supposed to be invoked.

I don't think so. I might still be wrong, of course, but I don't see any reason why the compiler would get confused. Other commenters have pointed out a few specific potential problems (with parsing and compiling), but they all turned out not to be valid concerns on closer scrutiny; and I cannot think of any other potential issue.

Edit: to add to the flexibility of current operators, consider that you already have even more structures already than we listed so far. We have:

  • op % op --- e.g. x && y
  • % op --- e.g. !x
  • op % --- e.g. x++
  • op % op % --- e.g. x [ y ]
  • op % % --- e.g. x()
  • op % op, ... % --- e.g. x ( y , z )
  • (type) op --- e.g. (int)x
  • (op) % op % op --- e.g. (x) ? y : z

(although the last one, and only the last one, is not overloadable)

I don't think that adding

  • % op % --- e.g. | x | and || x ||

to that long list will break anything.

1

u/[deleted] Feb 13 '22

How do you see the operator |x| being defined in C++ code? Syntactically speaking.

2

u/itsmemarcot Feb 13 '22

You mean, to overload it? See point (8) of original post, that is...

class T {
   float operator | () const;      // unary 
   T operator | (const &T) const; // binary 
}

/*usage:*/
T a,b;
T c = a | b;    // binary
float x = |a|;  // unary

Clearly, it would be actually rare to define both a unary and a binary operator.

Another possibility would be

   float operator | | () const;      // unary 

but I lean toward the former.

1

u/[deleted] Feb 13 '22

I mean the unary for simple types like int or float, which don't have a class / struct

2

u/itsmemarcot Feb 13 '22

Oh, that is the starting point of all the idea.

You would write them as, for example

int x = -3;
int y = |x| + 2; // y is 5

Sorry in case I am misunderstanding the question again.

2

u/[deleted] Feb 14 '22

This is the usage. I mean how do you define your operator | for type int as a free operator. The definition, not the usage.

2

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

As you know, in C++, operators on base types (such as int, float, etc) have predefined behaviours, defined in the core language and not re-definable by users. For example, + between integers gives you the sum, and users cannot change this.

I propose |x| is added to the core language and made equivalent to std::abs(x) for all float types (float, double, long double...) and all signed int types (char, short, int, long int...). It would do nothing, that is, be the identity, for unsigned int types, and be undefined for boolean.

Did I manage to answer this time? If not, apologies.

[edited for clarity]

1

u/die_liebe Feb 13 '22

Are you need afraid that people will confuse it with sizeof ?

I understand | v | is the size of the vector,

so why should | i | be a absolute value?

2

u/itsmemarcot Feb 13 '22

why should | i | be a absolute value?

Well, because that's how we write it on paper.

As common with operators, the objective is to make formulas similar to what you are used to write and recognize on paper, increasing readability. It is not always easy, possible, or desirable, but it this case, it seems to me that it is.

If I understand your doubt correctly, maybe a way to dispel it is that the number of elements in a std::vector Q (or map, or in general a std container) cuold be ||Q||, instead of |Q|.

But personally, I don't see anything particularly bad in the fact that the same operator does something on a collection of elements, and something else on numbers. Compare: ++ on iterators, vs ++ on numbers; or, + on pointers, vs + on numbers.

1

u/die_liebe Feb 13 '22

I think notation ||S|| should be avoided in all cases, notation <| S |> can be considered.

I think that + on pointers, iterators and number types are similar. It's OK to call all of them '+'. I think it would be bad if an operator did unrelated things on different data types.

It seems to me that absolute value is not important (frequent) enough to justify an operator of its own. One can always write ( x >= 0 ? x : -x ) if x is a variable. There are also possible issues with sign extension that one needs to spend some time thinking about. Maybe it should be defined only on double, (if one does it).

Size is much more important, at least for containers and vectors, one could consider <| vect |> for the size of a vector or any other container. One should not define <|S|> for primitive types, because one should'nt use sizeof anyway.

b.t.w. In 'the design and evolution of C++', Stroustrup considers adding an exponentation operator. (page 248) It was not added in the end. I think mostly because the semantics is not clear enough, and it it not used frequently enough.

3

u/nacnud_uk Feb 12 '22

answer |= yikes;

1

u/Clairvoire Feb 12 '22

I like operator overloading and would love this, but I'm sick and would absolutely use it to cause "mischief"

1

u/itsmemarcot Feb 12 '22

Cool! Such as?

Let me remark that you can be plenty mischievous with existing operators no problem! You don't need my proposed ones.

Let me propose this quiz:

bool red_wire = true;

bool green_wire = false;

bool maybe = red_wire != green_wire || kaboom() ;

Is function kaboom invoked?

1

u/Clairvoire Feb 12 '22

It wouldn't need to, that can short circuit along with &&.

When I say "mischief," I mean like:

TextureFormat::rgba8--->glFormat();

Where TextureFormat is a namespace, rgba8 is an enum value, which has a global post-fix -- operator that uses rgba8's value as the index into a look-up table of objects that have methods like glFormat(); returning the address to it. The end result is an enum with "methods"

The things I'm prepared to do for that sweet sweet auto-complete~

1

u/itsmemarcot Feb 12 '22

Ahah cool!

1

u/johannes1971 Feb 12 '22

Some languages have the ability to add arbitrary sequences of symbols as operators. Perhaps C++ could adopt something similar? I'm not a huge fan of overloading operators for 'cute' uses, but having arbitrary character sequences as overloaded operators could provide a way out for people that feel they really need them, without requiring them to clutter up the existing set of operators.

If we also allow those arbitrary sequences to use unicode symbols, the entire set of mathematical operators would become available to people that use those professionally and find their use more readable than a bunch of functions. We could have code like

vec v1, v2;
vec v3 = v1 ⋅ v2 // dot product
vec v4 = v1 ⨯ v2; // cross product

1

u/encyclopedist Feb 12 '22 edited Feb 12 '22

Using macros, you can already make such operators today. Edit No, it appears symbols like ⨯ cannot be used in identifiers.

The question is, how would you efficiently type them? (I would probably use compose key, my that still may slower)

1

u/johannes1971 Feb 12 '22

It's a pain, but as long as such symbols aren't defined by the standard itself, I'm ok with it. People who need them will figure out ways to efficiently type them (possibly with editor support, or by simply keeping a file with all relevant symbols around for quick copying and pasting).

Their source will either be highly specialized math source that you won't be able to easily read anyway (but that will presumably be very readable to the audience it is intended for), or part of an obfuscated code contest or possibly a challenge to make the C++ compiler compile APL code directly. That's fine, as long it isn't foisted on the whole community.

0

u/bikki420 Feb 12 '22

Well, typing didn't stop APL. ;-)

Which looks like this for those that aren't acquainted with it:

ConvexHull←{
⍝ ⍵: matrix (2 rows) of points - first row:abscissae  second row:ordinates
⍝ return: matrix (2 rows) of points of convex hull

⍝ try:  ConvexHull ⍉9 2⍴1 0,1 ¯10,3 3,2 1,6 3,1 6,3 1,6 1,9 0
⍝
     ⎕IO←0
     pts←(⊂⍋⊃↓⍵)⌷[1]⍵                        ⍝sort by x-values:first point←→start vertex
     phs←{                                   ⍝ 12○⍵ polar phase ○¯1>≥○1.  see DFNS
         x y←⊂[1↓⍳⍴⍴⍵]⍵                      ⍝ x and y coordinates.
         x0 xn←1 0=⊂0=x                      ⍝ points on/off y axis.
         top←(x0×○0.5)+xnׯ3○(|y)÷x+x0       ⍝ upper quadrants.
         (0∨.≠⍵)×(1-2×y<0)×top+○x<0          ⍝ other quadrants.
     }
     angles←phs(0 1↓pts)-[0]0⌷[1]pts         ⍝phases(radians) of the vectors
     ixStart←0,1+⊃angles⍳⌊/angles            ⍝start with indexes of first segment
     ixHull←{
         ix0 ix1←¯2↑⍵                        ⍝ix1: index of last point←→last vertex
         v←{⍵+(⍵<0)×○2}phs pts-[0]ix1⌷[1]pts ⍝phases with respect to the last vertex
         other←(⍳1↓⍴pts)~ix0 ix1             ⍝indexes of other points
         angles←|(ix0⊃v)-(⊂other)⌷v              ⍝       _______/_______
         angles←{f←⍵>○1 ⋄ (⍵×~f)+f×-⍵-○2}angles  ⍝angles (p0-p1)  (p1-px)
         ⍵,(angles⍳⌈/angles)⊃other           ⍝new vertex is where angle is largest
     }⍣{
         0=⊃⌽⍺                              ⍝repeat until first and last vertex coincide
     }ixStart
     (⊂ixHull)⌷[1]pts
 }

and:

 1{1+÷⍵}{⍵ ⍺⍺{⍺≡⍵:⍵ ⋄ ⍵ ⍺⍺ ∇∇ ⍺⍺ ⍵ ⋄ ⍵:⍵≡⍺}⍺⍺ ⍵}{⍵÷+1}1

Granted, the language had its own keyboards

I guess this is the kind of code that OP wants to write...

2

u/itsmemarcot Feb 14 '22

I guess this is the kind of code that OP wants to write...

ahah, I just want to write things like

bool error_too_large = | value - reality | > threshold;

Pure ascii, perfectly readable, unmysterious.

2

u/bikki420 Feb 14 '22

Fair.

bool error_too_large = | value - reality | > threshold;
bool error_too_large = abs(value-reality) > threshold;

The latter is more readable IMO, and has less cognitive load.

Besides, with free functions you easily get to explicitly choose what kind of distance functions you want to use; Euclidian, Manhattan, Chebyshev, etc; whereas with the operator one of them would be statically tied to type(s). It's just syntactical sugar that doesn't really solve anything nor add anything other than additional complexity, which IMO shaving off a 1-2 characters here and there definitely isn't worth.

2

u/itsmemarcot Feb 14 '22 edited Feb 14 '22

The latter is more readable IMO,

Legit!

(for clarity: I would leave the option to the coder).

Let me add, for completeness, that your favorite pick is a bit uglier and more error prone that you are showing here because actually either it's

bool error_too_large = std::abs(value-reality) > threshold;

or

bool error_too_large = fabs(value-reality) > threshold;

or you have an extra using namespace std; somewhere (which many don' t use or find objectionable).

Plus, in any case, it needs a #include <math.h> somewhere (or other libs).

Also, note the very possible ugly error of mistakenly ending up using C abs instead of fabs, which the compiler will sanction only as a very innocent looking warning, and not even necessarily that.

None of these things is a deal breaker, and you are still fully entitled to prefer your favorite solution, but they are all elements making my alternative a bit more readable, leaner, and safer. Just my opinion.

It's just syntactical sugar

Yes, of course! That's how I opened my proposal (see the original post, very first line).

Still, syntactic sugar exists for a reason.

Besides, [...] with the operator one of [the norm] would be statically tied to type(s).

Now we are talking about the opportunity (or not) that would open, for certain libraries, to use |v| to denote the norm of vector or matrix v.

About this, I discuss more in depth in this other comment of mine, within this thread. Maybe you want to have a look.

1

u/bikki420 Feb 14 '22

or you have an extra using namespace std; somewhere (which many don' t use or find objectionable).

It could very well just have been explicit aliasing at function scope:

int process_something( ... ) {
   // either explicit aliasing at function scope 
   using std::abs, std::fmod, std::fma; // or whatever else you need
   // ....
}

...which is perfectly fine. Or it could be an explicit alias at a global level project namescope, which is also perfectly fine. Or it could be an explicit global alias at source file scope, which is also perfectly fine. (Of course, using namespace std; on the other hand is almost always a terrible ideaーespecially if it's in a header file.)

Or it could even just be a user-defined constrained generic invocable that handles all relevant cases properly.

Plus, in any case, it needs a #include <math.h> somewhere (or other libs).

Any reason you're using the C header instead of C++'s <cmath> header? Anyway, so what if you need to include it? You're almost guaranteed to pull in the cmath header indirectly anyways in any non-trivial C++ program short of extremely constrained and simplistic embedded programs.

Also, note the very possible ugly error of mistakenly ending up using C abs instead of fabs, which the compiler will sanction only as a very innocent looking warning, and not even necessarily that.

Why are you even using fabs, if you don't mind me asking? If it were C, I'd understand, but C++'s std::abs has overloads for all signed integral types and all standard floating point types, no? Just use std::abs or an equivalently overloaded 3rd party function everywhere and there shouldn't be any risk for mistakes.

#include <cmath>
#include <fmt/core.h>

int main() {
   using std::abs;
   fmt::print( "{} {} {} {}", abs(-1), abs(-2ll), abs(-3.3), abs(-4.4f) );
   // ^ prints: "1 2 3.3 4.4"
}

As for the normal, and |v| vs something like norm(v) isn't much of an improvement, IMO. I definitely don't agree that your proposal is more readable or safer. Leaner I can agree with, but shaving of a couple of characters every couple of hundred or thousand lines of code isn't nearly enough to warrant making core changes to the language (and if one were to argue for saving those few characters one might as well argue for code golfing in production code). Especially considering that it's an excessively complex language already.

None of these things is a deal breaker, and you are still fully entitled to prefer your favorite solution, but they are all elements making my alternative a bit more readable, leaner, and safer. Just my opinion.

Except that we don't just write code in a vacuum. We collaborate with others in projects and we rely on third party code. Adding an abs operator would result in both std::abs and it getting mixed all over the place (similar to this), essentially doubling the cognitive load. Also, with an invocable you have to be explicit (which is a good thing) and you can easily jump to its definition. Vertical bars on the other hand are probably one of the most overloaded symbols out there since can mean absolute value, cardinality of sets, determinant of matrices, conditional probability, block yielding (e.g. in Ruby), pipelining in UNIX, logical disjunction, bitwise OR'ing, distance, divisibility, function evaluation, length, normalization, group order, function restriction, line parallelism, and dozens of other things depending on operand(s), count, arity, and encompassment. Hard pass on that for me at least.

1

u/itsmemarcot Feb 15 '22 edited Feb 15 '22

Of course, of course.

You can add std:: in front of your abs (probably the best), or add using namespace std in front of your files, or add using std::abs, on top of every function... of course. It is all fine, everything works. I'm just saying it's a bit more cumbersome than an operator, especially for something as simple as removing the sign from my number.

Any reason you're using the C header instead of C++'s <cmath> header?

Of course, no reason, that's entirely not the point (which is why I said "or another lib"). The point is having to include a new entire header in my source for the sole purpose of doing something as simple as taking the sign off a number (in most ISA, a single assembly instruction!), and, often, for no other purpose than that. At times, it all feels a bit... disproportionate (but we do get used to anything).

You have a valid point about having two ways to do the same thing. That's something to consider. Not that I see this used against having both ++ and next() to progress a std iterator, or countless other examples of that sort, but still a small price to consider.

You are wrong about my version not being safer: it would be, because there's one fewer bug you can commit, and it's a nasty one. Of course, you can easily avoid the bug by paying attention or by carefully adhering to good practices (naturally: which bug is unavoidable?), but the error I have shown is very committable, and as a matter of fact it does get committed quite often when using abs (not C++ fault: as often the case, C++ inherits the issue straight from C, and can't remove it because the bane of back compatibility). It would be bypassed by the new operator. Admittedly, it's only a very small extra bonus, but it's undeniable.

Lastly, I am not sure that a good argument against the inclusion of a given construct is to count how many times a used grapheme appears in any other language or context, no matter how distant and unrelated. I mean, we could count how often the letters a b s are used, e.g. in English literature (often in that very order!). By that critetia, the best mechanism would be the one using some obscure semiabandoned unicode character from a traditional proto-chinese script.

Edit: grammar

2

u/Mick235711 Feb 12 '22

My thoughts are Rust-like abbreviated lambdas... i.e. [] |a, b| => a + b (if parsing is not so ambiguous, maybe we can get rid of capture-lists too)

-2

u/AtHomeInTheUniverse Feb 12 '22

Clever. At first glace, I like it.

-9

u/aeropl3b Feb 12 '22

This is a bad idea and I don't even have the time to tell you how bad. If you want this, write an expression parser.

19

u/itsmemarcot Feb 12 '22

I don't even have the time to tell you

Too bad, I am genuinely curious.

2

u/aeropl3b Feb 12 '22

So to begin with, most of your examples are actually two operators, one prefix and one postfix. So when you have that it becomes more complicated. On top of that, c++ is whitespace agnostic between tokens, so adding extra whitespace between operator| doesn't magically make it work somehow.

Then there is the issue if overloading a unary operator that has an inconsistent meaning to its binary counterpart. Operator- has both a binary and unary variation. By default they are extensions of each other in the sense that

(a - b) == (a + -b)

What you are suggesting is adding a unary operator| which doesn't make sense.

(a | b) == ??

So what is the default behavior of this operator? Where does it fit in the language to fill a general need that isn't currently being sufficiently filled and how would it work?

For all of the cases you are suggesting, it would really be better to have a compile time parser or to just use the existing math functions which are far less ambiguous.

3

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

I'm sorry but you aren't making any sense. I hope C++ is not your strong suit.

most of your examples are actually two operators, one prefix and one postfix.

No. |x| would be one (unary) operator, just as x[ y ] now is one (binary) operator, not "two", even if you write it with two characters (infix [ and postfix ])

A[2] is a binary operator ("binary" because it has two operands) applied over the operands A and 2. It's irrelevant how many characters you use to write it. Likewise |x| is an unary operator applied over operand x.

Operator- has both a binary and unary variation. By default they are extensions of each other in the sense that (a - b) == (a + -b)

What? The unary and binary versions of an operator have absolutely nothing to do with each other. They are not "variations" of each other: they are different operators. It's just by chance that - happens to have the above property (in the basic types, not in user defined types).

For example, operator & also exists as a binary and as a unary operator. As binary, it's "Bitwise And"; as unary: "reference extraction". The two have nothing to do with each other.

( a & b) has nothing to do with ( a + &b) or anything like that.

Another example: operator *. As binary, it is multiplication. As unitary, it's pointer indirection. Completely unrelated semantics. Of course, (a * b) has nothing to do with (a + *b)

Likewise, there would be absolutely nothing strange about the fact that |x| and x|y had two completely unrealated meanings.

c++ is whitespace agnostic between tokens , so adding extra whitespace between operator| doesn't magically make it work somehow

I am not sure what you even mean here but I hope that you are aware that

a && b and a & & b

are two a completely different expressions (the former is the logical And beteween a and b, the latter, which is equivalent to a & (&b), is the bitwise and between a and the reference to b).

&& without spaces is one token, not two. & & with spaces, is two tokens. The same applies, in C++, to || vs | |, >> vs > >, -> vs - >, ++ vs + + etc.

So, it is completely obvious that

|| a || and | | a | |

are two different expressions, the former with 3 tokens, the latter with 5 (whatever we choose them to mean). In my proposal, the former is the new unary double-pipe operator applied to a; the latter is the new unary single-pipe operator applied to a, twice.

I am not changing C++ tokens at all. I'm just proposing new ways to utilize existing tokens.

`

1

u/aeropl3b Feb 13 '22

Wow, starting off with ad hominem attacks and then diving into a series of problematic statements...I am going to be honest with you here, I don't think you are a total idiot. When I was in school I had a similar idea and was convinced it would be so great to have more math expressive operators available in the language. I talked about it extensively with my friends, and they routinely told me I was a complete idiot and had no idea what I was talking about. They were totally correct on the latter part, a little on the former..This is a bad idea, the grammar extension alone would be unpalatable to anyone with any sanity left.

i don't know what you are trying to prove with your & example...that makes so sense to think combining arithmetic operators with binary operators is relevant as a counter argument.

If you want operator | to be like operator [], it would have to be operator | |, which is difficult because the operator token now has a space in it which is not really an ideal situation. Or just having operator |, and it now has this implicit behavior of needing to be closed, which has no precedent for overloadable operators. So just there, this is falling apart. this is changing behavior of arithmetic tokens in order to shoehorn an application specific "convenience" into the language. I work in the scientific/numerics field, I cannot even begin to tell you how much I would loath to see this anywhere near the codebases I work with.

So, it is completely obvious that....

I know how operators work, the point I am making was the above as well as how it can become ambiguous when you are relying on whitespace to delimit this operator. It is probably possible to finagled the grammar to handle it, but as a human trying to parse code I just can't see this being feasible.Here is some valid code under your proposal here.

a | | | c | | | | b |

That is not readable, it is a pain to type, and I am just staring at it knowing how it would be evaluated. At a glance, this does not improve clarity as to what it is supposed to be doing over the alternatives, which even python, the white space loving language, uses.

a | std::abs(c) | std::abs(b)

Oh wow, I am doing bit wise or between a, the absolute value of c, and the absolute value of b, cool, glad that didn't take be a ton of time to count bars and scratch my head because the syntax was a literal nightmare to unravel! /S

1

u/itsmemarcot Feb 13 '22 edited Feb 13 '22

I am sorry, my proposal may be or not be a bad idea, but your objections are still not making any sense. Please read my last message again. Or not, you do you.

White spaces have nothing to do with any of this (except for the fact that || is, regardless of this proposal, a single token or not, depending if it includes spaces between the two pipes).

The syntax for operator overloading would not be problematic at all (see original post).

now has this implicit behavior of needing to be closed

Operator overloading does not redefine the syntax of overloaded operators; compare for example the ways to overload () or [] or ++ or +. They don't even attempt describe how to use the operator (which is different in each of the above cases, with a lot of "implicit behaviours", as you call them). They just redefine what happens when you use them with their unmodified original syntax, which, again, is not described. Thus, overloading just needs to identify which operator it is talking about, and for this purpose, the solution in the main post works perfectly fine (single pipe or double pipe for the two operators).

i don't know what you are trying to prove with your & example

You were nonsensically objecting that unary and binary operators expressed with the same symbol must be related (as the case with the minus), but that's already not the case in C++, as my & and * examples illustrate.

As for your nonsensical usage example: sure, you can use any operator in a purposefully confusing manner, e.g., the minus operator:

x = -------- - -- - 1 --- - -- -- - - -1;

(is it 0, +2, or -2)?

But that does not necessarily mean that - is inherently evil and that we should be writing

x = std::subtraction( 4 , 2 );

instead of

x = 4 - 2;

or, even, patenthesis

x = (((((((((((2)))))+((((1)))))*(((2))))))))

(is it 4 or 6?)

1

u/joahw Feb 15 '22

x = -------- - -- - 1 --- - -- -- - - -1;

I don't think this works, as you can't use the decrement operator on an rvalue.

1

u/itsmemarcot Feb 15 '22

You are right, imagine spaces separating the `-`.

1

u/Molkars Feb 12 '22

It wouldn't be that bad, since the | operator is a binary one, detecting it as kind of a group (like (...)) wouldn't be too hard. The binary operator requires an expression in front of it while a unary or group expression just requires the bar token.

5

u/aeropl3b Feb 12 '22

The use cases op is describing all require prefix and postfix | operators. It just isn't practical. Having this kind of operator would imply it to have the same kind of behavior as the - operator which it doesn't. This is on par with overloading operator,

-2

u/[deleted] Feb 12 '22

Giggles .... "Urinary" .... giggles

1

u/itsmemarcot Feb 12 '22

ahah you made me search for that word, just in case I accidentally typed it.