1

我正在实施一些内置的 prolog 函数作为练习。但是,我在交集和差异方面遇到了麻烦,因为在我的基本递归情况下,我需要将返回值设置为空集。我不知道如何做到这一点,环顾四周我没有找到答案。

当我运行代码时,我得到以下信息:

1 ?- intersectionx([1,2,3],[3,4,5],Z).
Z = [3|_G3196] .

2 ?- differencex([1,2,3],[3,4,5],Z).
Z = [1, 2|_G3181] 

这是第 16 行和第 22 行的相关谓词的实际行。

/* memberx */
/* test is X a member of set Y, X subset Y */
memberx(X1,[X1|_]).
memberx(X2,[_|T2]) :- memberx(X2, T2).

/* unionx */
/* union sets X and Y and return the resulting set as Z. */
unionx([], Y3, Y3).             /* base case */
unionx([XH4|XT4], Y4, Z4) :- memberx(XH4, Y4), unionx(XT4, Y4, Z4).
unionx([XH5|XT5], Y5, [XH5|Z5]) :- not(memberx(XH5, Y5)), unionx(XT5, Y5, Z5).

/* intersectionx ???*/
/* Find the intersection of sets X and Y and return the result as set */
/* Z. X intersection Y = Z */
intersectionx([], Y6, Z6). /*In the base case here how do I set Z6 to []?*/
intersectionx([XH7|XT7], Y7, Z7) :- not(memberx(XH7, Y7)), intersectionx(XT7, Y7, Z7).
intersectionx([XH8|XT8], Y8, [XH8|Z8]) :- memberx(XH8, Y8), intersectionx(XT8, Y8, Z8).

/* differencex */
/* Find the difference of set X and Y and return the result as set Z. */
differencex([], Y9, Z9).
differencex([XH10|XT10], Y10, [XH10|Z10]) :- not(memberx(XH10, Y10)), differencex(XT10, Y10, Z10).
differencex([XH10|XT10], Y10, Z10) :- memberx(XH10, Y10), differencex(XT10, Y10, Z10).

我知道这可能是一件相对简单的事情,但它让我困惑了一段时间。

4

1 回答 1

2

这很简单:

intersectionx([], _, []).

我发现你的变量编号有点奇怪。你这样做是有原因的吗?您可以在不同的谓词中使用相同的变量名而不会遇到麻烦。

于 2013-04-03T21:36:49.667 回答