Hi, I was experimenting with the swap proc of the system module (here's the doc) since I need it in a uni project and I encountered a behavior that confuses me. If i go to the Nim Playground and I execute the following program:
from algorithm import fill
proc swapper[R,T](arr: var array[R, T]) =
let oldaddr = arr.addr
var support: array[R,T]
support.fill(1)
echo arr.addr == oldaddr
swap(support, arr)
echo arr.addr == oldaddr
echo support.addr == oldaddr
echo arr
when isMainModule:
var arr = [1,2,3,4,5,6,7,8,9]
echo arr
arr.swapper
echo arr
I get the following output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
true
false
false
[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Indicating that no swapping has occurred at global scope, neither by value nor by reference, while within the swapper proc scope the swapping is valid. So I'm curious to understand what is going on under the hood of this proc and why it is behaving in such a strange way. What should I do to work around the issue without directly meddling with addr?It's a bug. :-)
This works:
from algorithm import fill
type
O = object
a: array[9, int]
proc swapper(arr: var O) =
#let oldaddr = arr.addr
var support: O
support.a.fill(1)
#echo arr.addr == oldaddr
swap(support, arr)
#echo arr.addr == oldaddr
#echo support.addr == oldaddr
#echo arr
when isMainModule:
var arr = O(a: [1,2,3,4,5,6,7,8,9])
echo arr
arr.swapper
echo arr
is there any python like syntax for swap
a,b=b,a and a,b=b,a+b (fibonachi case)
(a, b) = (b, a)