Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

prolog

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't it result in Z = [1]??

like image 748
gregghz Avatar asked Jan 20 '26 08:01

gregghz


1 Answers

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!

like image 134
false Avatar answered Jan 23 '26 20:01

false