2010-02-15 78 views

回答

51

是的,它使用關鍵字if。從斯卡拉之旅的Case Classes部分,靠近底部:

def isIdentityFun(term: Term): Boolean = term match { 
    case Fun(x, Var(y)) if x == y => true 
    case _ => false 
} 

(這不是Pattern Matching頁提到,也許是因爲旅遊就是這樣一個快速瀏覽。)


在Haskell中,otherwise實際上只是一個綁定到True的變量。所以它不會爲模式匹配的概念添加任何力量。你可以通過重複你的初始模式沒有後衛得到它:

// if this is your guarded match 
    case Fun(x, Var(y)) if x == y => true 
// and this is your 'otherwise' match 
    case Fun(x, Var(y)) if true => false 
// you could just write this: 
    case Fun(x, Var(y)) => false 
19

是的,有花紋守衛。他們使用的是這樣的:

def boundedInt(min:Int, max: Int): Int => Int = { 
    case n if n>max => max 
    case n if n<min => min 
    case n => n 
} 

注意,而不是otherwise -clause,只需specifiy格局沒有保護。

+0

在這種情況下,'n'是什麼,請給出一個工作示例。 – Jet

+1

@Jet'n'將作爲該函數的參數。 [Here](http://ideone.com/HhSuF0)是使用該函數的一個例子。 – sepp2k

+0

明白了,謝謝:-) – Jet

8

簡單的答案是否定的。這不正是你正在尋找的(與Haskell語法完全匹配)。你可以使用Scala的「匹配」的聲明與保護,並提供一張外卡,如:

num match { 
    case 0 => "Zero" 
    case n if n > -1 =>"Positive number" 
    case _ => "Negative number" 
} 
3

我無意中發現這個帖子尋找如何衛士適用於具有多個參數匹配,它是不是真的直觀,所以我在這裏添加一個隨機的例子。

def func(x: Int, y: Int): String = (x, y) match { 
    case (_, 0) | (0, _) => "Zero" 
    case (x, _) if x > -1 => "Positive number" 
    case (_, y) if y < 0 => "Negative number" 
    case (_, _) => "Could not classify" 
} 

println(func(10,-1)) 
println(func(-10,1)) 
println(func(-10,0))