简体   繁体   English

列表的 Scala 匹配模式

[英]Scala match pattern for list

val res1 = -1
val res2: List[Int] = List.empty
val res3 = -1

After some operations, res2 can have multiple elements, but all values must be -1经过一些操作, res2可以有多个元素,但是所有的值都必须是-1

How I can made a pattern matching using this list?如何使用此列表进行模式匹配?

before this, when res2 was an Int , I used this pattern:在此之前,当res2Int时,我使用了这种模式:

(r1, r2, r3) match {
  case (-1, -1, -1) => Success()
  case _ => throw new Exception("Invalid results")
}

now I need something like现在我需要类似的东西

(r1, r2, r3) match {
  case (-1, List(-1, -1, ...), -1) => Success()
  case _ => throw new Exception("Invalid results")
}

I know I can use List.forall or List.exists , but this is outside matching pattern.我知道我可以使用List.forallList.exists ,但这超出了匹配模式。

Update: I found a solution which works fine更新:我找到了一个很好的解决方案

val r2res = r2.forall(x => x == -1)

 (r1, r2res, r3) match {
   case (-1, true, -1) => Success()
   case _ => throw new Exception("Invalid results")
 }

Feel free to post a reply if exist a method to match directly the result of res2.如果存在直接匹配 res2 结果的方法,请随时发表回复。 Thanks谢谢

You can use pattern guards in pattern matching:您可以在模式匹配中使用模式防护

(r1, r2, r3) match {
  case (-1, l:List[Int], -1) if l.forall(_ == -1) => Success()
  case _ => throw new Exception("Invalid results")
}

Try combining pattern binder with a guard尝试将模式活页夹与防护结合起来

(res1, res2, res3) match {
  case (-1, (l @ h :: _), -1) if l.forall(_ == -1) => // ok
  case _ => // nok
}

Note I used (l @ h:: _) pattern assuming empty list should not qualify because注意我使用(l @ h:: _)模式假设空列表不应该符合条件,因为

assert(List.empty[Int].forall(_ == -1))   // ok

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM