【发布时间】:2017-07-04 11:54:32
【问题描述】:
我从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
这样的事情可能吗?
【问题讨论】:
-
不可能对不同类型进行模式匹配,除非它们嵌入到 sum 类型(也称为变体类型、代数数据类型、可区分联合)中。
标签: ocaml