tmatrixconcept.nim 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. discard """
  2. output: "0\n0\n0"
  3. nimout: '''
  4. R=3 C=3 TE=9 FF=14 FC=20 T=int
  5. R=3 C=3 T=int
  6. '''
  7. """
  8. import typetraits
  9. template ok(x) = assert x
  10. template no(x) = assert(not x)
  11. const C = 10
  12. type
  13. Matrix[Rows, Cols, TotalElements, FromFoo, FromConst: static[int]; T] = concept m, var mvar, type M
  14. M.M == Rows
  15. Cols == M.N
  16. M.T is T
  17. m[int, int] is T
  18. mvar[int, int] = T
  19. FromConst == C * 2
  20. # more complicated static param inference cases
  21. m.data is array[TotalElements, T]
  22. m.foo(array[0..FromFoo, type m[int, 10]])
  23. MyMatrix[M, K: static[int]; T] = object
  24. data: array[M*K, T]
  25. # adaptor for the concept's non-matching expectations
  26. template N(M: type MyMatrix): untyped = M.K
  27. proc `[]`(m: MyMatrix; r, c: int): m.T =
  28. m.data[r * m.K + c]
  29. proc `[]=`(m: var MyMatrix; r, c: int, v: m.T) =
  30. m.data[r * m.K + c] = v
  31. proc foo(x: MyMatrix, arr: array[15, x.T]) = discard
  32. proc genericMatrixProc[R, C, TE, FF, FC, T](m: Matrix[R, C, TE, FF, FC, T]): T =
  33. static:
  34. echo "R=", R, " C=", C, " TE=", TE, " FF=", FF, " FC=", FC, " T=", T.name
  35. m[0, 0]
  36. proc implicitMatrixProc(m: Matrix): m.T =
  37. static:
  38. echo "R=", m.Rows,
  39. " C=", m.Cols,
  40. # XXX: fix these
  41. #" TE=", m.TotalElements,
  42. #" FF=", m.FromFoo,
  43. #" FC=", m.FromConst,
  44. " T=", m.T.name
  45. m[0, 0]
  46. proc myMatrixProc(x: MyMatrix): MyMatrix.T = genericMatrixProc(x)
  47. var x: MyMatrix[3, 3, int]
  48. static:
  49. # ok x is Matrix
  50. ok x is Matrix[3, 3, 9, 14, 20, int]
  51. no x is Matrix[3, 3, 8, 15, 20, int]
  52. no x is Matrix[3, 3, 9, 10, 20, int]
  53. no x is Matrix[3, 3, 9, 15, 21, int]
  54. no x is Matrix[3, 3, 9, 15, 20, float]
  55. no x is Matrix[4, 3, 9, 15, 20, int]
  56. no x is Matrix[3, 4, 9, 15, 20, int]
  57. echo x.myMatrixProc
  58. echo x.genericMatrixProc
  59. echo x.implicitMatrixProc