【问题标题】:OCaml error : "the variant type has no constructor ::"OCaml 错误:“变体类型没有构造函数 ::”
【发布时间】:2016-01-07 11:31:26
【问题描述】:

我现在正在学习 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 没有构造函数 ::

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

它适用于我使用列表的其他代码。

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

【问题讨论】:

    标签: constructor ocaml ml


    【解决方案1】:

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

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

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

    【讨论】:

    • 嗨,谢谢你的回答。它解决了错误消息,但现在弹出了其他错误消息。我会在另一个问题投票中再次问这个问题。
    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 2012-09-22
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多