Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

units of measurement - F# Ununit - reunit inside a function

This question is closely related to these ones (1, 2, 3)

I'm using an external library which doens't (yet) handle units of measure. I want to be able to 'ununit' values before I pass them in, then 'reunit' them when I get the results back.

The catch is that I'd like to avoid being forced to declare WHICH units in advance.

Example snippet

let ExternalNonUnitAwareFunction s = s + 1.

let MyUnitAwareClient (s:float<'u>) =  //'
    //1. this option "flattens" to no unit, or fixes to first inferred unit
    //let (unit:float<'u>) = 1.0<_>  
    //2. this works fine, except for 0!
    let unit = s / (float s) 
    s |> float |> ExternalNonUnitAwareFunction |> (*) unit

I haven't managed to work out how to handle this one...

Update If I have understood correctly, the final version of F# will include functions to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For now, boxing and casting appears to work:

let MyUnitAwareClient (s:float<'u>) =  
  let result = s |> float |> ExternalNonUnitAwareFunction
  (box result :?> float<'u>)

I wouldn't be surprised if the units of measure stuff goes through some further changes before release, though, which might break this. You can also make a more generic version, such as:

let reunit (f:float -> float) (v:float<'u>) =
  let unit = box 1. :?> float<'u>
  unit * (f (v/unit))

EDIT

There is now a FloatWithMeasure function to 'cast to units':

http://msdn.microsoft.com/en-us/library/ee806527(VS.100).aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...