Skip to content

Commit 7028c9e

Browse files
author
Nilay Vishwakarma
committed
mealy and moore machine example
1 parent 30464da commit 7028c9e

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

example/MealyMachine.cs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace SharpFsm.Example
8+
{
9+
public class MealyMachine
10+
{
11+
public enum MealyState { S0, S1 }
12+
public class MealyContext
13+
{
14+
public string Input { get; set; }
15+
public string Output { get; set; }
16+
}
17+
18+
public MealyMachine()
19+
{
20+
21+
var registry = new TransitionRegistry<MealyState, MealyContext>();
22+
registry.RegisterSideEffect("OutputA", (ctx, _, _) => ctx.Output = "A");
23+
registry.RegisterSideEffect("OutputB", (ctx, _, _) => ctx.Output = "B");
24+
25+
var builder = FiniteStateMachineBuilder<MealyState, MealyContext>.Create("Mealy")
26+
.WithInitialState(MealyState.S0)
27+
.WithRegistry(registry)
28+
.AddTransition(MealyState.S0, MealyState.S1)
29+
.When(ctx => ctx.Input == "x")
30+
.WithSideEffect("OutputA")
31+
.Done()
32+
.AddTransition(MealyState.S1, MealyState.S0)
33+
.When(ctx => ctx.Input == "y")
34+
.WithSideEffect("OutputB")
35+
.Done();
36+
var fsm = new FiniteStateMachine<MealyState, MealyContext>(builder.Build());
37+
}
38+
}
39+
}

example/MooreMachine.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace SharpFsm.Example
8+
{
9+
public class MooreMachine
10+
{
11+
public enum MooreState { S0, S1 }
12+
public class MooreContext
13+
{
14+
public string Output { get; set; }
15+
}
16+
17+
public MooreMachine()
18+
{
19+
var registry = new TransitionRegistry<MooreState, MooreContext>();
20+
// No side effects on transitions; output is determined by state
21+
22+
var builder = FiniteStateMachineBuilder<MooreState, MooreContext>.Create("Moore")
23+
.WithInitialState(MooreState.S0)
24+
.WithRegistry(registry)
25+
.AddTransition(MooreState.S0, MooreState.S1)
26+
.WithSideEffect((MooreContext ctx, MooreState oldState, MooreState newState) =>
27+
{
28+
switch (newState)
29+
{
30+
case MooreState.S0: ctx.Output = "A"; break;
31+
case MooreState.S1: ctx.Output = "B"; break;
32+
}
33+
})
34+
.Done()
35+
.AddTransition(MooreState.S1, MooreState.S0)
36+
.Done();
37+
38+
var fsm = new FiniteStateMachine<MooreState, MooreContext>(builder.Build());
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)