Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generically remove F# Units of measure

I've got some data manipulation code which spits out csv at the end.

I started upgrading it to add units of measure everywhere, but I now have a problem with my csv function:

val WriteCSV : string -> 'a list array -> 'b list -> string -> unit

(the parameters are fileName, column array, column headers, separator)

Where I previously sent [|s;x;y|] to WriteCSV, I now have a problem, because I can't send [|skm; xmm; ymm|].

I tried writing a function for generically removing units of measure, but it doesn't work.

let removeUnit (n:float<_>) = n/1.0<_>

My questions are:

  • Why doesn't it work?
  • Can it be made to work?
  • Is there another way to solve this particular problem?
like image 675
Benjol Avatar asked Mar 01 '23 02:03

Benjol


2 Answers

If I got your Problem right, casting it to "pure" float removes the Unit. For Example:

[<Measure>] type m
[<Measure>] type km

let removeUnit (x:float<_>) =
    float x

let foo = removeUnit 2.6<m>
let foo2 = removeUnit 2.1<km>

val removeUnit : float<'u> -> float

like image 133
leen Avatar answered Mar 06 '23 16:03

leen


Another way of doing this is to use the LanguagePrimitives.FloatWithMeasure function.

For example:

let removeUnit (x: float<'u>) =
  x / (LanguagePrimitives.FloatWithMeasure<'u> 1.0)

This has a type signature of:

val removeUnit: x: float<'u> -> float
like image 34
bmitc Avatar answered Mar 06 '23 16:03

bmitc