首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有额外约束的Scala无形状KList

带有额外约束的Scala无形状KList
EN

Stack Overflow用户
提问于 2012-08-21 08:24:41
回答 1查看 575关注 0票数 3

我想采用这个模式:

代码语言:javascript
复制
 def accept[T](a: RList[T]) = true
 def accept[T, V](a: RList[T], b: RList[V])(implicit ev: a.S =:= b.S) = true
 def accept[T, V, Q](a: RList[T], b: RList[V], c: RList[Q])(implicit ev: a.S =:= b.S, ev2: b.S =:= c.S) = true

但是让它接受一个KList,而不是手动覆盖所有的奇偶校验。基本上,我想说,“使用任意数量的RList,它们具有相同的S成员类型”

RList是一个包含S类型的特征。(有关RList的更多背景信息以及我为什么要这样做,请参阅:Constrain function based on origin (Path Dependent type? Type Generation?))

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-21 14:09:54

看起来您所做的只是试图让编译器检查类型是否一致,因为您的方法总是返回true。

你能不能接受一个“RLists列表”,保证S个都匹配,而不是让方法接受任意数量的匹配?

下面是这样一个列表的构建方式:

代码语言:javascript
复制
package rl {

// A simplified version of your RList:
trait RList[T] {
  type S
  def data: List[T]
}

// A list of RLists which have identical S
sealed trait RListList 

// RListNil is an empty list
trait RListNil extends RListList {
  def ::[H <: RList[_]](h: H) = rl.::[h.S,H,RListNil](h, this)
}
// there is exactly one RListNil
case object RListNil extends RListNil

// List can be a cons cell of lists sharing the same S
final case class ::[S, H <: RList[_], T <: RListList](head: H, tail: T) extends RListList {

  // We only allow you to cons another to this if we can find evidence that the S matches
  def ::[H2 <: RList[_]](h: H2)(implicit ev: =:=[h.S,S]) = rl.::[S,H2,::[S,H,T]](h, this)
}

现在,如果我们试图构造一个不是所有S类型都一致的RListList,编译器将捕获我们:

代码语言:javascript
复制
object RListTest {

  val list1 = new RList[Int] { type S = String; def data = List(1,2,3,4) }
  val list2 = new RList[String] { type S = String; def data = List("1","2","3","4") }
  val list3 = new RList[Double] { type S = Float; def data = List(1.1,2.2,3.3,4.4) }

  val listOfLists1 = list1 :: RListNil // fine
  val listOfLists2 = list2 :: listOfLists1 // still fine, since list1 and list2 have the same S
  val listOfLists3 = list3 :: listOfLists2 // compiler error: Cannot prove that java.lang.String =:= Float

}

这是使用依赖方法类型,这意味着您需要使用scala 2.10,或者需要在2.9.x中使用-Y依赖方法类型开关进行编译

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12046974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档