println ("foo") // case 1 c-6ren">
gpt4 book ai didi

scala - 具有多个匹配项的模式匹配

转载 作者:行者123 更新时间:2023-12-04 01:23:25 26 4
gpt4 key购买 nike

考虑以下 Scala 代码。

val a = "both"

a match {
case "both" | "foo" => println ("foo") // case 1
case "both" | "bar" => println ("bar") // case 2
}

我要 match工作,以便如果 a == "both" , Scala 将执行这两种情况。这是可能的还是有其他选择来实现我想要的?

最佳答案

标准模式匹配将始终只匹配一种情况。您可以通过使用模式可以被视为部分函数这一事实(请参阅 Language Specification ,第 8.5 节,模式匹配匿名函数)并定义您自己的匹配运算符来接近您想要的结果:

class MatchAll[S](scrutinee : =>S) {
def matchAll[R](patterns : PartialFunction[S,R]*) : Seq[R] = {
val evald : S = scrutinee
patterns.flatMap(_.lift(evald))
}
}

implicit def anyToMatchAll[S](scrut : =>S) : MatchAll[S] = new MatchAll[S](scrut)

def testAll(x : Int) : Seq[String] = x matchAll (
{ case 2 => "two" },
{ case x if x % 2 == 0 => "even" },
{ case x if x % 2 == 1 => "neither" }
)

println(testAll(42).mkString(",")) // prints 'even'
println(testAll(2).mkString(",")) // prints 'two,even'
println(testAll(1).mkString(",")) // prints 'neither'

语法略有不同,但对我来说,这样的结构仍然是 Scala 强大功能的见证。

你的例子现在写成:
// prints both 'foo' and 'bar'
"both" matchAll (
{ case "both" | "foo" => println("foo") },
{ case "both" | "bar" => println("bar") }
)

( 编辑 huynhjl 指出他给出了与 this question 惊人相似的答案。)

关于scala - 具有多个匹配项的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com