First of all, let me tell you that this happens to be the first time I ask something here, so if it's not the right place to do so, please forgive me.
I'm developing a rather complex software that has a Prolog core implementing a FSM. Since I don't want it to stop (ever), I'm trying to write a good loop-like predicate that would work using Prolog's recursion. After a few unsuccessful tries (mainly because of stack problems) I ended up having something similar to this:
/* Finite State Transition Network */
transition(st0,evnt0,st1).
transition(st1,evnt1,st2).
transition(st2,evnt2,st0).
fsm_state(state(st0),system(Energy,ActivePayloads),[]) :-
/* ... */
transition(st0,evnt0,NextState),
!,
fsm_state(state(NextState),system(Energy,ActivePayloads),[]).
fsm_state(state(st1),system(Energy,ActivePayloads),[]) :-
/* ... */
transition(st1,evnt1,NextState),
!,
fsm_state(state(NextState),system(Energy,ActivePayloads),[0,1,2]).
fsm_state(state(st2),system(Energy,ActivePayloads),[P|Params]) :-
/* ... */
transition(st2,evnt2,NextState),
!,
fsm_state(state(NextState),system(Energy,ActivePayloads),[]).
start :-
Sys = system(10,[]),
fsm_state(state(s0),Sys,[]).
Is this a good approach?
First a general remark: The way you go about this is a perfectly natural Prolog approach, declaratively (well, more or less, if it were not for the many !/0 that prevent you to use the predicate in all directions) describing a relation between successive states. This relation is naturally implemented with a recursive predicate.
What strikes me as odd is that you need so many clauses that all seem in essence the same. Why can you not use a single clause like:
fsm(State0, System0, Params0) :-
/* ... */
transition(State0, Event, State),
/* ... */
fsm(State, System, Params).
where maybe some additional goals relate Params0 with Params, System0 with System and maybe some other entities. The general way is usually to have a relation between states before and after a single "step" of the computation, and another relation (consisting of a single clause like above) that describes a sequence of successive states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With