繁体   English   中英

F#:如何编写经典的交换功能?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM