Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FSM
- def initialize
- @states = {}
- end
- def state(name, &block)
- s = State.new
- s.instance_eval(&block)
- @states[name] = s
- end
- def recognize(list)
- state = @states[:start]
- next_state = nil
- raise "no start state!" unless state
- list.each do |item|
- print "#{item} "
- next_state = state.execute(item)
- if next_state == :done
- puts "found it!"
- break
- end
- state = @states[next_state]
- end
- end
- class State
- def initialize
- @transitions = {}
- @otherwise = :start
- end
- def transition(trans)
- @transitions.merge!(trans)
- end
- def otherwise(other)
- @otherwise = other
- end
- def execute(item)
- @transitions[item] || @otherwise
- end
- end
- end
- fsm = FSM.new
- fsm.state :start do
- transition "1" => :one
- otherwise :start
- end
- fsm.state :one do
- transition "2" => :two
- transition "1" => :one
- otherwise :start
- end
- fsm.state :two do
- transition "3" => :done
- transition "1" => :one
- otherwise :start
- end
- fsm.recognize %w[1 4 2 1 1 2 1 2 3 2 3 1]
Add Comment
Please, Sign In to add comment