列表的 Scala 匹配模式
Scala match pattern for list
val res1 = -1
val res2: List[Int] = List.empty
val res3 = -1
经过一些操作,res2可以有多个元素,但所有的值必须是-1
如何使用此列表进行模式匹配?
在此之前,当 res2
是一个 Int
时,我使用了这个模式:
(r1, r2, r3) match {
case (-1, -1, -1) => Success()
case _ => throw new Exception("Invalid results")
}
现在我需要类似的东西
(r1, r2, r3) match {
case (-1, List(-1, -1, ...), -1) => Success()
case _ => throw new Exception("Invalid results")
}
我知道我可以使用 List.forall
或 List.exists
,但这是外部匹配模式。
更新:我找到了一个很好用的解决方案
val r2res = r2.forall(x => x == -1)
(r1, r2res, r3) match {
case (-1, true, -1) => Success()
case _ => throw new Exception("Invalid results")
}
如果有直接匹配res2结果的方法,欢迎post回复。谢谢
您可以在模式匹配中使用pattern guards:
(r1, r2, r3) match {
case (-1, l:List[Int], -1) if l.forall(_ == -1) => Success()
case _ => throw new Exception("Invalid results")
}
尝试将模式绑定器与保护器结合使用
(res1, res2, res3) match {
case (-1, (l @ h :: _), -1) if l.forall(_ == -1) => // ok
case _ => // nok
}
注意我使用了 (l @ h :: _)
模式,假设空列表不符合条件,因为
assert(List.empty[Int].forall(_ == -1)) // ok
val res1 = -1
val res2: List[Int] = List.empty
val res3 = -1
经过一些操作,res2可以有多个元素,但所有的值必须是-1
如何使用此列表进行模式匹配?
在此之前,当 res2
是一个 Int
时,我使用了这个模式:
(r1, r2, r3) match {
case (-1, -1, -1) => Success()
case _ => throw new Exception("Invalid results")
}
现在我需要类似的东西
(r1, r2, r3) match {
case (-1, List(-1, -1, ...), -1) => Success()
case _ => throw new Exception("Invalid results")
}
我知道我可以使用 List.forall
或 List.exists
,但这是外部匹配模式。
更新:我找到了一个很好用的解决方案
val r2res = r2.forall(x => x == -1)
(r1, r2res, r3) match {
case (-1, true, -1) => Success()
case _ => throw new Exception("Invalid results")
}
如果有直接匹配res2结果的方法,欢迎post回复。谢谢
您可以在模式匹配中使用pattern guards:
(r1, r2, r3) match {
case (-1, l:List[Int], -1) if l.forall(_ == -1) => Success()
case _ => throw new Exception("Invalid results")
}
尝试将模式绑定器与保护器结合使用
(res1, res2, res3) match {
case (-1, (l @ h :: _), -1) if l.forall(_ == -1) => // ok
case _ => // nok
}
注意我使用了 (l @ h :: _)
模式,假设空列表不符合条件,因为
assert(List.empty[Int].forall(_ == -1)) // ok