在 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);
我将如何用 F# 编写它?
(注意,我不想要功能等价物。我实际上需要通过引用语义传递。)
在 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);
我将如何用 F# 编写它?
(注意,我不想要功能等价物。我实际上需要通过引用语义传递。)
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
通常,您会使用ref-cells
而不是可变的 let's。
尝试以下
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
/// 交换元组中两个值顺序的函数
let Swap (a, b) = (b, a)