Skip to content

Instantly share code, notes, and snippets.

@zah
Created January 3, 2015 23:57
Show Gist options
  • Save zah/7984af4a7ba52108621b to your computer and use it in GitHub Desktop.
Save zah/7984af4a7ba52108621b to your computer and use it in GitHub Desktop.
type
DenseMatrixLayout* {.pure.} = enum
ColumnMajor,
RowMajor
DenseMatrix*[R, C: static[int], T; L: static[DenseMatrixLayout]] = object
elements: array[R*C, T]
Matrix4 = DenseMatrix[4, 4, float, DenseMatrixLayout.ColumnMajor]
proc makeDense[T](N, M: static[int], L: static[DenseMatrixLayout], data: array[N*M, T]): DenseMatrix[N, M, T, L] =
result.elements = data
var m = makeDense(2, 2, DenseMatrixLayout.ColumnMajor, [1.0, 2.0, 3.0, 4.0])
when false:
proc new(x: type DenseMatrix, data: array[x.N * x.M, x.T]): DenseMatrix =
result.elements = data
var m = Matrix4.new [1.0, 2.0, 3.0, 4.0]
when false:
converter fromArray[M, N, T, L](data: array[M*N, T]): Matrix[M, N, T, L] =
result.elements = data
var m = Matrix4 [1.0, 2.0, 3.0, 4.0]
@zah
Copy link
Author

zah commented Jan 4, 2015

Another way to do it:

type
  Layout = enum
    RowMajor
    ColMajor

  Matrix[R, C: static[int]; T; L: static[Layout]] = object
    elements: array[R*C, T]

proc `()`[N,T](data: array[N, T], R, C: static[int], L: static[Layout]): Matrix[R, C, T, L] =
  when R*C != high(data) + 1: {.error: "The specified Matrix size doesn't match the array size".}
  result.elements = data

var m = [1,2,3,3](2, 2, RowMajor)

@gmpreussner
Copy link

I think this would be ideal:

type
  Matrix = DenseMatrix[3, 3, int, RowMajor]
  TriMatrix = TriangularMatrix[3, int, Lower]

var m1: Matrix = [1, 2, 3,
                  4, 5, 6,
                  7, 8, 9]

var m2: TriMatrix = [1,
                     2, 3,
                     4, 5, 6]

@zah
Copy link
Author

zah commented Jan 4, 2015

In general, it's preferable to always rely on type inference. If you keep all type mentions on the right-hand side, the code is fully compatible for use in calls and other "anonymous" positions in the grammar:

transform(point, Matrix2 [0, 1,
                          1, 0])

var m1 = Matrix [1, 2, ...]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment