为什么这很好用?
module Account = struct
type account_type = Current of float | Savings of float
end
let sarah = Account.Current 100.0;;
虽然下面的最后一行产生
Error: syntax error
?module Account = struct
type 'a account_type = [> `Current of float | `Savings of float ] as 'a
end
let pete = Account.`Current 100.0;;
也就是为什么不打开模块就不能在模块外使用open union类型呢?我应该说我发现将最后一行更改为:
open Account;;
let pete = `Current 100.0;;
工作正常,但如果我使用
account_type
显然这很麻烦很多,或者我必须打开Account
在任何代码段的开头,其中 account_type
被使用,这意味着我会牺牲我通过使用 Account
的签名来获得的抽象。我浏览了几个 OCaml 教程以及 INRIA 文档,但我找不到任何关于你如何做到这一点的提及。
是否可以避免每次我想使用
account_type
时都必须打开模块? ?提前致谢,
扎克
最佳答案
在第二个示例中,您实际上不必 open Account
语法就是 `Current 100.0
.多态变体标签不参与任何特定类型。 `Current
的类型是 [> `Current ]
, 这 (>
) 表示类型至少为 `Current
,并且由于这是函数接受的类型的子集,因此它可以编译得很好。您可以将相同的值传递给许多接受同名多态变体的函数。当然,缺少静态类型信息,键入错误和情况会变得相当复杂。
Code Reuse through polymorphic variants谈论它们的一些优点和用例。
关于types - 在定义它们的模块之外使用开放联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918438/