F# match with mutable -


just started playing f# , want create mutable model inside app play with, using f# discriminated union instead of class hierarchy. there seems no way "downcast" discriminated union , "match with" doesn't propagate mutability. should do?

type foo = {     mutable x: int }  type foobar =      | foo of foo     | bar  let f = {x = 2}; f.x <- 3; //all ok  let fb = foo {x = 1} match fb     | foo {x = x} -> x <- 2 //"this value not mutable"     | bar -> () 

your problem is, match/deconstruct fb new pattern/value x : int (that not same f.x @ all!) of course immutable (as bindings/values in f# default).

you see better if don't give both (the value , pattern) same name:

> match fb foo { x = y } -> y;; val : int = 1 

see match x against y y value of x (but not mutable)


situation in c#

let's @ similar situation in c#

assuming have foo class:

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

and foobar base-class

class foo2 : foobar  {      public foo value { get; }  } 

(i striped ctors because lazy - idea)

now this:

var fb = new foo2(new foo(1)); var x = fb.value.x; x := 2; 

do think fb.value.x 2 or 1? ;)


how pattern-match / mutate

use

let fb = foo {x = 1} match fb     | foo f -> f.x <- 2     | bar -> () 

instead - deconstruct f out of fb , can set mutable record-field f.x

but suggest not starting learn f# trying out how use mutable values - try learn using immutability as can istead :)


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -