Guest User

Untitled

a guest
Apr 25th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. class FSM
  2.  
  3. def initialize
  4. @states = {}
  5. end
  6.  
  7. def state(name, &block)
  8. s = State.new
  9. s.instance_eval(&block)
  10. @states[name] = s
  11. end
  12.  
  13. def recognize(list)
  14. state = @states[:start]
  15. next_state = nil
  16. raise "no start state!" unless state
  17. list.each do |item|
  18. print "#{item} "
  19. next_state = state.execute(item)
  20. if next_state == :done
  21. puts "found it!"
  22. break
  23. end
  24. state = @states[next_state]
  25. end
  26. end
  27.  
  28. class State
  29. def initialize
  30. @transitions = {}
  31. @otherwise = :start
  32. end
  33.  
  34. def transition(trans)
  35. @transitions.merge!(trans)
  36. end
  37.  
  38. def otherwise(other)
  39. @otherwise = other
  40. end
  41.  
  42. def execute(item)
  43. @transitions[item] || @otherwise
  44. end
  45. end
  46.  
  47. end
  48.  
  49. fsm = FSM.new
  50. fsm.state :start do
  51. transition "1" => :one
  52. otherwise :start
  53. end
  54.  
  55. fsm.state :one do
  56. transition "2" => :two
  57. transition "1" => :one
  58. otherwise :start
  59. end
  60.  
  61. fsm.state :two do
  62. transition "3" => :done
  63. transition "1" => :one
  64. otherwise :start
  65. end
  66.  
  67. fsm.recognize %w[1 4 2 1 1 2 1 2 3 2 3 1]
Add Comment
Please, Sign In to add comment