What do prolog results like Z = [_G305] mean?

I have the following 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 does this not lead to Z = [1] ??

+3
source share
1 answer

Z = [_G305].

means this answer is correct for all members. That is, this is not only true for Z = [1] - as you would expect, but it is also true for Z = [2].

Clearly, this is not what you expected.

So where is the mistake? An easy way to detect this is to keep an eye on the anonymous variables denoted by _.

Consider:

intersectionx([H|T], Y, [_|Z]) :- memberx(H, Y), !, intersectionx(T, Y, Z).
                        ^^^

What you wrote means that the intersection of the list starting with H and one more list (if the goals on the right side are all right) are the list starting with nothing ... Replace something with this H!

+5
source

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


All Articles