Jonathan Allen
Jonathan Allen

Reputation: 70327

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

Upvotes: 6

Views: 3540

Answers (3)

Jugal Panchal
Jugal Panchal

Reputation: 1548

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

let Swap (a, b) = (b, a)

Upvotes: 2

Dario
Dario

Reputation: 49218

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.

Upvotes: 10

JaredPar
JaredPar

Reputation: 755141

Try the following

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

Upvotes: 9

Related Questions