No Ternary, No Problem
July 18, 2016 by Chris Johnson. Filed under programming languages, public.
While waiting around in a Peruvian airport, a friend I met at a conference was playing a boolean logic game I’ve been working on. On one level he wanted to use a ternary operator to model a shape that behaved differently depending on which half of the 10-by-10 game board you were on. He wanted expression a
for the left half and b
for the right half:
x < 5 ? a : b
I told him I didn’t support the ternary operator, but that I thought the ternary operator could be simulated using the regular logical operators, for boolean expressions at least. When the condition c
is true, we want the value of a
. When c
is false, we want the value of b
. This leads to the following truth table:
a
|
b
|
c
|
c ? a : b
|
0
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
0
|
1
|
0
|
1
|
0
|
1
|
1
|
0
|
1
|
0
|
0
|
0
|
1
|
0
|
1
|
1
|
1
|
1
|
0
|
1
|
1
|
1
|
1
|
1
|
Sitting there at Puerta 8, I suggested an alternative expression. But I was afraid to commit to it without proving its equivalency on paper. I’ve now had the time to do so and am happy to announce that an equivalent expression using just AND, OR, and NOT does indeed exist:
a
|
b
|
c
|
!c
|
c && a
|
!c && b
|
c && a || !c && b
|
0
|
0
|
0
|
1
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
1
|
0
|
1
|
1
|
0
|
1
|
1
|
0
|
0
|
0
|
0
|
1
|
0
|
0
|
1
|
0
|
0
|
0
|
1
|
0
|
1
|
0
|
1
|
0
|
1
|
1
|
1
|
0
|
1
|
0
|
1
|
1
|
1
|
1
|
1
|
0
|
1
|
0
|
1
|
So c ? a : b
is the same as c && a || !c && b
, when a
and b
are booleans. This seems trivial in retrospect. In fact, what we’ve just designed is a 2-to-1 multiplexer. Ahh, well. Progress is made via trivial advances.
The best news is that I don’t need to implement the ternary operator in my game!