immut design
Design goal
immut gives linear algebra with value semantics: a matrix or vector, once
built, never changes, and every operation returns a new value. Programs can
then keep old versions, share values freely between components and reason
about code by substitution. The package also aims to compute exactly whenever
the scalar type allows it, so that integer and big-integer matrices get exact
determinants and powers rather than floating-point approximations.
Constraints
- No public operation may modify an existing value, and no hidden mutable state may be observable (no caches inside values).
- Element types are generic, bounded by the
luna-generictraits; exact algorithms may use only ring operations and exact division, never a tolerance. - The package may depend only on
error,internal,luna-genericand the core persistent vector, not on the experimentalalgebraandcontainerlayers. - Names, argument order and checked/unchecked conventions follow
mutablewherever both packages offer an operation.
Design decisions
Persistent vector storage
Options. (a) A copied Array per update, (b) a persistent trie,
(c) functions only. Decision. (b) for Matrix and Vector, (c) offered
separately as MatrixFn. Why. A copied array makes set cost ; a
trie makes it while keeping reads fast and the value
immutable. Functions are useful for structured or symbolic matrices, but their
read cost depends on the history of operations, so they are a separate type
whose cost model is stated rather than hidden.
Exact algorithms where the scalar allows them
determinant requires the open DeterminantScalar strategy trait, which
extends Compare + Num + Div. Int, Int16, Int64 and BigInt select
Bareiss; Float and Double select PivotedLU. The operation bounds alone
cannot distinguish exact integer division from rounded floating-point
division, so callers must supply this strategy explicitly for custom types.
Bareiss preserves exact results over integral domains when division is exact
on divisible values and intermediate arithmetic does not overflow. LU uses
field-like division and is approximate on floating-point scalars. This local
algorithm choice does not change the upstream algebraic laws or bounds.
Checked short names, unchecked explicit names
matmul, trace, determinant and pow return Result; their
unchecked_* partners abort. The operators +, -, * cannot return
Result and abort on mismatched shapes. The checked form validates and then
calls the unchecked one, which gives the law
checked(x) == Ok(unchecked(x)) on the domain by construction.
Alignment with mutable
Names, argument order and checked/unchecked conventions match @mutable
wherever both packages offer an operation, and the
consistency tests compare their results. Differences are
deliberate and listed here:
| Operation | immut | mutable |
|---|---|---|
| identity | Matrix::identity(n) | top-level identity(n) |
| update | set returns a new matrix | set writes in place |
m[r][c] = x | not available | available |
| determinant | scalar strategy: Bareiss for integers, LU for floats without tolerance | LU with tolerance, floating point |
| decompositions, inverse, statistics | not available | available |
dot | not on Vector (see ImmutableDenseVector::dot) | Vector::dot |
No subtraction on Vector
Vector implements Add, Mul and Neg but not Sub; u - v is written
u + -v. This is an asymmetry inherited from earlier releases, not a
mathematical statement. The backends/default wrappers provide -.
Mathematical background
Value semantics and referential transparency
An expression is referentially transparent when it can be replaced by its value without changing the program. With immutable matrices,
so any expression mentioning means the same thing on either side of the update. Algebraic identities can then be used directly as program transformations: and denote the same value for exact scalars, and an intermediate result may be reused or recomputed at will.
Persistent storage
Entries live in row-major order in moonbitlang/core/immut/vector, a
persistent vector implemented as a trie with branching factor 32. Replacing
one element copies the path from the root to the leaf, one node of at most 32
slots per level, and shares every other node, so
and the old matrix stays valid. Reads also cost ; since
and , at most seven levels cover every size an
Int index can reach. Whole-matrix operations rebuild the trie in .
Matrix powers by repeated squaring
For a square matrix over a semiring, write in binary. Then
The rearrangement of the product is valid because matrix multiplication is
associative over any semiring (see the algebra design);
commutativity of the scalars is not needed, since all factors are powers of
the same and powers of one element of an associative ring commute with
each other. pow keeps a state , an exponent and a base with the
invariant
initially . If is odd, and ; if is even, . So the step preserves the invariant, and strictly decreases. The loop stops at with , or at (only for ) with . It squares times and multiplies into once per 1-bit of , so it performs
matrix products instead of ; the first product into is by . Over matrices that is scalar operations.
For fixed-width integers the result is exact in
( for Int, for Int64) even when it overflows, because
wrapping arithmetic is the ring arithmetic of that quotient, and the
argument above uses only the semiring laws.
Fraction-free determinant
Gaussian elimination over a field computes as the product of pivots but divides at every step, which leaves the integers. Bareiss’ algorithm keeps every intermediate value an integer.11 E. H. Bareiss, “Sylvester’s identity and multistep integer-preserving Gaussian elimination”, Mathematics of Computation 22 (1968), 565–578. Let , , and for and
Every value is a minor. Let be the leading block of (), and for let be the bordered minor formed by rows and columns :
We show (Sylvester’s determinant identity). It is enough to prove the identity for matrices whose entries are independent indeterminates, over their field of fractions, where every is invertible; both sides are polynomials with integer coefficients, so it then holds in every commutative ring. Block elimination gives
where is the Schur complement of in . The quotient property of Schur complements says that one more step of block elimination is one step of ordinary elimination on :
Substituting,
because . This is the recurrence, so by induction on the algorithm computes exactly the bordered minors. Two consequences follow. First, the division in the recurrence is exact: the quotient is a minor of , so over an integral domain such as the numerator is a multiple of the previous pivot and the quotient is unique. Second, the last value is the full determinant, . The attachment below gives the same proof in more detail.
Pivoting. The code chooses as pivot the candidate , ,
of largest abs. Row of depends only on row of and on
rows , so exchanging two rows with indices before step
is the same as running the algorithm on with those rows exchanged,
which multiplies the final result by ; the code tracks the sign. The
previous pivot, the divisor, sits in row and is not moved.
A zero pivot column. If every candidate , , is zero, the code returns at once. This is correct: the previous pivot is non-zero (otherwise the code would have stopped earlier), so for all . Column of the Schur complement is zero, so and
Size of intermediate values. Every intermediate value is a minor of , so Hadamard’s inequality bounds them:
over the rows involved (restricted to the chosen columns, which only
decreases the norms). Let
over all rows; every such
product is at most . The numerator of the recurrence is a difference of two
products of two minors, so every product is at most and the numerator at
most . This gives an overflow criterion for Int: if , no
intermediate value overflows and the result is exact (for Int64,
). Once a numerator wraps, the exact division no longer holds,
so the result is wrong rather than correct modulo . For BigInt the
algorithm is always exact; it uses arithmetic operations on integers
of at most bits.
Floating point. Bareiss forms products of minors before dividing. For
plus a superdiagonal of ones, triangularity gives
. Bareiss intermediates are leading minors,
so the products grow like and overflow binary64 even though
the final determinant is representable. Float and Double now select LU
with partial pivoting for every size, avoiding this source of minor growth.
Pivoted LU determinant
The kernel copies the matrix, chooses the largest absolute entry in the remaining pivot column, exchanges rows, and subtracts times the pivot row from each later row. Row addition preserves the determinant over a commutative field; each row exchange changes its sign. After elimination the matrix is upper triangular, so in exact arithmetic, where counts swaps. This argument requires field-like division and does not apply to truncating integer division; those scalars retain Bareiss.
There is no absolute or relative zero threshold. An exactly zero selected pivot returns zero; the method does not classify numerical rank. The empty pivot product is one. Inputs are immutable because all elimination occurs on a private array. Floating-point rounding and elimination growth remain. Finite pivots are accumulated with a normalized mantissa and a binary exponent, so their product does not overflow or underflow merely because intermediate pivots have opposing scales; a final result outside the scalar range still overflows or underflows. NaN and infinity follow scalar arithmetic without a checked error. Tests of known triangular and dense factorizations are finite evidence, not a universal accuracy proof.
Small sizes. For the package uses closed formulas instead. For it is the cofactor expansion along the first row; for it is Laplace’s expansion along the first two rows,
six products of complementary minors. These formulas use only ring
operations, so they are exact over every commutative ring and need no division
at all. Over Int they are therefore exact modulo even when an
intermediate value wraps, and the result is the true determinant whenever
.
Lazy matrices
A MatrixFn is a pair with .
Operations compose functions: is , transpose is
, and the product is
evaluated on demand. Nothing is cached, so reading one entry of a product costs the inner dimension times the cost of an entry of each factor. For a left-nested chain of products of matrices the cost of one entry satisfies , so . Repeated squaring is worse, because both factors of are the same unevaluated : , so one entry of costs reads of , that is for . Lazy powers are cheap to build and expensive to read.
Correctness and invariants
- Immutability. No public operation modifies an existing
Matrix,VectororMatrixFn;setandswap_*return new values. - Shape invariants. and the backing vector has exactly elements; constructors reject anything else by aborting.
- Bounds. Every public read checks row and column separately, so a column index that would land inside the next row is rejected rather than read.
- Exactness. Over
BigInt,determinantandpoware exact; overIntandInt64,powis exact modulo , anddeterminantis exact unless an intermediate product overflows () or the determinant itself does not fit (; see the Hadamard bound). - Empty cases. and of the matrix are and ; ; a product with inner dimension is the zero matrix.
- Complexity.
set: ;map,+,transpose,swap_*: ;matmul: multiply-adds;determinant: ;pow: at most products, .
Alternatives rejected
- LU for every scalar. Truncating integer division would invalidate elimination. Explicit scalar strategies preserve Bareiss for exact domains and use LU for floating point without introducing a tolerance policy.
- A runtime backend selector inside
Matrix. Backends are separate types (backends/default);Matrixhas one representation. - Caching in
MatrixFn. It would make a pure value hold mutable state and change the cost model silently. Materialize withMatrix::makeinstead.
Boundaries
immut does not provide in-place updates, views, inverses, decompositions,
eigenvalues, statistics or tolerance-based predicates; those belong to
mutable. It does not detect integer overflow, does not offer a
checked MatrixFn API, and does not implement the algebra
traits itself (the wrappers in backends/default do).
Footnotes
-
E. H. Bareiss, “Sylvester’s identity and multistep integer-preserving Gaussian elimination”, Mathematics of Computation 22 (1968), 565–578. ↩