1

I'm quite new to declarative programming as a whole and am having trouble understanding how to properly recursively create a list of "moves" using tail recursion. In Prolog, I've been aimlessly tinkering for hours and false/gtrace can only tell me so much. I'd really appreciate any advice!

% Recursive Step
path([LF1, LH1, B1, RF1, RH1], [LF2, LH2, B2, RF2, RH2], Explored, Moves) :- 
    move([LF1, LH1, B1, RF1, RH1], [LF3, LH3, B3, RF3, RH3]),
    not(member([LF3, LH3, B3, RF3, RH3], Explored)),
    path([LF3, LH3, B3, RF3, RH3],
         [LF2, LH2, B2, RF2, RH2],
         [[LF3, LH3, B3, RF3, RH3]|Explored],
         [[[LF3, LH3, B3],[LF1, LH1, B1]] | Moves]).

% Solution found
path([LF,LH,B,RF,RH],[LF,LH,B,RF,RH],[], []).
    
solve(P) :- path([3,3,1,0,0],[0,0,0,3,3], _, P).
Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • Evidently, you are describing here a state, it might be better, to use a single variable for it. – false Oct 01 '22 at 17:22
  • 1
    `Explored` should be `[]` initially. Thus, in stead of `_` write `[]`. And at the End, it is `_` since no one cares about it. – false Oct 01 '22 at 17:24

2 Answers2

1

Rather use this generic definition for path/4!

solve(Path) :-
   path(move, Path, [3,3,1,0,0],[0,0,0,3,3]).
false
  • 10,264
  • 13
  • 101
  • 209
0

Do it the other way around:

path([LF1, LH1, B1, RF1, RH1], [LF2, LH2, B2, RF2, RH2], 
      Explored, [[[LF3, LH3, B3],[LF1, LH1, B1]] | Moves]) :- 
    move([LF1, LH1, B1, RF1, RH1], [LF3, LH3, B3, RF3, RH3]),
    not(member([LF3, LH3, B3, RF3, RH3], Explored)),
    path([LF3, LH3, B3, RF3, RH3],
         [LF2, LH2, B2, RF2, RH2],
         [[LF3, LH3, B3, RF3, RH3]|Explored],
         Moves).
path([LF,LH,B,RF,RH],[LF,LH,B,RF,RH],[], []).

This builds the list in the top-down manner.

(I haven't looked closely at your code, just referred to what you've asked).

Will Ness
  • 70,110
  • 9
  • 98
  • 181