接口中的子类型约束 [英] Subtype constraints in interfaces

查看:117
本文介绍了接口中的子类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在几个模块中撰写几个特征。函数可能需要多个这样的特征作为其输入,即:

I want to compose several "traits" across several modules. A function might require multiple such "traits" as its input, i.e.:

type 'a x_t = < get_x : int ; .. > as 'a constraint 'a = < get_b : float ; .. >
val foo : x_t -> float 

在界面中手动编写这些特征既麻烦又容易出错,但完全可能。

composing these traits manually in the interface is cumbersome and error-prone, but perfectly possible.

但在一个理想的世界中,我应该能够使用特征而不是手动编写所有必需的字段,即写出如下内容:

But in an ideal world, I should be able to use the "trait's" name instead of manually composing all the required fields, i.e. write something like:

 type 'a x_t = < get_x : int ; .. > as 'a constraint 'a <: a_t

不幸的是,OCaml语法不允许这样做。这个似乎是纯粹的语法限制,所以我想知道是否有更深层次的原因?

Unfortunately, the OCaml syntax does not allow for this. This seems to be a purely syntactical restriction, so I wonder whether there is a deeper reason for this?

换句话说:为什么可以'我是否直接在OCaml类型签名中编写子类型约束?

In other words: Why can't I directly write subtype constraints in OCaml type signatures?

编辑:澄清用例:我有几个(有时是相互依赖的)模块,它们提供了一些共同的共享功能州。这些模块应该是可组合的并且松散耦合(即,仅需要它们的全局状态部分来满足它们的需要,因此,我总是可以用新功能扩展状态)。为了实现这一目标,将状态封装在一个提供多个镜头的物体中(上面我只使用了吸气剂,而不是定位器)。因此,如果我为我的模块提供接口定义,我需要通过对编码整个状态类型的类型参数的约束来描述我的函数签名中所需的镜头。现在我正在寻找一种方法来编写这些组合的签名要求尽可能简短和可读。

edit: To clarify the use-case: I have several (sometimes interdependent) modules which provide functionality on some common shared state. These modules shall be composable and loosely coupled (i.e., the only require their part of the global state to fulfill their needs and thus, I can always extend the state with new functionality). To achive this, the state is encapsulated in an object which provides several lenses (above I only used the getters, not the setters). Hence, if I provide interface definitions for my modules I need to describe the required lenses in the signature of my functions via constraints on the type parameter that encodes the whole state type. Now I am searching for a way to write these composed signature requirements as short and readable as possible.

推荐答案

如果将特征定义为类类型而不是对象类型,则可以使用 #foo 语法。

If you define your traits as class types instead of object types, you can use the #foo syntax.

class type b = object
  method get_b : float
end

class type c = object
  method get_c : bool
end

type 'a x_t = < .. > as 'a 
  constraint 'a = #b
  constraint 'a = #c

您还可以通过继承机制编写特征:

You can also compose traits through the inheritance mechanism:

class type e = object
  inherit b inherit c
end

(看起来类型太聪明了,但为什么不试验...)

(Looks like types that are too clever for their own good, but why not experiment...)

这篇关于接口中的子类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆