GADT类型为无形状副产品-如何构建具有任意数量的代数的解释器

问题描述 投票:0回答:1

假设我有两种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类型,将模式匹配的委托委托给适当的解释器。

scala shapeless gadt coproduct
1个回答
0
投票

您的意思是这样的?

// 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]())
© www.soinside.com 2019 - 2024. All rights reserved.