wren icon indicating copy to clipboard operation
wren copied to clipboard

wren/core: Add bitwise not operator for `Bool`.

Open mhermier opened this issue 4 years ago • 10 comments

For the sake of completeness, the operator is lacking the operator ~.

mhermier avatar Apr 23 '21 09:04 mhermier

I can't see much point in making this change as ~ will behave exactly like !.

However, I do think there is a case for the Bool class to support the bitwise operators &, |, ^.

In the absence of these, I have methods which convert a Bool to a Num (1 is true, 0 is false), do the bitwise operations and then convert the result back to a Bool (non-zero is true, zero is false).

However, not being able to extend the Bool class, I have to use words for the operators (and, or, xor) which is not as nice as being able to use the operators themselves.

PureFox48 avatar Apr 23 '21 10:04 PureFox48

I didn't though this deep, but true. I can add them trivially, for Bool op Bool. Supporting Num could be done, but would require too much care than what I expect this change set to be.

mhermier avatar Apr 23 '21 11:04 mhermier

As far as the Num class is concerned, I think all we'd really need would be a Num.toBool method.

This would simply convert 0 to false and anything else to true though it might be wise to exclude NaN from that.

PureFox48 avatar Apr 23 '21 11:04 PureFox48

This should then also include Bool.toNum. so it works 2-way

Orcolom avatar Apr 23 '21 11:04 Orcolom

Good point :)

PureFox48 avatar Apr 23 '21 11:04 PureFox48

Done. About the Num to/from Bool conversions, while I agree it should be done at some point in some way or another it should happens in another place. Since I don't what that discussion to be lost if the change is accepted.

mhermier avatar Apr 23 '21 11:04 mhermier

Yep, I just checked all the cases and that seems to work fine without converting to Num and back.

If support for &, | and ^ is added to Bool, then I'd be happy to include ~ as well for completeness.

PureFox48 avatar Apr 23 '21 11:04 PureFox48

There is an interesting side effect to it, it force evaluation of the right and side, contrary to logical operands. I think there is a potential use for that in some particular cases.

mhermier avatar Apr 23 '21 12:04 mhermier

Yes, it might be useful where the right operand is a function call which returns a Bool and you want to always call the function because of some side effect it has.

PureFox48 avatar Apr 23 '21 12:04 PureFox48

I do support &, | and ^ since they're not short-circuting, but I see no reason to have ~. Completeness alone isn't a strong enough argument, IMHO.

ChayimFriedman2 avatar Apr 24 '21 19:04 ChayimFriedman2