Phantom-algebra — a strongly-typed tensor library à la GLSL

Phantom-algebra is a pure OCaml library implementing strongly-typed small tensors with dimensions 0 ≤ 4, rank ≤ 2, and limited to square matrices.

It makes it possible to manipulate vector and matrix expressions with an uniform notation while still catching non-sensical operations at compile time

Tutorial

For instance, this extract is valid

    open Phantom_algebra.Core
    let v = vec3 1. 2. 3.
    let w = vec3 3. 2. 1.
    let u = scalar 2. + cross (v + w) (v - w)
    let rot = rotation u v 1.
    let r = w + rot * v

but adding a vector to a matrix is not, and yields a type error:

v + rot

Type errors tend to be quite long to say the least, but individual type of scalars, vectors and matrices are much simpler. However, the size of the type of higher order function may increase exponentially due to the exotic type construction used internally.

Phantom-algebra is inspired by GLSL conventions:

    let v = vec2 0. 1. + scalar 1. (* = (1. 2.) *)
  norm2 v = (v|*|v)
   let v = Math.cos (vec2 1. 2.)
    let id = eye d2
 let rxy t = rotation (vec3 1. 0. 0.) (vec3 0. 1. 0.) t
 let id = diag (vec3 1. 1. 1.)
 ;; exp (mat2 (0. 1.) (0. -1) ) = rxy 1.
   let v = scalar 0. |+| vec2 1. 0. |+| scalar 1.
let w = vec4' (scalar 1.)