Skip to content

Instantly share code, notes, and snippets.

@dmcinnes
Created December 3, 2009 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dmcinnes/248574 to your computer and use it in GitHub Desktop.
Save dmcinnes/248574 to your computer and use it in GitHub Desktop.
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