-----------------------------------
wtd
Fri Dec 10, 2021 7:31 pm
Algebra of conditionals
-----------------------------------
Let's examine the algebra of conditionals. We'll use Python syntax with symbols because it's pretty. We'll also assume for now that we don't have any statements outside nested conditionals.
A sample nested conditional.
if A:
if B:
if C:
X
elif D:
Y
else:
Z
else:
W
How can we flatten this?
We know we have to "and" the previous level with any nested conditions.
So, as a first step:
if A:
if B and C:
X
elif D:
Y
else:
Z
else:
W
But we can go right down to a single level with ease:
if A and B and C:
X
elif A and D:
Y
elif A:
Z
else:
W
Let's look at another example:
if A:
X
elif B:
Y
elif C:
Y
elif D:
Z
else:
Z
When two consecutive branches of a conditional yield the same result, we can "or" them together. If one of the consecutive conditions that leads to the same result is "else", we can just use "else".
if A:
X
elif B or C:
Y
else:
Z
But what happens if they're not consecutive. What if other branches lie in between?
if A:
X
elif not B:
Y
elif C:
X
else:
Z
We can still "or" those together, but we have to "and" the negation of each intermediate condition.
if A or C and not (not B):
X
elif not B:
Y
else:
Z
Or just:
if A or C and B:
X
elif not B:
Y
else:
Z