2013-04-03 46 views
1

我正在实现一些内置的序言功能。然而,我遇到了交叉和差异的麻烦,因为在我的基递归情况下,我需要将我的返回值设置为空集。我不知道如何做到这一点,环顾四周,我还没有找到答案。制作变量空集

当我运行代码,我得到如下:

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). 

我知道这实际线路可能是一个相对简单的事情,但一段时间以来我一直困惑着我。

回答

2

这是很简单的:

intersectionx([], _, []). 

我发现你的变量有点怪怪的编号。你有这样做的理由吗?您可以在不同的谓词中使用相同的变量名称,而不会造成麻烦。

+1

其实它应该是'intersectionx([],_,[])。' – gusbro 2013-04-03 21:43:44

+0

谢谢,我已经修复它。 – 2013-04-03 21:47:45

+0

谢谢。我知道这将是简单的事情,我只是不知道什么。 我对这些变量进行了编号,因为我正在模仿旧的家庭作业,我必须以这种方式完成所有这些工作,教授要求我们按这种方式编号。我最初的复制粘贴它从旧的文档,所以他们是一个神器。我即将解雇他们。 – stygma 2013-04-03 21:54:44