組み込みのプロローグ関数のいくつかを実践として実装しています。ただし、基本的な再帰的なケースでは、戻り値を空のセットに設定する必要があるため、交差と差で問題が発生しています。これを行う方法がわかりません。周りを見回しても答えが見つかりません。
コードを実行すると、次のようになります。
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).
これはおそらく比較的単純なことだと思いますが、しばらくの間、私を困惑させてきました。