Hacker News new | ask | show | jobs
by ambrop7 3413 days ago
> most programming languages don’t have an explicit “logical operator” for it

I guess the author never taught of <boolean> != <boolean>. The only thing to be careful with is that it doesn't implicitly convert arguments to boolean, so expressions like "<boolean> != (flags & Flag)" will go wrong without an explicit conversion "bool(flags & Flag)" or equivalent expression like "((flags & Flag) != 0)".

And let's not forget about the friend, ==. I've more than once seen code like "(a && b) || (!a && !b)".

A similar interesting pattern many don't think of is "bool(a1) + ... + bool(aN) == M" (particularly with M==1) and instead we see unreadable monstrosities :)

5 comments

If you only want to convert the second argument you can use the ==! operator ;)
C has so many wonderful operators, why don't people use them?

  while (x --> 0) x goes to zero;
  while (0 <---- x) goes much faster on some compilers (ymmv);
!!a != !!b also works, but that's unwieldy.

I think maybe part of the reason is that usually you're also doing something with the value of the lhs or rhs, so you end up having to separate the cases anyway:

    if (a && !b) { frob(a); }
    else if (b && !a) { twiddle(b); }
    else { panic(); }
You don't need to double-negate,

  !a != !b
is sufficient.
> The only thing to be careful with is that it doesn't implicitly convert arguments to boolean

Well, you could also use bitwise XOR in that case.

Is "bool(a1) + ... + bool(aN) == M" not just "a1 || a2...||an"?
No, it's true when exactly M are true. "a1 || a2 || ... || an" is true when at least one is true.

The latter is the same as "a1 + ... + an == 1 || a1 + ... + an == 2 || ... || a1 + ... + an == n".

So your + operator implicitly casts booleans to an integer type, with false=0 and true=1?
What you are saying is the only way I can imagine to interpret what I wrote, if one assumes I was intending to make any sense.

By the way, in Python, bool is a subtype of int (i.e., instanceof(True,int) == True), and True + True == 2. C is the same, and in Javascript booleans are converted to integers for arithmetic operations.

> What you are saying is the only way I can imagine to interpret what I wrote

One might imagine it (without experience, or not thinking, of any particular programming language) as being a logical OR on Booleans - which in EE at least is frequently written '+'.

In c++, yes. Not every language will do that though.
Obviously no, the first (for M==1) means exactly one is true, the latter at least one is true. But a1||...||aN is equivalent to bool(a1)+...+bool(aN)>0 (assuming no integer overflow :).
> "(a && b) || (!a && !b)"

It is XNOR, not XOR (no pun intended)

Boolean algebra laws excellently help if there are many input aN. I used to use it to simplify legacy ruby codes written by c-style programmer (you can imagine how the conditions look like)