Search code examples
ocamlcons

OCaml cons (::) operator?


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?


Solution

  • No. Cons (::) is a constructor, constructors can not be infix operators. The allowed infix symbols are here:

    http://caml.inria.fr/pub/docs/manual-caml-light/node4.9.html

    Some workarounds are (as you mention) the verbose

    (fun x l -> x :: l)
    

    and defining your own nontraditional infix cons

    let (+:) x l = x :: l