Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml cons (::) operator?

Tags:

ocaml

cons

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?

like image 966
Alan C Avatar asked Oct 20 '13 13:10

Alan C


People also ask

What does cons mean in OCaml?

Cons (::) is a constructor, constructors can not be infix operators.

How do I remove an item from a list in OCaml?

Lists in OCaml are immutable. So you can't remove things from them. You normally create another list that doesn't have the things you don't want.

What does Fold_right do in OCaml?

The function List. fold_right in OCaml “folds” a list to a single element via an operation.


2 Answers

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.

like image 67
camlspotter Avatar answered Sep 20 '22 22:09

camlspotter


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
like image 43
seanmcl Avatar answered Sep 19 '22 22:09

seanmcl