Finite state machine: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 36:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V states = [‘ready’ =
(‘Machine ready: (d)eposit, or (q)uit?’,
[String(‘d’), ‘q’]),
Line 80:
current_state = :states[next_state]
 
finite_state_machine(‘ready’, ‘q’)</langsyntaxhighlight>
 
{{out}}
Line 95:
=={{header|BASIC}}==
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="basic">
10 REM FINITE STATE MACHINE
20 LET MS=1: REM MACHINE STATE
Line 141:
5010 PRINT "MACHINE IS SHUTDOWN"
5020 END
</syntaxhighlight>
</lang>
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
Line 153:
Note that the program uses no variables and makes no use of the return stack: all the state is expressed in the (so to speak) state.
 
<langsyntaxhighlight lang="basic"> 10 PRINT "PRESS D(EPOSIT) OR Q(UIT)"
20 IF INKEY$="D" THEN GOTO 50
30 IF INKEY$="Q" THEN STOP
Line 167:
130 GOTO 120
140 PRINT "REFUNDED"
150 GOTO 10</langsyntaxhighlight>
{{out}}
It will be seen that the user has pressed, in order, <tt>D</tt>, <tt>R</tt>, <tt>D</tt>, <tt>S</tt>, <tt>R</tt>, and <tt>Q</tt>.
Line 181:
=={{header|C}}==
Here is a manually-constructed table-driven finite state machine that is fairly general and could be adapted to different applications.
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <ctype.h>
Line 233:
return 0;
}
</syntaxhighlight>
</lang>
Machine simulation :
<pre>
Line 251:
 
=={{header|C++}}==
<syntaxhighlight lang="c">
<lang C>
#include <map>
Line 416:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 442:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.conv;
import std.range;
import std.stdio;
Line 506:
void main() {
fsm();
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Finite_state_machine;
 
Line 595:
begin
fsm;
end.</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Phix}}
<langsyntaxhighlight lang="freebasic">Enum states
READY
WAITING
Line 647:
End Select
Loop
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 655:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 754:
func main() {
fsm()
}</langsyntaxhighlight>
 
{{out}}
Line 778:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class FiniteStateMachine {
private enum State {
Ready(true, "Deposit", "Quit"),
Line 826:
}
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Exit
import Data.Maybe
import Control.Monad
Line 900:
, Implicit "Refunding" "Ready" ]
finishStates = ["Exit"]
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 906:
This seems to be what the current draft task asks for:
 
<syntaxhighlight lang="text">NB. FSM builder:
explicit=: {{
states=: ~. states,x;y
Line 926:
Snm=: statename=: {{ ;:inv m{states }}
Tnm=: transitionname=: {{ ;:inv m{transitions }}
implicits=: {{ r=.'' while. next '' do. r=.r, current end. }}</langsyntaxhighlight>
 
With the above implementation, the task example would look like:
 
<langsyntaxhighlight Jlang="j">NB. task example FSM:
start 'ready'
'ready' 'deposit'explicit 'waiting'
Line 958:
echo 'implicit transition to: ',i statename
end.
}}</langsyntaxhighlight>
 
More advanced examples might put the FSM in a locale (allowing for multiple, independent FSMs), add callbacks and/or parameterization on transitions, or maybe include hardware specific code.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.*;
 
public class FiniteStateMachine {
Line 1,014:
}
}
}</langsyntaxhighlight>
<pre>[Deposit, Quit]
> Deposit
Line 1,033:
=={{header|JavaScript}}==
===On browser using blocking window methods===
<langsyntaxhighlight JavaScriptlang="javascript">//States
var states = [{
'name': 'Ready',
Line 1,101:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">abstract type State end
 
struct Ready <: State
Line 1,185:
 
runsim(Ready())
</langsyntaxhighlight>{{out}}
<pre>
Vending machine is ready. (q)uit, (d)eposit: d
Line 1,198:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
enum class State { READY, WAITING, EXIT, DISPENSE, REFUNDING }
Line 1,254:
fun main(args: Array<String>) {
fsm()
}</langsyntaxhighlight>
 
Sample input/output:
Line 1,277:
=={{header|Nim}}==
{{trans Kotlin}}
<langsyntaxhighlight Nimlang="nim">import strutils
 
type State {.pure.} = enum Ready, Waiting, Exit, Dispense, Refunding
Line 1,321:
break
 
fsm()</langsyntaxhighlight>
 
{{out}}
Line 1,341:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(import (scheme read))
 
Line 1,392:
; run
(state-machine states 'ready)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,424:
 
</pre>
<syntaxhighlight lang="pascal">
<lang Pascal>
{
fsm1.pas
Line 1,681:
end.
 
</syntaxhighlight>
</lang>
 
 
Line 1,757:
=={{header|Perl}}==
Added a dummy input called "IMPLICIT" that does not actually require input but automatically transitions to next state.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Finite_state_machine
Line 1,793:
waiting REFUND refunding take the refund
dispense REMOVE ready Thank You
refunding IMPLICIT ready</langsyntaxhighlight>
{{out}}
<pre>
Line 1,821:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/fsm.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Finite_State_Machine.exw
Line 1,900:
<span style="color: #7060A8;">IupHide</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PicoLisp}}==
Non-interactive random switch between states.
<langsyntaxhighlight PicoLisplang="picolisp">(seed (in "/dev/urandom" (rd 8)))
(de atm NIL
(state '(ready)
Line 1,918:
(nil (prinl "quit")) ) ) )
(do 3
(while (atm)) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,928:
=={{header|Prolog}}==
 
<langsyntaxhighlight Prologlang="prolog">state(ready, deposit, waiting).
state(ready, quit, exit).
state(waiting, select, dispense).
Line 1,952:
act(NextState).
print_message(State) :- message(State, Message), format(Message).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,974:
=={{header|Python}}==
{{works with|Python 3}}
<langsyntaxhighlight Pythonlang="python">''' Finite State Machine for Rosetta Code
Actually two of them. The main FSM described in the task and a second one of the Acceptor variety described on
the WP page to get the input from the user.
Line 2,033:
if __name__ == "__main__":
finite_state_machine('ready','q')
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,048:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(define states
Line 2,078:
(let/ec quit
(with-input-from-string "deposit select remove deposit refund quit"
(λ () (machine states void read quit)))))</langsyntaxhighlight>
{{out}}
<pre>CURRENT STATE: ready
Line 2,099:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>#===== The state machine =====#
 
class StateMachine {
Line 2,174:
$machine.add-transition("refunding", "ready");
 
$machine.run("ready");</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,188:
::* a mixture of uppercase and lowercase text is used for the output messages
::* messages have extra blanks for readability &nbsp; (and options are spelled out)
<langsyntaxhighlight lang="rexx">/*REXX pgm simulates a FSM (Finite State Machine), input is recognized by pressing keys.*/
10: say "Press D (deposit) or Q (quit)" /*display a prompt (message) to term. */
20: $=inkey(); upper $ /*since this a terminal, uppercase KEY.*/
Line 2,210:
 
140: say "Refunded" /*display what action just happened. */
signal 10 /*go & re-start process (ready state). */</langsyntaxhighlight>
{{out|output|text= &nbsp; when using (pressing) the exact same input(s) as the '''BASIC''' entry: &nbsp; &nbsp; <tt> D &nbsp; R &nbsp; D &nbsp; S &nbsp; R &nbsp; Q </tt>}}
<pre>
Line 2,231:
works withooRexx (and any other REXX).
key and Enter must be pressed-
<langsyntaxhighlight lang="rexx">/*REXX pgm simulates a FSM (Finite State Machine), input is recognized by pressing keys.*/
10: k=inkey('D (deposit) or Q (quit)','DQ')
if k=="D" then signal 50 /*Is response a "D" ? Process deposit.*/
Line 2,258:
Say 'Invalid key, try again.'
End
Return k</langsyntaxhighlight>
{{out}}
<pre>Press D (deposit) or Q (quit) and Enter
Line 2,278:
'''[dependencies]'''<br>
methods-enum = "0.2.4"
<langsyntaxhighlight lang="fsharp">enum State {
Ready,
Waiting,
Line 2,343:
std::io::stdin().read_line(&mut text).unwrap_or(0);
text.chars().next().unwrap_or('\x0d')
}</langsyntaxhighlight>
{{out}}
<pre>Ready: d - deposit / q - quit
Line 2,363:
=={{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.
<langsyntaxhighlight lang="tcl">set fsm [dict create \
ready {deposit waiting quit exit} \
waiting {select dispense refund refunding} \
Line 2,390:
set state [dict get $fsm $state {}]
}
}</langsyntaxhighlight>
{{out}}
<pre>$ tclsh fsm.tcl
Line 2,410:
=={{header|VBA}}==
{{trans|Phix}}
<langsyntaxhighlight lang="vb">Enum states
READY
WAITING
Line 2,461:
End Select
Loop
End Sub</langsyntaxhighlight>{{out}}
<pre>Machine is READY. (D)eposit or (Q)uit :
D
Line 2,481:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<langsyntaxhighlight lang="ecmascript">import "/str" for Str
import "io" for Stdin, Stdout
 
Line 2,532:
}
 
fsm.call()</langsyntaxhighlight>
 
{{out}}
Line 2,558:
 
If we need true state to state hops, we could use tail recursion (another name for goto).
<langsyntaxhighlight lang="zkl">class FSM{ // our Finite State Machine
var bank=0, item=Void;
fcn deposit(coin){ bank=coin }
Line 2,573:
}
 
Vault.add(FSM); // put class FSM where I can find it</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn run(program){ // convert text to FSM instructions and run them
program=program.replace("(",".fp("); // deposit(10)-->deposit.fp(10)
a,b,p := 0,0,Sink("class P(FSM){ state(); ");
Line 2,582:
// println(program); // WTH did I just do?
Compiler.Compiler.compileText(program)(); // compile and run our little FSM
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">run("select(); take(); deposit(10); select(\"snickers\"); take();");</langsyntaxhighlight>
The above is converted to:
<langsyntaxhighlight lang="zkl">class P(FSM){
state();
act(select.fp());
Line 2,592:
act( select.fp("snickers"));
act( take.fp());
}</langsyntaxhighlight>
The .fp() is function application (ie deferred execution) so I can extract the
function name and print it.
10,333

edits