微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

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

谢谢!

解决方法

的确,如果不能确定歧义性,您将获得最新定义的构造函数。正如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
,

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

dat2

,然后您可以选择所需的类型:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。