PetarMarendic
PetarMarendic

Reputation: 233

In OCaml, why is the list constructor :: not an operator

I was reading today Jason Hickey's online book "Introduction to Objective Caml" and in the chapter on Functors (page 140) I ran into the following line inside the Set functor's definition:

let add = (::)

Running the code resulted in a not very illuminating 'Syntax error' error message. After plugin in the line into ocaml toplevel I figured out that :: is in fact not an operator, but rather a type constructor.

However, from what little I know of Haskell the equivalent : constructor can be treated as an operator (function) as well.

Prelude> :t (:)
(:) :: a -> [a] -> [a]

My question is: have OCaml constructors never been first class values (implying that the code from the book was wrong from the start) and why is this the case?

Upvotes: 10

Views: 1935

Answers (1)

gasche
gasche

Reputation: 31459

In Caml Light, OCaml's predecessor, it used to be the case that constructors where promoted to functions when partially applied. I'm not exactly sure why this feature was removed when moving to OCaml, and I lament this as well, but the explanation I heard was "nobody used that". So no List.map Some foo anymore...

:: is slightly special as an algebraic datatype constructor as it is the only infix constructor (hardcoded in the parser), but otherwise behaves like any other datatype constructor.

Upvotes: 13

Related Questions