vec.nim 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import
  2. macros,
  3. "../config"
  4. type
  5. TV2*[T:SomeNumber=TR] = array[0..1, T]
  6. TV3*[T:SomeNumber=TR] = array[0..2, T]
  7. TV4*[T:SomeNumber=TR] = array[0..3, T]
  8. TVT*[T:SomeNumber=TR] = TV2|TV3|TV4
  9. #TV2* = array[0..1, TR]
  10. #TV3* = array[0..2, TR]
  11. #TV4* = array[0..3, TR]
  12. # TODO: Change to TVT when compiler issue is resolved.
  13. proc `$`*[T](o: TV2[T]): string =
  14. result = "("
  15. for i in 0 ..< o.len:
  16. result &= $o[0]
  17. if i != o.len - 1:
  18. result &= ", "
  19. result & ")"
  20. proc newV2T*[T](x, y: T=0): TV2[T] =
  21. [x, y]
  22. proc newV2*(x, y: TR=0.0): TV2[TR] =
  23. [x, y]
  24. proc newV2xy*(xy: TR): TV2[TR] =
  25. [xy, xy]
  26. proc x*[T](o: TV2[T]): T =
  27. o[0]
  28. proc y*[T](o: TV2[T]): T =
  29. o[1]
  30. proc `*`*(lhs: TV2[TR], rhs: TV2[TR]): TV2[TR] =
  31. [(lhs.x * rhs.x).TR, (lhs.y * rhs.y).TR]
  32. proc `+`*(lhs: TV2[TR], rhs: TV2[TR]): TV2[TR] =
  33. [(lhs.x + rhs.x).TR, (lhs.y + rhs.y).TR]
  34. #proc dotProduct[T](a: TVT[T], b: TVT[T]): T =
  35. # for i in 0 .. a.len - 1:
  36. # result += a[i] * b[i]
  37. proc dot[T](a, b: TV2[T]): T =
  38. for i in 0 ..< a.len:
  39. result += a[i] * b[i]
  40. assert dot(newV2(), newV2()) == 0.0
  41. assert dot(newV2(2, 3), newV2(6, 7)) == 33.0
  42. assert dot([2.0, 3.0], [6.0, 7.0]) == 33.0