替代图案与可变结合匹配?(Alternative pattern matching with var

2019-10-18 03:11发布

我尝试实施了,我也想对阵一些模式方面的等价关系。 但是我的关系是对称的,因此,模式匹配必须反映这一点。

看看下面的例子:

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

然而,如上所述例如,在这里 ,这是不允许的。 是否有人有这样那样的问题一个很好的解决方案? 任何帮助/指针高度赞赏。

Answer 1:

你可以创建一个这样自己不应用方法:

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


文章来源: Alternative pattern matching with variable binding?
标签: scala