简体   繁体   中英

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

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

///在元组中交换两个值的顺序的函数

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM