Is this way of making a matrix possible in nim?
type
Matrix[W,H : static[int], T] = object
data : array[W*H,T]
width : int
height : int
proc initMatrix [W,H,T] (width : W, height: H) : Matrix[W,H,T] =
result.width = width
result.height = height
#result
Ideally I would rather do this
type
Matrix[W,H : static[int], T] = object
data : array[W*H,T]
width : W
height : H
var m : Matrix[5*6, int]
with width and height automatically initiated to the value passed to Matrix.
I know I can already do this.
type
Matrix[W,H : static[int], T] = object
data : array[W,array[H,T]]
I was just wondering if it was possible to represent the matrix internally as a single array and automatically store width and height in variables.
This works:
type
Matrix[width, height: static[int], T] = object
data: array[width * height, T]
var m : Matrix[5, 6, int]
echo m.width # 5
If you dislike using real names for the type parameters you can also just add getter procs for them:
type
Matrix[W, H: static[int], T] = object
data: array[W * H, T]
proc width(m: Matrix): int {.inline.} = m.W
var m : Matrix[5, 6, int]
echo m.width # 5
Actually, it works for ALL of type's parameters, including types:
type Matrix[W, H: static[int], T] = object
data: array[W * H, T]
var m : Matrix[3, 2, int]
m.data = [1,2, 3,4, 5,6]
proc `[]`(m: Matrix, x, y: int): m.T {.inline.} = # here m.T is a return type
assert x < m.W
assert y < m.H
m.data[x*m.H + y]
for i in 0 .. m.W-1:
for j in 0 .. m.H-1:
echo i, ",", j, " -> ", m[i,j] # here m.T == int
It would be nice if types had an automatic string representation when you call them with echo. Or at least a string representation when you repr them. I don't know if that's easily done with how the language is currently implemented.