示例:
您有两个列表("类别"):
catLow = [1,2,3,4,5]
catHigh = [6,7,8,9,10]
使用模式匹配,您如何决定是否
val x = 7
是在第一个列表(类别)还是第二个列表中?
这是一般问题。我的具体问题是这样做,但在我的情况下,X在列表中,如:
val l = [1,7,2,4]
我希望将它与以下内容相匹配:
case catHigh :: tail // i.e. starts with a "high" number
case _ :: catLow :: tail // i.e. second element is a "low" number
// where "high" and "low" are example category names implemented as lists
答案 0 :(得分:4)
val lowSet = Set(1, 2, 3, 4, 5)
val highSet = Set(6, 7, 8, 9, 10)
someList match {
case catHigh :: tail if highSet(catHigh) => ...
case _ :: catLow :: tail if lowSet(catLow) => ...
}
Set
可以用作返回传递的元素是否在Set
中的函数。然后,在match语句中,您可以使用模式保护(与if
一起引入)来检查匹配的值是否在集合中。
答案 1 :(得分:1)
你可以这样做:
scala> class Cat( xs:Set[Int] ) {
def unapply( x:Int ) = if ( xs contains x ) Some(x) else None
}
defined class Cat
scala> object CatLow extends Cat( Set(1,2,3,4,5) )
defined object CatLow
scala> object CatHigh extends Cat( Set(6,7,8,9,10) )
defined object CatHigh
scala> def decode( zs:List[Int] ):Unit = zs match {
case Nil =>
case CatLow(z)::tail =>
println("Low "+z)
decode(tail)
case CatHigh(z)::tail =>
println("High "+z)
decode(tail)
case z::tail =>
println("???? "+z)
decode(tail)
}
decode: (zs: List[Int])Unit
scala> decode( List(1,7,2,0,4) )
Low 1
High 7
Low 2
???? 0
Low 4