OCaml 如何在重复的类型构造函数之间进行选择

OCaml how to choose between repeated type constructors

在 Ocaml 中,我在两个类型定义中使用相同的类型构造函数名称。喜欢:

type a=
     ...
   | The_constructor of ... 
   |  ...

type b:
     ...
   | The_constructor of ... 
   |  ...

当我用它作为(fun x-> The_constructor(x))时,the_constructor被直接赋值为'b'(猜测是因为它是最后一个),但我希望它是'a'。这是一种方法吗?我尝试了 (a.The_constructor) 之类的方法,但没有用。

提前致谢!

您需要在不同的模块中定义类型:

module A = struct
  type t=
    ...
    | The_constructor of ... 
    | ...
end 

module B = struct
  type t=
    ...
    | The_constructor of ... 
    | ...
end 

然后你可以选择你想要的类型:

let a = A.The_constructor x in
let b = B.The_constructor x in
...

确实,如果不能确定消歧,你会得到最新定义的构造函数。正如 Anthony 指出的那样,您可以通过在模块中定义类型来消除歧义。您还可以添加类型注释以帮助打字系统。

(* y has type `a` *)
let y : a = The_constructor x

(* a function from "whatever" to type `a` *)
((fun x -> The_constructor x) : _ -> a)

(* f returns a `a` (same function as the other one) *)
let f x : a = The_constructor x