Scala模式匹配——匹配多个成功案例 [英] Scala pattern matching - match multiple successful cases

查看:99
本文介绍了Scala模式匹配——匹配多个成功案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Scala 还很陌生,想知道 match 是否可以一次执行多个匹配案例.在不涉及太多细节的情况下,我基本上正在开发一个功能,该功能可以根据各种特征对某段文本进行评分";这些特征可以重叠,对于一个给定的字符串,多个特征可以为真.

I am fairly new to Scala, and would like to know if it is possible for a match to execute multiple matching cases at once. Without getting into too much detail, I am basically working on a function that "scores" a certain piece of text according to various traits; these traits can overlap, and multiple traits can be true for one given string.

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

To illustrate what I want in code, it would look something like this:

假设我们有一个字符串,str,值为Hello World".我想要以下内容:

Say we have a String, str, with a value of "Hello World". I would like something along the lines of the following:

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(作为元组或以任何其他方式).

I would like the above code to trigger both the first and third conditions, effectively returning both 2 and 3 (as a tuple or in any other way).

这可能吗?

我知道这可以通过一系列 if 来完成,这是我采用的方法.我只是很好奇是否有可能实现上述实现.

I know this can be done with a chain of if's, which is the approach I took. I'm just curious if something like the above implementation is possible.

推荐答案

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

You can turn your case statements to functions

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

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

这篇关于Scala模式匹配——匹配多个成功案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆