Domanda

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?

È stato utile?

Soluzione 2

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

Altri suggerimenti

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.

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.

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top