Had some code that was working fine under version 0.10.2., but now under version 0.11.2 I'm having some errors.
type
Matrix[T] = object
nrows: int # number of rows
ncols: int # number of columns
data: seq[T] # stores the entries of the matrix (a "flattened" matrix)
# entry i in flattened matrix
template `[]`[T](mat: Matrix[T], i: int): expr =
mat.data[i]
# assign value to entry i in flattened matrix
proc `[]=`[T](mat: var Matrix[T], i: int, val: T) =
mat.data[i] = val
# returns the index in the flattened matrix corresponding to row i, column j
proc index[T](mat: Matrix[T], r, c: int): int =
result = r * mat.ncols + c
# row i, column j in matrix
template `[]`[T](mat: var Matrix[T], r, c: int): expr =
mat[mat.index(r, c)]
# assign value row i, column j in matrix
proc `[]=`[T](mat: var Matrix[T], r, c: int, val: T) =
mat[mat.index(r, c)] = val
# allocate space for any existing matrix (will clear contents if they exist)
# sets to zeros
proc alloc[T](mat: var Matrix[T]) =
mat.data = newSeq[T](mat.nrows * mat.ncols)
# create new matrix
proc alloc[T](nrows, ncols: int): Matrix[T] =
result = Matrix[T]()
result.nrows = nrows
result.ncols = ncols
alloc(result)
# return a transposed matrix
proc transpose[T](mat: Matrix[T]): Matrix[T] =
result = alloc[T](mat.ncols, mat.nrows)
for i in 0 .. mat.nrows - 1:
for j in 0 .. mat.ncols - 1:
result[j, i] = mat[i, j] # problem seems to be here
# create a new 4x4 matrix
var mat = alloc[int](4, 4)
# works in version 0.10.2
# but does not work in version 0.11.2
var trans = mat.transpose()
Get the following error message. Seems to be happening when I call transpose.
test.nim(52, 16) Info: template/generic instantiation from here
test.nim(44, 25) Error: type mismatch: got (Matrix[system.int], int, int)
but expected one of:
test.[](mat: var Matrix[[].T], r: int, c: int)
test.[](mat: Matrix[[].T], i: int)
system.[](a: array[Idx, T], x: Slice[system.int])
system.[](s: string, x: Slice[system.int])
system.[](a: array[Idx, T], x: Slice[[].Idx])
system.[](s: seq[T], x: Slice[system.int])
However, it works when I use the body of the transpose function directly (instead of calling transpose).
# create a new 4x4 matrix
var mat = alloc[int](4, 4)
# this works in both versions
var trans = alloc[int](4, 4)
for i in 0 .. mat.nrows - 1:
for j in 0 .. mat.ncols - 1:
trans[j, i] = mat[i, j]
I'm using templates for the [] operator because I later go on to define +=, -= ect for matrices. See http://stackoverflow.com/questions/29461573/nim-operator-overloading
Get rid of the var here and it compiles again:
template `[]`[T](mat: Matrix[T], r, c: int): expr =
mat[mat.index(r, c)]