Menu
Home
Create new Paste
Log in
FSM with functions simple example.
Code
Theme: cobalt
Theme: eclipse
Theme: elegant
Theme: monokai
Theme: neat
Theme: night
Theme: rubyblue
module fsm; import std.stdio; import std.array; import std.conv; import std.typecons; import std.variant; struct FSM(Cargo) { alias Tuple!(Variant,Cargo) function(Cargo) State; alias Cargo function(Cargo) FinalState; Cargo cargo; State state; Cargo run(State s, Cargo c) { state = s; cargo = c; while(true) { auto temp = state(cargo); if (temp[0].peek!State) // not a final state { state = temp[0].get!State(); cargo = temp[1]; } else if (temp[0].peek!FinalState) { return temp[0].get!(FinalState)()(cargo); } else throw new Exception("Bad state!"); } } } template Handler(T) { alias Tuple!(Variant, T) Handler; } Handler!T handler(T)(Tuple!(Variant, T) function(T) h, T c) { return tuple(Variant(h), c); } Handler!T handler(T)(T function(T) f, T c) { return tuple(Variant(f), c); } //////////////////Example////////////////////////// Handler!string digit(string cargo) { auto f = cargo.front; switch(f) { case '\0': return handler(&end, cargo); case '0': .. case '9': writeln(f); cargo.popFront(); return handler(&digit, cargo); case '.': return handler(&dot, cargo); default: return handler(&error, cargo); } } Handler!string dot(string cargo) { writeln("."); cargo.popFront(); return handler(&digit, cargo); } string end(string cargo) { writeln("End."); return cargo; } string error(string cargo) { writeln("Error! cargo is ", to!string(cargo)); return cargo; } void main() { FSM!(string) fsm; fsm.run(&digit, "1234.30" ~ '\0'); }
Result:
Success
/
Return code: 0
/
Compilation time:
0.841
seconds
/
Run time:
0.001
seconds
Application output:
1
2
3
4
.
3
0
End.
Username
Message
Add comment
Paste info
Author:
Guest
Views:
169
Private:
no
Expires:
Never
Uploaded:
27.09.12 20:20
Votes
:
0
Tweet
Compilation
Compiler:
DMD 2.060
Pointer size:
m64
Actions
Download
Fork
Raw
×
Confirm
Are you sure you want to delete this paste?
There's no way back!
×
Confirm
Reason