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

OCaml: Why use custom data types?

Why do we use custom data types like:
type vegetables = (string * classification)

Can I use it? Can I create a vegetables list?

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 :

This is not a custom data type but just a type alias, much like we name values, e.g.,

let pi = 3.14
let country = "USA"

we can give names to types to make it easier to read and understand code, e.g.,

type point = float * float
type range = float

The type vegetables = (string * classification) alias just says that we give name vegetables for the pair of string and classification. And we can refer to this type either by the new name or by the old name, it doesn’t matter, though the new name is shorter and more informative.

You can build list of elements of any type in OCaml using the same syntax, [<elt1>; <elt2>; ...; <eltN>], and pairs are in OCaml created with the following syntax, e.g., (<x>,<y>).

There is also a special syntax for a list of pairs, which is [<x1>,<y1>; <x2>,<y2>; ...; <xN>,<yN>], e.g.,

let locations : point list = [
  1.2, 3.4;
  5.6, 7.8;
  pi, 0.1;
]
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