F #: How to write a classic sharing function?

In C #, the classic swap function:

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 do I write this with F #?

(Note that I do not need a functional equivalent. I really need to go through the reference semantics.)

+5
source share
3 answers

Try to execute

let swap (left : 'a byref) (right : 'a byref) =
  let temp = left
  left <- right
  right <- temp
+9
source

Jared Code Example:

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

Usually you should use ref-cellsmutable let's instead.

+8
source

/// Function that changes the order of two values ​​in a tuple

let Swap (a, b) = (b, a)
+1
source

All Articles