Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: How to write the classic swap function?

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

like image 518
Jonathan Allen Avatar asked Jun 03 '09 18:06

Jonathan Allen


3 Answers

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.

like image 142
Dario Avatar answered Nov 15 '22 12:11

Dario


Try the following

let swap (left : 'a byref) (right : 'a byref) =
  let temp = left
  left <- right
  right <- temp
like image 37
JaredPar Avatar answered Nov 15 '22 12:11

JaredPar


/// A function that swaps the order of two values in a tuple

let Swap (a, b) = (b, a)
like image 23
Jugal Panchal Avatar answered Nov 15 '22 12:11

Jugal Panchal