0

有没有一种简单/最好的方法来获得一个我可以像列表一样进行模式匹配的 BitSet?

val btst = BitSet(1,2,3,4)
btst match {
  ...
  case head :: tail => tail
}
4

2 回答 2

4

根据定义,一个集合是一个无序的集合,并且在这样的集合上进行模式匹配是容易出错的。如果您愿意,请将其转换为列表...此外,您不应依赖headtail始终返回相同的内容。

于 2012-11-17T17:31:48.440 回答
3

BitSet 是有序的,但没有提取器。

编辑:但不是没有幽默感。

object |<| {
  def unapply(s: BitSet): Option[(Int, BitSet)] =
    if (s.isEmpty) None
    else Some((s.head, s.tail))
}

  def flags(b: BitSet) = b match {
    case f"5 || 10" => println("Five and dime")  // alas, never a literal
    case 5 |<| any  => println(s"Low bit is 5iver, rest are $any")
    case i |<| any  => println(s"Low bit is $i, rest are $any")
    case _          => println("None")
  }

  def dump(b: BitSet) = println(b.toBitMask.mkString(","))
  val s = BitSet(5, 7, 11, 17, 19, 65)
  dump(s)
  // ordinary laborious tests
  s match { 
    case x if x == BitSet(5)                => println("Five")
    case x if x == BitSet(5,7,11,17,19,65)  => println("All")
    case x if x(5)          => println("Five or more")
    case _                  => println("None")
  }     
  // manually matching on the mask is laborious
  // and depends on the bit length
  s.toBitMask match {
    case Array(2L)          => println("One")
    case Array(657568L)     => println("First word's worth")
    case Array(657568L, _)  => println("All")
    case _                  => println("None") 
  }   
  // or truncate for special case
  s.toBitMask(0) match {
    case 2L                 => println("One")
    case 657568L            => println("First word's worth")
    case _                  => println("None")
  }   
于 2012-11-17T21:56:25.283 回答