Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type level integers in ocaml

Tags:

types

ocaml

gadt

Could anyone give me suggestions/advice on making type level integers in OCaml (3.12) supporting addition and subtraction operations on them?

For example, if I have numbers represented like this:

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

I need a way to define function on types like this:

val add: pos2 -> pos1 -> pos3

Little background: I'm trying to port some haskell code for operations on physical dimensions and i need the ability to define operations on dimension types (record of 7 type level ints representing exponents of 7 basic SI units). I need to do it this way to avoid dynamic binding (when using objects) and to enable compiler to evaluate and check all such expressions statically.

My current understanding is that I should make a GADT that implements operations as type constructors, but still I'm struggling with the idea, and any hint would be greatly appreciated.

like image 623
etaoin Avatar asked Aug 30 '11 13:08

etaoin


People also ask

Is OCaml strongly typed?

Object-oriented programming: OCaml allows for writing programs in an object-oriented style. In keeping with the language's philosophy, the object-oriented layer obeys the "strong typing" paradigm, which makes it impossible to send a message to an object that cannot answer it.

How does OCaml type inference work?

The OCaml type reconstruction algorithm attempts to never reject a program that could type check, if the programmer had written down types. It also attempts never to accept a program that cannot possibly type check.

What does :: mean in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.


2 Answers

You may also be interested in the article Many Holes in Hindley-Milner, by Sam Lindley, from the 2008 Workshop on ML.

like image 112
Pascal Cuoq Avatar answered Oct 11 '22 22:10

Pascal Cuoq


You might be able to use one of Oleg's many amazing constructions: http://caml.inria.fr/pub/ml-archives/caml-list/2009/07/2984f23799f442d0579faacbf4e6e904.en.html

Jane Street has another suggestion using first-class modules.

http://ocaml.janestreet.com/?q=node/81

Disclaimer: I mostly admire this kind of programming from afar.

like image 26
Jeffrey Scofield Avatar answered Oct 11 '22 23:10

Jeffrey Scofield