且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog仅删除唯一元素

更新时间:2022-12-12 13:23:02

这与原始解决方案相似,但它会在辅助列表中收集非唯一值并进行检查以避免从原始列表中删除最后一个: /p>

This is similar to the original solution but it collects the non-unique values in an auxiliary list and checks it to avoid removing the last one from the original:

remove_uniq_vals(L, R) :-
    remove_uniq_vals(L, [], R).

remove_uniq_vals([], _, []).
remove_uniq_vals([X|T], A, R) :-
    (   member(X, A)
    ->  R = [X|T1], A1 = A
    ;   member(X, T)
    ->  R = [X|T1], A1 = [X|A]
    ;   R = T1, A1 = A
    ),
    remove_uniq_vals(T, A1, T1).

正在测试...

| ?- remove_uniq_vals([1,2,3,1,2,3,1,2,3,4,3], Q).

Q = [1,2,3,1,2,3,1,2,3,3]

(1 ms) yes
| ?- remove_uniq_vals([1,1,2,2,3,4,4,5,6,6,6], Q).

Q = [1,1,2,2,4,4,6,6,6]

yes

因此,如果第一个参数是输入,则谓词的效果很好,并且可以保持列表中其余元素的原始顺序.

So the predicate works great if the first argument is an input, and it maintains the original order of the remaining elements in the list.

但是,此谓词并不完全是 relational ,因为在第一个参数是一个已知数量的元素的未实例化列表,而第二个参数是一个不同的列表时,它将失败固定数量的元素.所以这样的事情会起作用:

However, this predicate is not completely relational in that it will fail a case in which the first argument is an uninstantiated list of a known number of elements and the second argument is a list of a different fixed number of elements. So something like this will work:

| ?- remove_uniq_vals([A,B,C], L).

B = A
C = A
L = [A,A,A]

(1 ms) yes

但是类似以下的操作失败:

But something like the following fails:

| ?- remove_uniq_vals([A,B,C], [1,1]).

no