6

在 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# 编写它?

(注意,我不想要功能等价物。我实际上需要通过引用语义传递。)

4

3 回答 3

10

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。

于 2009-06-03T18:40:48.193 回答
9

尝试以下

let swap (left : 'a byref) (right : 'a byref) =
  let temp = left
  left <- right
  right <- temp
于 2009-06-03T18:31:35.437 回答
2

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

let Swap (a, b) = (b, a)
于 2013-10-07T09:15:30.567 回答