wtd
|
Posted: Fri Dec 10, 2021 7:31 pm Post subject: 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.
Python: | 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:
Python: | 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:
Python: | if A and B and C:
X
elif A and D:
Y
elif A:
Z
else:
W |
Let's look at another example:
Python: | 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".
Python: | 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?
Python: | 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.
Python: | if A or C and not (not B):
X
elif not B:
Y
else:
Z |
Or just:
Python: | if A or C and B:
X
elif not B:
Y
else:
Z |
|
|
|