假设我有两种GADT类型。
abstract class Numbers[A]()
case class IntType() extends Numbers[Int]
abstract class Letters[A]()
case class EnglishType() extends Letters[String]
我为每种GADT类型都有一个解释器,它将为每种GADT子类型打印出说明。
trait Interpreter[ALG[_],A] {
def description(a: ALG[A]) : String
}
case class NumbersInterpreter[A]() extends Interpreter[Numbers,A] {
override def description(a: Numbers[A]): String =
a match {
case i: IntType => "Int"
}
}
case class LettersInterpreter[A]() extends Interpreter[Letters,A] {
override def description(a: Letters[A]): String =
a match {
case e: EnglishType => "English"
}
}
我希望将两个GADT合并为一个名为All的GADT
type All[A] = Numbers[A] :+: Letters[A] :+: CNil
我可以通过对所有GADT值进行硬编码来创建新的解释器。
case class DualInterpreter[A](
numbersInterpreter: NumbersInterpreter[A],
lettersInterpreter: LettersInterpreter[A]) extends Interpreter[All,A] {
override def description(a: All[A]): String =
a match {
case Inl(num) => numbersInterpreter.description(num)
case Inr(Inl(let)) => lettersInterpreter.description(let)
case _ => sys.error("Unreachable Code")
}
}
但是,我想添加一堆GADT代数和解释器,然后将它们任意组合为一个代数,因此我正在寻找一种更通用的方法来替代DualInterpreter
上述内容。我可以看到类型签名类似于
case class ArbitraryInterpreter[ALG[_]<:Coproduct,A](???) extends Interpreter[ALG,A] {
override def description(a: ALG[A]): String = ???
}
我要抽象的最主要的是description
方法内部的模式匹配,因为随着可用代数的增加,它可能变得很丑陋。它将有一个解释器,其中构造函数参数是解释器,并且基于传递到描述方法中的ALG类型,将模式匹配的委托委派给适当的解释器。
你的意思是这样吗?
// using kind projector
def merge[L[_], R[_] <: Coproduct, A](
li: Interpreter[L, A],
ri: Interpreter[R, A]
): Interpreter[Lambda[A => L[A] :+: R[A]] , A] =
new Interpreter[Lambda[A => L[A] :+: R[A]] , A] {
override def description(lr: L[A] :+: R[A]): String =
lr match {
case Inl(l) => li.description(l)
case Inr(r) => ri.description(r)
}
}
也许与
implicit class InterpreterOps[L[_], A](val l: Interpreter[L, A]) extends AnyVal {
def ++ [R[_] <: Coproduct](r: Interpreter[R, A]): Interpreter[Lambda[A => L[A] :+: R[A]] , A] = merge(l, r)
}
用作
type CNilF[A] = CNil // trick to make things consistent on kind-level
case class CNilInterpreter[A]() extends Interpreter[CNilF, A] {
override def description(a: CNilF[A]): String = ???
}
def allInterpreter[A]: Interpreter[All, A] =
// :+: is right associative, but normal methods are left associative,
// so we have to use parens
NumbersInterpreter[A]() ++ (LettersInterpreter[A]() ++ CNilInterpreter[A]())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句