0

I would like to define a Measure type

[<Measure>] type kB

that converts to the number of bytes when explicitly cast to an int:

(int)7<kB>   // would result 1024kB - explicit would be fine

Since there is no way to add an explicit conversion operator to a type like in C#, I am stuck. Anyone has an idea? Even better would be an implicit conversion, so that when a function requires numbers of bytes, it can be called like

Allocate(7<kB>) // implicit would be superfine

Special conversion functions do not appeal - writing a kB function is trivial but not as nice:

let kB(n) = 1024 * n
kB(7)
7 |> kB

A conversion function that does the same with units is not cool either

7<kB> |> convertToByte
3
  • Maybe you fit this option ? dotnetfiddle.net/KgaqqL Aug 23, 2015 at 18:51
  • I think (but I'm not sure) that it's impossible and it seems this question is close in spirit to this one. There's a hack there that might help guide you, but overall there seems to be no feasible approach. Also, here's a link from the answer with another approach, but it's not without a cost compared to bare units of measure. Aug 23, 2015 at 20:05
  • @PatrykĆwiek thx a lot, yes its all said there.
    – citykid
    Aug 24, 2015 at 6:39

2 Answers 2

2

Are active patterns "cool" enough for you?

[<Measure>] type kB

// single case active pattern to convert from kB to raw B value
let (|Bytes|) (x : int<kB>) = int(x * 1024)

// use pattern matching in the declaration
// val printBytes : int<kB> -> unit
let printBytes (Bytes(b)) = 
    printfn "It's %d bytes" b

printBytes 7<kB>
// "It's 7168 bytes"
1
  • How to make gB and tB also available?
    – a_a
    Oct 20, 2016 at 3:29
1

The short answer to your question seems to be no. Which strikes me as add because this conversion is a bit shift. Alas, how about static methods as prescribed from "Programming f# 3.0" page 108?

[<Measure>]
type B =
    static member toKB (x: int<B>) =
        1<KB> * x / 1024<B> 

and [<Measure>] KB =
    static member toB (x: int<KB>) =
        x * 1024<B> / 1<KB>

let b1 = 1024<B>
let kb1 = B.toKB b1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.