本文介绍了如何合并定义相同类型的OCaml模块类型(签名)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在OCaml中,我有两种定义类型t的模块类型:

In OCaml, I have two module types defining a type t:

module type Asig = sig
    type t
    val a : t
end

module type Bsig = sig
    type t
    val b : t
end

我想自动创建合并它们的模块类型.我想创建一个等效于以下模块的类型:

I want to automate the creation of a module type merging them. I want to create a module type equivalent to:

module type ABsig_manual = sig
    type t
    val a : t
    val b : t
end

我尝试过

module type ABsig = sig
    include Asig
    include Bsig
end

,但这失败,并显示Error: Multiple definition of the type name t.似乎不可能在include中添加类型约束,所以我被困住了.

but this fails with Error: Multiple definition of the type name t. It seems impossible to add a type constraint to the include so I'm stuck.

上下文:我有一个模块AB,它确实实现了两个签名,我想将其提供给仿函数,例如:

Context: I have a module AB that does implement both signatures and I want to feed it to a functor like:

module MakeC(AB) = struct
    type t = AB.t list
    let c = [AB.a; AB.b]
end

module C = MakeC(AB)

我可以使用两个参数,例如:

I could use two arguments like in:

module UglyMakeC(A : Asig)(B : Bsig with type t = A.t) = struct
    type t = A.t list
    let c = [A.a; B.b]
end

module C = UglyMakeC(AB)(AB)

但这很丑陋,无法很好地扩展到更多函子或更多签名以进行合并.

but this (is ugly and) doesn't scale well to more functors or more signatures to merge.

那么,如何自动合并这两种模块类型?我可以根据需要修改A和B,但我想将它们分开.另外,也许我的方法是完全错误的,在那种情况下,我希望指针指向一个更好的方向.

So, how can I automate merging those two module types? I can modify A and B as needed but I want to keep them separated. Also, maybe my approach is completely wrong, and in that case I'd love pointers to a better direction.

OCaml中的类型共享-类型检查器错误是相关的,但是合并模块,而不是模块类型.

Type sharing in OCaml - typechecker error is related but merges modules, not module types.

推荐答案

这是实现此目的的方法:

Here is the way to do it :

module type Asig = sig
    type t
    val a : t
end

module type Bsig = sig
    type t
    val b : t
end

module type ABsig = sig
    include Asig
    include Bsig with type t := t
end

它被称为破坏性替代".

It's called "destructive substitution".

这篇关于如何合并定义相同类型的OCaml模块类型(签名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:22