Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify union clause with generic unit of measure in F#?

Is there anyway to define a DU whose clauses uses generic unit of measure? e.g.

type MyDU =
| A  of int<_>
| B  of float<_>

this code doesn't compile, but I can specify a regular function that takes in a numeric value with generic unit of measure:

let f (n : int<_>) = n * n;;
val f : int<'u> -> int<'u ^ 2>

considering that each union clause is ultimately a function that converts the type specified after of to the private types MyDU.A or MyDU.B is there a particular reason why it works on function definition but not type definition?

Is there a way to do what I want to do here? If not, I would love to know why it wouldn't work too!

Thanks,

like image 325
theburningmonk Avatar asked Dec 20 '22 17:12

theburningmonk


1 Answers

You need to use a generic union -

type MyDU<[<Measure>] 't> =
    | A  of int<'t>
    | B  of float<'t>

This is beacause a int<m> is different to an int<s>.

Note that this is not specific to measure types, it also applies to things like using a union to create lists etc.

like image 169
John Palmer Avatar answered Mar 16 '23 13:03

John Palmer