F# 度量单位:如何将一个字节表示为 8 位?
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>
比较有用的是把两个单位都抽象起来,定义一个转换函数:
[<Measure>]
type B
[<Measure>]
type KB
let bToKB (b:int<B>) : int<KB> = b / 1000<B/KB>
bToKB 1000<B> = 1<KB>
我尝试了以下方法,但它不起作用:
// 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>
比较有用的是把两个单位都抽象起来,定义一个转换函数:
[<Measure>]
type B
[<Measure>]
type KB
let bToKB (b:int<B>) : int<KB> = b / 1000<B/KB>
bToKB 1000<B> = 1<KB>