Skip to content

Built-in functions

Five functions are available in rule expressions. There are no others, and there is no way to define your own.

All of them operate on the absolute value of their numeric argument — the sign is discarded before any digit is inspected.

FunctionArityReturnsExample
digits(x)1Array of all digits, most significant firstdigits(123)[1, 2, 3]
highest_digit(x)1The most significant (leading) digithighest_digit(123)1
lowest_digit(x)1The least significant (trailing) digitlowest_digit(123)3
number_of_digits(x)1Count of digitsnumber_of_digits(123)3
digitAt(x, place)2The digit at a given decimal placedigitAt(123, 10)2

Argument counts are fixed. Calling a function with the wrong number of arguments is an error, and there are no zero-argument calls — digits() is invalid.

digits

Returns every digit as an array, most significant first. Its main purpose is to feed a quantifier.

digits(407)     -- [4, 0, 7]
digits(-407)    -- [4, 0, 7]   sign ignored
digits(5)       -- [5]
EVERY d IN digits(current_sum): d != 9

highest_digit

The leading digit.

highest_digit(4071)   -- 4
highest_digit(9)      -- 9
highest_digit(current_sum) != 9   -- result must not start with a 9

lowest_digit

The trailing digit — equivalent to the value modulo 10.

lowest_digit(4071)   -- 1
lowest_digit(40)     -- 0
lowest_digit(current_value) = 0   -- candidate must end in 0

number_of_digits

How many digits the value has.

number_of_digits(7)      -- 1
number_of_digits(4071)   -- 4
number_of_digits(current_sum) <= 2   -- result must stay within two digits

digitAt

Returns the digit of x at the decimal place named by place, computed as floor(abs(x) / place) % 10.

The second argument is a positional value (1 for ones, 10 for tens, 100 for hundreds), not an index.

digitAt(124, 1)     -- 4
digitAt(124, 10)    -- 2
digitAt(124, 100)   -- 1
digitAt(-124, 10)   -- 2      sign ignored
digitAt(124, 1000)  -- 0      no digit there

Unlike place / formula / digitBefore, digitAt does not care whether the value touches one decimal place or several — which makes it the right tool for reasoning about multi-place values:

digitAt(current_value, 10) != 9    -- tens digit of the candidate is not 9
digitAt(prev_sum, 1) = 0           -- running total has a clean ones digit

TIP

If you find yourself wanting formula or digitBefore on a step that might touch several places, digitAt is almost always what you actually want. See decimal places.

Shorthands

ALL_DIGITS(x) and SOME_DIGITS(x) look like functions but are syntax, not functions — they expand into quantifier expressions over digits(x) and can only appear in a comparison or membership test. See quantifiers.

See also

Reference and cookbook for mental-math rule and recipe authoring.