Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create an instance of a custom data type in OCaml?

If I have a custom data type ‘triple’ as follows, how would I create an instance of it that I can use?

type triple = int * int * int

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is an instance:

let my_instance = (1, 2, 3)

For what it’s worth, your type is not a new type, it’s just a handy abbreviation for the pre-existing type that’s a tuple of 3 ints. A type declaration without a constructor is just an abbreviation, so not really what I’d call a "custom" type.

# ((1, 2, 3) : triple) = (1, 2, 3)
- : bool = true

I’m not sure this matters to you, but if you need a new type that’s not compatible with any other, you need a constructor. Something like this:

type triple2 = T of int * int * int

Then you can make an instance like this:

let my_instance2 = T (1, 2, 3)

This new type triple2 is not compatible with any other type (such as, say, triple):

# T (1, 2, 3) = (1, 2, 3)
Error: This expression has type 'a * 'b * 'c
       but an expression was expected of type triple2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading