sharplib/fsm/FSM.cs

62 lines
977 B
C#

using System;
namespace fsm;
public record class Context : imm.Recorded<Context>
{
}
public record class State<T, CTX> : imm.Recorded<State<T, CTX>>
where T: State<T, CTX>
where CTX: Context
{
virtual public (CTX, T) onEnter(CTX ctx, State<T, CTX> oldState)
{
return (ctx, (T)this);
}
virtual public (CTX, T) onExit(CTX ctx, State<T, CTX> newState)
{
return (ctx, (T)this);
}
}
public record class FSM<T, CTX, ST> : imm.Recorded<FSM<T, CTX, ST>>
where T: FSM<T, CTX, ST>
where CTX: Context
where ST: State<ST, CTX>
{
public CTX Context { get; private set; }
public ST State { get; private set; }
public FSM(CTX context, ST state)
{
Context = context;
State = state;
}
public FSM<T, CTX, ST> Transition(ST newState)
{
var (newOldCTX, oldState) = State.onExit(Context, newState);
var (newCTX, storeState) = newState.onEnter(newOldCTX, oldState);
return this with
{
Context = newCTX,
State = storeState,
};
}
}