首先,我不知道如何正確標記我的問題。這也可能是我沒有找到有用資源的原因。任何提示都非常感謝。類型類和相關類型
trait Context[T]
{
self =>
trait Rule
{
def apply(value: T): Boolean
}
implicit class RichRule[A <: Rule](a: A)
{
def and[B <: Rule](b: B): and[A, B] = self.and(a, b)
def or[B <: Rule](b: B): or[A, B] = self.or(a, b)
}
sealed trait Group[A <: Rule, B <: Rule] extends Rule
{
def a: A
def b: B
override def apply(value: T) = ???
}
case class and[A <: Rule, B <: Rule](a: A, b: B) extends Group[A, B]
case class or[A <: Rule, B <: Rule](a: A, b: B) extends Group[A, B]
}
鑑於上面的代碼中,我能以這種方式現在定義和鏈Rules
S:
new Context[String]
{
class MyRule extends Rule
{
override def apply(value: String) = true
}
case class A() extends MyRule
case class B() extends MyRule
val x1: A and B or A = A() and B() or A()
}
這個工程,我打算,但現在到了棘手的部分。我想介紹一個Type Type Combination
,它解釋瞭如何加入兩條規則。
trait Combination[-A <: Rule, -B <: Rule]
{
type Result <: Rule
def combine(a: A, b: B): Result
}
trait AndCombination[-A <: Rule, -B <: Rule] extends Combination[A, B]
trait OrCombination[-A <: Rule, -B <: Rule] extends Combination[A, B]
此類型類現在應該與操作符一起傳遞。
implicit class RichRule[A <: Rule](a: A)
{
def and[B <: Rule](b: B)(implicit c: AndCombination[A, B]): and[A, B] = ???
def or[B <: Rule](b: B)(implicit c: OrCombination[A, B]): or[A, B] = self.or(a, b)
}
哪些經過一些調整後仍在工作。
implicit val c1 = new Combination[MyRule, MyRule]
{
type Result = MyRule
def combine(a: A, b: B): MyRule = a
}
val x: A and B = A() and B()
但是,如果它變得更加複雜,事情就會崩潰。
A() and B() and A()
會引發一個隱含的缺失錯誤:缺少Combination[and[A, B], A]
。但我希望它使用它已知道如何處理(Combination[and[A, B]#Result, A]
)的and[A, B]
(type Result = MyRule
)的隱式組合的結果。
對我來說,保留組合規則val x: A and B or A
的類型信息非常重要,將它們摺疊在一起以最終結果類型很容易,但不是我想要的。
雖然這樣儘可能地接近,但編譯失敗。
trait Context[T]
{
self =>
trait Rule
trait Value extends Rule
trait Group[A <: Rule, B <: Rule] extends Rule
{
def a: A
def b: B
implicit val resolver: Resolver[_ <: Group[A, B]]
}
case class and[A <: Rule, B <: Rule](a: A, b: B)(implicit val resolver: Resolver[and[A, B]]) extends Group[A, B]
implicit class RichRule[A <: Rule](a: A)
{
def and[B <: Rule](b: B)(implicit resolver: Resolver[and[A, B]]) = self.and[A, B](a, b)
}
trait Resolver[-A <: Rule]
{
type R <: Value
def resolve(a: A): R
}
}
object O extends Context[String]
{
implicit val c1 = new Resolver[A and A]
{
override type R = A
override def resolve(a: O.and[A, A]) = ???
}
implicit def c2[A <: Value, B <: Value, C <: Value](implicit r1: Resolver[A and B]) = new Resolver[A and B and C]
{
override type R = C
override def resolve(a: A and B and C): C =
{
val x: r1.R = r1.resolve(a.a)
new c2(x)
???
}
}
class c2[A <: Value, B <: Value](val a: A)(implicit r2: Resolver[A and B]) extends Resolver[A and B]
{
override type R = B
override def resolve(a: O.and[A, B]) = a.b
}
case class A() extends Value
val x: A and A and A = A() and A() and A()
}
您正在使用什麼版本的Scala以及哪些IDE? – eliasah
2.11.6使用IntelliJ,通過sbt控制檯編譯雖然 – Taig