views:

444

answers:

2

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.)

+7  A: 

Try the following

let swap (left : 'a byref) (right : 'a byref) =
  let temp = left
  left <- right
  right <- temp
JaredPar
+7  A: 

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.

Dario
Are you sure about that. I thought I read that one should prefer mutables when possible.
Jonathan Allen