Continue to work out the extensible conditional idiom.
Chris Pressey
4 years ago
215 | 215 | The next step will be combining these conditionals so that we can build a test |
216 | 216 | that tests for multiple cases. |
217 | 217 | |
218 | We note that we only have conditionals for greater than and less then. | |
219 | We don't have a conditional test for equality. We can work around that. | |
220 | ||
221 | We also note that we can't nest conditionals, because the original value | |
222 | is not available inside the conditional -- it's "hiding" on the stack | |
223 | during that period. We can work around that too. | |
218 | We've already noted that the original value being tested against isn't available | |
219 | inside the conditional -- it's "hiding" on the stack during that period. | |
220 | ||
221 | This rules out being able to test multiple cases by nesting conditionals. | |
222 | So instead of nesting conditionals, we'll chain them one after another. | |
223 | ||
224 | But there are some implications for this, when it's combined with the fact | |
225 | that we don't have conditional tests for equality, only tests for greater than | |
226 | and less then. | |
227 | ||
228 | We'll revert to a more conventional syntax to try to devise how we can overcome | |
229 | those implications. | |
230 | ||
231 | Say the value to be tested is either 1, 3, or 5, and say we want to execute | |
232 | _a_ if it's 1, _b_ if it's 3, or _c_ if it's 5. We could try to write our chain | |
233 | like this: | |
234 | ||
235 | if value > 0: | |
236 | A | |
237 | endif | |
238 | if value > 2: | |
239 | B | |
240 | endif | |
241 | if value > 4: | |
242 | C | |
243 | endif | |
244 | ||
245 | The problem is that A, B, and C don't match up exactly to _a_, _b_, and _c_. | |
246 | Instead we have: | |
247 | ||
248 | * If value is 1 then A is executed. | |
249 | * If value is 3 then A is executed then B is executed. | |
250 | * If value is 5 then A then B then C is executed. | |
251 | ||
252 | But we can overcome this by defining what A, B, and C are, in terms of | |
253 | _a_, _b_, and _c_, and code that **undoes** _a_, _b_, and _c_. Using | |
254 | the notation _x_′ to mean code that undoes _x_, we can choose the following | |
255 | equations: | |
256 | ||
257 | * A = _a_ | |
258 | * B = _a_′ _b_ | |
259 | * C = _b_′ _c_ | |
260 | ||
261 | And we can restate the scenario like | |
262 | ||
263 | * If value is 1 then _a_ is executed. | |
264 | * If value is 3 then _a_ is executed then _a_′ _b_ is executed. | |
265 | * _a_ _a_′ _b_ = _b_, so in effect, only _b_ is executed. | |
266 | * If value is 5 then _a_ then _a_′ _b_ then _b_′ _c_ is executed. | |
267 | * _a_ _a_′ _b_ _b_′ _c_ = _c_, so in effect, only _c_ is executed. | |
268 | ||
269 | So the idiom works out (in theory: now I need to write some test cases here.) |