Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Villane
Created September 22, 2012 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Villane/3767858 to your computer and use it in GitHub Desktop.
Save Villane/3767858 to your computer and use it in GitHub Desktop.
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) = Vec2⟨Vec2⟨A₀, A₁⟩ ∙ v,
Vec2⟨A₂, A₃⟩ ∙ v⟩
def *(M: Mat2) = Mat2⟨A₀ * M₀ + A₁ * M₂, A₀ * M₁ + A₁ * M₃,
A₂ * M₀ + A₃ * M₂, A₂ * M₁ + A₃ * M₃⟩
def transpose() = Mat2⟨A₀, 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() = Mat2⟨ A₃, -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