Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class DFA < Struct.new(:current_state, :accept_states, :rulebook)
- def accepting?
- puts accept_states.include?(current_state)
- end
- def read_character(character)
- self.current_state = rulebook.next_state(current_state, character)
- end
- def read_string(string)
- string.chars.each do |character|
- read_character(character)
- end
- end
- end
- class DFADesign < Struct.new(:start_state, :accept_states, :rulebook)
- def to_dfa
- DFA.new(start_state, accept_states, rulebook)
- end
- def accepts?(string)
- #tap evaluates the block and returns object it was called on
- to_dfa.tap{ |dfa| dfa.read_string(string) }.accepting?
- end
- end
- class FARule < Struct.new(:state, :character, :next_state)
- def applies_to?(state, character)
- self.state == state && self.character == character
- end
- def follow
- next_state
- end
- def inspect
- "#<FARule #{state.inspect } -- #{character} --> #{next_state.inspect}>"
- end
- end
- class DFARulebook < Struct.new(:rules)
- def next_state(state, character)
- rule_for(state, character).follow
- end
- def rule_for(state, character)
- if rules.detect{ |rule| rule.applies_to?(state, character) } == nil
- rules.push(FARule.new(state, character, state))
- rules.detect{ |rule| rule.applies_to?(state, character) }
- else
- rules.detect{ |rule| rule.applies_to?(state, character) }
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement