使用 prolog 消除列表元素的连续重复项 [英] Eliminate consecutive duplicates of list elements with prolog

查看:98
本文介绍了使用 prolog 消除列表元素的连续重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初的问题是想出一个方法来得到以下内容

The original problem was to come up with a way to get the following

remove([a,a,a,b,q,q,q,q,e,e,e]),X)
X = [a,b,q,e]

推荐答案

我们可以沿着列表迭代一次来解决这个问题.在列表中的任何一点,我们检查当前元素和下一个元素,如果它们相同,则忽略当前元素,否则,如果它们不同,则取当前元素.

We can solve this problem by one iteration along the list. At any point in the list we check the current element and the next element, if they are the same then we ignore the current element, else if they are different we take the current element.

rm_dup([], []).
rm_dup([X], [X]).
rm_dup([X1, X2 | Xs], [X1 | Ys]) :-
    dif(X1, X2), rm_dup([X2|Xs], Ys).
rm_dup([X, X | Xs], Ys) :-
    rm_dup([X | Xs], Ys).

第一和第二个子句是基本子句,其中没有重复的元素.第三条和第四条是递归规则.

The first and second clauses are base clauses in which there are no duplicate elements. The third and fourth clauses are recursive rules.

在第三个子句中,我们声明如果输入列表有两个值 X1X2 并且它们不同 dif(X1, X2),然后保持当前值.

In third clause we state that if the input list has two values X1 and X2 and they are different dif(X1, X2), then keep the current value.

在第四个子句中,如果我们有相同的连续值,那么我们忽略当前值.

In fourth clause if we have same consecutive values then we ignore the current value.

第三个和第四个子句是互斥的,因此为了使谓词确定性,最好将它们组合如下

The third and fourth clauses are mutually exclusive and hence to make the predicate deterministic it is better to combine them as follows

rm_dup([X], [X]) :- !.
rm_dup([X1, X2 | Xs], Ys) :-
    dif(X1, X2) -> (rm_dup([X2 | Xs], Ys1), Ys = [X1 | Ys1]);
    rm_dup([X2 | Xs], Ys).

更好的是只使用相等作为条件并翻转 thenelse 子句.

Even better is to just use equality as a condition and flip the then and else clauses.

rm_dup([X], [X]) :- !.
rm_dup([X1, X2 | Xs], Ys) :-
    X1 = X2 ->  rm_dup([X2 | Xs], Ys);
    rm_dup([X2 | Xs], Ys1), Ys = [X1 | Ys1].

这篇关于使用 prolog 消除列表元素的连续重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆