Jonathan Allen
Jonathan Allen

Reputation: 70327

How do you return multiple values and assign them to mutable variables?

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)

Upvotes: 11

Views: 5806

Answers (3)

Stephen Swensen
Stephen Swensen

Reputation: 22297

F# has "by reference" parameters just like C#, so you can write a classic swap function similarly:

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

let mutable x,y = 1,2
swap &x &y

Upvotes: 5

Robert
Robert

Reputation: 6437

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

Upvotes: 4

Brian
Brian

Reputation: 118895

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

Upvotes: 12

Related Questions