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:
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?
Where is the list? the name of the type is t, not list. where information of list is in?
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.
:: 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.