Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. class DFA < Struct.new(:current_state, :accept_states, :rulebook)
  2. def accepting?
  3. puts accept_states.include?(current_state)
  4. end
  5. def read_character(character)
  6. self.current_state = rulebook.next_state(current_state, character)
  7. end
  8. def read_string(string)
  9. string.chars.each do |character|
  10. read_character(character)
  11. end
  12. end
  13. end
  14.  
  15. class DFADesign < Struct.new(:start_state, :accept_states, :rulebook)
  16. def to_dfa
  17. DFA.new(start_state, accept_states, rulebook)
  18. end
  19. def accepts?(string)
  20. #tap evaluates the block and returns object it was called on
  21. to_dfa.tap{ |dfa| dfa.read_string(string) }.accepting?
  22. end
  23. end
  24.  
  25.  
  26. class FARule < Struct.new(:state, :character, :next_state)
  27. def applies_to?(state, character)
  28. self.state == state && self.character == character
  29. end
  30.  
  31. def follow
  32. next_state
  33. end
  34.  
  35. def inspect
  36. "#<FARule #{state.inspect } -- #{character} --> #{next_state.inspect}>"
  37. end
  38.  
  39. end
  40.  
  41.  
  42.  
  43. class DFARulebook < Struct.new(:rules)
  44. def next_state(state, character)
  45. rule_for(state, character).follow
  46. end
  47.  
  48. def rule_for(state, character)
  49. if rules.detect{ |rule| rule.applies_to?(state, character) } == nil
  50. rules.push(FARule.new(state, character, state))
  51. rules.detect{ |rule| rule.applies_to?(state, character) }
  52. else
  53. rules.detect{ |rule| rule.applies_to?(state, character) }
  54. end
  55. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement