Failure contexts and the Floor() function

You can factor an integer into digits with integer division and the integer Mod function. When using integer division, you get a rational number (type rational), which you must use the rational Floor function to get an integer out of.

Here’s a function that returns an array of digits (ordered from most significant to least significant):

GetDigits(I:int)<computes>:[]int=
    if(I=0) then array{}
    else if(Digit := Mod[I, 10]; Residual := Floor(I / 10)):
        GetDigits(Residual) + array{Digit}
    else:
        # This should never be reached because Mod and integer division only fail when the
        # divisor is zero. Nevertheless, the compiler doesn't know that, so this else is needed.
        Err("unreachable")

For example, GetDigits(12345)=array{1, 2, 3, 4, 5}.

4 Likes