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 sequences.private ;
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 ;
24 : ?set-nth ( elt n seq -- )
25 2dup bounds-check? [ set-nth-unsafe ] [ 3drop ] if ; inline
30 ! This isn't allowed to throw an error if the elt wasn't
33 [ f ] 2dip table>> ?set-nth
36 ! If you do binary set operations with a bit-set, it's expected
37 ! that the other thing can also be represented as a bit-set
41 ERROR: check-bit-set-failed ;
43 : check-bit-set ( bit-set -- bit-set )
44 dup bit-set? [ check-bit-set-failed ] unless ; inline
46 : bit-set-map ( seq1 seq2 quot -- seq )
50 [ [ length ] bi@ assert= ]
51 [ [ underlying>> ] bi@ ] 2bi
53 ] 3bi bit-array boa ; inline
55 : (bit-set-op) ( set1 set2 -- table1 table2 )
56 [ set-like ] keep [ table>> ] bi@ ; inline
58 : bit-set-op ( set1 set2 quot: ( a b -- c ) -- bit-set )
59 [ (bit-set-op) ] dip bit-set-map bit-set boa ; inline
64 [ bitor ] bit-set-op ;
67 [ bitand ] bit-set-op ;
70 [ bitnot bitand ] bit-set-op ;
73 [ intersect ] keep = ;
76 [ table>> length iota ] keep [ in? ] curry filter ;
80 : bit-set-like ( set bit-set -- bit-set' )
81 ! Throws an error if there are keys that can't be put
83 over bit-set? [ 2dup [ table>> length ] same? ] [ f ] if
85 [ members ] dip table>> length <bit-set>
86 [ [ adjoin ] curry each ] keep
92 bit-set-like check-bit-set ; inline
95 table>> clone bit-set boa ;
97 M: bit-set cardinality