Wiki

Clone wiki

Grape / Home

Introduction

As you may already know, there is a context in computer science named Finite State Machine which is referred as Automata sometimes. The principal is a machine containing numerous 'states' and moves from one to another using a condition called 'transition'. In fact, the machine considers the transition and moves to the next corresponding state. The way a state machine is modeled and calculated in mathematics, is a Graph. Each node indicates, and each edge shows a transition.

Getting Started

As you may guess, we are using variables for states and functions returning boolean for transition. The functions get a variable and return a boolean value. Therefore, we have a couple of predefined data types: one for states and another for transition input values. The first statement you may write is to define each of these data types:

    var machine = new StateMachine<string, int>();

In Grape project, each state has a name as string, for easier access and more readable code. You can declare states as following:

    machine.DeclareStates(
	new Dictionary<string, string> { 
	{"Page1" ,"First"},
	{"Page2" ,"Male"},
	{"Page3" ,"Female"}

After that, you may declare transitions. Note that in the above sample, we supposed the state data type is string. You can optionally use any appropriate data type. The only fixed data type is the name of the state, which must be string (The Dicitionary key). The next step is to declare transitions which are functions with input data type as defined in the first line, and returning boolean.

The wiki itself is actually a mercurial repository, which means you can clone it, edit it locally/offline, add images or any other file type, and push it back to us. It will be live immediately.

machine.DeclareTransitions(trans =>
{
	trans.From("Page1")
		.To("Page2").If(i => i == 0)
		.To("Page3").If(i => i == 1)
		.Loop().ElseWhere();
}
	);

The sample state machine, simply moves the user to page 1 if he is male, and moves her to page 2 if she is female. The latter statement, says the machine to loop to the previous state if non of the mentioned conditions met. As you can see, this is a fluent, readable structure. Anyway, if you have recommendation to get the structure more fluent or more readable, please don't hesitate to contact me. Now, to use the machine, simply give it the current state and the conditions input, and the result will be the next state.

Console.WriteLine(machine.Pass("First", 1));

Note that the machine currently does not persist the path and the previous states.

Updated