22

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?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Alan C
  • 413
  • 1
  • 3
  • 8

4 Answers4

16

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.

camlspotter
  • 8,990
  • 23
  • 27
14

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
seanmcl
  • 9,740
  • 3
  • 39
  • 45
  • For reference, the knowledge is introduced by [http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html#toc50] section Variants. – Gqqnbig Jan 23 '14 at 05:05
7

As of Ocaml 4.03, you can now use cons (in the List module). That is, cons x xs is the same as x :: xs.

John Wickerson
  • 1,204
  • 12
  • 23
-1

It's also possible to just define your own cons function:

let cons = fun a list -> a :: list

rithvik
  • 13
  • 3
  • 1
    Welcome to SO! I think this answer is subsumed by that of @seanmcl (which shows that you can define your own function) and that of @JohnWickerson (which says that such a function named `cons` already exists in the standard library). – Maëlan Jun 23 '22 at 15:49
  • True, sorry to reiterate that's my bad – rithvik Jun 30 '22 at 00:46