[英]F# units of measure: how to represent a byte as being 8 bits?
我尝试了以下方法,但它不起作用:
// bits
[<Measure>]
type b
// bytes
[<Measure>]
type B = b*8 // Expected unit-of-measure, not type; Invalid literal in type
// kilobytes
[<Measure>]
type KB = B^3 // This works though
谢谢
使用计量单位时可以指定的公式不代表换算,而是派生单位。 例如,您可以将Pascal定义为 N/m^2,但这不是转换 - 它只是说具有这两个单位的数值是相同的。
你的定义并没有让你真正做你所期望的。 例如,以下为您提供编译时错误:
[<Measure>]
type B
[<Measure>]
type KB = B^3
1000<B> = 1<KB>
更有用的是保持两个单元抽象并定义转换 function:
[<Measure>]
type B
[<Measure>]
type KB
let bToKB (b:int<B>) : int<KB> = b / 1000<B/KB>
bToKB 1000<B> = 1<KB>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.