I've got these definitions:
memberx(X, [X|_]).
memberx(X, [_|T]) :- memberx(X, T).
intersectionx([], _, []).
intersectionx([H|T], Y, [_|Z]) :- memberx(H, Y), !, intersectionx(T, Y, Z).
intersectionx([_|T], Y, Z) :- intersectionx(T, Y, Z).
I get the following result:
?- intersectionx([1], [1], Z).
Z = [_G305].
Why doesn开发者_StackOverflow社区't it result in Z = [1]??
Z = [_G305].
means that this answer is true for all terms. That is, it is not only true for Z = [1] - as you expect, but it is also true for Z = [2].
Clearly, that is not what you expected.
So where is the error? A simple way to detect it is to watch out for anonymous variables denoted _.
Consider:
intersectionx([H|T], Y, [_|Z]) :- memberx(H, Y), !, intersectionx(T, Y, Z).
^^^
What you have written means that the intersection of a list starting with H and another list will be (provided the goals on the right hand side are all true) a list starting with anything... Replace anything by that H!
精彩评论