Finite state machine: Difference between revisions

Add Tcl version
(Add Tcl version)
Line 1,946:
Refunded
Press D (deposit) or Q (quit) and Enter</pre>
 
=={{header|Tcl}}==
Using a nested dict where the leafs contain the output state corresponding to an action, and empty actions are implicit transitions. Would be marginally cleaner using a do..while proc.
<lang tcl>set fsm [dict create \
ready {deposit waiting quit exit} \
waiting {select dispense refund refunding} \
dispense {remove ready} \
refunding {{} ready} \
]
set state ready
 
proc prompt {fsm state} {
set choices [dict keys [dict get $fsm $state]]
while {1} {
puts -nonewline "state: $state, possible actions: $choices\n>"
if {[gets stdin line] == -1} {
exit
}
if {$line in $choices} {
return $line
}
}
}
 
while {$state ne "exit"} {
set action [prompt $fsm $state]
set state [dict get $fsm $state $action]
while {[dict exists $fsm $state {}]} {
set state [dict get $fsm $state {}]
}
}</lang>
{{out}}
<pre>$ tclsh fsm.tcl
state: ready, possible actions: deposit quit
>deposit
state: waiting, possible actions: select refund
>select
state: dispense, possible actions: remove
>remove
state: ready, possible actions: deposit quit
>deposit
state: waiting, possible actions: select refund
>re
state: waiting, possible actions: select refund
>refund
state: ready, possible actions: deposit quit
>quit</pre>
 
=={{header|VBA}}==
Anonymous user