OCaml cons (::) operator?
Asked Answered
R

4

21

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?

Riba answered 20/10, 2013 at 13:18 Comment(1)
It would work if you surround the arguments with parenthesis, like so: (::) (1, [2; 3; 4]);;Restrictive
H
13

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
Hautegaronne answered 20/10, 2013 at 14:27 Comment(1)
For reference, the knowledge is introduced by [caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html#toc50] section Variants.Dallapiccola
R
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.

Rickart answered 21/10, 2013 at 3:45 Comment(1)
This is still working in 4.11 so did it not get removed after all?Norword
H
13

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
Hautegaronne answered 20/10, 2013 at 14:27 Comment(1)
For reference, the knowledge is introduced by [caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html#toc50] section Variants.Dallapiccola
B
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.

Bladder answered 21/8, 2018 at 10:38 Comment(0)
E
-1

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

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

Espinoza answered 19/6, 2022 at 17:18 Comment(2)
Welcome to SO! I think this answer is subsumed by that of @Hautegaronne (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).Stockstill
True, sorry to reiterate that's my badEspinoza

© 2022 - 2024 — McMap. All rights reserved.