3 ms·
The definition of list is: type 'a list = [] | (::) of 'a * 'a list When you write a list like: [x; y; z] This is syntactic sugar for: x::y::z::[] W
by dan-robertson 5y ago
The definition of list is:
type 'a list = [] | (::) of 'a * 'a list
When you write a list like:
[x; y; z]
This is syntactic sugar for:
x::y::z::[]
Which is syntactic sugar for:
(::) (x, (::) (y, (::) (z, [])))
One can imagine using more ordinary constructor names instead:
type 'a list = Nil | Cons of 'a * 'a list
And then the above would be:
Cons (x, Cons (y, Cons (z, Nil)))
In OCaml, data constructor names mar be either a capital letter followed by set or more capital/lower letters/underscores/apostrophes/digits, or one of the following:
[]
()
true
false
(::)
Type directed constructor disambiguating means you can do funky things like:
type 'a nonempty = (::) of 'a * 'a list
And write such a value just like you would a normal list.
- cassepipe 5y agoThanks for the detailed explanation. One more question though, when I write type 'a = 'a :: list 'a It is syntactic sugar that allows me to get the * product type for free, right ?
- dan-robertson 5y agoI think that is made up syntax from the article but maybe I’m wrong.
- yawaramin 5y agoThat's actually invalid syntax. '::' can't be used infix in a type declaration. And type application is in reverse. So it's not list 'a but 'a list.