您是否考虑过将限制表示为一种不同的结构?这种嵌套确实是可能的,但它看起来像你可以使用HList
.
与其以这种方式表示 refs,不如简单地Node
使用以下内容来实现。我在这里提供了一些通用示例,说明使用超级简单的无形图案可以做什么。
如果您可以更具体地了解要求,我相信这里的许多人可以提供更多帮助,我的直觉告诉我有一种更简单的方法HList
可以解决您的问题,而无需任何讨厌的类型杂耍。
import shapeless._
import shapeless.ops.hlist._
import shapeless.::
class Node[P <: Hlist](hl: P) {
def append[T](obj: T): Node[P :: T] = new Node[P :: T](hl :: obj)
// Much like a normal List, HList will prepend by default.
// Meaning you need to reverse to get the input order.
def reverse[Out]()(
implicit rev: Reverse.Aux[P, Out]
): Out = rev(hl)
// you can enforce type restrictions with equality evidence.
// For instance you can use this to build a chain
// and then make sure the input type matches the user input type.
def equalsFancy[V1 <: Product, Rev, Out <: Product](v1: V1)(
// We inverse the type of the HList to destructure it
// and get the initial order.
implicit rev: Reverse.Aux[P, Rev],
// then convert it to a tuple for example.
tp: Tupler.Aux[Rev, Out],
ev: V1 =:= Out
): Boolean = tp(hl) == v1
}
object Node {
def apply: Node[HNil] = new Node[HNil]
Node().append[String]("test").append[Int](5).equalsFancy("test" -> 5)
}
也很容易将列表中的类型元素限制为仅Node
使用 an 的子类型LUBConstraint
。(类型的下限)。
class NodeList[HL <: HList](list: Node[_] :: HL)(implicit val c: LUBConstraint[HL, Node[_])
这将意味着你不能再附加那些不可以_ <:< Node[_]
给NodeList
你一些Poly
细节的元素。
trait A
trait B
object printPoly extends Poly1 {
// Let's assume these are your A, B and Cs
// You can use Poly to define type specific behaviour.
implicit def caseNodeA[N <: Node[A]] = at[N](node => println("This is an A node"))
implicit def caseNodeB[N <: Node[B]] = at[N](node => println("This is a B node"))
implicit def unknown[N <: Node[_]] = at[N](node => println("This is not known to us yet"))
}
val nodeList: NodeList[..] = ..
nodeList.list.map(printPoly)
更新
那么值得实现一个树状结构。
case class Node[A, F <: HList](value: A, children: F) {
def addChild[T, FF <: HList](
child: Node[T, FF]
): Node[A, HTree[T, FF] :: F] = {
new Node(value, child :: children)
}
def values = Node.Values(this)
}
object Node {
def apply[A](label: A) = new Node[A, HNil](label, HNil)
object Values extends Poly1 {
implicit def caseHTree[A, F <: HList, M <: HList](
implicit fm: FlatMapper.Aux[getLabels.type, F, M],
prepend: Prepend[A :: HNil, M]
): Case.Aux[HTree[A, F], prepend.Out] =
at[HTree[A, F]](tree => prepend(
tree.value :: HNil,
fm(tree.children))
)
}
}