簡體   English   中英

在 Scala 中匹配 BitSet 的模式

[英]Pattern matching a BitSet in Scala

有沒有一種簡單/最好的方法來獲得一個 BitSet 我可以像列表一樣模式匹配?

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

根據定義,集合是一個無序的集合,在這樣的集合上進行模式匹配很容易出錯。 如果您願意,請將其轉換為列表...此外,您不應該依賴headtail來始終返回相同的內容。

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")
  }   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM