Created
December 30, 2014 12:02
-
-
Save ToJans/99423537e7c97606c5e7 to your computer and use it in GitHub Desktop.
I love the sheer elegance of F#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Math | |
type Matrix = | |
| Matrix of decimal [,] | |
static member create l = Matrix l | |
member this.elements = | |
match this with | |
| Matrix l -> l | |
member this.rowcount = this.elements |> Array2D.length1 | |
member this.columncount = this.elements |> Array2D.length2 | |
member this.Item | |
with get (r, c) = this.elements.[r, c] | |
and set (r, c) value = this.elements.[r, c] <- value | |
static member zero n m = Array2D.create n m 0M |> Matrix.create | |
static member vector x y z = [[x];[y];[z];[1M]] |> array2D |> Matrix.create | |
static member unit n = | |
let result = Matrix.zero n n | |
[ for i in 0..n - 1 -> result.[i, i] <- 1M ] | |
|> ignore | |
result | |
static member (+) (l : Matrix, r : Matrix) = | |
let result = Matrix.zero l.rowcount l.columncount | |
[ for i in 0..(l.rowcount - 1) -> | |
[ for j in 0..(r.columncount - 1) -> result.[i, j] <- l.[i, j] + r.[i, j] ] ] | |
|> ignore | |
result | |
static member (*) (l : Matrix, r : Matrix) = | |
let result = Matrix.zero l.rowcount r.columncount | |
[ for i in 0..(l.rowcount - 1) -> | |
[ for j in 0..(r.columncount - 1) -> | |
[ for k in 0..(l.columncount - 1) -> result.[i, j] <- result.[i, j] + l.[i, k] * r.[k, j] ] ] ] | |
|> ignore | |
result | |
static member rotationAroundX (theta:decimal) = | |
let sin = theta |> double |> System.Math.Sin |> decimal | |
let cos = theta |> double |> System.Math.Cos |> decimal | |
[ [ 1M; 0M; 0M; 0M ] | |
[ 0M; cos;-sin; 0M ] | |
[ 0M; sin; cos; 0M ] | |
[ 0M; 0M; 0M; 1M ] ] | |
|> array2D | |
|> Matrix.create | |
static member rotationAroundY (theta:decimal) = | |
let sin = theta |> double |> System.Math.Sin |> decimal | |
let cos = theta |> double |> System.Math.Cos |> decimal | |
[ [ cos ;0M ;sin ; 0M ] | |
[ 0M; 1M; 0M; 0M ] | |
[ -sin; 0M; cos; 0M ] | |
[ 0M; 0M; 0M; 1M ] ] | |
|> array2D | |
|> Matrix.create | |
static member rotationAroundZ (theta:decimal) = | |
let sin = theta |> double |> System.Math.Sin |> decimal | |
let cos = theta |> double |> System.Math.Cos |> decimal | |
[ [ cos; -sin; 0M; 0M ] | |
[ sin; cos;0M ; 0M ] | |
[ 0M; 0M; 1M; 0M ] | |
[ 0M; 0M; 0M; 1M ] ] | |
|> array2D | |
|> Matrix.create | |
static member translation x y z = | |
[ [ 1M;0M;0M;x] | |
[ 0M;1M;0M;y] | |
[ 0M;0M;1M;z] | |
[ 0M;0M;0M;1M] ] | |
|> array2D | |
|> Matrix.create |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment