如何返回多个值并将它们分配给可变变量?
这是我到目前为止所拥有的。
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)
This is what I have so far.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能; 没有语法可以通过一次赋值来更新“多个可变变量”。 当然你可以做
You can't; there's no syntax to update 'more than one mutable variable' with a single assignment. Of course you can do
F# 与 C# 一样具有“通过引用”参数,因此您可以类似地编写经典的交换函数:
F# has "by reference" parameters just like C#, so you can write a classic swap function similarly:
您注释的代码不起作用,因为当您编写“x,y”时,您创建了一个新元组,该元组是不可变值,因此无法更新。 如果需要,您可以创建一个可变元组,然后用交换函数的结果覆盖它:
我的建议是研究 F# 的不可变方面,看看如何使用不可变结构来实现您以前所做的事情使用可变值。
抢
The code you have commented doesn't work because when you write "x, y" you create a new tuple that is an immutable value, so can't be updated. You could create a mutable tuple and then overwrite it with the result of the swap function if you want:
My advice would be to investigate the immutable side of F#, look at the ways you can use immutable structures to achieve what you previously would have done using mutable values.
Rob