Aya Abdelsalam
Aya Abdelsalam

Reputation: 500

operations on elements inside lists in prolog

I am writing a prolog code and in the middle i want to check is all the elements in a list are a not included in a certain predicate

Here is the code:
 trap(a).
 trap(b).

not_trap([A|B]):-
\+trap(A),
not_trap(B).

not_trap(B):-
\+trap(B).

but this wont work can anyone tell me where I went wrong? Thanks

Upvotes: 0

Views: 158

Answers (1)

Fred Foo
Fred Foo

Reputation: 363587

Your base case is wrong. Whatever list you give to this predicate will be classified as not containing a trap, since the second clause matches it:

?- trace.
true.

[trace]  ?- not_trap([a]).
   Call: (6) not_trap([a]) ? creep
   Call: (7) trap(a) ? creep
   Exit: (7) trap(a) ? creep
   Call: (7) trap([a]) ? creep
   Fail: (7) trap([a]) ? creep
   Exit: (6) not_trap([a]) ? creep
true.

You can fix this predicate by either using the typical list recursion base case of

not_trap([]).

or by rewriting it without explicit recursion as

not_trap(L) :-
    \+ (member(X, L), trap(X)).

(Read this as: there is no member X of L that is a trap.)

Upvotes: 1

Related Questions