Created
December 3, 2009 21:58
-
-
Save dmcinnes/248574 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
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment