我试图了解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
?
答案 0 :(得分:2)
由于{name = "Ron Smith"}
是person
,但您需要family_tree
定义为Person person
,并且您需要同时指定变体名称:
let ron: family_tree = Person {name = "Ron Smith"; ... }
否则,您无法将family_tree
区分为Person
和person
。