2012-11-17 86 views
0

有沒有一種容易/最好的方式來獲得一個BitSet我可以像列表模式匹配?匹配Scala中的BitSet的模式

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

回答

4

BitSet是ordered,但是無提取。

編輯:但不幽默。

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

根據定義,一個集合是一個無序集合,並且在這樣一個集合上的模式匹配是容易出錯的。將它轉換爲列表,如果你想......另外,你不應該依靠headtail總是返回相同的東西。