types - 结构可以在标准 ML 中实现多个签名吗?

标签 types sml

我最近想知道标准 ML 结构是否可以实现多个签名,类似于一个类如何在 Java 中实现多个接口(interface)。快速搜索显示 this web page Bob Harper 说这确实是可能的(强调我的):

[...] the relationship between signatures and structures in ML is many-to-many, whereas in some languages (such as Modula-2) the relationship is one-to-one or many-to-one. This means that in ML a signature may serve as the interface for many different structures, and that a structure may implement many different signatures.

但是,我找不到语法,粗略地查看修改后的定义中的模块语法似乎不支持上述引用。

我的问题是:

  1. 这可能吗?
  2. 如果是,语法是什么?

编辑:经过一番尝试,我认为 Bob Harper 实际上指的是签名匹配。这个片段是一个小例子,其中一个结构被发现与两个不同的签名相匹配:

signature S1 = sig val s1 : int end
signature S2 = sig val s2 : string end

functor F1 (A : S1) = struct val f1 = A.s1 end
functor F2 (B : S2) = struct val f2 = B.s2 end

structure C =
struct
  val s1 = 1
  val s2 = "1"
end

structure F1C = F1 (C)
structure F2C = F2 (C)

在这一点上,我假设,是的,一个结构可以被视为实现多个签名,但是没有办法在结构声明中使用签名规范来强制执行,例如:

structure C : S1 and S2 = ...

最佳答案

没有语法可以用单个注解强制执行它,但是你可以,例如做

structure C = struct ... end
structure C1 : S1 = C
structure C2 : S2 = C

如果您只是想进行健全性检查但避免使用辅助结构名称污染作用域,您可以将它们设为本地:

structure C = struct ... end
local
  structure C1 : S1 = C
  structure C2 : S2 = C
in end

不幸的是,不能在结构绑定(bind)中使用通配符...

您建议的符号会很棘手,因为它实际上会在签名上引入交集运算符。这具有深远的影响。考虑一下,例如:

signature S1 = sig type 'a t; val v : int t; val w : string t end
signature S2 = sig val v : int end
functor F (X : S1 and S2) = (* what is X.t here? *)

X.t 的类型有两种可能的解决方案,以便 X.v 的类型与两个签名一致:要么

type 'a t = int

type 'a t = 'a

问题是它们是无可比拟的,也就是说,没有一个比另一个更好。在一种情况下 X.w 是一个整数,在另一种情况下是一个字符串。本质上,这里发生的事情是您将通过后门引入一种高阶统一形式,这在一般情况下是不可判定的。

关于types - 结构可以在标准 ML 中实现多个签名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28788873/

相关文章:

swift - 在 Swift 中,如何获取 `Any` 变量的真实大小?

c# - 你如何解决类型和对象之间常见的命名冲突?

sml - val it = () : unit mean in SML? 是什么意思

sorting - 在 SML 中使用 Foldl 或 Foldr 编写冒泡排序

list - 记录列表上的 SML 功能

sml - SML中的 curry 匿名函数

javascript - 可以在这个特定的功能上下文中强制执行类型吗?

scala - F-Bounded Polymorphic 类型和非泛型子类型的存在类型?

function - 发送中缀运算符作为参数时 F# 类型不匹配

debugging - 在仿函数应用后查看 Polyml 中泛型的特化/子类型