Ternary operator syntax is not sufficient

Programming languages need an extra syntax operator: a “binary truth operator”.

We all know the ternary operator:

value = if_this_is_true ? do_this : else_do_this;

Let’s look at an example of the ternary operator:

firstName = "John"
surname = "Doe"
age = 40
fullName = firstName + " " + surname + (age > 0 ? "(" + age + ")" : null)

The result is:

John Doe (40)

By introducing a binary truth operator, we can imply that the false result is null, and make the statement more compact to read and comprehend.

A possible syntax for the binary truth operator is ?=, for example:

if_this_is_true ?= do_this;

For example:

fullName = firstName + " " + surname + (age ?= "(" + age + ")")

The result is still:

John Doe (40)

A “binary false operator” is also possible, using the syntax ?<>:

age = 0
fullName = firstName + " " + surname + (age ?<> "(Unknown age)")

The result would be:

John Doe (Unknown age)

Note that the following operators, while related to the binary truth operator, would not give the same result:

  • Null coalescing operator: ??
    • Problem: Only works if an object is null, and the operator doesn’t operate on boolean values
  • Null propagation operator: ?.
    • Problem: Only works if an object is not null, and the operator doesn’t operate on boolean values
  • Short-circuit AND expression: if_this_is_true && do_this
    • Problem: In statically-typed languages, the expression results in a boolean value, and not an object, like the binary truth operator would
  • Short-circuit OR expression: !if_this_is_false || do_this
    • In statically-typed languages, the expression results in a boolean value, and not an object, like the binary truth operator would
  • If and only if: iff
    • The iff operator is a candidate, and could be adapted for the binary truth operator

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s