c# - How to create a Union type in F# that is a value type? -
normal f# discriminated unions reference types. how can create simple (non-recursive , value-type fields) union type in f# value type?
based on internet searching current (non-working) attempt looks follows:
[<structlayout(layoutkind.explicit)>] type float = [<defaultvalue>] [<fieldoffset 0>] val mutable val1 : float [<defaultvalue>] [<fieldoffset 0>] val mutable int1 : int new (a:float) = {val1 = a} the following blog post appears show possible via c#
i'm aware above not idiomatic use of f# trying optimize performance of portion of application , profiling has shown cost of heap allocations (jit_new) causing performance bottleneck... simple union type perfect data structure needs, not heap allocated one.
first of all, not this, unless had very reasons. in cases, difference between structs , reference types not big - in experience, matters when have large array of them (then structs let allocate 1 big memory chunk).
that said, looks f# not constructor code in example. i'm not sure why (it seems doing check not quite work overlapping structs), following trick:
[<struct; structlayout(layoutkind.explicit)>] type mystruct = [<defaultvalue; fieldoffset 0>] val mutable val1 : float [<defaultvalue; fieldoffset 0>] val mutable int1 : int static member int(a:int) = mystruct(int1=a) static member float(f:float) = mystruct(val1=f) if wanted use this, add field tag containing 1 or 0 depending on case struct represents. pattern match on using active pattern , of safety of discriminated unions back:
let (|float|int|) (s:mystruct) = if s.tag = 0 float(s.val1) else int(s.int1)
Comments
Post a Comment