About Ocaml list type

Hi :slight_smile:

I’m a student who is learning OCaml language. I saw the implementation of type of list which is built-in type in OCaml

type 'a t = 'a list =
| []
| :: of 'a * 'a list

I have two questions:

  1. When I copy and paste whole code above in OCaml interpreter, an error is occurred with “syntax error” I think :: is a reason but the implementation uses ::. how does it work? and how can I execute?
  2. Where is the list? the name of the type is t, not list. where information of list is in?

Thank you.

Hello! Can I ask, where did you see that list implementation? In other words, where is that code from? It is indeed incorrect, the correct version is at https://github.com/ocaml/ocaml/blob/1d76e2ca91633ac63759c4672e9a8dddabac8a31/stdlib/list.ml#L17 which is using valid syntax.

The difference is that :: is considered an ‘operator’ as well as being a variant constructor, and thus needs to be defined using parentheses: (::).

As to your second question: list is a built-in type that is always available. The Stdlib.List module is aliasing the definition of the list type and calling it t, because in OCaml it’s customary for data types to be in their own modules and the actual types to be named t. There are a few exceptions, like list, option, etc. but some efforts are being made as you see to alias them into a more idiomatic module and naming convention.

1 Like

Thanks for grate explanation!

I saw the implementation here : https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html

Can I do one more question?

type a = (::) of int * int ;; is OK.

type a = (##) of int * int ;; is NOT OK.
type a = ($$) of int * int ;; is NOT OK.
type a = (%%) of int * int ;; is NOT OK… so on

Is there a rule for operator? why :: is allowed but others are not allowed ?

:: is one of a few exceptional operators that are allowed to be variant constructors in OCaml, I believe the others are [], (), true, and false (well the last two are not really operators but they fall into the same syntactic area when it comes to being variant constructors).

Other than the above, variant constructors must be alphanumeric and start with an uppercase letter.

Thank you very much :slight_smile: