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?
Cons (::) is a constructor, constructors can not be infix operators.
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.
The function List. fold_right in OCaml “folds” a list to a single element via an operation.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With