问题描述
从csv文件导入数字时,我需要将其转换为带单位的浮点数.
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>
这与我之前的问题相反(如何通常删除F#度量单位).
更新:对于自制设备,我已经尝试过了,可以正常工作:
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
,或者按照此答案中的问题
data |> List.map (float >> km.lift)
推荐答案
目前看来度量单位不能作为类型参数(不知道这种情况是否会改变).因此,最简单的写法是:
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>)
编辑
在此处也请参见FloatWithMeasure
http://msdn.microsoft.com/zh-cn/library/ee806527(VS.100).aspx
这篇关于F#度量单位-“提升"值以使其漂浮于某物上.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!