Skip to content

Instantly share code, notes, and snippets.

@colinbull
Last active December 25, 2015 12:09
Show Gist options
  • Save colinbull/6974405 to your computer and use it in GitHub Desktop.
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.
//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
@deneuxj
Copy link

deneuxj commented Oct 14, 2013

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)

@t0yv0
Copy link

t0yv0 commented Oct 14, 2013

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.

@colinbull
Copy link
Author

@deneuxj @ToyVo The problem is that I need to write functions for every numerical type. I wanted to try and avoid this and avoid the unsafe cast. I think I'm asking for the impossible, without static optimizations that is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment