OCaml变体类型:混淆编译器

时间:2014-06-11 20:04:11

标签: types ocaml

我试图了解OCaml中的变体(虽然这不是家庭作业,但这项任务取自我朋友的作业,所以请不要&#39 ;给出更正的代码)。

我有以下代码,代表一个家谱。这个想法是每个家谱都是未知的,或者是一个人;该人包含指向其他family_trees的链接。

type family_tree = Unknown | Person of person 
  and person = {name: string; year_of_birth: int; 
                mother: family_tree; father: family_tree}

然而,当我尝试实际使用代码来表示一个家庭时,我得到了错误

Error: This expression has type person but an expression was expected 
of type family_tree

产生错误的代码示例:

let ron: family_tree = {name = "Ron Smith"; year_of_birth = "1953";
                        mother = Unknown; father = Unknown}
let jim: family_tree = {name = "Jim Smith"; year_of_birth = "1983";
                        mother = Unknown; father = ron}

如何防止OCaml认为ron是person而不是family_tree

1 个答案:

答案 0 :(得分:2)

由于{name = "Ron Smith"}person,但您需要family_tree定义为Person person,并且您需要同时指定变体名称:

let ron: family_tree = Person {name = "Ron Smith"; ... }

否则,您无法将family_tree区分为Personperson