In C# the classic swap function is:
void swap (ref int a, ref int b){
int temp = a;
a = b;
b = temp;
}
int a = 5;
int b = 10;
swap( ref a, ref b);
How would I write that with F#?
(Note, I do not want the functional equivalent. I actually need pass by reference semantics.)
Example to Jared's code:
let mutable (a, b) = (1, 2)
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
printfn "a: %i - b: %i" a b
swap (&a) (&b)
printfn "a: %i - b: %i" a b
Normally, you would use ref-cells
instead of mutable let's.
Try the following
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
/// A function that swaps the order of two values in a tuple
let Swap (a, b) = (b, a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With