Merge pull request #9826 from cooldome/destructor_move_them_all

destructors: sink`em all
This commit is contained in:
Andreas Rumpf 2018-12-10 15:46:19 +01:00 • committed by GitHub
commit cd81f368d1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 179 additions and 71 deletions

View file

@ -52,6 +52,8 @@ proc matrix*(m, n: int, s: float): Matrix =
for i in 0 ..< m * n:
result.data[i] = s
proc len(m: Matrix): int = m.n * m.m
proc `[]`*(m: Matrix, i, j: int): float {.inline.} =
## Get a single element.
m.data[i * m.n + j]
@ -67,24 +69,26 @@ proc `[]=`*(m: var Matrix, i, j: int, s: float) =
proc `-`*(m: sink Matrix): Matrix =
## Unary minus
result = m
for i in 0 ..< m.m:
for j in 0 ..< m.n:
result[i, j] = -m[i, j]
for i in 0 ..< result.m:
for j in 0 ..< result.n:
result[i, j] = -result[i, j]
proc `+`*(a: sink Matrix; b: Matrix): Matrix =
## ``C = A + B``
assert(b.m == a.m and b.n == a.n, "Matrix dimensions must agree.")
doAssert(b.m == a.m and b.n == a.n, "Matrix dimensions must agree.")
doAssert(a.len == b.len) # non destructive use before sink is ok
result = a
for i in 0 ..< a.m:
for j in 0 ..< a.n:
result[i, j] = a[i, j] + b[i, j]
for i in 0 ..< result.m:
for j in 0 ..< result.n:
result[i, j] = result[i, j] + b[i, j]
proc `-`*(a: sink Matrix; b: Matrix): Matrix =
## ``C = A - B``
assert(b.m == a.m and b.n == a.n, "Matrix dimensions must agree.")
doAssert(a.len == b.len) # non destructive use before sink is ok
result = a
for i in 0 ..< a.m:
for j in 0 ..< a.n:
for i in 0 ..< result.m:
for j in 0 ..< result.n:
result[i, j] = a[i, j] - b[i, j]
proc info =

View file

@ -109,7 +109,19 @@ proc myfunc(x, y: int): (MySeqNonCopyable, MySeqNonCopyable) =
proc myfunc2(x, y: int): tuple[a: MySeqNonCopyable, b:int, c:MySeqNonCopyable] =
var cc = newMySeq(y, 5.0)
(a: newMySeq(x, 1.0), b:0, c: cc)
(a: case x:
of 1:
let (z1, z2) = myfunc(x,y)
z2
elif x > 5: raise newException(ValueError, "new error")
else: newMySeq(x, 1.0),
b: 0,
c: block:
var tmp = if y > 0: move(cc) else: newMySeq(1, 3.0)
tmp[0] = 5
tmp
)
let (seq1, seq2) = myfunc(2, 3)
doAssert seq1.len == 2
@ -122,4 +134,35 @@ doAssert seq3.len == 2
doAssert seq3[0] == 1.0
var seq4, seq5: MySeqNonCopyable
(seq4, i, seq5) = myfunc2(2, 3)
(seq4, i, seq5) = myfunc2(2, 3)
seq4 = block:
var tmp = newMySeq(4, 1.0)
tmp[0] = 3.0
tmp
doAssert seq4[0] == 3.0
import macros
seq4 =
if i > 0: newMySeq(2, 5.0)
elif i < -100: raise newException(ValueError, "Parse Error")
else: newMySeq(2, 3.0)
seq4 =
case (char) i:
of 'A', {'W'..'Z'}: newMySeq(2, 5.0)
of 'B': quit(-1)
else:
let (x1, x2, x3) = myfunc2(2, 3)
x3
#------------------------------------------------------------
#-- Move into array constructor
#------------------------------------------------------------
var ii = 1
let arr2 = [newMySeq(2, 5.0), if i > 1: newMySeq(3, 1.0) else: newMySeq(0, 0.0)]
var seqOfSeq2 = @[newMySeq(2, 5.0), newMySeq(3, 1.0)]