[英]F#: How to write the classic swap function?
In C# the classic swap function is: 在C#中,经典的交换功能是:
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#? 我怎么用F#写这个?
(Note, I do not want the functional equivalent. I actually need pass by reference semantics.) (注意,我不希望函数等价。我实际上需要通过引用语义传递。)
Example to Jared's code: Jared的代码示例:
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. 通常,你会使用
ref-cells
而不是mutable let。
Try the following 请尝试以下方法
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
///在元组中交换两个值的顺序的函数
let Swap (a, b) = (b, a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.