Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
2x2 Matrix implementation in Slang
val class Mat2 Double⁴ {
// instead of Double⁴ we could also write ⟨a: Double, b: Double, c: Double, d: Double⟩
// then we'd have access to the elements with a, b, c, d instead of A₀, A₁, A₂, A₃
private alias A = data // `data` is alias for `this`, but with type ⟨Double,Double,Double,Double⟩ or Double⁴
def subscript(i: Int) = A// a vector Double⁴ already has a subscript method, we expose it
def +(M: Mat2) = Mat2[A + M] // expose Double⁴.+, with the right type (PS there's implicit Mat2 -> Double⁴)
def -(M: Mat2) = Mat2[A - M] // expose Double⁴.-, with the right type
def *(x: Double) = Mat2[A * ⟨x,x,x,x⟩]
def /(x: Double) = Mat2[A / ⟨x,x,x,x⟩]
def *(v: Vec2) = Vec2Vec2A₀, A₁⟩ ∙ v,
Vec2A₂, A₃⟩ ∙ v⟩
def *(M: Mat2) = Mat2A* M+ A* M₂, A* M+ A* M₃,
A* M+ A* M₂, A* M+ A* M₃⟩
def transpose() = Mat2A₀, A₂,
A₁, A₃⟩
alias …ᵀ = transpose // Capital superscript letters can be postfix operators
alias …´ = transpose // so can "accute accent"
def determinant() = A* A- A* A
alias || = determinant // closed operator
def inverse() = Mat2A₃, -A₁,
-A₂, A₀⟩ / |this|
// we can't write `|A|` instead of `|this|` because |…| is not defined for Double⁴
def superscript(i: Int) = if i == -1 then inverse() else throw Exception("superscript is only defined for -1");
// this should ideally be compile time e.g.
// def superscript(-1) = inverse or
// alias superscript(-1) = inverse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment