Created
April 30, 2010 13:42
-
-
Save chad/385216 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This FSM recognizes the sequence 1 2 3 anywhere in the | |
# input. Note that 1 2 1 2 3 and 1 1 2 3 and both valid. | |
class FSM | |
class State | |
def initialize(name) | |
@name = name | |
@hash = {} | |
end | |
def transition(trigger_and_new_state) | |
@hash.merge!(trigger_and_new_state) | |
end | |
def otherwise(new_state) | |
@hash.default = new_state | |
end | |
def next_state(event) | |
new_state = @hash[event] | |
puts "#{event} => #{new_state}" | |
new_state | |
end | |
end | |
def initialize | |
@transitions = {} | |
end | |
def state(name, &transitions) | |
state = State.new(name) | |
state.instance_eval(&transitions) | |
@transitions[name] = state | |
end | |
def recognize(inputs) | |
current_state = :start | |
inputs.each do |event| | |
current_state = @transitions[current_state].next_state(event) | |
break if current_state == :done | |
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 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment