http://qs321.pair.com?node_id=116106


in reply to finite automata

Sorry, I could not resist ...

fsm.pl:

#!/usr/bin/perl -w use strict; my $config = do(shift || "fsm.config"); my $state = $config->{start_state}; my $input = ""; while (($state, $input) = compute($state, get_input())) { action($state, $input); } action($state, $input); # -------------------------------------------------- # subs # -------------------------------------------------- sub get_input { print "Your input (", join("|", @{$config->{input_alphabet}}), "): + "; my $input = <>; chomp($input); return $input; } sub compute { my ($state, $input) = @_; return $config->{transition_function}->{$state}->{$input}, $input; } sub action { my ($state, $input) = @_; $config->{action_function}->{$state}->{$input}->() if $config->{action_function}->{$state}->{$input}; die "REJECT\n" unless $state; die "ACCEPT\n" if accept_p($state); } sub accept_p { my ($state) = @_; return 1 if grep {$state eq $_} @{$config->{goal_states}}; return 0; }

fsm.config:

# template: # # my $config = { # states => [], # input_alphabet => [], # transition_function => { # "state" => { # "input" => "state", # "input" => "state", # }, # "state" => { # "input" => "state", # "input" => "state", # }, # }, # action_function => { # "state" => { # "input" => sub {}, # "input" => sub {}, # }, # "state" => { # "input" => sub {}, # "input" => sub {}, # }, # }, # start_state => "", # goal_states => [], # }; my $config = { states => [ "q0", "q1", "halt" ], input_alphabet => [ "a", "b", "#" ], transition_function => { "q0" => { "a" => "q0", "b" => "q1", }, "q1" => { "b" => "q1", "#" => "halt", }, }, action_function => { "q0" => { "a" => sub {print "q0 - +> q0\n"}, "b" => sub {print "q0 - +> q1\n"}, }, "q1" => { "b" => sub {print "q1 - +> q1\n"}, "#" => sub {print "q1 - +> halt\n"}, }, }, start_state => "q0", goal_states => [ "halt" ], };

Christian Lemburg
Brainbench MVP for Perl
http://www.brainbench.com