11

这就是我到目前为止所拥有的。

let Swap (left : int , right : int ) = (right, left)

let mutable x = 5
let mutable y = 10

let (newX, newY) = Swap(x, y) //<--this works

//none of these seem to work
//x, y <- Swap(x, y)
//(x, y) <- Swap(x, y)
//(x, y) <- Swap(x, y)
//do (x, y) = Swap(x, y)
//let (x, y) = Swap(x, y)
//do (x, y) <- Swap(x, y)
//let (x, y) <- Swap(x, y)
4

3 回答 3

12

你不能;没有语法可以通过单个赋值更新“多个可变变量”。你当然可以

let newX, newY = Swap(x,y)
x <- newX
y <- newY
于 2009-06-03T20:36:36.540 回答
4

您评论的代码不起作用,因为当您编写“x,y”时,您会创建一个新的元组,它是一个不可变的值,因此无法更新。您可以创建一个可变元组,然后根据需要用交换函数的结果覆盖它:

let mutable toto = 5, 10 

let swap (x, y) = y, x

toto  <- swap toto

我的建议是研究 F# 的不可变方面,看看你可以使用不可变结构来实现你以前使用可变值所做的事情。

于 2009-06-03T20:41:41.430 回答
4

F# 与 C# 一样具有“引用”参数,因此您可以类似地编写经典的交换函数:

let swap (x: byref<'a>) (y: byref<'a>) =
    let temp = x
    x <- y
    y <- temp

let mutable x,y = 1,2
swap &x &y
于 2011-04-04T04:19:16.580 回答