Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Thanks 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 ?


That'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.


I think that is made up syntax from the article but maybe I’m wrong.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: