taliased_reassign.nim 971 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. discard """
  2. matrix: "--mm:orc"
  3. """
  4. # bug #20993
  5. type
  6. Dual[int] = object # must be generic (even if fully specified)
  7. p: int
  8. proc D(p: int): Dual[int] = Dual[int](p: p)
  9. proc `+`(x: Dual[int], y: Dual[int]): Dual[int] = D(x.p + y.p)
  10. type
  11. Tensor[T] = object
  12. buf: seq[T]
  13. proc newTensor*[T](s: int): Tensor[T] = Tensor[T](buf: newSeq[T](s))
  14. proc `[]`*[T](t: Tensor[T], idx: int): T = t.buf[idx]
  15. proc `[]=`*[T](t: var Tensor[T], idx: int, val: T) = t.buf[idx] = val
  16. proc `+.`[T](t1, t2: Tensor[T]): Tensor[T] =
  17. let n = t1.buf.len
  18. result = newTensor[T](n)
  19. for i in 0 ..< n:
  20. result[i] = t1[i] + t2[i]
  21. proc toTensor*[T](a: sink seq[T]): Tensor[T] =
  22. ## This breaks it: Using `T` instead makes it work
  23. type U = typeof(a[0])
  24. var t: Tensor[U] # Tensor[T] works
  25. t.buf = a
  26. result = t
  27. proc loss() =
  28. var B = toTensor(@[D(123)])
  29. let a = toTensor(@[D(-10)])
  30. B = B +. a
  31. doAssert B[0].p == 113, "I want to be 113, but I am " & $B[0].p
  32. loss()