Skip to content

Commit 9ccd44d

Browse files
committed
[+]: Add nfa rule and ruleset class
1 parent a9a81fc commit 9ccd44d

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

machine/nfa.rb

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,34 @@
33
44
how to use:
55
simply run command irb with '--simple-prompt' agrument
6-
=end
6+
=end
7+
8+
require 'set'
9+
10+
class FARule < Struct.new(:state, :character, :next_state)
11+
def applies_to?(state,character)
12+
self.state == state && self.character == character
13+
end
14+
15+
def follow
16+
next_state;
17+
end
18+
19+
def inspect
20+
"#<FARule #{state.inspect} --#{character}--> #{next_state}>"
21+
end
22+
end
23+
24+
class NFARuleSet < Struct.new(:rules)
25+
def next_states(states, character)
26+
states.flat_map { |state| follow_rules_for(state, character) }.to_set
27+
end
28+
29+
def follow_rules_for(state, character)
30+
rules_for(state, character).map(&:follow)
31+
end
32+
33+
def rules_for(state, character)
34+
rules.select { |rule| rule.applies_to?(state, character) } # select * where
35+
end
36+
end

0 commit comments

Comments
 (0)