Why does Prolog map a variable to a result that fails if it is connected directly?

I am making a Prolog program that finds a subset of a list of lists. This subset must meet certain specific conditions, one aspect of which is that the lists of subsets cannot be identical. What confuses me is that when I try to find a match for variable X, it generates results that return false if I connect them to the query instead of X. For example:

?- containsSet(2, [[3],[7],[7]], X).
X = [[3], [7]] ;
X = [[3], [7]] ;
X = [[7], [7]] ;
false.

?- containsSet(2, [[3],[7],[7]], [[7],[7]]).
false.

How can it match X in [[7], [7]] if it returns false when connected directly?

The idea of ​​containsSet is to find a subset of lists with a length of-N (in this case 2) that have no matching elements in matching positions (i.e., none of the two lists in the subset has the same first element or the same second element, etc.). In the above example, the first (and only) elements from [7] and [7] are the same, so it returns false.

+4
source share
1 answer

First of all, congratulations to one of the most declarative and justified comments that I saw in the questions of newcomers!

, , . , Prolog , , (\+)/1, . , - , , Prolog. , , -, Prolog.

, , (\+)/1 :

?- X = d, \+ member(X, [a,b,c]).
X = d.

, :

?-  \+ member(X, [a,b,c]), X = d.
false.

, (\+)/1 : , :

?-  \+ member(X, [a,b,c]).
false.

?- \+ member(d, [a,b,c]).
true.

, . , , , , , , , .

, , , dif/2. dif/2 , . :

not_member(X, Ls) :- maplist(dif(X), Ls).

, :

?- not_member(X, [a,b,c]), X = d.
X = d.

?- X = d, not_member(X, [a,b,c]).
X = d.

not_member/2 , — — .

, , Prolog. . .

+3

Source: https://habr.com/ru/post/1611576/


All Articles