Arithmetic casting to generic type in F# -
i try write function generic casting arithmetic types, example function receives argument of type uint64
, converts type being same type parameter. idea is:
let convert<'t> (x:uint64) = 't x
but code not compile, , stuck here after trying several approaches like:
let convert<'t> (x:uint64) = match unchecked.defaultof<'t> | :? uint32 -> uint32 x ....
so how write such generic arithmetic casting in f#? (i start learning question maybe stupid, please take easy).
you can use static member constraints, here's "short" example:
type explicit = static member inline ($) (_:byte , _:explicit) = byte static member inline ($) (_:sbyte, _:explicit) = sbyte static member inline ($) (_:int16, _:explicit) = int16 static member inline ($) (_:int32, _:explicit) = int // more overloads let inline convert value: 't = (unchecked.defaultof<'t> $ unchecked.defaultof<explicit>) value // specialized uint64 let inline fromuint64 (value: uint64) :'t = convert value // usage let x:int = fromuint64 7ul
as said in comments can use function explicit
f#+ covers cases when there explicit operator. here's sample code.
now if @ source code of function defined in project (fscontrol) find more complicated workaround.
you may wonder why, here's long answer:
in theory should possible use single call invoking member op_explicit
, work when member exists not case native number types.
for cases f# compiler uses feature referred "simulated members" implemented using static optimizations that's not available outside f# compiler source code.
so fscontrol uses different feature instead: overload resolution, in sample code showed uses additional overload general case members contain op_explicit
static member.
Comments
Post a Comment