Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml nested structure

Tags:

types

ocaml

I'm pretty new to OCaml, but I was curious if a type declaration like the following is possible:

type some_type = {
  list_of_things: {
    amount: integer;
    date: string;
  } list;
};;

I'm sure I'm doing something wrong, but just wanted to know. Thanks!

like image 212
Jay Avatar asked Feb 04 '23 15:02

Jay


1 Answers

Nested structures are perfectly possible, however record types need to be defined before being used:

type transaction = {
    amount: integer;
    date: string;
  }

type some_type = {
  list_of_things: transaction list;
}

One reason is that OCaml type system is nominal (outside of the object system and module system): types are defined by their names, not by their contents. Consequently the type of the element of the list list_of_things needs to be defined, ie. named, somewhere.

It is also perfectly possible to define mutually recursive records:

type transaction = {
    amount: integer;
    date: string;
    other: some_type
  }

and some_type = {
  list_of_things: transaction list;
}

Starting with OCaml 4.03, it is also possible to define inlined record type within the definition of a sum type, for instance:

type tree = Leaf | Node of { left:tree; right:tree}

However, inlined records are not completely first-class, and cannot be used outside of the context of their constructor, because they lack a proper name.

like image 78
octachron Avatar answered Feb 15 '23 12:02

octachron