1

我尝试在我也想与某些模式匹配的术语上实现等价关系。但是我的关系是对称的,因此模式匹配也必须反映这一点。

看看下面的例子:

abstract class Term
case class Constructor(txt:String) extends Term
case class Variable(txt:String) extends Term

case class Equality(t1:Term, t2:Term)

def foobar(e:Equality) = e match {
    case Equality(Variable(x),Constructor(y)) => "do something rather complicated with x and y"
    case Equality(Constructor(y),Variable(x)) => "do it all over again"
}

事实上我想做这样的事情

def foobar(e:Equality) = e match {
    case Equality(Variable(x),Constructor(y)) | Equality(Constructor(y),Variable(x)) 
        => "yeah! this time we need to write the code only one time ;-)"
}

但是,如此所述,这是不允许的。有人对这类问题有很好的解决方案吗?任何帮助/指针都非常感谢。

4

1 回答 1

0

您可以像这样创建自己的 unapply 方法:

object CVEquality {
  def unapply(e: Equality): Option(String, String) = e match {
    case Equality(Variable(v), Constructor(c)) => Some(c -> v)
    case Equality(Constructor(c), Variable(v)) => Some(c -> v)
    case _ => None
  }
}

用法:

def foobar(e:Equality) = e match {
    case CVEquality(c, v) => "do something rather complicated with c and v"
}

最简单的方法是创建方法something rather complicated

def complicated(c: String, v: String) = "do something rather complicated with c and v"

def foobar(e:Equality) = e match {
    case Equality(Variable(x),Constructor(y)) => complicated(y, x)
    case Equality(Constructor(y),Variable(x)) => complicated(y, x)
}
于 2013-05-07T21:31:39.140 回答