Skip to content

Instantly share code, notes, and snippets.

@lrhn
Last active February 17, 2021 09:55
Show Gist options
  • Save lrhn/c10f3a26744f30c2a14cbda0c852b2ae to your computer and use it in GitHub Desktop.
Save lrhn/c10f3a26744f30c2a14cbda0c852b2ae to your computer and use it in GitHub Desktop.
Conditional Expression With Boolean Literal Rewrites
// If you use a conditional expression, `e1 ? e2 : e3`,
// where one of the expressions is a boolean literal (`true` or `false),
// then you can (and *should*) always rewrite it to a shorter expression
// using only `||` or `&&`, and possibly an `!`.
void testConditionals(bool e1, bool e2) {
// Conditional Rewrite
expect( e1 ? e2 : false , e1 && e2 );
expect( e1 ? e2 : true , !e1 || e2 );
expect( e1 ? false : e2 , !e1 && e2 );
expect( e1 ? true : e2 , e1 || e2 );
expect( true ? e1 : e2 , e1 ); // Well, duh.
expect( false ? e1 : e2 , e2 ); // ...
// Similarly, if the same value occurs twice in the conditional expression,
// possibly negated, the expression can also be simplified:
expect( e1 ? e1 : e2 , e1 || e2 );
expect( e1 ? e2 : e1 , e1 && e2 );
expect( e1 ? !e1 : e2 , !e1 && e2 );
expect( e1 ? e2 : !e1 , !e1 || e2 );
expect( e1 ? e2 : e2 , e2 ); // Unless e1 can throw, then: (e1 && false) || e2
expect( e1 ? !e2 : e2 , e1 ^ e2 );
expect( e1 ? e2 : !e2 , e1 ^ !e2 ); // or (!e1 ^ e2), !(e1 ^ e2)
}
// And run to check that it's true!
void main() {
testConditionals(true, true);
testConditionals(true, false);
testConditionals(false, true);
testConditionals(false, false);
print("Success!");
}
void expect(bool b1, bool b2) {
if (b1 != b2) throw "Bad!";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment