Lets assume a typical interview question:
Write some code to reverse words in a sentence without using .Net string functions. For example, “this and that” should become “sith dna taht”. We want to preserve space patterns also.
This is the state machine for this purpose:
And I can write it as follows:
public class TextContext { public string Text; public int Pos; //Current position public string Word; public string Result; } public static void Main() { var tc = new TextContex{Text="This and That"}; var sm = new StateMachineBuilder() .State("Space", c => true, c => { c.Word += " "; c.Pos++; }) .Then(c => c.Pos >= c.Text.Length, "Fine") .Then(c => c.Text[c.Pos] == ' ', "Space") .Then("Word", c => {c.Result += c.Word; c.Word = '';}) .State("Word", c => true, c => {c.Word = c.Text[c.Pos] + c.Word; c.Pos++;}) .Then(c => c.Pos >= c.Text.Length, "Fine") .Then(c => c.Text[c.Pos] != ' ', "Word") .Then("Space", c => {c.Result += c.Word; c.Word = '';}) .Finish("Fine") .BindTo(tc); sm.Start(); while(sm.MoveNext()){}; Console.WriteLn(tc.Result); }
UPDATE: SWE is re-design. With the new version, the above code will look like the following:
var str = "This and That"; var word = new StringBuilder(); var smbuilder = StateMachine<int,string>.Create("word") .State("leters", (s, i) => { if (str[i]==' ') { s.Return(word.ToString()); word.Clear(); return StateMachine.Named("spaces");}; word.Append(str[i]); s.UpldateObject(i+1); //Update the pointer return StateMachine.Loop }) .State("spaces", (s, i) => { s.UpdateObject(i+1); if(str[i]==' ') { return StateMachine.Loop; } return StateMachine.Named("letters"); }); var sm = smbuilder.BindTo(0); while(sm.Process()){ if (sm.HasReturn) { Console.WriteLn (sm.GetReturned();) } }