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 ; inline
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 [ f ] 2dip table>> ?set-nth
29 ! If you do binary set operations with a bit-set, it's expected
30 ! that the other thing can also be represented as a bit-set
34 ERROR: check-bit-set-failed ;
36 : check-bit-set ( bit-set -- bit-set )
37 dup bit-set? [ check-bit-set-failed ] unless ; inline
39 : bit-set-map ( seq1 seq2 quot -- seq )
43 [ [ length ] bi@ assert= ]
44 [ [ underlying>> ] bi@ ] 2bi
46 ] 3bi bit-array boa ; inline
48 : (bit-set-op) ( set1 set2 -- table1 table2 )
49 [ set-like ] keep [ table>> ] bi@ ; inline
51 : bit-set-op ( set1 set2 quot: ( a b -- c ) -- bit-set )
52 [ (bit-set-op) ] dip bit-set-map bit-set boa ; inline
57 [ bitor ] bit-set-op ;
60 [ bitand ] bit-set-op ;
63 [ bitnot bitand ] bit-set-op ;
66 [ intersect ] keep = ;
69 [ table>> length iota ] keep [ in? ] curry filter ;
73 : bit-set-like ( set bit-set -- bit-set' )
74 ! Throws an error if there are keys that can't be put
76 over bit-set? [ 2dup [ table>> length ] same? ] [ f ] if
78 [ members ] dip table>> length <bit-set>
79 [ [ adjoin ] curry each ] keep
85 bit-set-like check-bit-set ; inline
88 table>> clone bit-set boa ;
90 M: bit-set cardinality