A long standing problem
2008.Sep.30
Just a little idea sharing. For a little Verge-related experiment I’ve been doing (and losing due to crashes) this last couple of days, I decided I needed to implement a state machine validating system.
Well… Tada!! Somehow ready, in C# (I just need to add a delegate to do something when entering the state, but that’s a kinda special case.
And with C# 3.0 lambda expressions, this should be a to use. So, this should also work quite easily in Python, now that I think of it.
//A nice state machine generic validator in C# public class State<T> { protected LinkedList<KeyValuePair<Predicate<T>, State<T>>> transitions { get; set; } public State() { this.transitions = new LinkedList<KeyValuePair<Predicate<T>, State<T>>>(); } protected virtual State<T> GetTransition(T t) { foreach (KeyValuePair<Predicate<T>, State<T>> trans in transitions) { if (trans.Key(t)) return trans.Value; } return null; } public virtual void AddTransition(Predicate<T> condition, State<T> state) { transitions.AddLast(new KeyValuePair<Predicate<T>, State<T>>(condition, state)); } public bool Process(IEnumerator<T> it) { State<T> current = this; while (it.MoveNext()) { current = current.GetTransition(it.Current); if (current is FinalState<T>) return true; } return false; } } public sealed class FinalState<T> : State<T> { public FinalState() { this.transitions = null; } public override void AddTransition(Predicate<T> cond, State<T> s) { throw new NotSupportedException("A final state cannot have transitions"); } protected override State<T> GetTransition(T t) { throw new NotSupportedException("A final state cannot have transitions"); } }