【发布时间】:2014-05-23 02:01:35
【问题描述】:
我想通过一个自定义的通用 unapply 函数来压缩我的评估器,它评估参数并在成功时返回值。
但这会失败并出现错误error: not found: type Eval
有什么方法可以实现吗?我看过typetags、implicit conversions for unapply methods,但我不知道如何将它们整合到这个问题中。如何正确定义 Eval?
object Test {
case class Context()
trait Expr
trait Literal[T] extends Expr{
def value : T
}
case class IntLiteral(value: Int) extends Literal[Int]
case class StringLiteral(value: Int) extends Literal[Int]
case class Plus(e: Expr, f: Expr) extends Expr
object Eval { // Here I want the magic unapply to evaluate the expression.
def unapply[T](e: Expr)(implicit gctx: Context): Option[T] = {
eval(e) match {
case e: Literal[T] => Some(e.value)
case _ => None
}
}
}
def eval(e: Expr)(implicit c: Context): Expr = e match {
case Plus(Eval[Int](i), Eval[Int](j)) => IntLiteral(i+j) // Fails here.
case IntLiteral(i) => e
case StringLiteral(s) => e
}
eval(Plus(Plus(IntLiteral(1),IntLiteral(2)),IntLiteral(3)))(Context())
}
【问题讨论】:
-
对这个问题也很感兴趣...