Does any language have a unary boolean toggle operator?

Language AgnosticBitwise OperatorsNegation

Language Agnostic Problem Overview


So this is more of a theoretical question. C++ and languages (in)directly based on it (Java, C#, PHP) have shortcut operators for assigning the result of most binary operators to the first operand, such as

a += 3;   // for a = a + 3
a *= 3;   // for a = a * 3;
a <<= 3;  // for a = a << 3;

but when I want to toggle a boolean expression I always find myself writing something like

a = !a;

which gets annoying when a is a long expression like.

this.dataSource.trackedObject.currentValue.booleanFlag =
    !this.dataSource.trackedObject.currentValue.booleanFlag;

(yeah, Demeter's Law, I know).

So I was wondering, is there any language with a unary boolean toggle operator that would allow me to abbreviate a = !a without repeating the expression for a, for example

!=a;  
// or
a!!;

Let's assume that our language has a proper boolean type (like bool in C++) and that a is of that type (so no C-style int a = TRUE).

If you can find a documented source, I'd also be interested to learn whether e.g. the C++ designers have considered adding an operator like that when bool became a built-in type and if so, why they decided against it.


(Note: I know that some people are of the opinion that assignment should not use = and that ++ and += are not useful operators but design flaws; let's just assume I'm happy with them and focus on why they would not extend to bools).

Language Agnostic Solutions


Solution 1 - Language Agnostic

Toggling the boolean bit

> ... that would allow me to abbreviate a = !a without repeating the > expression for a ...

This approach is not really a pure "mutating flip" operator, but does fulfill your criteria above; the right hand side of the expression does not involve the variable itself.

Any language with a boolean XOR assignment (e.g. ^=) would allow flipping the current value of a variable, say a, by means of XOR assignment to true:

// type of a is bool
a ^= true;  // if a was false, it is now true,
            // if a was true, it is now false

As pointed out by @cmaster in the comments below, the above assumes a is of type bool, and not e.g. an integer or a pointer. If a is in fact something else (e.g. something non-bool evaluating to a "truthy" or "falsy" value, with a bit representation that is not 0b1 or 0b0, respectively), the above does not hold.

For a concrete example, Java is a language where this is well-defined and not subject to any silent conversions. Quoting @Boann's comment from below:

> In Java, ^ and ^= have explicitly defined behavior for booleans > and for integers > (15.22.2. > Boolean Logical Operators &, ^, and | ), where either both sides > of the operator must be booleans, or both sides must be integers. > There's no silent conversion between those types. So it's not going to > silently malfunction if a is declared as an integer, but rather, > give a compile error. So a ^= true; is safe and well-defined in > Java.


Swift: toggle()

As of Swift 4.2, the following evolution proposal has been accepted and implemented:

This adds a native toggle() function to the Bool type in Swift.

> toggle() > > Toggles the Boolean variable’s value. > > Declaration > > mutating func toggle() > > Discussion > > Use this method to toggle a Boolean value from true to false or > from false to true. > > var bools = [true, false] > > bools[0].toggle() // bools == [false, false]

This is not an operator, per se, but does allow a language native approach for boolean toggling.

Solution 2 - Language Agnostic

In C++ it is possible to commit the Cardinal Sin of redefining the meaning of operators. With this in mind, and a little bit of ADL, all we need to do in order to unleash mayhem on our user base is this:

#include <iostream>

namespace notstd
{
    // define a flag type
    struct invert_flag {    };

    // make it available in all translation units at zero cost
    static constexpr auto invert = invert_flag{};

    // for any T, (T << invert) ~= (T = !T)    
    template<class T>
    constexpr T& operator<<(T& x, invert_flag)
    {
        x = !x;
        return x;
    }
}

int main()
{
    // unleash Hell
    using notstd::invert;

    int a = 6;
    std::cout << a << std::endl;

    // let confusion reign amongst our hapless maintainers    
    a << invert;
    std::cout << a << std::endl;

    a << invert;
    std::cout << a << std::endl;

    auto b = false;
    std::cout << b << std::endl;
    
    b << invert;
    std::cout << b << std::endl;
}

expected output:

6
0
1
0
1

Solution 3 - Language Agnostic

As long as we include assembly language...

FORTH

INVERT for a bitwise complement.

0= for a logical (true/false) complement.

Solution 4 - Language Agnostic

Decrementing a C99 bool will have the desired effect, as will incrementing or decrementing the bit types supported in some tiny-microcontroller dialects (which from what I've observed treat bits as single-bit wide bitfields, so all even numbers get truncated to 0 and all odd numbers to 1). I wouldn't particularly recommend such usage, in part because I'm not a big fan of the bool type semantics [IMHO, the type should have specified that a bool to which any value other than 0 or 1 is stored may behave when read as though it holds an Unspecified (not necessarily consistent) integer value; if a program is trying to store an integer value that isn't known to be 0 or 1, it should use !! on it first].

Solution 5 - Language Agnostic

Solution 6 - Language Agnostic

I'm assuming you're not going to be choosing a language based solely upon this :-) In any case, you can do this in C++ with something like:

inline void makenot(bool &b) { b = !b; }

See the following complete program for example:

#include <iostream>

inline void makenot(bool &b) { b = !b; }

inline void outBool(bool b) { std::cout << (b ? "true" : "false") << '\n'; }

int main() {
    bool this_dataSource_trackedObject_currentValue_booleanFlag = false;
    outBool(this_dataSource_trackedObject_currentValue_booleanFlag);

    makenot(this_dataSource_trackedObject_currentValue_booleanFlag);
    outBool(this_dataSource_trackedObject_currentValue_booleanFlag);

    makenot(this_dataSource_trackedObject_currentValue_booleanFlag);
    outBool(this_dataSource_trackedObject_currentValue_booleanFlag);
}

This outputs, as expected:

false
true
false

Solution 7 - Language Agnostic

PostScript, being a concatenative, stack-oriented language like Forth, has a unary toggle, not. The not operator toggles the value on top of the stack. For example,

true    % push true onto the stack
not     % invert the top of stack
        % the top of stack is now false

See the PostScript Language Reference Manual (pdf), p. 458.

Solution 8 - Language Agnostic

Visual Basic.Net supports this via an extension method.

Define the extension method like so:

<Extension>
Public Sub Flip(ByRef someBool As Boolean)
    someBool = Not someBool
End Sub

And then call it like this:

Dim someVariable As Boolean
someVariable = True
someVariable.Flip

So, your original example would look something like:

me.DataSource.TrackedObject.CurrentValue.BooleanFlag.Flip

Solution 9 - Language Agnostic

This question is indeed interesting from a purely theoretical standpoint. Setting aside whether or not a unary, mutating boolean toggle operator would be useful, or why many languages have opted to not provide one, I ventured on a quest to see whether or not it indeed exists.

TL;DR apparently no, but Swift lets you implement one. If you'd only like to see how it's done, you can scroll to the bottom of this answer.


After a (quick) search to features of various languages, I'd feel safe to say that no language has implemented this operator as a strict mutating in-place operation (do correct me if you find one). So the next thing would be to see if there are languages that let you build one. What this would require is two things:

  1. being able to implement (unary) operators with functions
  2. allowing said functions to have pass-by-reference arguments (so that they may mutate their arguments directly)

Many languages will immediately get ruled out for not supporting either or both of these requirements. Java for one does not allow operator overloading (or custom operators) and in addition, all primitive types are passed by value. Go has no support for operator overloading (except by hacks) whatsoever. Rust only allows operator overloading for custom types. You could almost achieve this in Scala, which let's you use very creatively named functions and also omit parentheses, but sadly there's no pass-by-reference. Fortran gets very close in that it allows for custom operators, but specifically forbids them from having inout parameters (which are allowed in normal functions and subroutines).


There is however at least one language that ticks all the necessary boxes: Swift. While some people have linked to the upcoming .toggle() member function, you can also write your own operator, which indeed supports inout arguments. Lo and behold:

prefix operator ^

prefix func ^ (b: inout Bool) {
    b = !b
}

var foo = true
print(foo)
// true

^foo

print(foo)
// false

Solution 10 - Language Agnostic

In Rust, you can create your own trait to extend the types that implement the Not trait:

use std::ops::Not;
use std::mem::replace;

trait Flip {
    fn flip(&mut self);
}

impl<T> Flip for T
where
    T: Not<Output = T> + Default,
{
    fn flip(&mut self) {
        *self = replace(self, Default::default()).not();
    }
}

#[test]
fn it_works() {
    let mut b = true;
    b.flip();
    
    assert_eq!(b, false);
}

You can also use ^= true as suggested, and in the case of Rust, there is no possible issue to do this because false is not a "disguised" integer like in C or C++:

fn main() {
    let mut b = true;
    b ^= true;
    assert_eq!(b, false);

    let mut b = false;
    b ^= true;
    assert_eq!(b, true);
}

Solution 11 - Language Agnostic

In Python

Python supports such functionality, if the variable has bool type (which is True or False) with the exclusive or (^=) operator:

a = False
a ^= True
print(a)  # --> True
a ^= True
print(a)  # --> False

Solution 12 - Language Agnostic

In C#:

boolean.variable.down.here ^= true;

The boolean ^ operator is XOR, and XORing with true is the same as inverting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCompuChipView Question on Stackoverflow
Solution 1 - Language AgnosticdfribView Answer on Stackoverflow
Solution 2 - Language AgnosticRichard HodgesView Answer on Stackoverflow
Solution 3 - Language AgnosticDrSheldonView Answer on Stackoverflow
Solution 4 - Language AgnosticsupercatView Answer on Stackoverflow
Solution 5 - Language AgnosticAdrianView Answer on Stackoverflow
Solution 6 - Language AgnosticpaxdiabloView Answer on Stackoverflow
Solution 7 - Language AgnosticWayne ConradView Answer on Stackoverflow
Solution 8 - Language AgnosticReginald BlueView Answer on Stackoverflow
Solution 9 - Language AgnosticLauri PiispanenView Answer on Stackoverflow
Solution 10 - Language AgnosticBoiethiosView Answer on Stackoverflow
Solution 11 - Language AgnosticAndriy IvaneykoView Answer on Stackoverflow
Solution 12 - Language AgnosticrakensiView Answer on Stackoverflow