2013-04-03 22 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