Mindshift: Part 17

Passing Through Zero (and Surviving!)

In the previous blog, we started preparing for the use of abstract functions that can represent signed integers. We did this by combining a Boolean (to represent the sign) and a quantity function (to represent the magnitude) together as a PAIR.

But no sooner had we done that, than we discovered our functions for finding the SUCCessor and PREDecessor of a quantity function are now broken.

Previously, our ability to move up or down the number line stopped at zero. Now we must be able to pass in either direction through ZERO without our PREDecessor and SUCCessor functions generating nonsense.

We are now faced with several issues:

  1. Irrespective of a NUMBER's absolute value:
    1. The SUCCessor function must always move a number towards the right on the number line.
    2. The PREDecessor function must always move a number towards the left on the number line.
  2. Two special cases must be handled:
    1. PRED(0) must return -1
    2. SUCC(-1) must return 0

So to handle these conditions, we will need a set of functions to perform various tests such as whether a NUMBER's absolute value is 0 or -1.

Currently, our existing SUCCessor and PREDecessor functions operate on unsigned quantity functions, and these will still be needed, but now we must make various tests before calling them.

The first thing we can do is rename the existing SUCCessor and PREDecessor functions to SUCC_MAGNITUDE and PRED_MAGNITUDE. This is to indicate that these functions operate on abstract quantity functions rather than NUMBERs.

Remember that the PRED function (now renamed to PRED_MAGNITUDE) works out the predecessor of a quantity function by counting upwards from ZERO in PAIRs of (n-1, n). The predecessor of any number n is then the first quantity function in such a PAIR.

We must also define all the necessary low-level functions that will help us here:

Now that our existing SUCC and PRED functions have been renamed and we have all the necessary low-level functions, we can define a new SUCCessor function as follows:

The PRED function is defined in a similar manner:

Good, so now we need to test these extended functions.

In the past, we have tested calculations involving abstract quantity functions by passing the result to function to_integer. This function reifies an abstract quantity function into a JavaScript native type (an integer).

The problem now is that since we have started working with functions that represent signed integers, our to_integer function will need to be adjusted to handle NUMBERs instead of abstract quantity functions.

This is done as follows:

Now we can finally start testing:

Good, that works nicely!

Now we are in a position to extend the arithmetic functions of ADD, SUBTRACT and MULTIPLY to handle these abstract signed integer functions.

Chris W


All source code from the Mindshift blog series can be found on GitHub