Guest User

Fun with swap in Nim

a guest
Jan 4th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 0.84 KB | None | 0 0
  1. # This is chopped up to only be the relevant code of course.
  2.  
  3. iterator mitems*[T](a: var seq[T]): var T {.inline.} =
  4.   var i = 0
  5.   let L = len(a)
  6.   while i < L:
  7.     yield a[i]
  8.     inc(i)
  9.     assert(len(a) == L, "seq modified while iterating over it")
  10.  
  11. type
  12.   MemoryCell* = object
  13.     id*: int
  14.     data*: CellData
  15.  
  16.   Memory* = seq[ref MemoryCell]
  17.  
  18.   Link* = object
  19.     source*: MemoryCell
  20.     dest*: MemoryCell
  21.  
  22.   Links* = seq[Link]
  23.  
  24. proc reverse*(links: var Links) =
  25.   # reverses data flow in links
  26.   for link in links.mitems:
  27.     swap(link.source, link.dest) # What happens here? Is this the right way to do what I want? Is this needless copying?
  28.     # If I had refs, would the instance count keep rising with the swap or neatly swap the pointers which is what I want ideally.
  29.     # Am I better off using effects to manage this?
Advertisement
Add Comment
Please, Sign In to add comment