我现在正在学习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)]))
我得到一个错误:
文件",第11行,字符3-5:
错误:变量类型aexp没有构造函数::
我学过::是将单个元素连接到列表或列表的另一个元素。
它与我使用list的其他代码一起工作。
为什么这里不工作?
模式Times [l]
将节点Times
与一个名为l
的元素匹配。您想要编写Times l
,它将节点Times
与包含任意数量元素的列表相匹配,并在子句体中绑定到l
。
| Times (Var "x" :: _) -> h
| Times (Power ("x",a) :: _ ) -> ...
| ...