2013-05-07 127 views
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 ;-)" 
} 

然而,正如例如注意在here,這是不允許的。有人對這類問題有一個很好的解決方案嗎?任何幫助/指針非常感謝。

回答

0

你可以創建自己的不應用方法是這樣的:

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

我懷疑我必須像你的答案中描述的那樣做,但希望有一個簡單的解決方案:D無論如何,我更喜歡你的第二個想法更多b因爲我希望編譯器能夠使用後向追蹤,即如果有其他幾十個其他案例語句,就會產生更高效的代碼。 – 2013-05-12 07:29:06