2015-10-09 104 views
1

我正在學習OCaml的,現在,我做到這一點後,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 ::

我瞭解到::是單個元素與列表或列表的另一個元素的串聯。

它與我使用列表的其他代碼一起工作。

爲什麼它不在這裏工作?

回答

0

您的模式Times [l]與節點Times匹配,並且只有一個元素名稱爲l。你想寫Times l,該節點與節點Times相匹配,其中包含任何數量元素的列表,綁定到子句主體中的l

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

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

嗨,THX的答案。它解決了錯誤信息,但現在出現了其他錯誤消息。我會在另一個問題調查中再次提出這個問題。 –

相關問題