1 ! Copyright (C) 2008, 2009 Doug Coleman, Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays assocs combinators fry kernel locals
4 math math.order regexp.nfa regexp.transition-tables sequences
5 sets sorting vectors sequences.deep math.functions regexp.classes ;
6 USING: io prettyprint threads ;
9 :: (while-changes) ( obj quot: ( obj -- obj' ) comp: ( obj -- key ) old-key -- obj )
10 obj quot call :> new-obj
11 new-obj comp call :> new-key
14 [ new-obj quot comp new-key (while-changes) ]
17 : while-changes ( obj quot pred -- obj' )
18 3dup nip call (while-changes) ; inline
22 : make-partition ( choices classes -- partition )
23 zip [ first ] partition parts boa ;
25 : powerset-partition ( classes -- partitions )
26 ! Here is where class algebra will happen, when I implement it
27 [ length [ 2^ ] keep ] keep '[
28 _ [ ] map-bits _ make-partition
31 : partition>class ( parts -- class )
33 [ <or-class> ] bi@ <not-class> 2array <and-class> ;
35 : get-transitions ( partition state-transitions -- next-states )
36 [ in>> ] dip '[ at ] gather ;
38 : disambiguate-overlap ( nfa -- nfa' )
41 [ keys powerset-partition ] keep '[
43 [ _ get-transitions ] bi
46 ] change-transitions ;
48 : find-delta ( states transition nfa -- new-states )
49 transitions>> '[ _ swap _ at at ] gather sift ;
51 : (find-epsilon-closure) ( states nfa -- new-states )
54 : find-epsilon-closure ( states nfa -- new-states )
55 '[ dup _ (find-epsilon-closure) union ] [ length ] while-changes
58 : find-closure ( states transition nfa -- new-states )
59 [ find-delta ] keep find-epsilon-closure ;
61 : find-start-state ( nfa -- state )
62 [ start-state>> 1vector ] keep find-epsilon-closure ;
64 : find-transitions ( dfa-state nfa -- next-dfa-state )
69 : add-todo-state ( state visited-states new-states -- )
70 3dup drop key? [ 3drop ] [
71 [ conjoin ] [ push ] bi-curry* bi
74 :: new-transitions ( nfa dfa new-states visited-states -- nfa dfa )
75 new-states [ nfa dfa ] [
77 state nfa find-transitions
79 state trans nfa find-closure :> new-state
80 new-state visited-states new-states add-todo-state
81 state new-state trans transition make-transition dfa add-transition
83 nfa dfa new-states visited-states new-transitions
86 : states ( hashtable -- array )
88 [ values [ values concat ] map concat append ] bi ;
90 : set-final-states ( nfa dfa -- )
92 [ final-states>> keys ]
93 [ transitions>> states ] bi*
94 [ intersects? ] with filter
95 ] [ final-states>> ] bi
96 [ conjoin ] curry each ;
98 : initialize-dfa ( nfa -- dfa )
100 swap find-start-state >>start-state ;
102 : construct-dfa ( nfa -- dfa )
105 dup start-state>> 1vector
108 [ set-final-states ] keep ;