这个问题通常发生在使用F#中的类型约束时。
例如,假设有以下类型定义:
type Animal =
| Cat of string
| Dog of string
type PetShop<'a> =
member this.Pets : 'a list -> Animal list
然后,我们定义了一个函数,该函数想要将类型为 'a list -> Animal list 的 PetShop 绑定到类型为 'T list 的 customers:
let printPets (customers: 'T list) (petShop: PetShop<'a>) =
match petShop.Pets with
| [] -> printfn "No pets found."
| pets ->
pets |> List.iter (fun pet -> printfn "A %s was found." pet)
这会导致编译器抛出上述类型比较错误。要解决这个问题,请使用适当的类型约束来定义函数:
let printPets<'a, 'b when 'b :> Animal> (customers: 'a list) (petShop: PetShop<'b>) =
match petShop.Pets customers with
| [] -> printfn "No pets found."
| pets ->
pets |> List.iter (fun pet -> printfn "A %s was found." pet)
在这里,我们添加了泛型类型参数 'b,该类型约束了类型必须是派生自 Animal 类型的类型。我们也添加了类型约束 'a,指示客户列表的类型。这会消除类型比较错误并使代码工作。