F# units of measure: how to represent a byte as being 8 bits?

Viewed 84

I tried the following but it doesn't work:

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

Thank you

1 Answers

The formulas you can specify when using units of measure do not represent conversions but rather derived units. For example, you can define Pascal to be N/m^2, but this is not conversion - it just says that numerical values that have these two units are the same.

Your definition does not let you actually do what you'd expect. For example, the following gives you a compile time error:

[<Measure>]
type B

[<Measure>]
type KB = B^3

1000<B> = 1<KB>

A more useful thing is to keep both units abstract and define a conversion function:

[<Measure>]
type B

[<Measure>]
type KB

let bToKB (b:int<B>) : int<KB> = b / 1000<B/KB>

bToKB 1000<B> = 1<KB>
Related