8

是否可以将案例模式作为参数传递给其他函数?像这样的东西:

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

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

3 回答 3

4

所以你想将模式匹配块传递给另一个函数?这可以用PartialFunctions 来完成,如下例所示:

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

foo {
  case "" => 0
  case s => s.toInt
}
于 2012-08-16T12:20:20.997 回答
3

我认为 Kim Stebel 的第一个答案接近你想要的。“模式匹配本身”在 Scala 中不是孤立的实体。匹配可以定义为aFunction1PartialFunction

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)
}
于 2012-08-16T15:49:30.100 回答
0

您的魔法类型可以写成具有 unapply 方法的结构类型。根据您需要的提取器类型,您将需要不同类型的unapplyor unapplySeq。下面是一个简单的例子。

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)
  }
}
于 2012-08-16T14:45:51.543 回答