F # matches with volatile

I just started playing with F #, and I want to create some mutable model inside my application to play with it using a differentiated F # union, not a class hierarchy. However, there seems to be no way to “omit” the discriminatory union, and “coinciding with” does not spread volatility. What should I do?

type Foo = {
    mutable x: int
}

type FooBar = 
    | Foo of Foo
    | Bar

let f = {x = 2};
do f.x <- 3; //All ok

let fb = Foo {x = 1}
do match fb with
    | Foo {x = x} -> x <- 2 //"This value is not mutable"
    | Bar -> ()
+4
source share
1 answer

Your problem is that you map / deconstruct fbto a new template / value x : int(this is not at all the same as f.x!), Which, of course, will be unchanged (like bindings / values ​​in F # by default).

you probably see it much better if you don't give both (value and pattern) the same name:

> match fb with Foo { x = y } -> y;;
val it : int = 1

, x y, y x ( )


C#

, #

Foo:

class Foo { public int x { get; set; } }

a FooBar

class Foo2 : FooBar 
{ 
    public Foo Value { get; } 
}

( , - )

:

var fb = new Foo2(new Foo(1));
var x = fb.Value.x;
x := 2;

, fb.Value.x 2 1?;)


/

let fb = Foo {x = 1}
do match fb with
    | Foo f -> f.x <- 2
    | Bar -> ()

- f fb, f.x

F #, - , istead:)

+8

All Articles