Types, promotion and JSON
Mixed arithmetic moves up a ladder, Integer → Rational → RationalInterval, and an exact result never moves down silently. Type guards, a JSON reviver and the TypePromotion helpers make the types easy to handle from outside.
The ladder
An operation on two values first raises the lower one to the higher level (an integer becomes , a rational becomes ), then computes there. One exception keeps results tidy: dividing integers gives an Integer when the division is exact. The R template goes one step further and returns any whole Rational result as an Integer.
import { Integer, Rational, RationalInterval, TypePromotion } from "@ratmath/core";
new Integer(2).add(new Rational(1, 3)); // Rational 7/3
new Rational(1, 3).multiply(new RationalInterval(1, 2)); // RationalInterval 1/3:2/3
new Integer(8).divide(new Integer(4)); // Integer 2
TypePromotion.getTypeLevel(new Rational(1, 2)); // 1
TypePromotion.promoteToCommonType(new Integer(1), new RationalInterval(2, 3)); // two intervals
Certified approximations sit beside the ladder: arithmetic with an Integer or Rational keeps a CertifiedApproximation, and an explicit operation with a RationalInterval gives an interval.
Type guards
isInteger, isRational, isRationalInterval, isRationalIntervalSet, isCertifiedApproximation, isFraction, isFractionInterval, isBaseSystem and isCoreNumber work even when two copies of the library are loaded (where instanceof can fail).
JSON
Every value has a tagged toJSON(), so JSON.stringify keeps the exact parts as strings, and reviveCoreValue turns them back into values:
import { R, reviveCoreValue } from "@ratmath/core";
const text = JSON.stringify({ x: R`1/3`, I: R`1:2` });
// {"x":{"$ratmath":"Rational","numerator":"1","denominator":"3"},"I":{…}}
const back = JSON.parse(text, reviveCoreValue);
back.x.toString(); // "1/3"
@ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.