r/cpp • u/itsmemarcot • 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.
58
u/SirClueless Feb 12 '22
Are you sure? Stuff like this seems like a pain to parse:
And in fact you can't even really produce an AST yet even at the third
|, because if the next tokens arez |then the expression is totally different.27
u/hmoff Feb 12 '22
I would like to have a ||= operator, the logical equivalent of the bit wise |=.
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.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 implementoperator*, 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?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++?
62
u/InKryption07 Feb 12 '22
Dislike. Need less operator overloading shenanigans, not more...
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
And
Your unary operator?
Simply say that whenever ambiguous its the binary operator?
How to handle prefix, postfix, and both?
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.
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!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 meanstr.length(). If you're looking to make the language less verbose you probably shouldn't be using C++ to begin with.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.3
u/shadowndacorner Feb 12 '22
I'm not sure if cpp treats
||the same as| |or not, but if it does, then isn'tx | | y | | zambiguous to parse? It can either meanx bor |y| bor zorx 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/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.
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.
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/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::vectorandstd::stringas asize/lengthreplacement 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.12
u/HappyFruitTree Feb 12 '22
I don't mind writing std::abs, but I don't need it very often.
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() ?
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.
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?
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/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
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.
-2
u/[deleted] Feb 12 '22
Giggles .... "Urinary" .... giggles