1 ! Copyright (C) 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel accessors sequences byte-arrays bit-arrays math
4 math.bitwise hints sets ;
7 TUPLE: bit-set { table bit-array read-only } ;
9 : <bit-set> ( capacity -- bit-set )
10 <bit-array> bit-set boa ;
15 over integer? [ table>> ?nth ] [ 2drop f ] if ; inline
18 ! This is allowed to throw an error when the elt couldn't
20 [ t ] 2dip table>> set-nth ;
23 ! This isn't allowed to throw an error if the elt wasn't
26 table>> 2dup bounds-check? [
31 ! If you do binary set operations with a bit-set, it's expected
32 ! that the other thing can also be represented as a bit-set
36 ERROR: check-bit-set-failed ;
38 : check-bit-set ( bit-set -- bit-set )
39 dup bit-set? [ check-bit-set-failed ] unless ; inline
41 : bit-set-map ( seq1 seq2 quot -- seq )
45 [ [ length ] bi@ assert= ]
46 [ [ underlying>> ] bi@ ] 2bi
48 ] 3bi bit-array boa ; inline
50 : (bit-set-op) ( set1 set2 -- table1 table2 )
51 [ set-like ] keep [ table>> ] bi@ ; inline
53 : bit-set-op ( set1 set2 quot: ( a b -- c ) -- bit-set )
54 [ (bit-set-op) ] dip bit-set-map bit-set boa ; inline
59 [ bitor ] bit-set-op ;
62 [ bitand ] bit-set-op ;
65 [ bitnot bitand ] bit-set-op ;
68 [ intersect ] keep = ;
71 [ table>> length iota ] keep [ in? ] curry filter ;
75 : bit-set-like ( set bit-set -- bit-set' )
76 ! Throws an error if there are keys that can't be put
78 over bit-set? [ 2dup [ table>> length ] bi@ = ] [ f ] if
80 [ members ] dip table>> length <bit-set>
81 [ [ adjoin ] curry each ] keep
87 bit-set-like check-bit-set ; inline
90 table>> clone bit-set boa ;
92 M: bit-set cardinality