2016-02-03 41 views
0

scala中函數頭的模式匹配是否可能?scala中函數參數的模式匹配

例如,可我寫的線沿線的東西:

def myFunction(a:: b:: xs): Int = ??? 
def myFunction(a:: xs): Int = ??? 
def myFunction(List.empty): Int = ??? 
+3

很酷的想法,但遺憾的是沒有 - 問題是,你只能定義具有特定簽名的一次函數(沒有什麼編譯器糖這件事爲你)。你當然可以有'def foo(ls)= ls match {..' – Hamish

+0

謝謝。這在Erlang中有效,所以我希望有一個等價的方法來避免嵌套的case語句。 –

+2

相關:http://stackoverflow.com/questions/14803222/is-there-any-fundamental-limitations-that-stops-scala-from-implementing-pattern/14810638#14810638 –

回答

2

您可以使用部分功能,對於這種情況。例如:

val myFunctionCase1: PartialFunction[List[Int], Int] = { 
    case a :: b :: xs => ??? 
    } 

    val myFunctionCase2: PartialFunction[List[Int], Int] = { 
    case a :: xs => ??? 
    } 

    val myFunctionCase3: PartialFunction[List[Int], Int] = { 
    case Nil => ??? 
    } 

    // compose functions 
    val myFunction: List[Int] => Int = 
       myFunctionCase1 orElse myFunctionCase2 orElse myFunctionCase3 

使用示例:

myFunctionCase1(List(1,2,3)) // invoke 
myFunctionCase1(List(1))  // throw MatchError 
myFunctionCase2(List(1))  // invoke 
... 

myFunction(List(1,2,3)) 
myFunction(List(1))  
myFunction(Nil) 
... 
+0

沒有必要定義幾個部分函數,部分函數可以有多個case作爲匹配表達式。 (而且我不認爲有必要在這裏分開處理)。然而,我寧願寫一個正常的定義,並在這種情況下使用匹配表達式,即def func(l:List [Int])= l match {...} – dth