Let's say I have a condition expression x and that I want to check if it is TRUE or FALSE depending on the value of a boolean y:

y ? x : !x

Is there a way to express it without repeating x expression? Something like how we can get a number or its opposite depending on a bool, without repeating the number in the expression:

number * (opposite ? -1 : 1)

Example, note the repetition of date.hour < 12 that I want to avoid:

tellTheThruth = FALSE; // or TRUE 
if (tellTheThruth && date.hour < 12 || !tellTheThruth && !(date.hour < 12) {
    print "It's AM"
} else {
    print "It's PM" 

Is it possible in all common languages (I was thinking in Javascript and I can't find a solution)? If not, is there some language in which you can?

  • 2
    \$\begingroup\$ Checking whether the two bools are equal should work: y==x, or tellTheTruth == (date.hour < 12). Are you asking though for actual code, where readability is a concern, or for brevity in code golf contests? \$\endgroup\$ – xnor Nov 24 '15 at 0:41
  • 1
    \$\begingroup\$ You could always get 1 or 0 for truthy and falsey respectively and then XOR them, is that what you want? example: tellTheTruth ^ (date.hour < 12) \$\endgroup\$ – Downgoat Nov 24 '15 at 0:43
  • 6
    \$\begingroup\$ voting to re-open. golfing tips questions are on-topic here. \$\endgroup\$ – Sparr Nov 24 '15 at 1:01
  • 1
    \$\begingroup\$ Like I said in chat, his question explicitly asks about removing repetition of an expression (x) \$\endgroup\$ – Sparr Nov 24 '15 at 1:29
  • 4
    \$\begingroup\$ I'm voting to close this question as off-topic because it doesn't really look like a code-golfing tips question to me. \$\endgroup\$ – isaacg Nov 24 '15 at 1:47

for two booleans x and y, y ? x : !x can be rewritten as y ^ !x (y XOR NOT x) or similar in most languages.



import Data.Bool.Extras

bool from Data.Bool.Extras is similar to the ? operator in other languages. It takes 3 arguments, a False case, a True case and a boolean to decide which one to use. =<< works here in function context ( i.e. (f=<<g) x is f (g x) x), so we can use it as (bool=<<not) <x> <y> which is bool (not <x>) <x> <y>.

Example: (bool=<<not) True False -> False.


Not the answer you're looking for? Browse other questions tagged or ask your own question.