在 F# 程序中我更喜欢使用
[<RequireQualifiedAccess>]
type MyType =
| FirstOption of string
| SecondOption of int
因此,在使用MyType
的代码中,我被迫编写MyType.FirstOption
,而不仅仅是FirstOption
。有没有办法在 OCaml 中强制执行此操作?
最佳答案
您可以通过在模块中定义类型来获得类似的效果。
$ ocaml
OCaml version 4.02.1
# module MyType = struct
type t = FirstOption of string | SecondOption of int
end ;;
module MyType : sig type t = FirstOption of string | SecondOption of int end
# MyType.FirstOption "abc";;
- : MyType.t = MyType.FirstOption "abc"
# FirstOption "abc";;
Error: Unbound constructor FirstOption
#
如果您这样做,类型的名称(如您所见)是 MyType.t。
关于f# - F# 中是否存在与 DU 的 [<RequireQualifiedAccess>] 属性等效的 OCaml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564299/