Type of level integers in ocaml

Can someone give me some tips / advice on creating level integers in OCaml (3.12) that support addition and subtraction operations on them?

For example, if I have numbers represented as follows:

type zero
type 'a succ
type pos1 = zero succ
type pos2 =  zero succ succ
...

I need a way to define a function for these types:

val add: pos2 -> pos1 -> pos3

Small background: I'm trying to transfer some haskell code for operations with physical dimensions, and I need the ability to define operations on dimension types (a record of 7 types of type level representing exponents of 7 basic SI units). I need to do this in such a way as to avoid dynamic binding (when using objects) and let the compiler evaluate and check all such expressions statically.

, GADT, , , .

+5
3
+3

, , -

type fancyInt = Zero | Succ of fancyInt ;;

then add will be

let rec add a b = match a with Zero -> b | Succ c -> add c (Succ b);;

In the background story, hints at another solution, create a class that represents distances. Keep the value internally, however you need to provide an interface that allows you to get and set the distance in units needed at that time. Or, if you want to stay with a functional approach, just create types for your departments, then the functions should be the same, since Ocaml itself handles such things, that is, meters_o_k_k.

0
source

All Articles