tmetatypematrix.nim 1016 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. discard """
  2. output: "1.01.01.0"
  3. """
  4. # Test overloading of [] with multiple indices
  5. type
  6. TMatrix* = object
  7. data: seq[float]
  8. fWidth, fHeight: int
  9. template `|`(x, y: int): untyped = y * m.fWidth + x
  10. proc createMatrix*(width, height: int): TMatrix =
  11. result.fWidth = width
  12. result.fHeight = height
  13. newSeq(result.data, width*height)
  14. proc width*(m: TMatrix): int {.inline.} = return m.fWidth
  15. proc height*(m: TMatrix): int {.inline.} = return m.fHeight
  16. proc `[]`*(m: TMatrix, x, y: int): float {.inline.} =
  17. result = m.data[x|y]
  18. proc `[]=`*(m: var TMatrix, x, y: int, val: float) {.inline.} =
  19. m.data[x|y] = val
  20. proc `-|`*(m: TMatrix): TMatrix =
  21. ## transposes a matrix
  22. result = createMatrix(m.height, m.width)
  23. for x in 0..m.width-1:
  24. for y in 0..m.height-1: result[y,x] = m[x,y]
  25. #m.row(0, 2) # select row
  26. #m.col(0, 89) # select column
  27. const
  28. w = 3
  29. h = 20
  30. var m = createMatrix(w, h)
  31. for i in 0..w-1:
  32. m[i, i] = 1.0
  33. for i in 0..w-1:
  34. stdout.write(m[i,i]) #OUT 111
  35. stdout.write "\n"