OCaml cons (::) operator?

Alan C picture Alan C · Oct 20, 2013 · Viewed 11.2k times · Source

In OCaml, is there a way to refer to the cons operator by itself?

For example, I can use (+) and ( * ) as int -> int -> int functions, but I cannot use (::) as a 'a -> 'a list -> 'a list function, as the following example show:

# (+) 3 5;;
- : int = 8
# ( * ) 4 6;;
- : int = 24
# (::) 1 [2;3;4];;
Error: Syntax error: operator expected.

Is there a way to produce a result like (::) other than with fun x y -> x::y? And does anyone know why (::) wasn't implemented in OCaml?

Answer

camlspotter picture camlspotter · Oct 21, 2013

Adding to the answer of @seanmcl,

Actually OCaml supports a prefix form of (::):

# (::)(1, []);;
- : int list = [1]

This is in the uncurried form, corresponding with the fact that all the OCaml variant constructors are not curried and cannot be partially applied. This is handled by a special parsing rule just for (::), which is why you got a rather strange error message Error: Syntax error: operator expected..

Update:

Upcoming OCaml 4.02 removes this parsing rule, therefore this is no longer available.