Skip to content

Instantly share code, notes, and snippets.

@ToJans
Created December 17, 2014 15:27
Show Gist options
  • Save ToJans/48633bf5d6b71b81725a to your computer and use it in GitHub Desktop.
Save ToJans/48633bf5d6b71b81725a to your computer and use it in GitHub Desktop.
Better matrix - but it crashes the pretty printer in FSI
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 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
//works:
(Matrix.unit 3).elements;;
//crashes fsi pretty printer:
Matrix.unit 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment