[英]F#: How to write the classic swap function?
在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
而不是mutable let。
請嘗試以下方法
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.