F # cast / convert custom type for primitive

I designed my app domain with F # custom types, but now it seems that these custom types will be PITA when I want to actually use the data for various tasks ... i.e. write values โ€‹โ€‹to CSV file using other libraries that rely on primitives, etc.

For example, I have a custom type like this (which is used as a building block for other larger types):

type CT32 = CT32 of float

      

But code like this doesn't work:

let x = CT32(1.2)
let y = float x //error: The type "CT32" does not support a conversion...
let z = x.ToString() //writes out the namespace, not the value (1.2)

      

I tried using box / unbox and Convert.ToString () and two F # statements, but neither of them allows me to access the underlying primitive value contained in my types. Is there an easy way to get primitive values โ€‹โ€‹in custom types, because until now they have been more of a headache than really useful.

+3


source to share


2 answers


Yours type CT32

is a Discriminatory Union with one case identifier CT32 of float

. It's not a alias

float type, so you can't just put it in a float. To extract a value from it, you can use pattern matching (this is the easiest way).

type CT32 = CT32 of float
let x = CT32(1.2)

let CT32toFloat = function CT32 x -> x
let y = CT32toFloat x
let z = y.ToString()

      



Alternatively (if your custom types are numeric) you can use Units https://msdn.microsoft.com/en-us/library/dd233243.aspx They have no runtime overhead (I believe discriminatory unions are compiled for classes), but enforce compile-time type safety.

+1


source


Adding support for float

simple:



type CT32 = CT32 of float with
    static member op_Explicit x =
        match x with CT32 f -> f

let x = CT32(1.2)
let y = float x

      

+3


source







All Articles