casting - F# cast / convert custom type to primitive -


i've designed app domain custom f# types, seems these custom types pita when want use data various tasks... i.e. writing values csv file, using other libraries rely on primitives, etc.

for example, have custom type (which used building block other larger types):

type ct32 = ct32 of float 

but code doesn't work:

let x = ct32(1.2) let y = float x //error: type "ct32" not support conversion... let z = x.tostring() //writes out namespace, not value (1.2) 

i've tried use box/unbox , convert.tostring() , 2 f# casting operators none of them seem allow me access base primitive value contained types. there easy way primitive values in custom types because far they've been more of headache useful.

your type ct32 discriminated union 1 case identifier ct32 of float. it's not alias float type couldn't cast float. extract value can use pattern matching (this 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() 

as alternative (if custom types numeric) can use units of measure https://msdn.microsoft.com/en-us/library/dd233243.aspx don't have runtime overhead (i believe discriminated unions compiled classes) provide type safety @ compile time.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -