2012-08-16 31 views
8

是否可以將案例模式作爲參數傳遞給其他函數?類似這樣的:斯卡拉案例模式頭等艙嗎?

def foo(pattern: someMagicType) { 
    x match { 
    pattern => println("match") 
    } 
} 

def bar() { 
    foo(case List(a, b, c)) 
} 
+0

我使用Scala 2.10的'Try'發揮各地,你改變了你的問題之前。也許你仍然覺得很有用:http://stackoverflow.com/questions/11990017/threading-trys-through-for-comprehension – 2012-08-16 15:57:34

回答

3

我認爲金Stebel的第一個答案是接近你想要什麼。 「模式匹配」在Scala中不是孤立的實體。匹配可以是,其定義爲 a Function1PartialFunction

def foo[A, B](x: A)(pattern: PartialFunction[A, B]): Unit = 
    if(pattern.isDefinedAt(x)) println("match") 

def bar(list: List[String]): Unit = 
    foo(list){ case List("a", "b", "c") => } 

測試:

bar(Nil) 
bar(List("a", "b", "c")) 

或者使用組成:

def foo[A, B](x: A)(pattern: PartialFunction[A, B]): Unit = { 
    val y = pattern andThen { _ => println("match")} 
    if (y.isDefinedAt(x)) y(x) 
} 
4

所以你想傳遞一個模式匹配塊到另一個函數?可與PartialFunction s內完成,如下例所示:

def foo(f:PartialFunction[String, Int]) = { 
    f("") 
} 

foo { 
    case "" => 0 
    case s => s.toInt 
} 
0

你的魔法類型可以寫成一個具有不應用方法的結構類型。根據您需要的提取器類型,您將需要不同種類的unapplyunapplySeq。下面是一個簡單的例子。

def foo(x:Int, Pattern: { def unapply(x:Int):Boolean }) { 
    x match { 
    case Pattern => println("match") 
    } 
} 

foo(1, new { def unapply(x:Int) = x > 0 }) 

,這是它是如何對列表進行:

foo(List(1,2,3), new { def unapplySeq(x:List[Int]):Option[List[Int]] = if (x.size >= 3) Some(x) else None }) 

def foo(x:List[Int], Pattern: { def unapplySeq(x:List[Int]):Option[List[Int]] }) { 
    x match { 
    case Pattern(a,b,c) => println("match: " + a + b + c) 
    } 
} 
+0

foo(1,...'''位在REPL(我使用2.9.2),它引導我進行了一次有趣的討論:http://www.scala-lang.org/node/10730 – opyate 2012-08-17 07:34:22

+0

實際上,它也沒有編譯。你使用了哪個版本的Scala,@金? – opyate 2012-08-17 07:47:33