我从this question得知可以使用模式匹配与记录。但是,我注意到我在尝试匹配不同类型的记录时遇到了问题。含模式匹配记录的歧义
我在这个例子中的目标是能够区分不同的记录。我得到了一个记录,我不完全确定它是哪种类型,我试图用模式匹配来解决它。
这里有一个简单的例子:
module IceCream = struct
type t = {
temperature: float;
toppings: string list;
}
end
module Candy = struct
type t = {
flavour: string;
colour: string;
volume: int;
}
end
(* Could be Candy or IceCream *)
let example =
{ Candy.
flavour = "mint";
colour = "green";
volume = 10 }
let printFavoriteTreat treat = match treat with
| { Candy.
flavour = "mint";
colour;
volume } -> "It's Candy"
| { IceCream.
temperature;
toppings } -> "It's IceCream"
let() = printFavoriteTreat example
当我尝试建立这个文件,我得到:
Error: The field IceCream.temperature belongs to the record type IceCream.t
but a field was expected belonging to the record type Candy.t
正在做这样的事情可能吗?
不同类型的模式匹配是不可能的,除非它们被嵌入到和类型(也称为变体类型,代数数据类型,区分联合)中。 – didierc