Prolog: predicate to check if elements of a list are present in a pre-defined list

StackOverflow https://stackoverflow.com/questions/23373121

  •  12-07-2023
  •  | 
  •  

Question

I have a fact defined as:

list([1,2,3,4,5]).

Now, I want to write a predicate pred(X) which succeeds if all elements of X are present in the list. For example, pred([1,3,4,2]) should succeed, while pred([2,6,8]) should not.

I tried the following:

pred([],[]).
pred([H|T]) :- list(X), member(H,X), pred(T). 

But, it always gives false.

Was it helpful?

Solution

You have a recursive clause but not a base clause. Thus, when you finish traversing the list, the last call is pred([]), which will fail as it doesn't unify with the head of you single clause for the predicate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top