Scala shapeless KList with extra constraint

混江龙づ霸主 提交于 2019-12-04 14:40:42

It looks like what you are doing is just trying to get the compiler to check that the types agree, since your methods ALWAYS return true.

Can you perhaps, instead of making methods which accept an arbitrary number of these, accept a "List of RLists" which is guaranteed to have S all matching?

Here is how such a list might be constructed:

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)
}

Now, if we try to construct a RListList that doesn't have all the S types agreeing, the compiler will catch us:

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

}

This is using dependent method types, which means you need to use scala 2.10 or you need to compile with the -Ydependent-method-types switch in 2.9.x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!