tags:

views:

251

answers:

3

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)
+4  A: 

You can't; there's no syntax to update 'more than one mutable variable' with a single assignment. Of course you can do

let newX, newY = Swap(x,y)
x <- newX
y <- newY
Brian
I was hoping for a more favorable answer, but at least this is a correct one. Sigh, F#'s inconsistencies are quickly becomming a pain in my side. I realize that I'm pushing against the boundries, but I shouldn't be hitting them this soon.
Jonathan Allen
I'm not sure I'd characterize as a "boundary" the idea that language constructs that are discouraged have less-convenient syntax than the preferred constructs. Making best practices also the most convenient seems like a smart idea to me.
Joel Mueller
@Joel. Isn't that the definition of boundary? If I was using the preferred syntax I wouldn't have used that term.
Jonathan Allen
+2  A: 

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:

let mutable toto = 5, 10 

let swap (x, y) = y, x

toto  <- swap toto

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

Robert
This is what is probably wanted
John Weldon
If you want to generalize this, you still have to unpack the mutable tuple back to the original values. So really using a mutable tuple is a waste.
Jonathan Allen
It's unclear to me why you need to unpack or even replace the new x and y in the original variable. I any real world exmaple you'd just write "let x', y' = swap x y" and directly use x and y prime.
Robert
@Robert, This isn't about using idomatic F#. This is about pushing on the edges and seeing where the cracks are. I never use swap in real code, but I still need to know whether or not it is possible because other designs may require it.
Jonathan Allen
I would be interested to know what kind of design could require this behaviour.
Robert
A: 

To expand on Robert's answer:

let swap (x : int, y : int) = y, x
let mutable x = 5
let mutable y = 10
let mutable xy = x, y

xy <- swap xy

Makes both the variables and the tuple mutable.

John Weldon
Doesn't work. When you print out x and y, you will see that they didn't change. Making xy mutable was just a red-herring, since you could have just as easily passed in the original variables.
Jonathan Allen
Correct, the x, and y don't get updated.
John Weldon