替代模式匹配变量绑定?

时间:2013-05-07 21:16:13

标签: scala

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

看一下以下示例:

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 ;-)"
}

然而,如上所述,在here中,这是不允许的。有人为这类问题找到了一个很好的解决方案吗?任何帮助/指针都非常受欢迎。

1 个答案:

答案 0 :(得分: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)
}