F# Units of measure - 'lifting' values to

2019-01-20 02:16发布

问题:

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>)