开发者

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

开发者 https://www.devze.com 2023-01-23 20:08 出处:网络
I\'ve got these definitions: memberx(X, [X|_]). memberx(X, [_|T]) :- memberx(X, T). intersectionx([], _, []).

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号