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.)
(注意,我不希望函数等价。我实际上需要通过引用语义传递。)
3 个解决方案
#1
Try the following
请尝试以下方法
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
#2
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。
#3
/// A function that swaps the order of two values in a tuple
///一个交换元组中两个值的顺序的函数
let Swap (a, b) = (b, a)
#1
Try the following
请尝试以下方法
let swap (left : 'a byref) (right : 'a byref) =
let temp = left
left <- right
right <- temp
#2
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。
#3
/// A function that swaps the order of two values in a tuple
///一个交换元组中两个值的顺序的函数
let Swap (a, b) = (b, a)