Search several items in a Prolog list

1

I'm trying to find several items in a list:

buscar([]).
buscar([X|Xs]):-  member(X,[a,b,c,d,e]), buscar(Xs).

but just look for me if all the elements in the list are equal, true Y if an item is not the same, the query gives false

but that's not what I'm looking for.

The result should come out like this:

? .- search ([a, b, c]).

true. true true.

or so:

? .- search ([a, x, c, e]).

true. false. true true.

I do not know what I'm doing wrong.

    
asked by goku venz 08.10.2016 в 18:07
source

1 answer

3

This is because you are not defining a stop condition for recursion, and when you scroll through the list of items when you poll the empty list, then it is not a member of the [a,b,c,d,e] list, which causes that the condition fails and the whole predicate itself. Conclusion, to avoid this, you should consider the case of the empty list.

buscar([]).
buscar([X|Xs]):-  member(X,[a,b,c,d,e]), buscar(Xs).

In this way, your buscar/1 predicate will no longer fail to complete the list:

?- buscar([a,b,c]).
true

?- buscar([a,f,g]).
false

On the other hand, it would be advisable that you add a cut condition in the second clause of the predicate, in this way you would avoid doing bactracking (looking for an alternative solution), which does not make sense, because from what I understand your predicate is only to determine if a list of elements is contained in another list of elements. Adding the cut condition, buscar/1 , would look like this:

buscar([]).
buscar([X|Xs]):-  member(X,[a,b,c,d,e]), !, buscar(Xs).

So that you understand the difference: If we ask the following question using the first definition of the predicate:

?- buscar([a,b,c]).

You would get the following answers:

true;
false.

However, using the second definition of the predicate, we would only get one answer, the correct one:

true.

UPDATE

Taking into account the editing of your question, I am enclosing a new answer for your case, where I detail it less, because basically it is the same principle, only that in this case you need a new variable to instantiate the result, now the predicate would be buscar/2 , staying as follows

buscar([], []).
buscar([X|Xs], [true|Tail]):-  member(X,[a,b,c,d,e]),! , buscar(Xs, Tail).
buscar([_|Xs], [false|Tail]):-  buscar(Xs, Tail).

A valid query would be the following:

?- buscar([a,x,c,e], L).
 L = [true, false, true, true]
    
answered by 11.10.2016 / 18:43
source