下面的 Prolog 程序定义了一个谓词deleted/3
,用于从传入第二个参数的列表中删除所有出现在第一个参数中的项目,并导致在第三个参数中传递的列表:
deleted(_, [], []).
deleted(X, [X|Y], Z) :-
deleted(X, Y, Z).
deleted(U, [V|W], [V|X]) :-
deleted(U, W, X),
U \= V.
- 它适用于此参数模式下的查询:
?- deleted(a, [a, b, a], [b]).
true
; false.
- 它也适用于这种参数模式下的查询:
?- deleted(X, [a, b, a], [b]).
X = a
; false.
- 它也适用于这种参数模式下的查询:
?- deleted(a, [a, b, a], Z).
Z = [b]
; false.
- 它也适用于这种参数模式下的查询:
?- deleted(X, [a, b, a], Z).
X = a, Z = [b]
; X = b, Z = [a, a]
; false.
- 它也适用于这种参数模式下的查询:
?- deleted(a, Y, Z).
Y = Z, Z = []
; Y = [a], Z = []
; Y = [a, a], Z = []
; Y = [a, a, a], Z = []
; Y = [a, a, a, a], Z = []
; …
- 它也适用于这种参数模式下的查询:
?- deleted(X, Y, Z).
Y = Z, Z = []
; Y = [X], Z = []
; Y = [X, X], Z = []
; Y = [X, X, X], Z = []
; Y = [X, X, X, X], Z = []
; …
- 但它会在这种参数模式下通过查询耗尽资源:
?- deleted(a, Y, [b]).
Stack limit (0.2Gb) exceeded
Stack sizes: local: 0.2Gb, global: 28.1Mb, trail: 9.3Mb
Stack depth: 1,225,203, last-call: 0%, Choice points: 1,225,183
Possible non-terminating recursion:
[1,225,203] deleted(a, _1542, [length:1])
[1,225,202] deleted(a, [length:1|_1584], [length:1])
- 它还会在此参数模式下通过查询耗尽资源:
?- deleted(X, Y, [b]).
Stack limit (0.2Gb) exceeded
Stack sizes: local: 0.2Gb, global: 28.1Mb, trail: 9.3Mb
Stack depth: 1,225,179, last-call: 0%, Choice points: 1,225,159
Possible non-terminating recursion:
[1,225,179] deleted(_1562, _1564, [length:1])
[1,225,178] deleted(_1596, [length:1|_1606], [length:1])
如何为所有参数模式实现列表项删除?