与其他单位数量建立度量关系单位 [英] Establish Units of Measure Relationships With a Quantity of Another Unit

查看:72
本文介绍了与其他单位数量建立度量关系单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到您可以表达与单位维度的关系,例如

I realize that you can express relationships with dimensions of units, like

[<Measure>] type cc = cm^3

并在以后执行有意义的计算.

and perform meaningful calculations later.

给出某种计量单位类型,

Given some unit of measure type,

[<Measure>] type m

是否可以将一个单位与另一个单位的数量定义为关系?例如

Is it possible to define a unit in a relationship with a quantity of another unit? For example,

// doesn't compile
[<Measure>] type mm = 0.001<m>

// later
let length = 500.0<mm>
let length2 = 0.5<m>
printfn "%A" (length = length2) // prints true

推荐答案

总之:否.

度量单位是基元上的注释.时期.您可能知道,它们将在编译过程中被删除.

Units of measure are annotations on primitives. Period. As you probably know, they will be deleted during compilation.

所以这是它们的基本局限性:您不能附加任何功能,因为它们都会变成普通的float.

So here's their fundamental limitation: you cannot attach any kind of functionality to them, because they will all turn into plain old floats.

编译器将检查您的表达式在维度上是否有效,但是(目前)它不会自动生成或插入任何类型的默认"类型转换函数.

The compiler will check that your expressions are dimensionally valid, but (for now) it does not automatically generate or insert any sort of 'default' type-conversion functions.

您必须自己编写和使用这些功能,并且最好的办法是使它们尽可能简单明了.

You must write and use those functions yourself, and the best you can do is to make them as straightforward as possible.

这是我整理您的示例的方式:

Here's how I'd organise your example:

[<Measure>] type mm    
[<Measure>] type mt

// first, I like to define basic functions to quickly annotate dimensionless values
let mm = (*) 1.0<mm>
let mt = (*) 1.0<mt>

// we define a constant conversion
let MmPerMt = 1000.0<mm/mt>

// (though nothing forbids us from defining any conversion we want, and the compiler cannot privilege one over another)
let INeverPaidAttentionInGradeSchool = 12345<mm/mt>

// for ease of use, we bake the conversion constant into functions
let MtToMm = (*) MmPerMt

// usage
let someUserInputInMeters = "12414.23"

let desiredValueInMillimeters = someUserInputInMeters
                                |> float
                                |> mt
                                |> MtToMm

这篇关于与其他单位数量建立度量关系单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆