2012-08-16 80 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