The R template
R is a tagged template that reads exact arithmetic written as text: R`1/3 + 1/6` is the Rational . Literals are spelled as in RiX and RatCalc, so text moves between them unchanged.
Literals
| form | example | value |
|---|---|---|
integer, _ groups digits | 1_000 | 1000 |
| fraction, mixed number | 3/4, 1..2/3 | , |
decimal, repeating #, digit runs | .5, 0.#3, 0.{3~4}1 | , , |
| uncertainty | 1.2[3:6], 1.5[+-0.01] | , |
| interval | 2:5 | |
| continued fraction | 3.~7~15~1, ~-1.~2 | , |
| radix shift | 1_^3, 2.5_^-2, 0t1_^10 | , , |
| base prefix | 0xff.8, 0b0.#01, 0z[7]66 | , , |
| certified | 1.5?, 3.~7? | a CertifiedApproximation |
A radix shift belongs to the literal before it: 1/2_^3 is . A leading - is negation, so -3.~7 is ; write ~-3.~7 for a negative first term (see continued fractions). There is no E notation (use _^). The shift is by the literal's own base, with the exponent written in that base: 1_^3 is , 0t1_^10 is (ternary 10 is 3), 0xff_^1 is , and under R.base(16) 1_^a is .
Operators
From loosest to tightest: a spaced :; + -; * /; unary -; ^ and ** (the same power, right-associative, integer exponents); postfix ! and !!. So -2^2 is and 2^3^2 is . A whole Rational result comes back as an Integer: R`0.#3 * 3` is the Integer 1.
Spacing decides what a colon holds
A colon written without spaces binds to the unspaced text around it before any spaced operator applies; a colon with spaces binds loosest. This is how RiX reads it too:
| text | reads as | value |
|---|---|---|
| 1:2 + 3:4 | (1:2) + (3:4) | 4:6 |
| 1:2 * 2 | (1:2) * 2 | 2:4 |
| 1:2*2 | 1:(2*2) | 1:4 |
| 1:n+1 | 1:(n+1) | (with n interpolated) |
| 1 : 2 + 3 | 1:(2 + 3) | 1:5 |
| 1/2:3/4 | (1/2):(3/4) | 1/2:3/4 |
With one unspaced colon, unspaced arithmetic stays on its endpoint. Three or more values joined by colons are a betweenness chain and give a boolean.
Interpolation is exact
${value} inserts a value as a value, not as text. It accepts Core numbers, bigints, safe integers and strings (read as literals). A float like 0.1 throws a TypeError: it is already inexact, and Core will not guess which decimal you meant. Pass the string "0.1" instead.
import { R, Rational } from "@ratmath/core";
const third = new Rational(1, 3);
R`(${third} + 1) ^ 2`; // Rational 16/9
R`${"0.1"} + ${"0.2"}`; // Rational 3/10
R`${2n ** 70n} / 3`; // a big Rational
R.base(16)`ff.8 / 3`; // Rational 511/6, literals read in base 16
R.base(2)`101 + 0x10`; // 21: prefixed literals keep their own base
Errors
SyntaxError for text R cannot read (unknown characters, unbalanced parentheses, an unknown base prefix); TypeError for a non-integer exponent, ! of a non-integer, an interval whose end is an interval, a chain used in arithmetic, or an inexact interpolation. Division by zero comes from the number classes.
@ratmath/core in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.