Swapping Variables in F#
[F#, .NET]
In the previous post, Swapping Variables In C# With ValueTuples, we saw how to swap variables in C#.
As a recap, the problem is as follows:
You have two variables,
a
and b, such thata
is10
andb
is20
.Write a program that swaps the values.
F# has some considerations when it comes to this problem, the most significant one being that values are immutable by default.
The traditional solution using a temporary value would look like this:
let mutable a = 10
let mutable b = 30
let temp = a
a <- b
b <- temp
printfn "a = %d, b = %d" a b
Note our values, a
and b, are mutable here.
The solution using a tuple also works:
let mutable a = 10
let mutable b = 30
a, b <- b, a
printfn "a = %d, b = %d" a b
TLDR
F# also allows the use of tuples to swap values.
Happy hacking!