Last active
December 25, 2015 12:09
-
-
Save colinbull/6974405 to your computer and use it in GitHub Desktop.
I know from this [link](http://cs.hubfs.net/topic/None/59380) that this is bad.... but how else can I achieve something similar.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//I can do the following to cast a given unit but this leads to an individual | |
//lift function for everyType | |
type [<Measure>] type megawatt | |
type [<Measure>] type therm | |
module Megawatt = | |
let inline liftFloat a = (float a) * 1.0<megawatt> | |
let inline liftInt a = (int a) * 1<megawatt> | |
//This gets dull quickly for lots of units of measure | |
//The following gets a deprecated warning and from the link in the description it is bad but would save alot of code | |
//I understand there maybe truncation ect, and some loss of type safety | |
//but this seems so convenient. | |
let inline retype<'T,'U> (x:'T) : 'U = (# "" x : 'U #) | |
let inline liftUnit a = | |
retype (float a) | |
//Example usage, | |
let value : int<megawatt> = liftUnit 6 | |
Was the problem the fact you need functions for every unit of measure, or that you need functions for every numerical type?
The following solves the former case
let liftToFloat (x : float) : float<'M> =
Microsoft.FSharp.Core.LanguagePrimitives.FloatWithMeasure<'M>(x)
Are you asking how to write an unsafe cast? You can always do: let retype<'A,'B> (x: 'A) : 'B = unbox (box a)
- if you don't mind structs jumping on the heap for a bit there.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BTW.. I realise that this is really just an unsafe cast. I guess the alternative would be to use static optimisations but I think these raise a compiler error when used outside of the FSharp.Core library.