Jay
Jay

Reputation: 1056

OCaml nested structure

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!

Upvotes: 4

Views: 1293

Answers (1)

octachron
octachron

Reputation: 18892

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.

Upvotes: 8

Related Questions