Generic swap: Difference between revisions

m
→‎{{header|Wren}}: Now uses List.swap method.
(→‎{{header|Kotlin}}: added another possible solution)
m (→‎{{header|Wren}}: Now uses List.swap method.)
Line 3,488:
However, it is still not possible to write a generic swap function. This is because all variables are passed to functions or methods by value and prescribing that they should be passed by reference instead is not supported. Moreover, variables of simple types (numbers, bools and nulls) are never boxed and so a function cannot mutate the original variable.
 
Perhaps the nearest we can get to a generic swap function is to pass the variables in a list (the list's address is then passed by value under the hood), swap the list elements (lists do have a swap method) and then unpack the list to the original variables after the function returns.
 
Another approach would be to box simple variables (using a user defined class) so that they can be mutated. However, the problem with this is that they usually need to be 'unboxed' when the function returns.
 
Both approaches are illustrated below.
<syntaxhighlight lang="ecmascript">var swap = Fn.new { |l| l.swap(0, 1) }
var t = l[0]
l[0] = l[1]
l[1] = t
}
 
var a = 6
9,476

edits