breily / states
- Source
- Commits
- Network (0)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Tree:
fb556c6
states /
README
DFA
===
* DFA lets you easily create deterministic finite automata in Ruby.
* You create a machine by giving it a list of states and then feeding
it input.
Example
-------
* A DFA to represent open and closed doors:
> require 'dfa'
>
> machine = automaton "Opened", {'close_door' => "Closed"},
> "Closed", {'open_door' => "Opened"}
>
=> <DFA: [Opened, Closed]>
> machine.give "close_door"
- exit state[Opened] >> input[close_door]
+ input[close_door] >> enter state[Closed]
=> <State: Closed :: {"open_door"=>"Opened"}>
> machine.give "open_door"
- exit state[Closed] >> input[open_door]
+ input[open_door] >> enter state[Opened]
=> <State: Opened :: {"close_door"=>"Closed"}>
* Further examples are in machines.rb.
Notes
-----
* The start state of the DFA is automatically the first state given.
* The DFA will continue to transition until an input doesn't match, at which
point it returns nil instead of a State.
* The special symbol :dot will match any input, but would only be matched
if no other input matches.
* The special state :error will raise an Exception if it is ever entered.
* See the 'nice_machine' for an example of both.
Actions
-------
* Each state has @onentry and @onexit procs that fire accordingly when you
enter or exit the state. Each gets the input causing the transition as
a parameter.
* By default, the @onentry proc prints the lines from the above example that
say "enter state[...]". The @onexit proc prints the "exit state[...]" lines.
* To define these easily, use the 'state' function, which takes a state name
and a block:
state 1 do
transition "c" => 2, :dot => :error
on_exit { |i| puts "input causing exit is: #{i}" }
end

