listprologwin-prolog

Win Prolog List partly works


Im trying to relate a locker with a code. This is what i have so far.

    lockerof(C, [], V).
    lockerof(C,[C|_], V).
    lockerof(C, [[C, V]|_], V).

When i type in:

    lockerof(a, [[a,1],[b,2]], V).

It gives me the value for a so i get:

    V = 1

but when i type in:

    lockerof(b, [[a,1],[b,2]], V).

i get a 'no' but i want the output to be:

    V =2

What have i done wrong and how do i fix this problem?


Solution

  • You need to scan tail of the list too. Use recursion:

    lockerof(C, [_|T], V) :- lockerof(C, T, V).
    

    That is "if [C,V] is in tail of the list, then it is also in the list itself".

    Also, I don't think your first two rules are necessary.

    Finally, you could had implement it in one line with member/2 predicate:

    lockerof(C, L, V) :- member([C,V], L).