Process List in Prolog

427 Views Asked by At

I'm having trouble using lists in Prolog. I am implementing a Wumpus World example and need to move the wumpus during each user movement. The movement for the wumpus is predefined in a list, and I have no idea how to pop off the head of the list to set the wumpus' location. The Wumpus list would be: [left,right,up,down,...,right]. Here is what I have so far, which is obviously wrong.

I don't really need exact code for my code, just an example of a list and how to set a direction/value from a list and how to remove the popped off head of the list would be ideal.

wumpusPath([left,up,down,right,left,down]).

moveWumpus :-
    wumpusDirection(wumpusPath),
    wumpusLocation(X,Y),
    newLocation(X,Y,wumpusDirection,X1,Y1),
    worldSize(CheckX,CheckY),
    X1 =< CheckX,
    X1 > 0,
    Y1 =< CheckY,
    Y1 > 0,
    !,
    retract(wumpusLocation(X,Y)),
    assert(wumpusLocation(X1,Y1)).
2

There are 2 best solutions below

0
On BEST ANSWER
wumpusPath([left,up,down,right,left,down]).

wumpusDirection([D|P],D,P).                   % see below ****

moveWumpus :-
    wumpusPath(Path),                         % retrieve the Path
    wumpusDirection(Path,Direction,NewPath),  % set Direction from it ****
    wumpusLocation(X,Y),
    newLocation(X,Y,Direction,X1,Y1),
    worldSize(CheckX,CheckY),
    X1 =< CheckX,
    X1 > 0,
    Y1 =< CheckY,
    Y1 > 0,
    !,
    retractall(wumpusLocation(X,Y)),          % remember NewPath somehow too
    asserta(wumpusLocation(X1,Y1)).

But instead of asserting facts it's better to make your move predicate work with arguments: some will go "in", and some "out":

moveWumpus(Path,X,Y, NewPath,X1,Y1) :-

    wumpusDirection(Path,Direction,NewPath), 

    newLocation(X,Y,Direction,X1,Y1),
    worldSize(CheckX,CheckY),
    X1 =< CheckX,
    X1 > 0,
    Y1 =< CheckY,
    Y1 > 0,
    !
    .
0
On

Remember that a list is accessible by head an tail : if L = [a, b,c] and L = [H | T] then H is unified with a, and T with [b, c].