Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching of mutable values using F#

I would like to point out a 'risky' part in F#. Consider the following code

let mutable a, b as ab = 0, 0
a <- 4
a
ab

You will get a = 4 and ab = 0, 0. It is probably a correct behaviour, I just wanted to point it out and know your opinion. Do you find this behaviour logical or not, and why? I have some problems to accept it, because I have always assumed that (a, b) and ab should be identical.

like image 216
Oldrich Svec Avatar asked Dec 03 '25 21:12

Oldrich Svec


2 Answers

If you run let mutable a, b as ab = 0, 0 in F# interactive you will get :

val mutable ab : int * int = (0, 0)
val mutable b : int = 0
val mutable a : int = 0

Which mean the expression has created 3 different and separate values. Modifying one value wont effect other values

like image 160
Ankur Avatar answered Dec 06 '25 10:12

Ankur


It is true that this may be confusing at first, but once you understand how F# treates the declaration (as explained by Ankur), it should make good sense.

You can get the other behavior (where modifying one value also modifies a tuple) if you use reference cells instead of mutable variables:

let a, b as ab = ref 0, ref 0
a := 4
!(fst ab) // returns 4
like image 36
Tomas Petricek Avatar answered Dec 06 '25 11:12

Tomas Petricek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!