F# Units of measure - 'lifting' values to float<something>

不羁岁月 提交于 2019-11-27 07:15:06

问题


When importing numbers from a csv file, I need to convert them to floats with unit.

Currently I do this with an inline function:

data |> List.map float |> List.map (fun n -> n * 1.0<m>)

But I'm wondering if there is a more elegant way to do this - or do I have to create my own 'units' module with conversion functions?

What would be really nice would be something like this, but I doubt it's possible...

data |> List.map float |> List.map lift<m>

This is the opposite of my previous question (How to generically remove F# Units of measure).

UPDATE: For homemade units, I've tried this, which works ok:

[<Measure>]
type km = 
    static member lift (v:float) = v * 1.0<km>

data |> List.map float |> List.map km.lift

or, following the question in this answer

data |> List.map (float >> km.lift)

回答1:


It looks like units of measure can't be type parameters for the moment (no idea if this will change). So the shortest way to write this is:

data |> List.map float |> List.map ((*) 1.0<m>)

EDIT

See also now FloatWithMeasure here

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




回答2:


Is there any reason why you have to map twice? What's wrong with this:

data |> List.map (fun x -> (float x) * 1.0<m>)


来源:https://stackoverflow.com/questions/419521/f-units-of-measure-lifting-values-to-floatsomething

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!