F# Immutable Class Interop -
how f# immutable types interface c#. i'm starting learn f# , i'd mix in c# code have, want f# classes immutable.
let's we're making vector class in f#. vector.x , vector.y should re-assignable, returning new vector class. in c# take allot of legwork make .withx(float x) clone existing object , return new one. there easy way in f#?
i've been searching time , can't seem find docs on this. great.
and finally, if imported class c# interface like? f# code restrict me doing stupid vector.x = 10
?
this similar regardless of whether it's c# or f#.
you "in c# take legwork", cmon, think
vector withx(float x) { return new vector(x, this.y); }
is it, right?
in both c# , f#, prevent assignment x property, author property 'getter' no 'setter'.
i think you're making of out harder is, or maybe i'm misunderstanding you're asking.
edit
for (i think rare) case of there 20 field , may want change small arbitrary subset of them, found cute hack use f# , c# optional parameters nicely.
f# code:
namespace global open system.runtime.interopservices type util = static member some<'t>(x:'t) = x type myclass(x:int, y:int, z:string) = new (toclone:myclass, [<optional>] ?x, [<optional>] ?y, [<optional>] ?z) = myclass(defaultarg x toclone.x, defaultarg y toclone.y, defaultarg z toclone.z) member this.x = x member this.y = y member this.z = z
f# client code:
let = new myclass(3,4,"five") let b = new myclass(a, y=44) // clone change y
c# client code:
var m = new myclass(3, 4, "five"); var m2 = new myclass(m, y:util.some(44)); // clone m change y
that is, optional parameters nice way this, , while c# optional parameters have limitations, can expose f# optional parameters in way works ok c#, suggested above.
Comments
Post a Comment