OCaml error : "the variant type has no constructor ::"

OCaml error : "the variant type has no constructor ::"

我现在正在研究 OCaml,在我这样做之后,

type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list

let rec diff : aexp * string -> aexp
=fun (aexp,x) -> match aexp with
|Const a -> Const 0
|Var "x" -> Const 1
|Power ("x", a) -> (match a with
 |2 -> Times[Const 2; Var "x"]
 |1 -> Const 1
 |0 -> Const 0
 |_ -> Times[Const a; Power ("x", a-1)])
|Times [l] -> (match l with
 |h::t -> (match t with
  |Var "x" -> h
  |Power ("x",a) -> Times [Times [h;Const a];diff(Power ("x",a),x)]))

我收到一个错误:

File "", line 11, characters 3-5:

Error: The variant type aexp has no constructor ::

我了解到 :: 是将单个元素连接到列表或列表的另一个元素。

它与我使用列表的其他代码一起工作。

为什么它在这里不起作用?

您的模式 Times [l] 与一个节点 Times 匹配,且恰好有一个名为 l 的元素。你想写 Times l,它匹配一个节点 Times 和一个包含任意数量元素的列表,绑定到子句正文中的 l

请注意,在 OCaml 中您可以使用嵌套模式匹配,例如:

| Times (Var "x" :: _) -> h
| Times (Power ("x",a) :: _ ) -> ...
| ...