views:

126

answers:

2

Is there built in version of the type casting functions that preserves units and if not how would I make them? So for example with this code how would I cast intWithSecondsMeasure to a float without losing the measure or multiplying by 1.0<s>?

[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
+4  A: 

I don't think that there's a built-in way to do it, but you can easily define your own unit-preserving conversion function:

let float_unit (x:int<'u>) : float<'u> = unbox float x
let floatWithSecondsMeasure = float_unit intWithSecondsMeasure
kvb
+2  A: 

See my answer to this question:

http://stackoverflow.com/questions/1504632/unit-safe-square-roots

which suggests this today:

[<Measure>] 
type s
let intWithSecondsMeasure = 1<s>

let intUtoFloatU< [<Measure>] 'u>( x : int<'u> ) : float<'u> = //'
    let i = int x       //  drop the units
    let f = float i     //  cast
    box f :?> float<'u> //' restore the units

let floatWithS = intUtoFloatU intWithSecondsMeasure
Brian
Will something with this signature go in the library? Obviously it'll be writable in terms of the planned FloatWithMeasure, but it'd be nicer to have a function that's clearly unit-safe directly available.
Ganesh Sittampalam