Prolog, list which identifies an item is in a current place

97 Views Asked by At

Im having trouble work out how to write in prolog that the chest "C" is at location "L" This is the code i have at the moment but i think im making it too complicated and going in the wrong direction

    location(C, L).

    location(C, [[C,L]|_]).
    location(C, [_|T]) :-
            location(C, T, L).

Can anyone help or point me in the right direction into solving this.

To check it, i use this code:

    location(b, [(a,10), (b,6), (c,8), (d,14)]).

I have now changed it and have:

    location(C, L, P). 
    location(C, L, P) :- memberchk((C,P), L).

and

    location(b, [(a,10), (b,6), (c,8), (d,14)], P).

But it doesnt seem to work, what have i missed out?

2

There are 2 best solutions below

2
CapelliC On

try

location(S, L, P) :- memberchk((S,P), L).

then you'll get

?- location(b, [(a,10), (b,6), (c,8), (d,14)], P).
P = 6.
4
nullpotent On

Here's another one, although CapelliC solution is just fine.

location(C, [(C,P)|_], P):-!.
location(C, [_|T], P) :- location(C, T, P).