我從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