首页 文章

Scala模式匹配 - 匹配多个成功案例

提问于
浏览
1

我对Scala相当新,并且想知道 match 是否可以同时执行多个匹配的情况 . 在没有深入细节的情况下,我基本上正在开发一个函数,根据各种特征"scores"某个文本;这些特征可以重叠,并且对于一个给定的字符串,多个特征可以为真 .

为了说明我想要的代码,它看起来像这样:

假设我们有一个字符串 str ,其值为"Hello World" . 我想要的是以下几点:

str match {
    case i if !i.isEmpty => 2
    case i if i.startsWith("world") => 5
    case i if i.contains("world") => 3
    case _ => 0
}

我希望上面的代码触发第一个和第三个条件,有效地返回2和3(作为元组或以任何其他方式) .

这可能吗?

编辑:我知道这可以通过 if 's, which is the approach I took. I'链来完成,只是好奇,如果上述实现可能的话 .

2 回答

  • 2

    您可以将 case 语句转换为函数

    val isEmpty = (str: String) => if ( !str.isEmpty) 2 else 0
    val startsWith = (str: String) => if ( str.startsWith("world"))  5  else 0
    val isContains = (str: String) => if (str.toLowerCase.contains("world")) 3  else 0
    
    val str = "Hello World"
    
    val ret = List(isEmpty, startsWith, isContains).foldLeft(List.empty[Int])( ( a, b ) =>  a :+ b(str)   )
    
    ret.foreach(println)
    //2
    //0
    //3
    

    您可以使用 filter 过滤0值

    val ret0 = ret.filter( _ > 0)
     ret0.foreach(println)
    
  • 1

    请考虑这个解决方案:

    val matches = Map[Int, String => Boolean](2 -> {_.isEmpty}, 3 -> {_.contains("world")}, 5 -> {_.startsWith("world")})
    val scores = matches.filter {case (k, v) => v(str)}.keys
    

相关问题